From ad6314967fab363a4bb987ce43cff3f27c06b7c7 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Tue, 27 Oct 2026 19:58:37 +0100 Subject: [PATCH 001/258] blocks: REFEDIT edits xrefs in place and writes their drawing back REFEDIT on an xref (or a block that came with one) edits it in place, and REFCLOSE Save writes the change into the source drawing (the old file kept as .bak, symbol prefixes removed, host symbols copied, handles kept) and reloads the xref. Refused for read-only files, files locked by another program or open in another tab, and files changed since they were loaded or during the edit. Nested references are picked through their parents (path, nested, refedit.levels, "Select nesting level [OK/Next]"). Everything outside the working set is drawn faded (XFADECTL), and an Edit Reference bar offers Add to/Remove from Working Set and Save/Discard Changes. Gap F2. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/doc/src/lib.rs | 2 +- crates/doc/src/refedit.rs | 22 + crates/engine/src/cmd/blocks/refedit.rs | 580 ++++++++++++++++++++-- crates/engine/src/cmd/blocks/xref/load.rs | 50 +- crates/engine/src/sysvars/table.rs | 2 + crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/refedit.rs | 5 +- crates/engine/tests/it/refedit_xref.rs | 243 +++++++++ crates/render/src/draw.rs | 9 + crates/ui-egui/src/canvas.rs | 3 + crates/ui-egui/src/canvas/refedit.rs | 72 +++ crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + docs/gaps.md | 7 +- docs/target-app-parity.md | 5 +- 15 files changed, 956 insertions(+), 57 deletions(-) create mode 100644 crates/engine/tests/it/refedit_xref.rs create mode 100644 crates/ui-egui/src/canvas/refedit.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index eafea9e27..49cd46863 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -31,7 +31,7 @@ pub use gdt::*; pub use header::{HVal, Header}; pub use plotstyle::*; pub use plotter::*; -pub use refedit::{RefEdit, WorkItem}; +pub use refedit::{RefEdit, WorkItem, XrefSource}; pub use store::EntityStore; pub use tables::*; diff --git a/crates/doc/src/refedit.rs b/crates/doc/src/refedit.rs index eb0927365..78dfa1764 100644 --- a/crates/doc/src/refedit.rs +++ b/crates/doc/src/refedit.rs @@ -42,6 +42,28 @@ pub struct RefEdit { /// Block objects taken out of the working set with their edits (block coordinates, the block /// object's handle). pub released: Vec, + /// The nested references picked through to reach the edited block: block references inside + /// block definitions, outermost first. Empty when the picked reference's own block is edited. + pub path: Vec, + /// Set when the edited block comes from an external reference: REFCLOSE Save writes it back + /// into its source drawing. + pub xref: Option, +} + +/// Where an xref edited in place is written back to. +#[derive(Clone, Debug, PartialEq)] +pub struct XrefSource { + /// The xref (its block name in this drawing). + pub xref: String, + /// The source drawing file. + pub file: String, + /// The block of the source drawing being edited; `None` for its model space. + pub block: Option, + /// The file's size and modification time (nanoseconds since 1970) when the edit began. + pub stamp: Option<(u64, u128)>, + /// Edited block objects (their handles in this drawing) and the objects of the source + /// drawing they were loaded from. + pub sources: Vec<(Handle, Handle)>, } impl RefEdit { diff --git a/crates/engine/src/cmd/blocks/refedit.rs b/crates/engine/src/cmd/blocks/refedit.rs index 0a61122a5..1e3b213db 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -1,42 +1,57 @@ -//! REFEDIT, REFSET and REFCLOSE: edit a block reference in place. +//! REFEDIT, REFSET and REFCLOSE: edit a block reference or an xref in place. //! //! REFEDIT hides the picked reference and puts the block's objects (all, or the ones named) into //! the drawing where the reference shows them: the *working set*, ordinary objects that every //! command edits. The rest of the block stands there as faded copies, and everything else in the -//! drawing is locked ([`crate::cmd::curves::is_locked`], enforced by [`after_command`]). Objects -//! drawn while editing join the working set. REFSET adds objects to or removes them from it. -//! REFCLOSE writes the working set back into the block definition, so every reference to the -//! block shows the change, or discards the edit. +//! drawing is locked ([`crate::cmd::curves::is_locked`], enforced by [`after_command`]) and drawn +//! faded (XFADECTL). Objects drawn while editing join the working set. REFSET adds objects to or +//! removes them from it. REFCLOSE writes the working set back into the block definition, so every +//! reference to the block shows the change, or discards the edit. +//! +//! A reference nested in another block is picked through its parents (`path`, or "Select nesting +//! level [OK/Next]" at the command line): its own block is edited, the parents' other objects +//! stand faded around it. +//! +//! An xref (or a block that came with one) is edited the same way, and REFCLOSE Save writes the +//! change into its source drawing: the previous file is kept as `name.bak`, and the save is +//! refused when the file is read-only, open in another program (or another drawing tab), or +//! changed since it was loaded. The xref is then loaded again from the file it wrote. //! //! The state is [`Drawing::refedit`]: it travels with undo, is never written to a file (files //! are written from [`Drawing::committed`]) and ends with the drawing it belongs to. //! -//! Not yet: external references (their source drawing would have to be written back), nested -//! references picked at a depth, annotative scale contexts and attribute synchronisation. +//! Not yet: annotative scale contexts, attribute synchronisation and xrefs nested in xrefs (open +//! those with XOPEN). -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use cadcraft_doc::{Drawing, Entity, EntityStore, Handle, RefEdit, Transparency, WorkItem}; +use cadcraft_doc::{Block, Drawing, Entity, EntityKind, EntityStore, Handle, RefEdit, Transparency, WorkItem, XrefSource, XrefStatus}; use cadcraft_geom::Mat3; use serde_json::{Value, json}; use super::super::curves::handle_value; -use super::super::machines::{SelOutcome, SelectPhase, SelectRun}; +use super::super::machines::{SelOutcome, SelectPhase}; use super::references_block; +use super::xref::load::{self, Sym}; use crate::cmd::{CommandSpec, bad, bool_or, has_doc, str_param, targets}; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; -/// Transparency of the faded copies of the block's other objects. -const GHOST_FADE: u8 = 70; +/// Most nesting levels offered for one picked reference. +const MAX_LEVELS: usize = 256; pub(super) fn specs() -> Vec { vec![ CommandSpec::new("refedit", "Edit Reference In-Place", run_refedit) .menu(&["Tools", "Xref and Block In-place Editing", "Edit Reference In-Place"]) - .params("{handle? | handles? | name? (a block reference, default the selection), objects?: [block object handles] (default all)} → {block, insert, working: [handles], faded}") + .alias(&["-refedit"]) + .params("{handle? | handles? | name? (a block or xref reference, default the selection), path?: [handles of nested block references, outermost first] | nested?: block name (the first nested reference to it), objects?: [block object handles] (default all)} → {block, insert, working: [handles], faded, path, xref?: {name, file}}. Editing an xref writes its file back on REFCLOSE Save.") .enabled(has_doc) - .interactive(|_| Ok(Box::new(SelectRun::single("refedit", "REFEDIT", "Select reference")))), + .interactive(|_| Ok(Box::new(RefeditM::default()))), + CommandSpec::new("refedit.levels", "Reference Nesting Levels", run_levels) + .params("{handle (a block or xref reference)} → {levels: [{name, path: [handles], xref}]} (the picked reference first, then the references nested in it)") + .enabled(has_doc) + .noundo(), CommandSpec::new("refset", "Working Set", run_refset) .menu(&["Tools", "Xref and Block In-place Editing", "Add to Working Set"]) .params("{add?: [handles], remove?: [handles]} (or {handles, mode?: \"add\"|\"remove\"}); with neither: lists the working set → {working: [handles], added, removed}") @@ -44,7 +59,7 @@ pub(super) fn specs() -> Vec { .interactive(|_| Ok(Box::new(RefsetM::default()))), CommandSpec::new("refclose", "Save Reference Edits", run_refclose) .menu(&["Tools", "Xref and Block In-place Editing", "Save Reference Edits"]) - .params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects}") + .params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects, file? (an xref's source drawing written), backup?}") .enabled(editing) .interactive(|_| Ok(Box::new(RefcloseM))), ] @@ -59,13 +74,19 @@ fn active(s: &Session, cmd: &str) -> Result { s.doc()?.refedit.clone().ok_or_else(|| bad(cmd, "no block reference is being edited (REFEDIT)")) } -/// A block object as the drawing shows it through the edited reference. -fn to_host(to_world: &Mat3, e: &Entity, h: Handle, ghost: bool) -> Entity { +/// How much the block's other objects fade (XFADECTL, 0–90 percent). +fn xfadectl(s: &Session) -> Result { + Ok(u8::try_from(s.doc()?.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50)) +} + +/// A block object as the drawing shows it through the edited reference; `fade` (XFADECTL, a +/// percentage) shows the block's other objects faded. +fn to_host(to_world: &Mat3, e: &Entity, h: Handle, fade: Option) -> Entity { let mut c = e.clone(); c.handle = h; c.kind.transform(to_world); - if ghost { - c.common.transparency = Transparency::Percent(GHOST_FADE); + if let Some(f) = fade { + c.common.transparency = Transparency::Percent(f.min(90)); } c } @@ -88,6 +109,173 @@ fn hexes(hs: impl IntoIterator) -> Vec { hs.into_iter().map(|h| h.hex()).collect() } +// ---------------- nesting ---------------- + +/// One level of a picked reference: a block, how its objects show in the drawing, and the +/// reference inside it that leads to the next level (none at the last). +struct Level { + block: Arc, + to_world: Mat3, + next: Option, +} + +/// Whether a reference with transform `m` can be edited in place (finite, not flat, scaled the +/// same in X and Y). +fn editable_transform(m: &Mat3, sx: f64, sy: f64) -> bool { + let finite = [m.a, m.b, m.c, m.d, m.e, m.f].iter().all(|v| v.is_finite()); + finite && m.det().abs() >= 1e-12 && (sx.abs() - sy.abs()).abs() <= 1e-9 * sx.abs().max(sy.abs()) +} + +/// The levels from top reference `ins` down `path` (references inside the block definitions). +fn levels(d: &Drawing, ins: &cadcraft_doc::Insert, path: &[Handle]) -> Result> { + let mut block = d.block(&ins.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", ins.block)))?; + let mut m = ins.transform(block.base.xy()); + if !editable_transform(&m, ins.scale.x, ins.scale.y) { + return Err(bad("refedit", "the reference must be scaled equally in X and Y (and not flat) to be edited in place")); + } + if path.len() >= cadcraft_doc::MAX_BLOCK_DEPTH { + return Err(bad("refedit", "the reference is nested too deeply")); + } + let mut out = Vec::with_capacity(path.len() + 1); + for h in path { + let e = block.entities.get(*h).ok_or_else(|| bad("refedit", format!("object {} is not a reference in block \"{}\"", h.hex(), block.name)))?; + let EntityKind::Insert(child) = &e.kind else { return Err(bad("refedit", format!("object {} is not a block reference", h.hex()))) }; + let cb = d.block(&child.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", child.block)))?; + let cm = m.then_before(child.transform(cb.base.xy())); + if !editable_transform(&cm, child.scale.x, child.scale.y) { + return Err(bad("refedit", format!("the nested reference to \"{}\" must be scaled equally in X and Y", cb.name))); + } + out.push(Level { block, to_world: m, next: Some(*h) }); + block = cb; + m = cm; + } + out.push(Level { block, to_world: m, next: None }); + Ok(out) +} + +/// The references nested in block `name` (depth first): (path of handles, block name). +fn nested(d: &Drawing, name: &str, path: &mut Vec, out: &mut Vec<(Vec, String)>) { + if path.len() + 1 >= cadcraft_doc::MAX_BLOCK_DEPTH || out.len() >= MAX_LEVELS { + return; + } + let Some(b) = d.block(name) else { return }; + for e in b.entities.iter() { + let EntityKind::Insert(i) = &e.kind else { continue }; + // Generated geometry (dimensions, arrays) is not offered. + if i.block.starts_with('*') || d.block(&i.block).is_none_or(|c| c.array.is_some()) || out.len() >= MAX_LEVELS { + continue; + } + path.push(e.handle); + out.push((path.clone(), i.block.clone())); + nested(d, &i.block, path, out); + path.pop(); + } +} + +/// The nesting levels of reference `ih`: the reference itself, then every reference nested in it. +fn level_list(d: &Drawing, ih: Handle) -> Result, String)>> { + let Some(EntityKind::Insert(ins)) = d.entity(ih).map(|e| &e.kind) else { return Err(bad("refedit", "select a block reference")) }; + let mut out = vec![(Vec::new(), ins.block.clone())]; + nested(d, &ins.block, &mut Vec::new(), &mut out); + Ok(out) +} + +fn run_levels(s: &mut Session, p: &Value) -> Result { + let ih = targets(s, p)?.into_iter().next().ok_or_else(|| bad("refedit.levels", "select a block reference"))?; + let d = s.doc()?; + let levels: Vec = level_list(d, ih)? + .into_iter() + .map(|(path, name)| json!({ "name": name, "path": hexes(path), "xref": xref_of(d, &name).is_some() })) + .collect(); + Ok(json!({ "levels": levels })) +} + +// ---------------- xrefs ---------------- + +/// The xref block `name` belongs to: (the xref's name, the block of its source drawing or `None` +/// for its model space). `None` for a block of this drawing. +fn xref_of(d: &Drawing, name: &str) -> Option<(String, Option)> { + let b = d.block(name)?; + if b.xref_path.is_some() { + return Some((b.name.clone(), None)); + } + let (root, rest) = name.split_once('|')?; + let x = d.block(root).filter(|x| x.xref_path.is_some())?; + Some((x.name.clone(), Some(rest.to_string()))) +} + +/// The source file of xref `name`, checked for an edit in place: found, not open in another +/// drawing tab, writable, not changed since it was loaded. +fn xref_file(s: &Session, name: &str) -> Result { + if cfg!(target_arch = "wasm32") { + return Err(bad("refedit", "editing xrefs in place is not available on the web; open the xref's drawing instead")); + } + let d = s.doc()?; + let b = d.block(name).ok_or_else(|| bad("refedit", format!("no xref \"{name}\"")))?; + if b.xref_status != XrefStatus::Loaded { + return Err(bad("refedit", format!("xref \"{}\" is not loaded ({}); reload it first", b.name, b.xref_status.label()))); + } + let path = b.xref_path.clone().unwrap_or_default(); + let host = s.state().ok().and_then(|st| st.path.clone()); + let file = load::find(&path, host.as_deref().map(std::path::Path::new), false).map_err(|_| bad("refedit", format!("{path}: file not found")))?; + let canon = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + let me = canon(&file); + for (i, st) in s.docs.iter().enumerate() { + if i != s.active && st.path.as_deref().is_some_and(|p| canon(std::path::Path::new(p)) == me) { + return Err(bad("refedit", format!("{} is open in another drawing tab: edit it there, or close it first", file.display()))); + } + } + writable(&file).map_err(|e| bad("refedit", e))?; + if let (Some(then), Some(now)) = (load::loaded_stamp(&file), load::stamp(&file)) + && then != now + { + return Err(bad("refedit", format!("{} changed since xref \"{}\" was loaded; reload it first", file.display(), b.name))); + } + Ok(file) +} + +/// Whether `file` may be written: not read-only and not open in another program (AutoCAD's +/// `.dwl` lock file beside it, or a file that can't be opened for writing). +fn writable(file: &std::path::Path) -> std::result::Result<(), String> { + #[cfg(target_arch = "wasm32")] + { + let _ = file; + Err("files are not available on the web".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let meta = std::fs::metadata(file).map_err(|e| format!("{}: {e}", file.display()))?; + if meta.permissions().readonly() { + return Err(format!("{} is read-only", file.display())); + } + let lock = file.with_extension("dwl"); + if lock.is_file() { + return Err(format!("{} is open in another program (lock file {})", file.display(), lock.display())); + } + std::fs::OpenOptions::new().append(true).open(file).map(|_| ()).map_err(|e| format!("{} can't be written: {e}", file.display())) + } +} + +/// The objects of the source drawing a block of xref `x` came from, matched one to one with the +/// block's objects (the order loading keeps). Refused when they no longer match. +fn source_handles(blk: &Block, src: &Drawing, inner: Option<&str>) -> Result> { + let store = match inner { + None => &src.model, + Some(n) => { + let b = src.block(n).ok_or_else(|| bad("refedit", format!("block \"{n}\" is no longer in the xref's drawing; reload the xref")))?; + if b.xref_path.is_some() { + return Err(bad("refedit", format!("\"{n}\" is an xref of the xref's drawing: open it with XOPEN to edit it"))); + } + &b.entities + } + }; + let kind = |e: &Entity| std::mem::discriminant(&e.kind); + if store.len() != blk.entities.len() || store.iter().zip(blk.entities.iter()).any(|(a, b)| kind(a) != kind(b)) { + return Err(bad("refedit", "the xref's drawing no longer matches what was loaded; reload the xref first")); + } + Ok(blk.entities.iter().zip(store.iter()).map(|(a, b)| (a.handle, b.handle)).collect()) +} + // ---------------- REFEDIT ---------------- fn run_refedit(s: &mut Session, p: &Value) -> Result { @@ -100,34 +288,45 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { .model .iter() .chain(d.layouts.iter().flat_map(|l| l.entities.iter())) - .find(|e| matches!(&e.kind, cadcraft_doc::EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(n))) + .find(|e| matches!(&e.kind, EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(n))) .map(|e| e.handle), - None => targets(s, p)?.into_iter().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, cadcraft_doc::EntityKind::Insert(_)))), + None => targets(s, p)?.into_iter().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Insert(_)))), }; let ih = picked.ok_or_else(|| bad("refedit", "select a block reference"))?; let (ins, space) = match d.entity(ih).map(|e| &e.kind) { - Some(cadcraft_doc::EntityKind::Insert(i)) => (i.clone(), d.space_of(ih).ok_or_else(|| bad("refedit", "the reference is in no space"))?), + Some(EntityKind::Insert(i)) => (i.clone(), d.space_of(ih).ok_or_else(|| bad("refedit", "the reference is in no space"))?), _ => return Err(bad("refedit", "select a block reference")), }; - let blk = d.block(&ins.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", ins.block)))?; - if blk.xref_path.is_some() { - return Err(bad( - "refedit", - format!( - "\"{}\" is an external reference: editing it in place would write its source drawing, which is not available yet. Open it with XOPEN, edit and save it, then reload.", - blk.name - ), - )); - } + let path: Vec = match (p.get("path"), str_param(p, "nested")) { + (Some(Value::Array(a)), _) => { + a.iter().map(|v| handle_value(v).ok_or_else(|| bad("refedit", format!("`path`: {v} is not an object handle")))).collect::>()? + } + (Some(Value::Null) | None, Some(n)) => level_list(d, ih)? + .into_iter() + .find(|(path, name)| !path.is_empty() && name.eq_ignore_ascii_case(n)) + .map(|(path, _)| path) + .ok_or_else(|| bad("refedit", format!("no reference to \"{n}\" is nested in this one")))?, + (Some(Value::Null) | None, None) => Vec::new(), + (Some(v), _) => return Err(bad("refedit", format!("`path` must be an array of object handles, got {v}"))), + }; + let levels = levels(d, &ins, &path)?; + let Some(edit) = levels.last() else { return Err(bad("refedit", "select a block reference")) }; + let blk = edit.block.clone(); + let to_world = edit.to_world; if blk.name.starts_with('*') || blk.array.is_some() { return Err(bad("refedit", format!("\"{}\" is generated geometry and can't be edited in place", blk.name))); } - let to_world = ins.transform(blk.base.xy()); - let (sx, sy) = (ins.scale.x.abs(), ins.scale.y.abs()); - let finite = [to_world.a, to_world.b, to_world.c, to_world.d, to_world.e, to_world.f].iter().all(|v| v.is_finite()); - if !finite || to_world.det().abs() < 1e-12 || (sx - sy).abs() > 1e-9 * sx.max(sy) { - return Err(bad("refedit", "the reference must be scaled equally in X and Y (and not flat) to be edited in place")); - } + // An xref's block: where it is written back. + let xref = match xref_of(d, &blk.name) { + Some((x, inner)) => { + let file = xref_file(s, &x)?; + let src = load::read_file(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; + let sources = source_handles(&blk, &src, inner.as_deref())?; + Some(XrefSource { xref: x, file: file.to_string_lossy().into_owned(), block: inner, stamp: load::stamp(&file), sources }) + } + None => None, + }; + let d = s.doc()?; let chosen: Option> = match p.get("objects") { None | Some(Value::Null) => None, Some(Value::String(a)) if a.eq_ignore_ascii_case("all") => None, @@ -157,20 +356,38 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { items: Vec::new(), ghosts: Vec::new(), released: Vec::new(), + path: path.clone(), + xref, }; + let fade = xfadectl(s)?; let doc = s.doc_mut()?; for e in blk.entities.iter() { let working = chosen.as_ref().is_none_or(|c| c.contains(&e.handle)); let h = doc.new_handle(); - put(doc, &r, to_host(&to_world, e, h, !working))?; + put(doc, &r, to_host(&to_world, e, h, (!working).then_some(fade)))?; if working { r.items.push(WorkItem { copy: h, source: Some(e.handle) }); } else { r.ghosts.push((h, e.handle)); } } + // The parents' other objects stand faded around a nested block. + for level in levels.iter().filter(|l| l.next.is_some()) { + for e in level.block.entities.iter().filter(|e| Some(e.handle) != level.next && !matches!(e.kind, EntityKind::AttDef(_))) { + let h = doc.new_handle(); + put(doc, &r, to_host(&level.to_world, e, h, Some(fade)))?; + r.ghosts.push((h, e.handle)); + } + } doc.modify_entity(ih, |e| e.common.visible = false).map_err(|e| bad("refedit", e.to_string()))?; - let out = json!({ "block": r.block, "insert": ih.hex(), "working": hexes(r.items.iter().map(|i| i.copy)), "faded": r.ghosts.len() }); + let out = json!({ + "block": r.block, + "insert": ih.hex(), + "working": hexes(r.items.iter().map(|i| i.copy)), + "faded": r.ghosts.len(), + "path": hexes(r.path.iter().copied()), + "xref": r.xref.as_ref().map(|x| json!({ "name": x.xref, "file": x.file })), + }); let sel: Vec = r.items.iter().map(|i| i.copy).collect(); doc.refedit = Some(r); s.set_selection(sel); @@ -214,22 +431,26 @@ fn apply_refset(s: &mut Session, add: &[Handle], remove: &[Handle]) -> Result Some(r.released.remove(i)), None => blk.entities.get(src).map(|e| (**e).clone()), }; if let Some(cur) = cur { let c = doc.new_handle(); - put(doc, &r, to_host(&r.to_world, &cur, c, false))?; + put(doc, &r, to_host(&r.to_world, &cur, c, None))?; r.items.push(WorkItem { copy: c, source: Some(src) }); added += 1; } @@ -248,7 +469,7 @@ fn apply_refset(s: &mut Session, add: &[Handle], remove: &[Handle]) -> Result Result { // Work on a copy: the drawing changes only when everything went through. let mut nd: Drawing = s.doc()?.clone(); let mut objects = 0; + let mut written = None; if save { objects = commit_block(&mut nd, &r)?; + if let Some(x) = &r.xref { + // The file first: when it can't be written the edit stays open (Discard ends it). + written = Some(write_back(&nd, &r, x)?); + } } nd.end_refedit_discard(&r); + let mut notes = Vec::new(); + if let (Some(x), Some(_)) = (&r.xref, &written) { + let host = s.state().ok().and_then(|st| st.path.clone()); + notes = load::load(&mut nd, &x.xref, host.as_deref(), false); + } *s.doc_mut()? = nd; s.set_selection(Vec::new()); - Ok(json!({ "block": r.block, "saved": save, "objects": objects })) + for o in notes { + s.echo(o.message()); + } + let mut out = json!({ "block": r.block, "saved": save, "objects": objects }); + if let (Some(x), Some(backup)) = (&r.xref, written) { + out["file"] = json!(x.file); + out["backup"] = json!(backup); + } + Ok(out) } /// Replace the block's objects by the working set (and move the drawing objects added to it @@ -331,6 +570,158 @@ fn commit_block(nd: &mut Drawing, r: &RefEdit) -> Result { Ok(n) } +// ---------------- writing an xref back ---------------- + +/// Write the edited block of `nd` (committed) into xref source `x`. Returns the backup's path. +fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result { + let file = std::path::Path::new(&x.file); + writable(file).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?; + if load::stamp(file) != x.stamp { + return Err(bad( + "refclose", + format!("{} changed since the edit began; it is not overwritten (REFCLOSE Discard ends the edit)", file.display()), + )); + } + let hooks = crate::cmd::file::io().ok_or_else(|| bad("refclose", "file formats are not available in this build"))?; + let mut src = load::read_file(file).map_err(|e| bad("refclose", format!("{}: {e}", file.display())))?; + let blk = nd.block(&r.block).ok_or_else(|| bad("refclose", format!("block \"{}\" is gone", r.block)))?; + let prefix = format!("{}|", x.xref); + let map: HashMap = x.sources.iter().copied().collect(); + let mut store = EntityStore::new(); + let mut wanted: Vec<(Sym, String)> = Vec::new(); + for e in blk.entities.iter() { + let mut e = (**e).clone(); + e.handle = match map.get(&e.handle) { + Some(h) => *h, + None => src.new_handle(), + }; + rename_into_source(&mut e, &prefix, &mut wanted); + store.push(e); + } + bring_symbols(nd, &mut src, &prefix, wanted); + match &x.block { + None => src.model = store, + Some(name) => { + let key = src + .blocks + .keys() + .find(|k| k.eq_ignore_ascii_case(name)) + .cloned() + .ok_or_else(|| bad("refclose", format!("block \"{name}\" is gone from {}", file.display())))?; + if let Some(b) = src.blocks.get_mut(&key) { + Arc::make_mut(b).entities = store; + } + } + } + let bytes = (hooks.write)(&src, &x.file).map_err(|e| bad("refclose", format!("writing {}: {e}", file.display())))?; + replace_file(file, &bytes).map_err(|e| bad("refclose", e)) +} + +/// Symbol names of a host object as the xref's drawing has them: `xref|name` loses its prefix; +/// the host's own symbols keep their names and are noted in `wanted` (copied into the drawing). +fn rename_into_source(e: &mut Entity, prefix: &str, wanted: &mut Vec<(Sym, String)>) { + let found = std::cell::RefCell::new(Vec::new()); + load::rename_refs(e, &|sym, n| { + if load::has_prefix(n, prefix) { + return n.get(prefix.len()..).map(str::to_string); + } + found.borrow_mut().push((sym, n.to_string())); + None + }); + wanted.extend(found.into_inner()); +} + +/// Copy the host's symbols that objects written into `src` use and `src` lacks (layers, +/// linetypes, text and dimension styles, and blocks with what they use in turn). +fn bring_symbols(host: &Drawing, src: &mut Drawing, prefix: &str, mut wanted: Vec<(Sym, String)>) { + let mut seen: HashSet<(Sym, String)> = HashSet::new(); + let mut guard = 0usize; + while let Some((sym, name)) = wanted.pop() { + guard += 1; + if guard > 100_000 || name.is_empty() || !seen.insert((sym, name.to_ascii_uppercase())) { + continue; + } + match sym { + Sym::Layer => { + if name != "0" + && src.layer(&name).is_none() + && let Some(l) = host.layer(&name) + { + wanted.push((Sym::Linetype, l.linetype.clone())); + src.layers.push(l.clone()); + } + } + Sym::Linetype => { + let builtin = ["ByLayer", "ByBlock", "Continuous"].iter().any(|n| n.eq_ignore_ascii_case(&name)); + if !builtin + && src.linetype(&name).is_none() + && let Some(t) = host.linetype(&name) + { + src.linetypes.push(t.clone()); + } + } + Sym::Style => { + if src.text_style(&name).is_none() + && let Some(t) = host.text_style(&name) + { + src.text_styles.push(t.clone()); + } + } + Sym::DimStyle => { + if src.dim_style(&name).is_none() + && let Some(t) = host.dim_style(&name) + { + wanted.push((Sym::Style, t.text_style.clone())); + src.dim_styles.push(t.clone()); + } + } + Sym::Block => { + if src.block(&name).is_none() + && let Some(b) = host.block(&name) + && b.xref_path.is_none() + { + let mut nb = (**b).clone(); + let mut store = EntityStore::new(); + for e in b.entities.iter() { + let mut e = (**e).clone(); + e.handle = src.new_handle(); + rename_into_source(&mut e, prefix, &mut wanted); + store.push(e); + } + nb.entities = store; + src.blocks.insert(nb.name.clone(), Arc::new(nb)); + } + } + Sym::MLeaderStyle | Sym::TableStyle => {} + } + } +} + +/// Replace `file` by `bytes`: the old file is kept as `name.bak`, the new one is written beside +/// it and moved over it. Returns the backup's path. +fn replace_file(file: &std::path::Path, bytes: &[u8]) -> std::result::Result { + #[cfg(target_arch = "wasm32")] + { + let _ = (file, bytes); + Err("files are not available on the web".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let backup = file.with_extension("bak"); + std::fs::copy(file, &backup) + .map_err(|e| format!("the backup {} can't be written: {e}; {} is unchanged", backup.display(), file.display()))?; + let mut tmp = file.as_os_str().to_owned(); + tmp.push(".cadcraft-tmp"); + let tmp = std::path::PathBuf::from(tmp); + std::fs::write(&tmp, bytes).map_err(|e| format!("{} can't be written: {e}", tmp.display()))?; + if let Err(e) = std::fs::rename(&tmp, file) { + let _ = std::fs::remove_file(&tmp); + return Err(format!("{} can't be replaced: {e}; it is unchanged", file.display())); + } + Ok(backup.to_string_lossy().into_owned()) + } +} + // ---------------- while editing ---------------- /// After a command ran: objects it created join the working set, and a command that changed @@ -374,6 +765,94 @@ pub(crate) fn locked(d: &Drawing, h: Handle) -> bool { // ---------------- interactive ---------------- +/// REFEDIT at the command line: "Select reference", then "Select nesting level [OK/Next]" when +/// the reference has others nested in it. +#[derive(Default)] +struct RefeditM { + sel: SelectPhase, + picked: Option, + levels: Vec<(Vec, String)>, + at: usize, +} + +impl RefeditM { + fn picked(&mut self, s: &mut Session, hs: &[Handle]) -> Result { + let d = s.doc()?; + let Some(h) = hs.iter().copied().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Insert(_)))) else { + s.echo("Select a block or xref reference."); + self.sel = SelectPhase::single(); + return Ok(Step::Continue); + }; + self.levels = level_list(d, h)?; + self.picked = Some(h); + if self.levels.len() > 1 { + self.echo_level(s); + return Ok(Step::Continue); + } + self.finish(s) + } + fn echo_level(&self, s: &mut Session) { + if let Some((path, name)) = self.levels.get(self.at) { + s.echo(format!("Reference name: {name}{}", if path.is_empty() { String::new() } else { format!(" (nested {} deep)", path.len()) })); + } + } + fn finish(&mut self, s: &mut Session) -> Result { + let Some(h) = self.picked else { return Ok(Step::Cancel) }; + let path = self.levels.get(self.at).map(|(p, _)| hexes(p.iter().copied())).unwrap_or_default(); + let r = run_refedit(s, &json!({ "handle": h.hex(), "path": path }))?; + let n = r["working"].as_array().map_or(0, Vec::len); + s.set_selection(Vec::new()); + s.echo(format!("{n} object(s) in the working set. Use REFCLOSE to save or discard the changes.")); + Ok(Step::Done) + } +} + +impl Interactive for RefeditM { + fn name(&self) -> &'static str { + "REFEDIT" + } + fn begin(&mut self, s: &mut Session) -> Result { + self.sel = SelectPhase::begin(s); + self.sel.single = true; + if self.sel.done { + let hs = self.sel.picked.clone(); + return self.picked(s, &hs); + } + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + if self.picked.is_none() { + return Prompt::new("Select reference", Accept::SELECT); + } + Prompt::new("Select nesting level", Accept::TEXT).kw(&["OK", "Next"]).default("Next") + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + if self.picked.is_none() { + return match self.sel.feed(s, &i)? { + SelOutcome::More => Ok(Step::Continue), + SelOutcome::Empty => Ok(Step::Done), + SelOutcome::Done(hs) => self.picked(s, &hs), + }; + } + let k = match &i { + Input::Keyword(k) | Input::Text(k) => k.trim().to_ascii_lowercase(), + Input::Enter => "next".into(), + _ => return Ok(Step::Continue), + }; + if k.starts_with('o') { + return self.finish(s); + } + if k.starts_with('n') { + self.at = (self.at + 1) % self.levels.len().max(1); + self.echo_level(s); + } + Ok(Step::Continue) + } +} + #[derive(Default)] enum RStage { #[default] @@ -462,8 +941,13 @@ impl Interactive for RefcloseM { _ => return Ok(Step::Cancel), }; let r = close(s, save)?; - s.echo(if save { "Reference changes saved." } else { "Reference changes discarded." }); - let _ = r; + s.echo(match (save, r.get("file").and_then(Value::as_str)) { + (true, Some(f)) => { + format!("Reference changes saved to {f} (the previous file is kept as {}).", r["backup"].as_str().unwrap_or("a .bak file")) + } + (true, None) => "Reference changes saved.".to_string(), + (false, _) => "Reference changes discarded.".to_string(), + }); Ok(Step::Done) } } diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index fac289f23..a6073d50a 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -133,7 +133,7 @@ struct Ctx { } /// The folder of the host drawing at `host` (a file path). -fn folder(host: Option<&Path>) -> Option { +pub(crate) fn folder(host: Option<&Path>) -> Option { let p = host?.parent()?; Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() }) } @@ -244,6 +244,10 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { return Err(too_big()); } cx.bytes = cx.bytes.saturating_add(n); + // Remembered so an edit in place can tell whether the file changed since (REFEDIT). + if let Some(st) = stamp(file) { + remember(file, st); + } (hooks.read)(&bytes, &file.to_string_lossy()) } #[cfg(target_arch = "wasm32")] @@ -253,6 +257,50 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { } } +/// Size and modification time (nanoseconds since 1970) of each referenced file when it was last +/// read, by canonical path. +#[cfg(not(target_arch = "wasm32"))] +static LOADED: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +/// Most files [`LOADED`] remembers. +#[cfg(not(target_arch = "wasm32"))] +const MAX_REMEMBERED: usize = 10_000; + +/// The size and modification time of `file` (nanoseconds since 1970). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn stamp(file: &Path) -> Option<(u64, u128)> { + let m = std::fs::metadata(file).ok()?; + let t = m.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos(); + Some((m.len(), t)) +} +#[cfg(target_arch = "wasm32")] +pub(crate) fn stamp(_file: &Path) -> Option<(u64, u128)> { + None +} + +#[cfg(not(target_arch = "wasm32"))] +fn remember(file: &Path, st: (u64, u128)) { + let mut m = LOADED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if m.len() >= MAX_REMEMBERED { + m.clear(); + } + m.insert(canonical(file), st); +} + +/// The size and modification time `file` had when it was last loaded as an xref. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn loaded_stamp(file: &Path) -> Option<(u64, u128)> { + LOADED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&canonical(file)).copied() +} +#[cfg(target_arch = "wasm32")] +pub(crate) fn loaded_stamp(_file: &Path) -> Option<(u64, u128)> { + None +} + +/// Read the drawing file `file` (with the size limits of xref loading). +pub(crate) fn read_file(file: &Path) -> Result { + read(file, &mut Ctx::new(None)) +} + /// Load every xref of `d` that isn't unloaded from the paths saved in it; `host` is the drawing's /// own path. pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec { diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index fa319d3f1..3fe1298fd 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -74,6 +74,8 @@ const HEADER: &[(&str, Kind, Def)] = &[ ("TRIMEXTENDMODE", Kind::Choice(&[0, 1]), Def::Int(1)), ("TRIMMODE", Kind::Choice(&[0, 1]), Def::Int(1)), ("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)), + // How much objects outside the working set fade while a reference is edited in place (REFEDIT). + ("XFADECTL", Kind::Int(0, 90), Def::Int(50)), ]; /// The standard lineweights in hundredths of a millimetre. diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c4c4a1ce6..21e4ef08b 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -104,6 +104,7 @@ mod quickcalc; mod recent_commands; mod rectang_ortho; mod refedit; +mod refedit_xref; mod region; mod rename_cmdline; mod rotate_reference; diff --git a/crates/engine/tests/it/refedit.rs b/crates/engine/tests/it/refedit.rs index df3aa5ea1..8bc9b981b 100644 --- a/crates/engine/tests/it/refedit.rs +++ b/crates/engine/tests/it/refedit.rs @@ -277,7 +277,7 @@ fn interactive_refedit_refset_and_refclose() { } #[test] -fn xrefs_are_refused_with_a_message() { +fn an_xref_that_is_not_loaded_is_refused_with_a_message() { let mut s = Session::new(); s.doc_mut().unwrap().blocks.insert( "X".into(), @@ -289,5 +289,6 @@ fn xrefs_are_refused_with_a_message() { ); let x = insert(&mut s, "X", (0.0, 0.0), 1.0, 0.0); let e = s.execute("refedit", &json!({ "handle": x })).unwrap_err(); - assert!(e.to_string().contains("external reference"), "{e}"); + // Xrefs are edited in place and written back (refedit_xref.rs); one not loaded can't be. + assert!(e.to_string().contains("not loaded"), "{e}"); } diff --git a/crates/engine/tests/it/refedit_xref.rs b/crates/engine/tests/it/refedit_xref.rs new file mode 100644 index 000000000..ef6b93c7c --- /dev/null +++ b/crates/engine/tests/it/refedit_xref.rs @@ -0,0 +1,243 @@ +//! REFEDIT on xrefs and nested references (gap F2): the source drawing written back on REFCLOSE +//! Save (with a backup; refused for read-only, locked or changed files) and nesting levels. +//! Files go in a folder under Cargo's temporary directory for integration tests. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::geom::{Vec2, Vec3}; +use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, Insert, Layer, Line, XrefStatus}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn hooks() { + set_io(IoHooks { + read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), + write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: None, + }); +} + +/// A fresh folder for one test. +fn folder(tag: &str) -> PathBuf { + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("refedit-xref").join(format!("{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn save(d: &Drawing, path: &Path) { + std::fs::write(path, cadcraft_io::write(d, &path.to_string_lossy()).unwrap()).unwrap(); +} + +fn read(path: &Path) -> Drawing { + cadcraft_io::read(&std::fs::read(path).unwrap(), &path.to_string_lossy()).unwrap() +} + +fn line(d: &mut Drawing, layer: &str, a: (f64, f64), b: (f64, f64)) -> Handle { + let h = d.new_handle(); + let mut e = Entity::new(h, EntityKind::Line(Line { a: Vec3::new(a.0, a.1, 0.0), b: Vec3::new(b.0, b.1, 0.0) })); + e.common.layer = layer.into(); + d.model.push(e); + h +} + +fn insert(block: &str, at: Vec3) -> Insert { + Insert { + block: block.into(), + insert: at, + 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, + } +} + +/// A site plan: a line on layer Walls and a reference to its block Tree (a circle). +fn site() -> (Drawing, Handle) { + let mut d = Drawing::new_metric(); + d.layers.push(Layer { name: "Walls".into(), ..Layer::default() }); + let wall = line(&mut d, "Walls", (0.0, 0.0), (10.0, 0.0)); + let mut tree = Block::new("Tree"); + let c = d.new_handle(); + tree.entities.push(Entity::new(c, EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 1.0 }))); + d.blocks.insert("Tree".into(), Arc::new(tree)); + let h = d.new_handle(); + d.model.push(Entity::new(h, EntityKind::Insert(insert("Tree", Vec3::new(5.0, 0.0, 0.0))))); + (d, wall) +} + +/// A host drawing (saved as host.dxf) with site.dxf attached at (100, 0). +fn attached(tag: &str) -> (Session, PathBuf, Handle, String) { + hooks(); + let dir = folder(tag); + let (d, wall) = site(); + save(&d, &dir.join("site.dxf")); + let host = dir.join("host.dxf"); + save(&Drawing::new_metric(), &host); + let mut s = Session::new(); + s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap(); + let r = s.execute("xattach", &json!({ "path": "site.dxf", "at": [100, 0] })).unwrap(); + let insert = r["handle"].as_str().unwrap().to_string(); + (s, dir, wall, insert) +} + +fn hx(v: Value) -> String { + v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_string() +} + +fn working(r: &Value) -> Vec { + r["working"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect() +} + +fn find_line(s: &Session, hs: &[String]) -> String { + let d = s.doc().unwrap(); + hs.iter().find(|h| matches!(d.entity(Handle::parse_hex(h).unwrap()).unwrap().kind, EntityKind::Line(_))).unwrap().clone() +} + +#[test] +fn editing_an_xref_writes_its_drawing_back_with_a_backup() { + let (mut s, dir, wall, insert) = attached("save"); + let file = dir.join("site.dxf"); + let r = s.execute("refedit", &json!({ "handle": insert })).unwrap(); + assert_eq!(r["xref"]["name"], "site"); + let work = working(&r); + assert_eq!(work.len(), 2); + // Everything but the working set is locked while editing, and drawn faded. + let l = find_line(&s, &work); + s.execute("move", &json!({ "handles": [l], "delta": [0, 5] })).unwrap(); + s.execute("layer", &json!({ "option": "make", "name": "Added" })).ok(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(out["objects"], 3); + assert!(out["file"].as_str().unwrap().ends_with("site.dxf")); + assert!(dir.join("site.bak").is_file(), "the previous file is kept"); + // The file holds the edit, in its own coordinates, with the line's own handle. + let back = read(&file); + assert_eq!(back.model.len(), 3); + let moved = back.entity(wall).expect("the edited line keeps its handle"); + let EntityKind::Line(ln) = &moved.kind else { panic!() }; + assert!((ln.a.y - 5.0).abs() < 1e-9 && (ln.a.x).abs() < 1e-9, "{ln:?}"); + assert_eq!(moved.common.layer, "Walls", "the xref's layer loses its prefix"); + let new_line = back.model.iter().find(|e| matches!(&e.kind, EntityKind::Line(l) if (l.a.y - 20.0).abs() < 1e-9)).unwrap(); + assert!(back.layer(&new_line.common.layer).is_some(), "a host layer the new line uses comes along"); + // The host shows the xref as written (loaded again), and nothing of the edit is left. + let d = s.doc().unwrap(); + assert!(d.refedit.is_none()); + assert_eq!(d.block("site").unwrap().entities.len(), 3); + assert_eq!(d.block("site").unwrap().xref_status, XrefStatus::Loaded); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_block_of_the_xref_is_written_into_that_block() { + let (mut s, dir, _, insert) = attached("nested"); + let levels = s.execute("refedit.levels", &json!({ "handle": insert })).unwrap(); + let names: Vec<&str> = levels["levels"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["site", "site|Tree"]); + let r = s.execute("refedit", &json!({ "handle": insert, "nested": "site|Tree" })).unwrap(); + assert_eq!(r["block"], "site|Tree"); + assert_eq!(r["path"].as_array().unwrap().len(), 1); + assert!(r["faded"].as_u64().unwrap() >= 1, "the site's other objects stand faded around it"); + let c = working(&r)[0].clone(); + // The circle shows at the tree's place in the drawing: (100 + 5, 0). + let EntityKind::Circle(circle) = &s.doc().unwrap().entity(Handle::parse_hex(&c).unwrap()).unwrap().kind else { panic!() }; + assert!((circle.center.x - 105.0).abs() < 1e-9); + s.execute("scale", &json!({ "handles": [c], "base": [105, 0], "factor": 2 })).unwrap(); + s.execute("refclose", &json!({})).unwrap(); + let back = read(&dir.join("site.dxf")); + let EntityKind::Circle(c) = &back.block("Tree").unwrap().entities.iter().next().unwrap().kind else { panic!() }; + assert!((c.radius - 2.0).abs() < 1e-9); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn locked_read_only_or_changed_files_are_not_overwritten() { + // A lock file of another program: refused at the start. + let (mut s, dir, _, insert) = attached("locked"); + let file = dir.join("site.dxf"); + std::fs::write(dir.join("site.dwl"), b"lock").unwrap(); + let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("open in another program"), "{e}"); + std::fs::remove_file(dir.join("site.dwl")).unwrap(); + + // Changed on disk while editing: the save is refused, the edit stays, Discard ends it. + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + let mut other = read(&file); + line(&mut other, "0", (0.0, 50.0), (1.0, 50.0)); + std::thread::sleep(std::time::Duration::from_millis(20)); + save(&other, &file); + let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string(); + assert!(e.contains("changed since"), "{e}"); + assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open"); + s.execute("refclose", &json!({ "option": "discard" })).unwrap(); + assert_eq!(read(&file).model.len(), 3, "the other program's change is kept"); + + // Changed since it was loaded: reload first. + let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("since") && e.contains("reload"), "{e}"); + s.execute("-xref", &json!({ "option": "reload", "names": "site" })).unwrap(); + + // Read-only: refused. + let mut perm = std::fs::metadata(&file).unwrap().permissions(); + perm.set_readonly(true); + std::fs::set_permissions(&file, perm.clone()).unwrap(); + let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("read-only"), "{e}"); + #[allow(clippy::permissions_set_readonly_false)] + perm.set_readonly(false); + std::fs::set_permissions(&file, perm).unwrap(); + + // Open in another drawing tab of this session: refused. + s.execute("qsave", &json!({})).unwrap(); + let host = s.state().unwrap().path.clone().unwrap(); + s.execute("open", &json!({ "path": file.to_string_lossy() })).unwrap(); + s.execute("open", &json!({ "path": host })).unwrap(); + let ih = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Insert(_))).unwrap().handle; + let e = s.execute("refedit", &json!({ "handle": ih.hex() })).unwrap_err().to_string(); + assert!(e.contains("another drawing tab"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn nested_block_references_are_picked_through_their_parents() { + let mut s = Session::new(); + let c = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Inner", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap(); + let i = hx(s.execute("insert", &json!({ "name": "Inner", "at": [10, 0] })).unwrap()); + let l = hx(s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()); + s.execute("block", &json!({ "name": "Outer", "base": [0, 0], "handles": [i, l], "keep": "delete" })).unwrap(); + let o = hx(s.execute("insert", &json!({ "name": "Outer", "at": [100, 100] })).unwrap()); + + // At the command line: pick, Next to the nested level, OK. + s.start("refedit").unwrap(); + s.input(Input::Pick(vec![Handle::parse_hex(&o).unwrap()])).unwrap(); + assert!(s.prompt_text().contains("Select nesting level"), "{}", s.prompt_text()); + assert!(s.log.iter().any(|m| m.contains("Reference name: Outer"))); + s.input(Input::Enter).unwrap(); // Next + assert!(s.log.iter().any(|m| m.contains("Reference name: Inner"))); + s.cmdline("o").unwrap(); + let d = s.doc().unwrap(); + let r = d.refedit.clone().unwrap(); + assert_eq!(r.block, "Inner"); + assert_eq!(r.items.len(), 1); + assert_eq!(r.ghosts.len(), 1, "Outer's line stands faded"); + let EntityKind::Circle(circle) = &d.entity(r.items[0].copy).unwrap().kind else { panic!() }; + assert!(circle.center.xy().near(Vec2::new(110.0, 100.0), 1e-9)); + // Only the working set can change: Outer's faded line is locked. + s.execute("move", &json!({ "handles": [r.items[0].copy.hex()], "delta": [0, 3] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Circle(c) = &d.block("Inner").unwrap().entities.iter().next().unwrap().kind else { panic!() }; + assert!(c.center.xy().near(Vec2::new(0.0, 3.0), 1e-9), "{c:?}"); + assert_eq!(d.block("Outer").unwrap().entities.len(), 2, "the parent is untouched"); + // Bad paths are refused. + assert!(s.execute("refedit", &json!({ "handle": o, "path": ["FFFFF"] })).is_err()); + assert!(s.execute("refedit", &json!({ "handle": o, "path": "x" })).is_err()); + assert!(s.execute("refedit", &json!({ "handle": o, "nested": "Nope" })).is_err()); + let _ = Vec2::ZERO; +} diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 5ce0bd6c0..08ae08be0 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -66,6 +66,15 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { if b.opts.transparency { b.transparency = transparency(e.common.transparency, layer_transparency, ctx.block_transparency); } + // While a reference is edited in place (REFEDIT) everything outside the working set is + // faded by XFADECTL percent on screen. + if !b.plotting + && let Some(r) = &ctx.d.refedit + && !r.is_working(if ctx.depth == 0 { e.handle } else { ctx.top }) + { + let fade = u8::try_from(ctx.d.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50); + b.transparency = b.transparency.max(fade); + } // A plot style's linetype replaces the object's. let lt = match b.styles.and_then(|s| s.linetype(rgb, b.named)) { Some(over) => over, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 787aa1a2f..d7bfa33b8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -778,6 +778,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.canvas.draw_ms = crate::now_ms() - t0; compare::paint(app, ui.ctx(), &painter, &xf_paper, rect); blockedit::paint(app, ui.ctx(), &painter, &xf_paper, rect); + refedit::paint(app, ui.ctx(), rect); // Constraint bars and dynamic dimensional constraints (model space, or inside a viewport). if sheet.is_none() || active_vp.is_some() { let clip = match &active_vp { @@ -939,3 +940,5 @@ mod compare; /// Background rebuilds of the display list for a new view. mod rebuild; +/// The Edit Reference bar while a reference is edited in place (REFEDIT). +mod refedit; diff --git a/crates/ui-egui/src/canvas/refedit.rs b/crates/ui-egui/src/canvas/refedit.rs new file mode 100644 index 000000000..de9250205 --- /dev/null +++ b/crates/ui-egui/src/canvas/refedit.rs @@ -0,0 +1,72 @@ +//! Editing a reference in place (REFEDIT) on the canvas: a bar over the drawing with the +//! reference's name (and, for an xref, the file it writes to), the working set's size, Add to / +//! Remove from Working Set, and Save Changes / Discard Changes (REFCLOSE). The rest of the +//! drawing is drawn faded by the renderer (XFADECTL) and locked by the engine. + +use egui::{Rect, RichText, Stroke, vec2}; +use serde_json::json; + +use crate::CadApp; +use crate::theme::Tokens; + +fn id() -> egui::Id { + egui::Id::unique("cadcraft-refedit-bar") +} + +/// The edit shown: (block, xref file, working-set size). +fn editing(app: &CadApp) -> Option<(String, Option, usize)> { + let r = app.session.state().ok()?.doc.refedit.clone()?; + Some((r.block, r.xref.map(|x| x.file), r.items.len())) +} + +/// What a bar button asks for. +enum Act { + Start(&'static str), + Run(&'static str, serde_json::Value), +} + +/// The bar (over the drawing, at its top). +pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, rect: Rect) { + let Some((name, file, count)) = editing(app) else { return }; + let t = Tokens::get(); + let sel: Vec = app.session.selection().iter().map(|h| h.hex()).collect(); + let mut act = None; + egui::Area::new(id()).order(egui::Order::Foreground).pivot(egui::Align2::CENTER_TOP).fixed_pos(rect.center_top() + vec2(0.0, 8.0)).show( + ctx, + |ui| { + egui::Frame::new().fill(t.cmd_bg).stroke(Stroke::new(1.0, t.accent)).corner_radius(4.0).inner_margin(6.0).show(ui, |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(crate::tl!("Edit Reference")).color(t.accent).strong()); + let shown = ui.label(RichText::new(&name).color(t.text)); + if let Some(f) = &file { + shown.on_hover_text(crate::tf!("Saving writes {file}", file = f)); + } + ui.label(RichText::new(crate::tf!("{n} in the working set", n = count)).color(t.text_dim)); + ui.separator(); + if ui.button(crate::tl!("Add to Working Set")).clicked() { + act = Some(if sel.is_empty() { Act::Start("refset") } else { Act::Run("refset", json!({ "add": sel })) }); + } + if ui.button(crate::tl!("Remove from Working Set")).clicked() { + act = Some(if sel.is_empty() { Act::Start("refset") } else { Act::Run("refset", json!({ "remove": sel })) }); + } + ui.separator(); + if ui.button(RichText::new(crate::tl!("Save Changes")).color(t.accent)).clicked() { + act = Some(Act::Run("refclose", json!({ "option": "save" }))); + } + if ui.button(crate::tl!("Discard Changes")).clicked() { + act = Some(Act::Run("refclose", json!({ "option": "discard" }))); + } + }); + }); + }, + ); + match act { + Some(Act::Start(id)) => app.start(id), + Some(Act::Run(id, p)) => { + if let Err(e) = app.run(id, p) { + app.set_status(e); + } + } + None => {} + } +} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 634249093..bde314339 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1367,3 +1367,9 @@ 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 Reference Modifica riferimento + Saving writes {file} Il salvataggio scrive {file} + {n} in the working set {n} nel gruppo di lavoro + Remove from Working Set Rimuovi dal gruppo di lavoro + Save Changes Salva modifiche + Discard Changes Annulla modifiche diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d71b3ccd7..0503ef6d4 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1373,3 +1373,9 @@ Check for Updates… Перевірити оновлення… CADCraft is up to date. Встановлено найновішу версію CADCraft. Could not check for updates. Не вдалося перевірити оновлення. + Edit Reference Редагування посилання + Saving writes {file} Збереження записує {file} + {n} in the working set {n} у робочому наборі + Remove from Working Set Вилучити з робочого набору + Save Changes Зберегти зміни + Discard Changes Скасувати зміни diff --git a/docs/gaps.md b/docs/gaps.md index 9c0bf3630..7a3ffb1f5 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 (REFEDIT on xrefs and nested references: F2 and top-10 row 4 narrowed) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -16,7 +16,7 @@ do them first. | 1 | **[alpha blocker]** **Saving DWG drops what we don't model** (DXF now writes back unknown entities and objects, foreign xdata, extension dictionaries, reactors, layer states and colour books, #528, and native MULTILEADERs, #459 (not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour books and reactors) | Opening a colleague's DWG and saving it still deletes some content: the one thing a CAD user can't forgive | 6–10 | [file formats](file-format-parity.md) | | 2 | **[alpha blocker]** **No real-file test corpus and no check in AutoCAD** | All 36 file tests are synthetic; nobody has verified a CADCraft DWG/DXF opens cleanly in AutoCAD | 10–15 + human | [file formats](file-format-parity.md#tests) | | 3 | **Ellipse and spline geometry is tessellated** (intersections, offsets, closest points; polyline offset ignores bulges) | Coordinates are subtly wrong; offsets of ellipses come out as polylines | 30–50 | [geometry](geometry-parity.md) | -| 4 | **[alpha blocker]** **No dynamic blocks or REFEDIT; xrefs can't be edited in place or clipped** (xrefs, #525, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) | +| 4 | **[alpha blocker]** **No dynamic blocks or REFEDIT; xrefs can't be clipped** (xrefs, #525, REFEDIT on blocks and xrefs, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) | | 5 | **No autosave in the web build** (the desktop app has SAVETIME autosave, Drawing Recovery, AUDIT and RECOVER since #406) | Browser users lose unsaved work when the tab or the browser goes down | 3–5 | [features](#features) | | 6 | **No CI runs the Rust tests on pull requests** (`cargo fmt` on main is fixed) | open PRs land without a gate; regressions go unseen | 2–3 | [stability](#stability) | @@ -25,7 +25,7 @@ do them first. | # | Gap | Evidence | User impact | Est. | |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | -| F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | +| F2 | XREF 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). An xref, or a block that came with one, is edited in place too and REFCLOSE Save writes its source drawing back (the old file kept as `.bak`; refused when the file is read-only, locked by another program, open in another tab or changed since it was loaded), nested references are picked through their parents ("Select nesting level [OK/Next]", `refedit.levels`), the rest of the drawing is drawn faded (XFADECTL) and an Edit Reference bar offers Add to/Remove from Working Set and Save/Discard Changes (2026-10-27); left: attribute sync of other references (ATTSYNC) and xrefs nested in xrefs (XOPEN opens them). 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`, `cmd/blocks/refedit.rs` | Medium: xrefs can't be clipped | 8–14 | | F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | REFEDIT on xrefs writes the source drawing back on REFCLOSE Save (backup, refused for read-only, locked, open or changed files, the xref reloaded from what was written), nested references picked through their parents (`path`, `nested`, `refedit.levels`, "Select nesting level [OK/Next]"), everything outside the working set drawn faded (XFADECTL), and the Edit Reference bar with Add to/Remove from Working Set and Save/Discard Changes: F2 and top-10 row 4 narrowed | | 2026-10-25 | minor | Named Viewports (View ▸ Viewports ▸ Named Viewports..., `vports.named`) lists the saved viewport configurations with a preview and the current one's name, and restores or deletes one; in a layout Restore places it as MVIEW Restore does: U11 narrowed. F15 and U11 no longer list MVIEW Restore (#633), and F21 no longer says PURGE skips multiline styles | | 2026-10-25 | minor | DIMTFILL limits: with DIMTFILL 1 (the drawing's background color) the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI: F7 updated | | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b5407d60..d9d593dab 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: CADCraft vs AutoCAD 2027 -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (COMPAREEXPORT; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (REFEDIT on xrefs; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 The authoritative assessment of how close CADCraft is to AutoCAD, and how much Opus 5.5 work remains. [ROADMAP.md](../ROADMAP.md) summarises it, [gaps.md](gaps.md) lists every shortfall, @@ -154,7 +154,7 @@ presence: an option that prints "not available yet" doesn't count. | Text and MTEXT | 6% | 35% | 30–45 | TrueType, formatting codes, stacking; MTEXT prompt options (#408), indents, tabs, bullets, numbering and columns (#547), annotative scaling (#468); editor is a dialog, not in place; no fields or SPELL (open PR #551), no SHX | [gaps](gaps.md#features) | | Leaders, tables, fields | 4% | 25% | 25–35 | MLEADER options and block content (#408), native MULTILEADER in DXF (#459); tables with cell styles, formulas, breaking and CSV data links (#534); no MLEADEREDIT/ALIGN/COLLECT, no FIELD | [gaps](gaps.md#features) | | Hatch and gradients | 5% | 35% | 15–25 | pick points with islands; 23 patterns of ~85; gradients render flat; origin, gap tolerance, separate hatches, island styles and HATCHEDIT options (#451); Hatch and Gradient / Hatch Edit dialogs (no Preview or Inherit Properties) | [gaps](gaps.md#features) | -| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; no dynamic-block authoring, XCLIP, DesignCenter | [gaps](gaps.md#features) | +| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT on blocks, nested references and xrefs (the xref's drawing written back); dynamic block references read and edited; no dynamic-block authoring, XCLIP, DesignCenter | [gaps](gaps.md#features) | | Layouts, viewports, plotting | 9% | 35% | 35–50 | layouts, per-VP layers, page setups, plot styles (CTB/STB), Plot dialog (#160), Plot Preview and PUBLISH (#186), plotter devices (#564), PDF with text, layers and sheets (#567, #571), polygonal/object/clipped viewports (#453), annotative scales (#468); no MVIEW Restore, no system printers | [gaps](gaps.md#features) | | Inquiry and utilities | 4% | 30% | 30–45 | DIST, AREA, ID, LIST, MEASUREGEOM, CAL, FIND, COUNT across layouts, QuickCalc, COMPARE (#563) and COMPAREEXPORT, MASSPROP on regions (#510), autosave/recovery, AUDIT, RECOVER (#406), OPTIONS (#23); no SPELL (open PR #551), ETRANSMIT | [gaps](gaps.md#features) | | Parametric constraints | 2% | 50% | 20–30 | all 12 geometric and the dimensional constraints, own solver; DOF report, G2 Smooth, ellipse/spline/block geometry and CONSTRAINTINFER landed (#546) | [geometry-parity](geometry-parity.md#constraint-solver--50) | @@ -223,6 +223,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Blocks, attributes, xrefs, groups row: REFEDIT edits nested references and xrefs in place, writing the xref's drawing back; parity percentages and hours not re-measured | | 2026-10-24 | minor | Inquiry and utilities row: COMPAREEXPORT exports a comparison to a new drawing; parity percentages and hours not re-measured | | 2026-10-22 | minor | Draw row: RECTANG gained a centre construction mode (`Center` keyword, `center: true`) beside its corner mode (#1127); parity percentages and hours not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured | From 2827d420b127f3e7b7fc106f88ed6c06182fbb5b Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:23:43 -0600 Subject: [PATCH 002/258] DXF: a block record keeps its annotative flag and uniform scaling A BLOCK_RECORD's AcadAnnotative xdata (references to the block are annotative) was dropped on reading, AcadAnnotative being among the applications CADCraft writes itself, and never written: a saved drawing's annotative blocks came back plain, and AutoCAD then scaled their references by units instead of the annotation scale (a metre block showed Unit factor 1000 and Scale 0.005). Group 281 (scale uniformly) was dropped too. Both are now read into the block (`Block::annotative`, `Block::scale_uniformly`) and written back. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/tables.rs | 4 ++++ crates/io/src/dxf_read.rs | 14 ++++++++++++-- crates/io/src/dxf_read/document.rs | 4 ++-- crates/io/src/dxf_read/tables.rs | 10 ++++++++-- crates/io/src/dxf_write/common.rs | 2 +- crates/io/src/dxf_write/sections.rs | 8 +++++++- 6 files changed, 34 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index a2c63ca6a..100d58f08 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -716,6 +716,9 @@ pub struct Block { pub explodable: bool, #[serde(default)] pub units: u8, + /// References to this block scale uniformly (the BLOCK_RECORD's group 281). + #[serde(default)] + pub scale_uniformly: bool, /// The parameters of an associative array when this is an array block. #[serde(default, skip_serializing_if = "Option::is_none")] pub array: Option, @@ -764,6 +767,7 @@ impl Block { xref_path: None, explodable: true, units: 0, + scale_uniformly: false, array: None, } } diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 1489f4def..e34e9588d 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -34,6 +34,15 @@ use tables::{header, tables}; pub(crate) mod mtext_dxf; +/// A block record's properties (see [`Rx::block_props`]). +#[derive(Clone, Copy, Default)] +struct BlockProps { + units: u8, + explodable: bool, + scale_uniformly: bool, + annotative: bool, +} + /// Handle maps and references gathered while reading. #[derive(Default)] struct Rx { @@ -43,8 +52,9 @@ struct Rx { brs: HashMap, /// LTYPE record handle (upper case) → linetype name (DIMLTYPE, DIMLTEX1, DIMLTEX2). ltypes: HashMap, - /// Upper-case block name → (insertion units, explodable) from its BLOCK_RECORD. - block_props: HashMap, + /// Upper-case block name → its BLOCK_RECORD's properties: units (70), explodable (280), + /// scale uniformly (281) and annotative (`AcadAnnotative` xdata). + block_props: HashMap, /// Upper-case names of anonymous `*T` blocks drawn by ACAD_TABLE entities. table_blocks: std::collections::HashSet, /// Upper-case block names used by INSERTs. diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index d732f4450..48110d9a7 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -204,8 +204,8 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec, rx: &mut Rx, let mut b = Block::new(&name); b.base = base; b.description = description; - if let Some(&(units, explodable)) = rx.block_props.get(&up) { - (b.units, b.explodable) = (units, explodable); + if let Some(p) = rx.block_props.get(&up) { + (b.units, b.explodable, b.scale_uniformly, b.annotative) = (p.units, p.explodable, p.scale_uniformly, p.annotative); } if xref & 4 != 0 { b.xref_path = Some(String::new()); diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 8a57f7f9e..c750ee3ff 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -1,7 +1,7 @@ use super::common::T; use super::objects::MAX_OBJECTS; use super::{ - Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, Vec3, + BlockProps, Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, Vec3, VportConfig, VportTile, records, }; @@ -290,7 +290,13 @@ fn index_table_handles(recs: &[(String, Vec)], rx: &mut Rx) { } "BLOCK_RECORD" => { let units = table.i(70).and_then(|units| u8::try_from(units).ok()).unwrap_or(0); - rx.block_props.insert(name.to_ascii_uppercase(), (units, table.i(280).unwrap_or(1) != 0)); + let props = BlockProps { + units, + explodable: table.i(280).unwrap_or(1) != 0, + scale_uniformly: table.i(281).unwrap_or(0) != 0, + annotative: annotative(tags), + }; + rx.block_props.insert(name.to_ascii_uppercase(), props); if let Some(array) = crate::dxf_ext::read_array(tags) { rx.block_arrays.insert(name.to_ascii_uppercase(), array); } diff --git a/crates/io/src/dxf_write/common.rs b/crates/io/src/dxf_write/common.rs index b09d90410..88ad71566 100644 --- a/crates/io/src/dxf_write/common.rs +++ b/crates/io/src/dxf_write/common.rs @@ -4,7 +4,7 @@ use super::{ VAlign, Vec3, Version, W, dxf_ext, }; -/// `AcadAnnotative` xdata marking an annotative style. +/// `AcadAnnotative` xdata marking an annotative style or block. pub(super) fn annotative_xdata(w: &mut W) { w.s(1001, "AcadAnnotative"); w.s(1000, "AnnotativeData"); diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 9a21ef7a9..48979755a 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -996,10 +996,16 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec Date: Wed, 14 Oct 2026 10:32:18 -0600 Subject: [PATCH 003/258] DXF: a block reference keeps its annotation scale contexts, following the reference A reference to an annotative block holds its scale at each annotation scale in its extension dictionary (AcDbContextDataManager, ACDB_ANNOTATIONSCALES). CADCraft dropped it with the other annotation contexts it means to write from its model, but it models none for references: with the block's annotative flag kept, AutoCAD then scaled the reference once more by the current annotation scale (5 became 25). A reference's contexts are now kept, and refreshed on writing: each moves, turns and scales by what the reference did since the file was read (its default context was the reference then), so a reference left alone keeps them as read. The scales they name are found by name (SCALE group 300), as the scale list is written again from the model. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 114 +++++++- crates/io/tests/annotative_block_contexts.rs | 287 +++++++++++++++++++ 2 files changed, 392 insertions(+), 9 deletions(-) create mode 100644 crates/io/tests/annotative_block_contexts.rs diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 9b755f80f..89557979c 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -41,6 +41,19 @@ const MODELLED_KEYS: &[&str] = &[ /// changes that model them; stale copies would contradict the drawing). const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"]; +/// The annotation scale contexts of a block reference are kept, though: CADCraft doesn't model a +/// reference's scale at each annotation scale, and without them AutoCAD scales an annotative +/// reference once more by the current annotation scale. They are refreshed from the reference +/// when written ([`block_contexts`]). +const CONTEXTS_KEY: &str = "ACDBCONTEXTDATAMANAGER"; + +/// Whether extension dictionary entry `key` is left to CADCraft's model, in the extension +/// dictionary of a block reference (`of_insert`) or of something else. +fn modelled_xdict_key(key: &str, of_insert: bool) -> bool { + let k = up(key); + MODELLED_XDICT_KEYS.contains(&k.as_str()) && !(of_insert && k == CONTEXTS_KEY) +} + /// Applications whose xdata CADCraft reads and writes itself. `ACAD` holds dimension overrides /// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept. const OWN_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"]; @@ -204,6 +217,13 @@ fn identities(tables: &Recs, blocks: &Recs, objects: &Recs) -> HashMap {} } } + // Annotation scales by name (written again from the model, maybe under other keys): what + // annotation scale contexts refer to. + for (kind, _, t) in objects.iter().filter(|(k, _, _)| k.eq_ignore_ascii_case("SCALE")) { + if let Some(name) = val(t, 300).filter(|n| !n.trim().is_empty()) { + put(head(t).handle, (kind.to_ascii_uppercase(), up(&name))); + } + } let Some((_, _, root)) = objects.first().filter(|(k, _, _)| is_dictionary(k)) else { return out }; put(head(root).handle, ("NOD".into(), String::new())); let by_handle: HashMap = objects.iter().filter_map(|(k, _, t)| Some((head(t).handle?, (k.as_str(), *t)))).rev().collect(); @@ -347,7 +367,10 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { let (Some(h), Some(o)) = (hd.handle, hd.owner) else { return false }; !by_handle.contains_key(&o) && xdict_of.get(&o) == Some(&h) && (ents.contains_key(&o) || ids.contains_key(&o)) }; - let memo = retained_objects(&objects, &ents, &ids, &by_handle, root.as_deref(), &root_entries, &xdict_of); + // Block references (their extension dictionaries keep annotation scale contexts). + let inserts: HashSet = all_entities(d).filter(|e| matches!(e.kind, EntityKind::Insert(_))).map(|e| e.handle.hex()).collect(); + let of_insert = |t: &[Tag]| head(t).owner.is_some_and(|o| inserts.contains(&o)); + let memo = retained_objects(&objects, &ents, &ids, &by_handle, (root.as_deref(), &root_entries), &xdict_of, &inserts); let mut f = Foreign::default(); let mut kept: HashSet = HashSet::new(); for (i, (kind, _, t)) in objects.iter().enumerate() { @@ -357,7 +380,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { let Some(h) = head(t).handle.and_then(|h| handle(&h)) else { continue }; let mut tags: Vec = t.iter().map(raw).collect(); if is_xdict(i) { - strip_entries(&mut tags); + strip_entries(&mut tags, of_insert(t)); } if head(t).owner == root && let Some(key) = root_key(&h.hex()) @@ -488,10 +511,11 @@ fn retained_objects( entities: &HashMap, records: &HashMap, by_handle: &HashMap, - root: Option<&str>, - root_entries: &[(String, String)], + (root, root_entries): (Option<&str>, &[(String, String)]), xdict_of: &HashMap, + inserts: &HashSet, ) -> HashMap { + let of_insert = |tags: &[Tag]| head(tags).owner.is_some_and(|owner| inserts.contains(&owner)); let root_key = |handle: &str| root_entries.iter().find(|(_, entry_handle)| entry_handle == handle).map(|(key, _)| key); let is_xdict = |index: usize| { let Some((_, _, tags)) = objects.get(index) else { return false }; @@ -500,7 +524,7 @@ fn retained_objects( !by_handle.contains_key(&owner) && xdict_of.get(&owner) == Some(&handle) && (entities.contains_key(&owner) || records.contains_key(&owner)) }; let modelled_entry = |tags: &[Tag], handle: &str| { - entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && MODELLED_XDICT_KEYS.contains(&up(key).as_str())) + entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && modelled_xdict_key(key, of_insert(tags))) }; let mut retained = HashMap::new(); for index in 0..objects.len() { @@ -531,7 +555,7 @@ fn retained_objects( continue; } if is_xdict(current) { - break entries(tags).iter().any(|(key, _)| !MODELLED_XDICT_KEYS.contains(&up(key).as_str())); + break entries(tags).iter().any(|(key, _)| !modelled_xdict_key(key, of_insert(tags))); } break entities.get(&owner) == Some(&true); }; @@ -619,12 +643,81 @@ pub(crate) fn data_store(tags: &mut Vec, d: &Drawing, modern: bool) { tags.splice(at..at, out); } -/// Drop a dictionary's modelled entries (key and handle) from its groups. -fn strip_entries(tags: &mut Vec) { +/// The kept annotation scale contexts of block references, brought up to date with each +/// reference (see [`CONTEXTS_KEY`]). A context holds the reference's insertion point, rotation +/// (degrees) and scale at one annotation scale; the default context (group 290 = 1) was the +/// reference itself when the file was read, so each context moves, turns and scales by what the +/// reference did since. Only the contexts of references that changed are returned (by handle). +fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> HashMap { + let num = |o: &ForeignObject, code: i32| { + o.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()) + }; + // The entity a kept object belongs to: the owner past the kept dictionaries. + let owner_entity = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + match owners.get(&cur) { + Some(o) if owners.contains_key(o) => cur = o.clone(), + Some(o) => return Handle::parse_hex(o), + None => return None, + } + } + None + }; + // The contexts of each reference, together (they share their dictionary). + let mut by_parent: BTreeMap> = BTreeMap::new(); + for o in f.objects.iter().filter(|o| o.kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS")) { + if let Some(p) = owners.get(&o.handle.hex()) { + by_parent.entry(p.clone()).or_default().push(o); + } + } + let mut out = HashMap::new(); + for list in by_parent.values() { + let Some(first) = list.first() else { continue }; + let Some(EntityKind::Insert(ins)) = owner_entity(&first.handle.hex()).and_then(|h| d.entity(h)).map(|e| &e.kind) else { continue }; + let def = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).unwrap_or(first); + let (Some(x0), Some(y0)) = (num(def, 10), num(def, 20)) else { continue }; + let turn = (ins.rotation.to_degrees() - num(def, 50).unwrap_or(0.0)).to_radians(); + let at0 = cadcraft_doc::geom::Vec2::new(x0, y0); + let ratio = |code: i32, now: f64| num(def, code).filter(|s| s.abs() > 1e-12).map_or(1.0, |s| now / s); + let ratios = [(41, ratio(41, ins.scale.x)), (42, ratio(42, ins.scale.y)), (43, ratio(43, ins.scale.z))]; + let unchanged = (ins.insert.xy() - at0).len() < 1e-9 && turn.abs() < 1e-12 && ratios.iter().all(|(_, r)| (r - 1.0).abs() < 1e-12); + if unchanged || !ratios.iter().all(|(_, r)| r.is_finite()) || !turn.is_finite() { + continue; + } + for c in list { + let mut o = (*c).clone(); + // Its offset from the default context turns with the reference. + let at = match (num(c, 10), num(c, 20)) { + (Some(x), Some(y)) => ins.insert.xy() + (cadcraft_doc::geom::Vec2::new(x, y) - at0).rotate(turn), + _ => ins.insert.xy(), + }; + for t in &mut o.tags { + let v = match t.code { + 10 => Some(at.x), + 20 => Some(at.y), + 30 => Some(ins.insert.z), + 50 => num(c, 50).map(|r| r + turn.to_degrees()), + 41..=43 => ratios.iter().find(|(k, _)| *k == t.code).and_then(|(k, r)| num(c, *k).map(|s| s * r)), + _ => None, + }; + if let Some(v) = v.filter(|v| v.is_finite()) { + t.value = v.to_string(); + } + } + out.insert(o.handle.hex(), o); + } + } + out +} + +/// Drop an extension dictionary's modelled entries (key and handle) from its groups (`of_insert`: +/// it is a block reference's). +fn strip_entries(tags: &mut Vec, of_insert: bool) { let mut out = Vec::with_capacity(tags.len()); let mut i = 0; while let Some(t) = tags.get(i) { - if t.code == 3 && MODELLED_XDICT_KEYS.contains(&up(&t.value).as_str()) && tags.get(i + 1).is_some_and(|n| matches!(n.code, 350 | 360)) { + if t.code == 3 && modelled_xdict_key(&t.value, of_insert) && tags.get(i + 1).is_some_and(|n| matches!(n.code, 350 | 360)) { i += 2; continue; } @@ -921,6 +1014,8 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { .iter() .filter_map(|o| Some((o.handle.hex(), head(&o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect::>()).owner?))) .collect(); + // Block references' annotation scale contexts, up to date with the references. + let contexts = block_contexts(f, d, &owners); let mut alive_memo: HashMap = HashMap::new(); for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) { alive_memo.insert(o.handle.hex(), false); @@ -977,6 +1072,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { } if r.kind == "ENDSEC" && r.sec == "OBJECTS" { for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex())) { + let o = contexts.get(&o.handle.hex()).unwrap_or(o); let number = is_proxy(&o.kind).then(|| renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str()))))).flatten(); match number { Some(n) => { diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs new file mode 100644 index 000000000..da3931651 --- /dev/null +++ b/crates/io/tests/annotative_block_contexts.rs @@ -0,0 +1,287 @@ +//! An annotative block survives a save: its BLOCK_RECORD keeps the `AcadAnnotative` xdata and +//! uniform scaling (281), and a reference keeps its annotation scale contexts (the reference's +//! scale at each annotation scale), pointing at the same scales and following the reference when +//! it is moved, turned or scaled. Without them AutoCAD scales the reference by its units, or once +//! more by the current annotation scale. +//! +//! The fixture is synthetic: block SIGN (metres) with one line, a reference at (10, 20) scaled 5, +//! and its contexts for 1:5 (default, scale 5) and 1:1 (scale 1). + +use cadcraft_doc::geom::Vec2; +use cadcraft_doc::{Drawing, Handle}; +use cadcraft_io::{read_dxf, write_dxf}; + +const FIXTURE: &str = " +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $INSUNITS +70 6 +0 ENDSEC +0 SECTION +2 TABLES +0 TABLE +2 BLOCK_RECORD +5 1 +330 0 +100 AcDbSymbolTable +70 1 +0 BLOCK_RECORD +5 1F +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 SIGN +70 6 +280 1 +281 1 +1001 AcadAnnotative +1000 AnnotativeData +1002 { +1070 1 +1070 1 +1002 } +0 ENDTAB +0 ENDSEC +0 SECTION +2 BLOCKS +0 BLOCK +5 20 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 SIGN +70 0 +10 0 +20 0 +30 0 +3 SIGN +1 +0 LINE +5 21 +330 1F +100 AcDbEntity +8 0 +100 AcDbLine +10 0 +20 0 +30 0 +11 1 +21 0 +31 0 +0 ENDBLK +5 22 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 ENDSEC +0 SECTION +2 ENTITIES +0 INSERT +5 40 +102 {ACAD_XDICTIONARY +360 41 +102 } +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockReference +2 SIGN +10 10 +20 20 +30 0 +41 5 +42 5 +43 5 +50 0 +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +3 ACAD_SCALELIST +350 50 +0 DICTIONARY +5 50 +330 C +100 AcDbDictionary +281 1 +3 A0 +350 51 +3 A1 +350 52 +0 SCALE +5 51 +330 50 +100 AcDbScale +70 0 +300 1:1 +140 1 +141 1 +290 0 +0 SCALE +5 52 +330 50 +100 AcDbScale +70 0 +300 1:5 +140 1 +141 5 +290 0 +0 DICTIONARY +5 41 +330 40 +100 AcDbDictionary +280 1 +281 1 +3 AcDbContextDataManager +360 42 +0 DICTIONARY +5 42 +330 41 +100 AcDbDictionary +281 1 +3 ACDB_ANNOTATIONSCALES +350 43 +0 DICTIONARY +5 43 +330 42 +100 AcDbDictionary +281 1 +3 *A1 +350 44 +3 *A2 +350 45 +0 ACDB_BLKREFOBJECTCONTEXTDATA_CLASS +5 44 +330 43 +100 AcDbObjectContextData +70 4 +290 1 +100 AcDbAnnotScaleObjectContextData +340 52 +50 0 +10 10 +20 20 +30 0 +41 5 +42 5 +43 5 +0 ACDB_BLKREFOBJECTCONTEXTDATA_CLASS +5 45 +330 43 +100 AcDbObjectContextData +70 4 +290 0 +100 AcDbAnnotScaleObjectContextData +340 51 +50 0 +10 10 +20 20 +30 0 +41 1 +42 1 +43 1 +0 ENDSEC +0 EOF +"; + +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 written file's records: (type, groups). +fn records(text: &str) -> Vec<(String, Vec<(i32, String)>)> { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out: Vec<(String, Vec<(i32, String)>)> = Vec::new(); + for pair in lines.chunks(2) { + let (Some(code), Some(value)) = (pair.first().and_then(|c| c.parse::().ok()), pair.get(1)) else { continue }; + if code == 0 { + out.push((value.to_string(), Vec::new())); + } else if let Some((_, tags)) = out.last_mut() { + tags.push((code, value.to_string())); + } + } + out +} + +fn get<'a>(tags: &'a [(i32, String)], code: i32) -> Option<&'a str> { + tags.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str()) +} + +/// The written block reference contexts: (scale name, default, insertion, rotation, x scale). +fn contexts(text: &str) -> Vec<(String, bool, Vec2, f64, f64)> { + let recs = records(text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let num = |t: &[(i32, String)], c: i32| get(t, c).and_then(|v| v.parse::().ok()).unwrap_or(f64::NAN); + recs.iter() + .filter(|(k, _)| k == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS") + .map(|(_, t)| { + let scale = get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(); + (scale, get(t, 290) == Some("1"), Vec2::new(num(t, 10), num(t, 20)), num(t, 50), num(t, 41)) + }) + .collect() +} + +fn read() -> Drawing { + read_dxf(dxf(FIXTURE).as_bytes()).unwrap() +} + +#[test] +fn an_annotative_block_keeps_its_record_and_its_reference_s_contexts() { + let d = read(); + let b = d.block("SIGN").unwrap(); + assert!(b.annotative && b.scale_uniformly && b.units == 6); + let text = write_dxf(&d); + // The record: units, uniform scaling and the annotative flag. + let recs = records(&text); + let (_, rec) = recs.iter().find(|(k, t)| k == "BLOCK_RECORD" && get(t, 2) == Some("SIGN")).unwrap(); + assert_eq!((get(rec, 70), get(rec, 281)), (Some("6"), Some("1"))); + assert!(rec.iter().any(|(c, v)| *c == 1001 && v == "AcadAnnotative"), "{rec:?}"); + // The contexts, as read, at the same scales. + let mut ctx = contexts(&text); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect(); + assert_eq!(got, [("1:1".to_string(), false, 1.0), ("1:5".to_string(), true, 5.0)]); + assert!(ctx.iter().all(|c| c.2 == Vec2::new(10.0, 20.0) && c.3 == 0.0)); + // Read back: still annotative. + assert!(read_dxf(text.as_bytes()).unwrap().block("SIGN").unwrap().annotative); +} + +#[test] +fn a_reference_s_contexts_follow_it_when_it_is_moved_turned_and_scaled() { + let mut d = read(); + let r = Handle::parse_hex("40").unwrap(); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + i.rotation = 30f64.to_radians(); + i.scale = i.scale * 2.0; + } + }) + .unwrap(); + let mut ctx = contexts(&write_dxf(&d)); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + for (scale, _, at, rot, sx) in &ctx { + assert!((at.x - 15.0).abs() < 1e-9 && (at.y - 20.0).abs() < 1e-9, "{scale}: {at:?}"); + assert!((rot - 30.0).abs() < 1e-9, "{scale}: {rot}"); + // Each context doubles: 1 → 2 at 1:1, 5 → 10 at 1:5. + let want = if scale == "1:1" { 2.0 } else { 10.0 }; + assert!((sx - want).abs() < 1e-9, "{scale}: {sx}"); + } + assert_eq!(ctx.len(), 2); +} From 425054a9624895214beb66575bcb82a9e09b0b1e Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:42:55 -0600 Subject: [PATCH 004/258] Block literals in tests take scale_uniformly; a test helper's lifetime is elided Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/spatial.rs | 1 + crates/engine/tests/it/pick_text.rs | 1 + crates/io/tests/annotative_block_contexts.rs | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index dd2e0d593..2341bec2d 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -308,6 +308,7 @@ mod tests { xref_path: None, explodable: true, units: 0, + scale_uniformly: false, array: None, }; blk.entities diff --git a/crates/engine/tests/it/pick_text.rs b/crates/engine/tests/it/pick_text.rs index b0df6d8a3..0341e8761 100644 --- a/crates/engine/tests/it/pick_text.rs +++ b/crates/engine/tests/it/pick_text.rs @@ -103,6 +103,7 @@ fn a_dimension_drawn_from_its_block_is_picked_on_the_block_text() { xref_path: None, explodable: true, units: 0, + scale_uniformly: false, array: None, }; d.blocks.insert("*D1".into(), std::sync::Arc::new(block)); diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index da3931651..74d33c097 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -218,7 +218,7 @@ fn records(text: &str) -> Vec<(String, Vec<(i32, String)>)> { out } -fn get<'a>(tags: &'a [(i32, String)], code: i32) -> Option<&'a str> { +fn get(tags: &[(i32, String)], code: i32) -> Option<&str> { tags.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str()) } From f344a13e63e4539f0f1f441cb95d8f1bb660514f Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 11:44:39 -0600 Subject: [PATCH 005/258] DXF: a block reference's attributes keep their annotation scale contexts The attributes of an annotative reference hold their own contexts (insertion and alignment points and rotation at each annotation scale, under the ATTRIB's extension dictionary), dropped like the reference's were. CADCraft writes attributes with new handles, so their extension dictionaries are now kept by attribute, as its reference's handle and tag, and put back on the attribute written with that reference and tag. On writing each context keeps its own place in the block at its scale, moves by what the attribute did in the block since (its default context then, the attribute now), and is placed by the reference's context for that scale as it is now: a reference left alone keeps them as read; one moved, turned or scaled carries them exactly. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 161 ++++++++++++++++++- crates/io/tests/annotative_block_contexts.rs | 123 ++++++++++++++ 2 files changed, 276 insertions(+), 8 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 89557979c..d8aaa1689 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -193,13 +193,17 @@ fn modelled_key(key: &str) -> bool { /// The roles of a file's handles (see [`ForeignKey`]): table records and tables by type and /// name, blocks by name, the named object dictionary, its entries, and their entries. -fn identities(tables: &Recs, blocks: &Recs, objects: &Recs) -> HashMap { +fn identities(tables: &Recs, blocks: &Recs, entities: &Recs, objects: &Recs) -> HashMap { let mut out: HashMap = HashMap::new(); let mut put = |h: Option, k: ForeignKey| { if let Some(h) = h { out.entry(h).or_insert(k); } }; + // Attributes (written with new handles each time) by their reference and tag. + for (kind, _, t) in blocks.iter().chain(entities).filter(|(k, _, _)| k == "ATTRIB") { + put(head(t).handle, (kind.clone(), attrib_key(t))); + } for (kind, _, t) in tables { let name = up(&val(t, 2).unwrap_or_default()); if kind == "TABLE" || !name.is_empty() { @@ -347,7 +351,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { let (classes, tables, blocks, entities, objects) = (get("CLASSES"), get("TABLES"), get("BLOCKS"), get("ENTITIES"), get("OBJECTS")); // The drawing's entities by handle: whether each is of a type CADCraft doesn't model. let ents = entity_types(d); - let ids = identities(&tables, &blocks, &objects); + let ids = identities(&tables, &blocks, &entities, &objects); // Extension dictionaries of entities and records: owner → dictionary. let xdict_of = extension_dictionaries(&tables, &blocks, &entities); // Objects by handle: the first of each, and none that has an entity's handle. @@ -367,9 +371,10 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { let (Some(h), Some(o)) = (hd.handle, hd.owner) else { return false }; !by_handle.contains_key(&o) && xdict_of.get(&o) == Some(&h) && (ents.contains_key(&o) || ids.contains_key(&o)) }; - // Block references (their extension dictionaries keep annotation scale contexts). + // Block references and their attributes (their extension dictionaries keep annotation scale + // contexts). let inserts: HashSet = all_entities(d).filter(|e| matches!(e.kind, EntityKind::Insert(_))).map(|e| e.handle.hex()).collect(); - let of_insert = |t: &[Tag]| head(t).owner.is_some_and(|o| inserts.contains(&o)); + let of_insert = |t: &[Tag]| head(t).owner.is_some_and(|o| inserts.contains(&o) || ids.get(&o).is_some_and(|k| k.0 == "ATTRIB")); let memo = retained_objects(&objects, &ents, &ids, &by_handle, (root.as_deref(), &root_entries), &xdict_of, &inserts); let mut f = Foreign::default(); let mut kept: HashSet = HashSet::new(); @@ -410,6 +415,12 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { } } put_xdata(d, xdata_of); + // Attributes' extension dictionaries (their annotation scale contexts), by attribute. + for (kind, _, t) in blocks.iter().chain(&entities).filter(|(k, _, _)| k == "ATTRIB") { + if let Some(xd) = head(t).xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)) { + f.records.entry((kind.clone(), attrib_key(t))).or_insert(ForeignExtra { xdict: Some(xd), ..ForeignExtra::default() }); + } + } for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| k == "BLOCK")) { let Some(key) = head(t).handle.and_then(|h| ids.get(&h).cloned()) else { continue }; let x = extra(kind, t, kind == "BLOCK", false, &kept); @@ -515,7 +526,9 @@ fn retained_objects( xdict_of: &HashMap, inserts: &HashSet, ) -> HashMap { - let of_insert = |tags: &[Tag]| head(tags).owner.is_some_and(|owner| inserts.contains(&owner)); + let of_insert = |tags: &[Tag]| { + head(tags).owner.is_some_and(|owner| inserts.contains(&owner) || records.get(&owner).is_some_and(|key| key.0 == "ATTRIB")) + }; let root_key = |handle: &str| root_entries.iter().find(|(_, entry_handle)| entry_handle == handle).map(|(key, _)| key); let is_xdict = |index: usize| { let Some((_, _, tags)) = objects.get(index) else { return false }; @@ -643,6 +656,12 @@ pub(crate) fn data_store(tags: &mut Vec, d: &Drawing, modern: bool) { tags.splice(at..at, out); } +/// An attribute's identity across saves (its handle is new each time): its reference's handle +/// and its tag. +fn attrib_key(tags: &[Tag]) -> String { + format!("{}/{}", head(tags).owner.unwrap_or_default(), up(&val(tags, 2).unwrap_or_default())) +} + /// The kept annotation scale contexts of block references, brought up to date with each /// reference (see [`CONTEXTS_KEY`]). A context holds the reference's insertion point, rotation /// (degrees) and scale at one annotation scale; the default context (group 290 = 1) was the @@ -711,6 +730,128 @@ fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> out } +/// The kept annotation scale contexts of block references' attributes, brought up to date. A +/// context holds the attribute's insertion and alignment points (10, 11) and rotation (50) at one +/// annotation scale. It keeps its own place in the block at that scale (as read, through the +/// reference's context for the same scale), moved by what the attribute did in the block since +/// (seen in its default context, 290 = 1), and is placed by the reference's context as it is now +/// (`block`: the reference contexts [`block_contexts`] refreshed). Only changed contexts are +/// returned (by handle). +fn attribute_contexts( + f: &Foreign, + d: &Drawing, + owners: &HashMap, + block: &HashMap, +) -> HashMap { + use cadcraft_doc::geom::{Mat3, Vec2}; + let num = |o: &ForeignObject, code: i32| { + o.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()) + }; + let text = |o: &ForeignObject, code: i32| o.tags.iter().find(|t| t.code == code).map(|t| norm(&t.value)); + // The last kept object up the owner chain (an extension dictionary) and its owner. + let top = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + match owners.get(&cur) { + Some(o) if owners.contains_key(o) => cur = o.clone(), + Some(o) => return Some((cur, o.clone())), + None => return None, + } + } + None + }; + // Attributes' extension dictionaries: (reference, tag). + let attribs: HashMap = f + .records + .iter() + .filter(|(k, _)| k.0 == "ATTRIB") + .filter_map(|(k, x)| { + let (ins, tag) = k.1.split_once('/')?; + Some((x.xdict?.hex(), (Handle::parse_hex(ins)?, tag.to_string()))) + }) + .collect(); + // A reference's context at each scale, as read and as written: (insertion, degrees, scale). + type Place = (Vec2, f64, (f64, f64)); + let place = + |o: &ForeignObject| -> Option { Some((Vec2::new(num(o, 10)?, num(o, 20)?), num(o, 50).unwrap_or(0.0), (num(o, 41)?, num(o, 42)?))) }; + let mut read: HashMap<(Handle, String), Place> = HashMap::new(); + let mut now: HashMap<(Handle, String), Place> = HashMap::new(); + for o in f.objects.iter().filter(|o| o.kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS")) { + let (Some((_, r)), Some(s)) = (top(&o.handle.hex()), text(o, 340)) else { continue }; + let Some(r) = Handle::parse_hex(&r) else { continue }; + if let Some(p) = place(o) { + read.insert((r, s.clone()), p); + } + if let Some(p) = place(block.get(&o.handle.hex()).unwrap_or(o)) { + now.insert((r, s), p); + } + } + // The block-to-drawing transform of a reference placed at `p` (its block's base `base`). + let matrix = |ins: &cadcraft_doc::Insert, base: Vec2, p: Place| { + let mut i = ins.clone(); + i.insert = p.0.to3(ins.insert.z); + i.rotation = p.1.to_radians(); + i.scale = cadcraft_doc::geom::Vec3::new(p.2.0, p.2.1, ins.scale.z); + i.transform(base) + }; + // Each attribute's contexts, together. + let mut by_attrib: BTreeMap> = BTreeMap::new(); + for o in f.objects.iter().filter(|o| up(&o.kind).contains("ATTRIBUTEOBJECTCONTEXTDATA")) { + if let Some((xd, _)) = top(&o.handle.hex()) { + by_attrib.entry(xd).or_default().push(o); + } + } + let mut out = HashMap::new(); + for (xd, list) in &by_attrib { + let Some((r, tag)) = attribs.get(xd) else { continue }; + let Some(EntityKind::Insert(ins)) = d.entity(*r).map(|e| &e.kind) else { continue }; + let Some(a) = ins.attribs.iter().find(|a| up(&a.tag) == *tag) else { continue }; + let base = d.block(&ins.block).map(|b| b.base.xy()).unwrap_or_default(); + let Some(to_block_now) = ins.transform(base).inverse() else { continue }; + let Some(def) = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).or(list.first()) else { continue }; + let at = |o: &ForeignObject, x: i32| Some(Vec2::new(num(o, x)?, num(o, x + 10)?)); + // What the attribute did in the block since: its default context then, the attribute now. + let Some(def_place) = text(def, 340).and_then(|s| read.get(&(*r, s))).copied() else { continue }; + let Some(to_block_then) = matrix(ins, base, def_place).inverse() else { continue }; + let now_ins = to_block_now.apply(a.text.insert.xy()); + let now_align = to_block_now.apply(a.text.align_pt.unwrap_or(a.text.insert).xy()); + let (Some(then_ins), Some(then_align)) = (at(def, 10).map(|p| to_block_then.apply(p)), at(def, 11).map(|p| to_block_then.apply(p))) else { + continue; + }; + let turn = (a.text.rotation.to_degrees() - ins.rotation.to_degrees()) - (num(def, 50).unwrap_or(0.0) - def_place.1); + for c in list { + let Some(s) = text(c, 340) else { continue }; + let (Some(was), Some(is)) = (read.get(&(*r, s.clone())).copied(), now.get(&(*r, s)).copied()) else { continue }; + let (Some(from), to): (Option, Mat3) = (matrix(ins, base, was).inverse(), matrix(ins, base, is)) else { continue }; + let moved = |x: i32, delta: Vec2| at(c, x).map(|p| to.apply(from.apply(p) + delta)); + let (new_ins, new_align) = (moved(10, now_ins - then_ins), moved(11, now_align - then_align)); + let rot = num(c, 50).map(|v| v + (is.1 - was.1) + turn); + let mut o = (*c).clone(); + let mut changed = false; + for t in &mut o.tags { + let v = match t.code { + 10 => new_ins.map(|p| p.x), + 20 => new_ins.map(|p| p.y), + 11 => new_align.map(|p| p.x), + 21 => new_align.map(|p| p.y), + 50 => rot, + _ => None, + }; + if let Some(v) = v.filter(|v| v.is_finite()) + && t.value.trim().parse::().map_or(true, |old| (old - v).abs() > 1e-9) + { + t.value = v.to_string(); + changed = true; + } + } + if changed { + out.insert(o.handle.hex(), o); + } + } + } + out +} + /// Drop an extension dictionary's modelled entries (key and handle) from its groups (`of_insert`: /// it is a block reference's). fn strip_entries(tags: &mut Vec, of_insert: bool) { @@ -908,6 +1049,8 @@ fn extra_for<'a>(f: &'a Foreign, xd: &XdataOf, rec: &Rec, body: &[Tag], block: & match (rec.sec.as_str(), rec.kind.as_str()) { ("BLOCKS", "BLOCK") => f.records.get(&("BLOCK".to_string(), block.to_string())).map(Cow::Borrowed), ("BLOCKS", "ENDBLK") => None, + // An attribute by its reference and tag (its handle is new). + ("ENTITIES" | "BLOCKS", "ATTRIB") => f.records.get(&("ATTRIB".to_string(), attrib_key(body))).map(Cow::Borrowed), ("ENTITIES" | "BLOCKS", _) => entity_extra(f, xd, handle(&head(body).handle?)?), ("TABLES", kind) => { let name = up(&val(body, 2).unwrap_or_default()); @@ -951,9 +1094,9 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let by_sec = |name: &str| -> Recs { recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.clone(), r.start, body(r))).collect() }; - let (tables, blocks, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("OBJECTS")); + let (tables, blocks, entities, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("ENTITIES"), by_sec("OBJECTS")); let mut roles: HashMap = HashMap::new(); - for (h, k) in identities(&tables, &blocks, &objects) { + for (h, k) in identities(&tables, &blocks, &entities, &objects) { roles.entry(k).or_insert(h); } let mut written: HashSet = recs.iter().filter_map(|r| head(body(r)).handle).collect(); @@ -1015,7 +1158,9 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { .filter_map(|o| Some((o.handle.hex(), head(&o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect::>()).owner?))) .collect(); // Block references' annotation scale contexts, up to date with the references. - let contexts = block_contexts(f, d, &owners); + let mut contexts = block_contexts(f, d, &owners); + let attribute = attribute_contexts(f, d, &owners, &contexts); + contexts.extend(attribute); let mut alive_memo: HashMap = HashMap::new(); for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) { alive_memo.insert(o.handle.hex(), false); diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index 74d33c097..ad5cca0b7 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -97,6 +97,29 @@ const FIXTURE: &str = " 42 5 43 5 50 0 +66 1 +0 ATTRIB +5 70 +102 {ACAD_XDICTIONARY +360 71 +102 } +330 40 +100 AcDbEntity +8 0 +100 AcDbText +10 15 +20 30 +30 0 +40 1 +1 X +100 AcDbAttribute +2 TAG +70 0 +0 SEQEND +5 77 +330 40 +100 AcDbEntity +8 0 0 ENDSEC 0 SECTION 2 OBJECTS @@ -188,6 +211,60 @@ const FIXTURE: &str = " 41 1 42 1 43 1 +0 DICTIONARY +5 71 +330 70 +100 AcDbDictionary +280 1 +281 1 +3 AcDbContextDataManager +360 73 +0 DICTIONARY +5 73 +330 71 +100 AcDbDictionary +281 1 +3 ACDB_ANNOTATIONSCALES +350 74 +0 DICTIONARY +5 74 +330 73 +100 AcDbDictionary +281 1 +3 *A1 +350 75 +3 *A2 +350 76 +0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS +5 75 +330 74 +100 AcDbObjectContextData +70 4 +290 1 +100 AcDbAnnotScaleObjectContextData +340 52 +70 0 +50 0 +10 15 +20 30 +11 15 +21 30 +290 0 +0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS +5 76 +330 74 +100 AcDbObjectContextData +70 4 +290 0 +100 AcDbAnnotScaleObjectContextData +340 51 +70 0 +50 0 +10 11 +20 22 +11 11 +21 22 +290 0 0 ENDSEC 0 EOF "; @@ -237,6 +314,19 @@ fn contexts(text: &str) -> Vec<(String, bool, Vec2, f64, f64)> { .collect() } +/// The written attribute contexts: (scale name, insertion point), and the ATTRIB they hang on +/// (its tag, through its extension dictionary). +fn attribute_contexts(text: &str) -> Vec<(String, Vec2)> { + let recs = records(text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let num = |t: &[(i32, String)], c: i32| get(t, c).and_then(|v| v.parse::().ok()).unwrap_or(f64::NAN); + recs.iter() + .filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS") + .map(|(_, t)| (get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(), Vec2::new(num(t, 10), num(t, 20)))) + .collect() +} + fn read() -> Drawing { read_dxf(dxf(FIXTURE).as_bytes()).unwrap() } @@ -260,6 +350,39 @@ fn an_annotative_block_keeps_its_record_and_its_reference_s_contexts() { assert!(ctx.iter().all(|c| c.2 == Vec2::new(10.0, 20.0) && c.3 == 0.0)); // Read back: still annotative. assert!(read_dxf(text.as_bytes()).unwrap().block("SIGN").unwrap().annotative); + // The attribute's contexts, on the written attribute (its handle is new), as read. + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]); + let recs = records(&text); + let (_, attrib) = recs.iter().find(|(k, t)| k == "ATTRIB" && get(t, 2) == Some("TAG")).unwrap(); + assert!(attrib.iter().any(|(c, v)| *c == 102 && v == "{ACAD_XDICTIONARY"), "{attrib:?}"); +} + +#[test] +fn an_attribute_s_contexts_follow_its_reference() { + // Moved 5 along x and scaled 2 (the attribute with it, as MOVE and SCALE move it): at 1:5 + // the attribute goes to (15 + 10, 20 + 20); at 1:1, through the reference's 1:1 context (now + // at (15, 20), scale 2), to (15 + 2, 20 + 4). + let mut d = read(); + let r = Handle::parse_hex("40").unwrap(); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + i.scale = i.scale * 2.0; + for a in &mut i.attribs { + a.text.insert = cadcraft_doc::geom::Vec3::new(25.0, 40.0, 0.0); + a.text.align_pt = Some(a.text.insert); + } + } + }) + .unwrap(); + let mut actx = attribute_contexts(&write_dxf(&d)); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + let near = |p: Vec2, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9; + assert_eq!(actx.len(), 2); + assert!(near(actx[0].1, 17.0, 24.0), "1:1 {:?}", actx[0]); + assert!(near(actx[1].1, 25.0, 40.0), "1:5 {:?}", actx[1]); } #[test] From 6aa64a13c90ed3948e1e494d7a3bcb3509d9581b Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:08:05 -0600 Subject: [PATCH 006/258] DWG: block reference annotation contexts keep their rotation, insertion and scales AutoCAD's DXF has a block reference context's rotation (50, degrees), insertion point and scales straight after its scale (340). acadrust 0.6.4 reads them after an AcDbBlkRefObjectContextData marker, with the rotation in radians, and without the marker read zeros: a drawing saved as DWG had every annotative reference at scale 0 at its other annotation scales, where AutoCAD then drew nothing. The DWG bridge now gives acadrust the contexts its way (marker, radians) and turns its DXF back into AutoCAD's (no marker, degrees). Co-Authored-By: Claude Opus 5.5 --- crates/dwg/src/lib.rs | 60 +++++++++++++++++++- crates/io/tests/annotative_block_contexts.rs | 32 +++++++++++ 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 037aa26b5..39d1f27fa 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -121,7 +121,7 @@ mod native { )); } written.map_err(|e| format!("DWG→DXF: {e}"))?; - Ok((add_header_vars(out.buf, &doc.header), notes)) + Ok((add_header_vars(blkref_contexts(&out.buf, false), &doc.header), notes)) } /// Most record types named in the skipped-records note. @@ -574,6 +574,62 @@ mod native { } } + /// Block reference annotation contexts (`ACDB_BLKREFOBJECTCONTEXTDATA_CLASS`) as acadrust + /// reads and writes them (`to_acadrust`), or back as AutoCAD writes them. AutoCAD's DXF has + /// the rotation (50, degrees), insertion point and scales straight after the context's scale + /// (340); acadrust 0.6.4 looks for them after an `AcDbBlkRefObjectContextData` marker, with + /// the rotation in radians (as DWG holds it), and without the marker reads zeros (an + /// annotative reference at scale 0 draws nothing in AutoCAD). Text that isn't UTF-8, or has + /// no such context, is returned as it is. + pub(crate) fn blkref_contexts(dxf: &[u8], to_acadrust: bool) -> Vec { + const KIND: &str = "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS"; + const MARKER: &str = "AcDbBlkRefObjectContextData"; + let Ok(text) = std::str::from_utf8(dxf) else { return dxf.to_vec() }; + if !text.contains(KIND) { + return dxf.to_vec(); + } + let lines: Vec<&str> = text.split('\n').collect(); + let eol = |l: &str| if l.ends_with('\r') { "\r" } else { "" }; + let mut out: Vec = Vec::with_capacity(lines.len() + 16); + let (mut inside, mut marked) = (false, false); + let mut i = 0; + while let (Some(&code_line), Some(&value_line)) = (lines.get(i), lines.get(i + 1)) { + let (code, value) = (code_line.trim(), value_line.trim_end_matches('\r')); + if code == "0" { + inside = value.trim() == KIND; + marked = false; + } + let mut value = value.to_string(); + if inside { + if code == "100" && value.trim() == MARKER { + marked = true; + i += 2; + if !to_acadrust { + continue; + } + out.push(code_line.to_string()); + out.push(value_line.to_string()); + continue; + } + if code == "50" { + if to_acadrust && !marked { + out.push(format!("100{}", eol(code_line))); + out.push(format!("{MARKER}{}", eol(value_line))); + marked = true; + } + if let Ok(a) = value.trim().parse::() { + value = if to_acadrust { a.to_radians() } else { a.to_degrees() }.to_string(); + } + } + } + out.push(code_line.to_string()); + out.push(format!("{value}{}", eol(value_line))); + i += 2; + } + out.extend(lines.get(i..).unwrap_or(&[]).iter().map(|l| (*l).to_string())); + out.join("\n").into_bytes() + } + fn convert(dxf: &[u8], version: Option) -> Result, String> { // Reject a pathologically large DXF before handing it to the third-party decoder, which // allocates tables and section buffers from the input's declared sizes and cannot be @@ -586,7 +642,7 @@ mod native { mb(Limits::DEFAULT.max_dxf_bytes as u64) )); } - let data = dxf.to_vec(); + let data = blkref_contexts(dxf, true); let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) .map_err(|_| "the DXF→DWG conversion failed".to_string())? .map_err(|e| format!("DXF: {e}"))?; diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index ad5cca0b7..6c3cff476 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -408,3 +408,35 @@ fn a_reference_s_contexts_follow_it_when_it_is_moved_turned_and_scaled() { } assert_eq!(ctx.len(), 2); } + +/// A reference's annotation contexts as CADCraft's model keeps them: (scale's SCALE handle, +/// rotation, x scale) of each, by the order kept. +fn kept_contexts(d: &Drawing) -> Vec<(f64, f64)> { + let num = |o: &cadcraft_doc::foreign::ForeignObject, c: i32| { + o.tags.iter().find(|t| t.code == c).and_then(|t| t.value.trim().parse::().ok()).unwrap_or(f64::NAN) + }; + d.foreign.objects.iter().filter(|o| o.kind == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS").map(|o| (num(o, 50), num(o, 41))).collect() +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_reference_s_contexts_survive_dwg() { + // Turned 30° first, so the rotation's unit shows (DXF degrees, DWG radians). + let mut d = read(); + let r = Handle::parse_hex("40").unwrap(); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.rotation = 30f64.to_radians(); + } + }) + .unwrap(); + let back = + cadcraft_io::read(&cadcraft_io::read_dxf(write_dxf(&d).as_bytes()).map(|d| cadcraft_io::write(&d, "x.dwg").unwrap()).unwrap(), "x.dwg") + .unwrap(); + let mut ctx = kept_contexts(&back); + ctx.sort_by(|a, b| a.1.total_cmp(&b.1)); + assert_eq!(ctx.len(), 2, "{ctx:?}"); + for ((rot, sx), want) in ctx.iter().zip([1.0, 5.0]) { + assert!((rot - 30.0).abs() < 1e-9 && (sx - want).abs() < 1e-9, "{ctx:?}"); + } +} From 8a0ca4da379c5220fcb346e543bdf75d4e453e6c Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:29:04 -0600 Subject: [PATCH 007/258] DXF: kept reference contexts follow the drawing's and the reference's scales A kept block reference or attribute context whose SCALE is no longer in the drawing's list is not written (its dictionary entry goes with it), so no context points at a null scale. A reference CADCraft's model keeps annotative has a context for exactly the scales it supports: contexts of scales it dropped go, and one per new scale is made from the default context, scaled by the ratio of the scales about the reference's insertion point. One context stays the default. Attributes are identified by reference, tag and their place among the reference's attributes with that tag, so two attributes with one tag keep their own extension dictionaries and contexts. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 302 +++++++++++++++++-- crates/io/tests/annotative_block_contexts.rs | 122 ++++++++ 2 files changed, 392 insertions(+), 32 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index d8aaa1689..5a6d291c4 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -201,8 +201,9 @@ fn identities(tables: &Recs, blocks: &Recs, entities: &Recs, objects: &Recs) -> } }; // Attributes (written with new handles each time) by their reference and tag. - for (kind, _, t) in blocks.iter().chain(entities).filter(|(k, _, _)| k == "ATTRIB") { - put(head(t).handle, (kind.clone(), attrib_key(t))); + let attribs: Vec<&[Tag]> = blocks.iter().chain(entities).filter(|(k, _, _)| k == "ATTRIB").map(|(_, _, t)| *t).collect(); + for (t, key) in attribs.iter().zip(attrib_keys(attribs.iter().copied())) { + put(head(t).handle, ("ATTRIB".into(), key)); } for (kind, _, t) in tables { let name = up(&val(t, 2).unwrap_or_default()); @@ -416,9 +417,10 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { } put_xdata(d, xdata_of); // Attributes' extension dictionaries (their annotation scale contexts), by attribute. - for (kind, _, t) in blocks.iter().chain(&entities).filter(|(k, _, _)| k == "ATTRIB") { + let attribs: Vec<&[Tag]> = blocks.iter().chain(&entities).filter(|(k, _, _)| k == "ATTRIB").map(|(_, _, t)| *t).collect(); + for (t, key) in attribs.iter().zip(attrib_keys(attribs.iter().copied())) { if let Some(xd) = head(t).xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)) { - f.records.entry((kind.clone(), attrib_key(t))).or_insert(ForeignExtra { xdict: Some(xd), ..ForeignExtra::default() }); + f.records.entry(("ATTRIB".into(), key)).or_insert(ForeignExtra { xdict: Some(xd), ..ForeignExtra::default() }); } } for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| k == "BLOCK")) { @@ -656,10 +658,29 @@ pub(crate) fn data_store(tags: &mut Vec, d: &Drawing, modern: bool) { tags.splice(at..at, out); } -/// An attribute's identity across saves (its handle is new each time): its reference's handle -/// and its tag. -fn attrib_key(tags: &[Tag]) -> String { - format!("{}/{}", head(tags).owner.unwrap_or_default(), up(&val(tags, 2).unwrap_or_default())) +/// The identities across saves (an attribute's handle is new each time) of ATTRIB records, in +/// order: the reference's handle, the tag and the attribute's place among the reference's +/// attributes with that tag (a block can have two attributes with one tag; reading and writing +/// keep their order). +fn attrib_keys<'a>(attribs: impl Iterator) -> Vec { + let mut seen: HashMap = HashMap::new(); + attribs + .map(|t| { + let base = format!("{}/{}", head(t).owner.unwrap_or_default(), up(&val(t, 2).unwrap_or_default())); + let n = seen.entry(base.clone()).or_insert(0); + let key = format!("{base}/{n}"); + *n += 1; + key + }) + .collect() +} + +/// An attribute's identity ([`attrib_keys`]) split: its reference, tag and place among the +/// reference's attributes with that tag. +fn split_attrib_key(key: &str) -> Option<(Handle, &str, usize)> { + let (ins, rest) = key.split_once('/')?; + let (tag, nth) = rest.rsplit_once('/')?; + Some((Handle::parse_hex(ins)?, tag, nth.parse().ok()?)) } /// The kept annotation scale contexts of block references, brought up to date with each @@ -760,16 +781,7 @@ fn attribute_contexts( } None }; - // Attributes' extension dictionaries: (reference, tag). - let attribs: HashMap = f - .records - .iter() - .filter(|(k, _)| k.0 == "ATTRIB") - .filter_map(|(k, x)| { - let (ins, tag) = k.1.split_once('/')?; - Some((x.xdict?.hex(), (Handle::parse_hex(ins)?, tag.to_string()))) - }) - .collect(); + let attribs = attribute_xdicts(f); // A reference's context at each scale, as read and as written: (insertion, degrees, scale). type Place = (Vec2, f64, (f64, f64)); let place = @@ -803,9 +815,9 @@ fn attribute_contexts( } let mut out = HashMap::new(); for (xd, list) in &by_attrib { - let Some((r, tag)) = attribs.get(xd) else { continue }; + let Some((r, tag, nth)) = attribs.get(xd) else { continue }; let Some(EntityKind::Insert(ins)) = d.entity(*r).map(|e| &e.kind) else { continue }; - let Some(a) = ins.attribs.iter().find(|a| up(&a.tag) == *tag) else { continue }; + let Some(a) = ins.attribs.iter().filter(|a| up(&a.tag) == *tag).nth(*nth) else { continue }; let base = d.block(&ins.block).map(|b| b.base.xy()).unwrap_or_default(); let Some(to_block_now) = ins.transform(base).inverse() else { continue }; let Some(def) = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).or(list.first()) else { continue }; @@ -852,6 +864,206 @@ fn attribute_contexts( out } +fn is_blkref_context(kind: &str) -> bool { + kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS") +} + +fn is_attribute_context(kind: &str) -> bool { + up(kind).contains("ATTRIBUTEOBJECTCONTEXTDATA") +} + +/// Attributes' kept extension dictionaries: (reference, tag, place among the reference's +/// attributes with that tag), by dictionary handle. +fn attribute_xdicts(f: &Foreign) -> HashMap { + f.records + .iter() + .filter(|(k, _)| k.0 == "ATTRIB") + .filter_map(|(k, x)| { + let (ins, tag, nth) = split_attrib_key(&k.1)?; + Some((x.xdict?.hex(), (ins, tag.to_string(), nth))) + }) + .collect() +} + +/// The kept contexts of block references and their attributes, in line with the drawing's +/// scales ([`reconcile`]). +#[derive(Default)] +struct Reconciled { + /// Contexts not written: their scale is gone from the drawing's scale list, or their + /// reference is annotative in CADCraft's model and no longer supports it. + dropped: HashSet, + /// New contexts for the scales such a reference supports without a context, with handles + /// above every file handle ([`MAX_HANDLE`]); their dictionaries list them. + added: Vec, + /// The SCALE objects the added contexts name (group 340): stand-in handle → the scale's role. + scales: HashMap, +} + +/// Bring the kept contexts of block references and their attributes (`contexts`: those already +/// refreshed, by handle) in line with the scales: a context whose SCALE is not written (deleted +/// from the drawing's list) goes. A reference CADCraft's model keeps annotative (it supports +/// scales, [`cadcraft_doc::Common::anno_scales`]) has a context for exactly the scales it +/// supports: one per new scale is made from its default context, scaled by the ratio of the two +/// scales about the reference's insertion point (as AutoCAD adds a scale). One context of each +/// reference stays the default (290 = 1). Changed dictionaries and contexts go into `contexts`. +fn reconcile( + f: &Foreign, + d: &Drawing, + owners: &HashMap, + roles: &HashMap, + contexts: &mut HashMap, +) -> Reconciled { + use cadcraft_doc::geom::Vec2; + let mut out = Reconciled::default(); + let num = |o: &ForeignObject, code: i32| { + o.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()) + }; + // The written scale a context names (upper case), if its SCALE is written. + let scale_of = |o: &ForeignObject| -> Option { + let v = o.tags.iter().find(|t| t.code == 340)?; + let k = f.targets.get(&handle(&norm(&v.value))?)?; + (k.0 == "SCALE" && roles.contains_key(k)).then(|| k.1.clone()) + }; + let is_default = |o: &ForeignObject| o.tags.iter().find(|t| t.code == 290).is_some_and(|t| t.value.trim() == "1"); + let set_default = |o: &mut ForeignObject, on: bool| { + if let Some(t) = o.tags.iter_mut().find(|t| t.code == 290) { + t.value = if on { "1" } else { "0" }.into(); + } + }; + // The last kept object up the owner chain (an extension dictionary) and its owner. + let top = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + match owners.get(&cur) { + Some(o) if owners.contains_key(o) => cur = o.clone(), + Some(o) => return Some((cur, o.clone())), + None => return None, + } + } + None + }; + let attribs = attribute_xdicts(f); + // The contexts (as refreshed) by their dictionary, with the reference they belong to and + // whether they are an attribute's. + let mut groups: BTreeMap)> = BTreeMap::new(); + for o in f.objects.iter().filter(|o| is_blkref_context(&o.kind) || is_attribute_context(&o.kind)) { + let h = o.handle.hex(); + let (Some(parent), Some((xd, owner))) = (owners.get(&h), top(&h)) else { continue }; + let attribute = is_attribute_context(&o.kind); + let reference = if attribute { attribs.get(&xd).map(|a| a.0) } else { Handle::parse_hex(&owner) }; + let Some(reference) = reference else { continue }; + groups.entry(parent.clone()).or_insert((reference, attribute, Vec::new())).2.push(contexts.get(&h).unwrap_or(o).clone()); + } + let mut next = MAX_HANDLE; + let mut fresh = || { + next = next.saturating_add(1); + format!("{next:X}") + }; + // Each annotative reference's default context: (scale, insertion point). + let mut ref_default: HashMap = HashMap::new(); + for (r, attribute, list) in groups.values() { + if let (false, Some(def)) = (attribute, list.iter().find(|o| is_default(o)).or(list.first())) + && let (Some(s), Some(x), Some(y)) = (scale_of(def), num(def, 10), num(def, 20)) + { + ref_default.insert(*r, (s, Vec2::new(x, y))); + } + } + let current = up(&d.current_anno_scale().name); + for (dict, (r, attribute, list)) in &groups { + let e = d.entity(*r).filter(|e| matches!(e.kind, EntityKind::Insert(_)) && cadcraft_doc::is_annotative(e)); + // The scales the reference supports, when CADCraft's model says (each written once). + let mut wanted: Vec = Vec::new(); + for s in e.map(|e| e.common.anno_scales.as_slice()).unwrap_or_default() { + let n = up(&s.name); + if s.is_valid() && roles.contains_key(&("SCALE".to_string(), n.clone())) && !wanted.contains(&n) { + wanted.push(n); + } + } + let mut have: Vec<(String, ForeignObject)> = Vec::new(); + for c in list { + match scale_of(c) { + Some(s) if e.is_none() || (wanted.contains(&s) && !have.iter().any(|(x, _)| *x == s)) => have.push((s, c.clone())), + _ => { + out.dropped.insert(c.handle.hex()); + } + } + } + // New contexts, from the context at the reference's default scale. + let mut added: Vec<(String, ForeignObject)> = Vec::new(); + if let Some(e) = e + && let Some((def_scale, at)) = ref_default.get(r) + && let Some(template) = list.iter().find(|c| scale_of(c).as_ref() == Some(def_scale)) + { + let factor = |name: &str| { + d.scales + .iter() + .chain(&e.common.anno_scales) + .find(|s| up(&s.name) == name) + .map(cadcraft_doc::AnnoScale::factor) + .filter(|f| f.is_finite() && *f > 0.0) + }; + for s in wanted.iter().filter(|s| !have.iter().any(|(x, _)| x == *s)) { + let (Some(to), Some(from)) = (factor(s), factor(def_scale)) else { continue }; + let k = to / from; + let (h, scale) = (fresh(), fresh()); + let mut o = template.clone(); + o.handle = Handle::parse_hex(&h).unwrap_or(o.handle); + for t in &mut o.tags { + let v = t.value.trim().parse::().ok().filter(|v| v.is_finite()); + let new = match (t.code, v) { + (5, _) => Some(h.clone()), + (340, _) => Some(scale.clone()), + (41..=43, Some(v)) if !attribute => Some((v * k).to_string()), + // An attribute's points scale about the reference's insertion point. + (10 | 11, Some(v)) if *attribute => Some((at.x + (v - at.x) * k).to_string()), + (20 | 21, Some(v)) if *attribute => Some((at.y + (v - at.y) * k).to_string()), + _ => None, + }; + if let Some(new) = new { + t.value = new; + } + } + set_default(&mut o, false); + out.scales.insert(scale, ("SCALE".into(), s.clone())); + added.push((s.clone(), o)); + } + } + // One default: the one kept, else the current scale's, else the first. + if !have.iter().chain(&added).any(|(_, o)| is_default(o)) { + let pick = have.iter().chain(&added).position(|(s, _)| *s == current).unwrap_or(0); + if let Some((_, o)) = have.get_mut(pick) { + set_default(o, true); + contexts.insert(o.handle.hex(), o.clone()); + } else if let Some((_, o)) = added.get_mut(pick.saturating_sub(have.len())) { + set_default(o, true); + } + } + if added.is_empty() { + continue; + } + // The dictionary lists the new contexts (as `*A`, after its own). + let Some(mut dobj) = contexts.get(dict).or_else(|| f.objects.iter().find(|o| o.handle.hex() == *dict)).cloned() else { continue }; + let mut n = dobj + .tags + .iter() + .filter(|t| t.code == 3) + .filter_map(|t| t.value.trim().strip_prefix("*A").and_then(|n| n.parse::().ok())) + .max() + .unwrap_or(0); + let at = dobj.tags.iter().position(|t| t.code >= 1000).unwrap_or(dobj.tags.len()); + let mut entries = Vec::new(); + for (_, o) in &added { + n = n.saturating_add(1); + entries.push(RawTag { code: 3, value: format!("*A{n}") }); + entries.push(RawTag { code: 350, value: o.handle.hex() }); + } + dobj.tags.splice(at..at, entries); + contexts.insert(dict.clone(), dobj); + out.added.extend(added.into_iter().map(|(_, o)| o)); + } + out +} + /// Drop an extension dictionary's modelled entries (key and handle) from its groups (`of_insert`: /// it is a block reference's). fn strip_entries(tags: &mut Vec, of_insert: bool) { @@ -952,6 +1164,8 @@ struct Map<'a> { roles: HashMap, /// Entities in the written file. entities: HashSet, + /// Stand-in handles of the scales new contexts name ([`Reconciled::scales`]). + scales: &'a HashMap, } impl Map<'_> { @@ -965,6 +1179,9 @@ impl Map<'_> { if self.raw.contains(&v) { return self.alive.get(&v).cloned(); } + if let Some(role) = self.scales.get(&v) { + return self.roles.get(role).cloned(); + } let h = handle(&v)?; if let Some(role) = self.f.targets.get(&h) { return self.roles.get(role).cloned(); @@ -1045,12 +1262,19 @@ impl Map<'_> { } /// The extras of a written record, if the drawing keeps any for it. -fn extra_for<'a>(f: &'a Foreign, xd: &XdataOf, rec: &Rec, body: &[Tag], block: &str) -> Option> { +fn extra_for<'a>( + f: &'a Foreign, + xd: &XdataOf, + attribs: &HashMap, + rec: &Rec, + body: &[Tag], + block: &str, +) -> Option> { match (rec.sec.as_str(), rec.kind.as_str()) { ("BLOCKS", "BLOCK") => f.records.get(&("BLOCK".to_string(), block.to_string())).map(Cow::Borrowed), ("BLOCKS", "ENDBLK") => None, // An attribute by its reference and tag (its handle is new). - ("ENTITIES" | "BLOCKS", "ATTRIB") => f.records.get(&("ATTRIB".to_string(), attrib_key(body))).map(Cow::Borrowed), + ("ENTITIES" | "BLOCKS", "ATTRIB") => f.records.get(&("ATTRIB".to_string(), attribs.get(&rec.start)?.clone())).map(Cow::Borrowed), ("ENTITIES" | "BLOCKS", _) => entity_extra(f, xd, handle(&head(body).handle?)?), ("TABLES", kind) => { let name = up(&val(body, 2).unwrap_or_default()); @@ -1130,6 +1354,9 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let root = objects.first().filter(|(k, _, _)| is_dictionary(k)).map(|(_, s, _)| *s); let root_keys: HashSet = objects.iter().find(|(_, s, _)| Some(*s) == root).map(|(_, _, t)| entries(t).into_iter().map(|(k, _)| up(&k)).collect()).unwrap_or_default(); + // The written attributes' identities, by record. + let attrib_recs: Vec<&Rec> = recs.iter().filter(|r| matches!(r.sec.as_str(), "ENTITIES" | "BLOCKS") && r.kind == "ATTRIB").collect(); + let attribs: HashMap = attrib_recs.iter().map(|r| r.start).zip(attrib_keys(attrib_recs.iter().map(|r| body(r)))).collect(); // Extension dictionaries that go on a written record (one without its own). let mut block = String::new(); let mut attached: HashSet = HashSet::new(); @@ -1137,7 +1364,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { if r.kind == "BLOCK" { block = up(&val(body(r), 2).unwrap_or_default()); } - if let Some(x) = extra_for(f, &xd, r, body(r), &block) + if let Some(x) = extra_for(f, &xd, &attribs, r, body(r), &block) && let Some(xd) = x.xdict && head(body(r)).xdict.is_none() { @@ -1148,11 +1375,9 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let x = head(t.get(1..).unwrap_or(&[])).handle.and_then(|h| handle(&h)).and_then(|h| entity_extra(f, &xd, h)); attached.extend(x.and_then(|x| x.xdict).map(Handle::hex)); } - // Which kept objects are written: those whose owner chain ends at a written owner. - let objs: HashMap = f.objects.iter().map(|o| (o.handle.hex(), o)).collect(); let dict_entries: HashMap = f.dictionary.iter().map(|(k, h)| (h.hex(), k.as_str())).collect(); let nod = f.targets.iter().filter(|(_, k)| k.0 == "NOD" && k.1.is_empty()).map(|(h, _)| h.hex()).collect::>(); - let owners: HashMap = f + let mut owners: HashMap = f .objects .iter() .filter_map(|o| Some((o.handle.hex(), head(&o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect::>()).owner?))) @@ -1161,11 +1386,21 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let mut contexts = block_contexts(f, d, &owners); let attribute = attribute_contexts(f, d, &owners, &contexts); contexts.extend(attribute); + // In line with the drawing's scales and each reference's. + let rec = reconcile(f, d, &owners, &roles, &mut contexts); + let all: Vec<&ForeignObject> = f.objects.iter().chain(&rec.added).collect(); + for o in &rec.added { + if let Some(parent) = o.tags.iter().find(|t| t.code == 330) { + owners.insert(o.handle.hex(), norm(&parent.value)); + } + } + // Which kept objects are written: those whose owner chain ends at a written owner. + let objs: HashMap = all.iter().map(|o| (o.handle.hex(), *o)).collect(); let mut alive_memo: HashMap = HashMap::new(); for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) { alive_memo.insert(o.handle.hex(), false); } - for o in &f.objects { + for o in &all { let mut path: Vec = Vec::new(); let mut cur = o.handle.hex(); let verdict = loop { @@ -1193,15 +1428,18 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { alive_memo.insert(p, verdict); } } + for h in &rec.dropped { + alive_memo.insert(h.clone(), false); + } // New handles for the written kept objects, above every written handle and the seed. let mut next = seed(tags).max(max_handle(tags).saturating_add(1)); let mut alive: HashMap = HashMap::new(); - for o in f.objects.iter().filter(|o| alive_memo.get(&o.handle.hex()) == Some(&true)) { + for o in all.iter().filter(|o| alive_memo.get(&o.handle.hex()) == Some(&true)) { alive.insert(o.handle.hex(), format!("{next:X}")); next = next.saturating_add(1); } let entities: HashSet = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect(); - let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities }; + let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities, scales: &rec.scales }; let mut out: Vec = Vec::with_capacity(tags.len() + f.objects.iter().map(|o| o.tags.len() + 1).sum::()); let mut block = String::new(); for r in &recs { @@ -1216,8 +1454,8 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { } } if r.kind == "ENDSEC" && r.sec == "OBJECTS" { - for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex())) { - let o = contexts.get(&o.handle.hex()).unwrap_or(o); + for o in all.iter().filter(|o| map.alive.contains_key(&o.handle.hex())) { + let o = contexts.get(&o.handle.hex()).unwrap_or(*o); let number = is_proxy(&o.kind).then(|| renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str()))))).flatten(); match number { Some(n) => { @@ -1238,7 +1476,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { record(&map, &ur, ub, x.as_deref(), true, false, &mut out); } out.extend(tags.get(r.start).cloned()); - let x = extra_for(f, &xd, r, b, &block); + let x = extra_for(f, &xd, &attribs, r, b, &block); if x.is_none() && Some(r.start) != root { out.extend(b.iter().cloned()); continue; diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index 6c3cff476..56f502db4 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -440,3 +440,125 @@ fn a_reference_s_contexts_survive_dwg() { assert!((rot - 30.0).abs() < 1e-9 && (sx - want).abs() < 1e-9, "{ctx:?}"); } } + +/// Every written ACDB_ANNOTATIONSCALES dictionary entry names a written context, and every +/// written context is listed once. +fn listed_contexts(text: &str) -> usize { + let recs = records(text); + let handles: std::collections::HashSet<&str> = + recs.iter().filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")).filter_map(|(_, t)| get(t, 5)).collect(); + let mut listed = 0; + for (_, t) in recs.iter().filter(|(k, _)| k == "DICTIONARY") { + for (c, v) in t { + if *c == 350 && handles.contains(v.as_str()) { + listed += 1; + } + } + } + assert_eq!(listed, handles.len(), "contexts listed in their dictionaries"); + listed +} + +#[test] +fn a_context_whose_scale_was_deleted_is_not_written() { + let mut d = read(); + d.scales.retain(|s| s.name != "1:1"); + let text = write_dxf(&d); + let ctx = contexts(&text); + assert_eq!(ctx.iter().map(|c| (c.0.as_str(), c.1)).collect::>(), [("1:5", true)]); + let actx = attribute_contexts(&text); + assert_eq!(actx.iter().map(|c| c.0.as_str()).collect::>(), ["1:5"]); + assert_eq!(listed_contexts(&text), 2); +} + +#[test] +fn an_annotative_reference_s_contexts_follow_its_scales() { + // CADCraft's model makes the reference annotative at 1:5 and a new 1:2 (1:1 no longer): + // the 1:1 contexts go, 1:2 ones are made from the default 1:5 ones, scaled 2/5 about the + // reference's insertion point. + let mut d = read(); + let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0); + d.scales.push(half.clone()); + let five = d.scales.iter().find(|s| s.name == "1:5").cloned().unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| e.common.anno_scales = vec![five, half]).unwrap(); + let text = write_dxf(&d); + let mut ctx = contexts(&text); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect(); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!((got[0].0.as_str(), got[0].1), ("1:2", false)); + assert!((got[0].2 - 2.0).abs() < 1e-9, "{got:?}"); + assert_eq!(got[1], ("1:5".to_string(), true, 5.0)); + assert!(ctx.iter().all(|c| c.2 == Vec2::new(10.0, 20.0))); + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx.len(), 2, "{actx:?}"); + assert_eq!(actx[0].0, "1:2"); + assert!((actx[0].1 - Vec2::new(12.0, 24.0)).len() < 1e-9, "{actx:?}"); + assert_eq!(actx[1], ("1:5".to_string(), Vec2::new(15.0, 30.0))); + assert_eq!(listed_contexts(&text), 4); + // Read back, the reference keeps them (and nothing points at a missing scale). + let back = read_dxf(text.as_bytes()).unwrap(); + assert!(contexts(&write_dxf(&back)).iter().all(|c| c.0 != "?")); +} + +#[test] +fn two_attributes_with_one_tag_keep_their_own_contexts() { + // A second attribute TAG on the reference, with its own extension dictionary (no contexts + // in it): each written ATTRIB gets its own dictionary, the first keeps the contexts. + let second = " +0 ATTRIB +5 80 +102 {ACAD_XDICTIONARY +360 81 +102 } +330 40 +100 AcDbEntity +8 0 +100 AcDbText +10 1 +20 2 +30 0 +40 1 +1 Y +100 AcDbAttribute +2 TAG +70 0 +0 SEQEND"; + let objs = " +0 DICTIONARY +5 81 +330 80 +100 AcDbDictionary +280 1 +281 1 +3 OTHER +360 82 +0 XRECORD +5 82 +330 81 +100 AcDbXrecord +1 kept +0 ENDSEC +0 EOF"; + let src = FIXTURE.replacen("0 SEQEND", second, 1); + let at = src.rfind("0 ENDSEC").unwrap(); + let src = format!("{}{objs}", &src[..at]); + let d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let text = write_dxf(&d); + let recs = records(&text); + let xdict = |t: &[(i32, String)]| { + let i = t.iter().position(|(c, v)| *c == 102 && v == "{ACAD_XDICTIONARY")?; + t.get(i + 1).map(|(_, v)| v.clone()) + }; + let attribs: Vec<(String, Option)> = + recs.iter().filter(|(k, _)| k == "ATTRIB").map(|(_, t)| (get(t, 1).unwrap_or_default().to_string(), xdict(t))).collect(); + assert_eq!(attribs.len(), 2, "{attribs:?}"); + let (x, y) = (attribs[0].1.clone().unwrap(), attribs[1].1.clone().unwrap()); + assert_ne!(x, y, "{attribs:?}"); + // The first attribute's dictionary leads to its contexts, the second's to the xrecord. + let owner_of = |h: &str| recs.iter().find(|(_, t)| get(t, 5) == Some(h)).and_then(|(_, t)| get(t, 330)).map(str::to_string); + let xrec = recs.iter().find(|(k, t)| k == "XRECORD" && get(t, 1) == Some("kept")).map(|(_, t)| get(t, 5).unwrap().to_string()).unwrap(); + assert_eq!(owner_of(&xrec), Some(y)); + assert_eq!(attribute_contexts(&text).len(), 2); +} From 97e225f324570ad33a2893b1b9db5c22fdeb1524 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:12:07 -0600 Subject: [PATCH 008/258] DXF: new reference contexts come from one whose scale is still written When the default context's scale had been deleted from the drawing's list, a reference CADCraft keeps annotative got no new contexts for its added scales; the template is now its default context, else its first, among those whose SCALE is written. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 6 +++-- crates/io/tests/annotative_block_contexts.rs | 25 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 5a6d291c4..f52cd9d07 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -959,10 +959,12 @@ fn reconcile( next = next.saturating_add(1); format!("{next:X}") }; - // Each annotative reference's default context: (scale, insertion point). + // Each reference's template for new contexts: (scale, insertion point) of its default + // context, else of its first, among those whose scale is still written. let mut ref_default: HashMap = HashMap::new(); for (r, attribute, list) in groups.values() { - if let (false, Some(def)) = (attribute, list.iter().find(|o| is_default(o)).or(list.first())) + let written: Vec<&ForeignObject> = list.iter().filter(|o| scale_of(o).is_some()).collect(); + if let (false, Some(def)) = (attribute, written.iter().find(|o| is_default(o)).or(written.first())) && let (Some(s), Some(x), Some(y)) = (scale_of(def), num(def, 10), num(def, 20)) { ref_default.insert(*r, (s, Vec2::new(x, y))); diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index 56f502db4..f3c740d97 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -562,3 +562,28 @@ fn two_attributes_with_one_tag_keep_their_own_contexts() { assert_eq!(owner_of(&xrec), Some(y)); assert_eq!(attribute_contexts(&text).len(), 2); } + +#[test] +fn new_contexts_come_from_one_whose_scale_remains() { + // The default context's scale (1:5) is deleted, and the reference is annotative at 1:1 and a + // new 1:2: the 1:2 contexts are made from the 1:1 ones (scale 1 → 2 about the insertion + // point), and 1:1 becomes the default. + let mut d = read(); + let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0); + d.scales.retain(|s| s.name != "1:5"); + d.scales.push(half.clone()); + let one = d.scales.iter().find(|s| s.name == "1:1").cloned().unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| e.common.anno_scales = vec![one, half]).unwrap(); + let text = write_dxf(&d); + let mut ctx = contexts(&text); + ctx.sort_by(|a, b| a.0.cmp(&b.0)); + let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect(); + assert_eq!(got, [("1:1".to_string(), true, 1.0), ("1:2".to_string(), false, 2.0)]); + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx.len(), 2, "{actx:?}"); + assert_eq!(actx[0], ("1:1".to_string(), Vec2::new(11.0, 22.0))); + assert_eq!(actx[1].0, "1:2"); + assert!((actx[1].1 - Vec2::new(12.0, 24.0)).len() < 1e-9, "{actx:?}"); + assert_eq!(listed_contexts(&text), 4); +} From 37bf128ffde672f64f0945f7ce8dd3aa38ab9bdc Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:01:39 -0600 Subject: [PATCH 009/258] DXF: kept reference contexts follow the reference as read; one default rule A kept context is brought up to date by what its block reference did since the file was read. That baseline was the default context, which needn't be where the reference was (an unchanged save then moved every context); the reference and its attributes as read are now kept (`Foreign::placements`) and used, the default context only for data without them. A context's own offset from the reference now scales and mirrors with it (back into the reference's frame then, scaled, turned to its frame now), not only turns. The default context is the one whose first 290 group is 1 everywhere (an attribute context has a later 290 of its own). Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/foreign.rs | 15 ++++ crates/io/src/dxf_raw.rs | 66 ++++++++++++---- crates/io/tests/annotative_block_contexts.rs | 81 ++++++++++++++++++++ 3 files changed, 147 insertions(+), 15 deletions(-) diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index e0ebb81a4..84ca2031b 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -75,6 +75,20 @@ pub struct Foreign { /// surfaces, which from 2013 on those entities don't carry themselves: each `ACDSRECORD` /// names its entity with a 320 handle (see [`Foreign::data_store_entities`]). pub data_store: Vec, + /// Block references with kept annotation scale contexts, as they were read: what a context + /// is brought up to date from (see [`KeptPlacement`]), by handle. + pub placements: BTreeMap, +} + +/// A block reference as read: its insertion point, rotation (radians) and scale, and each of its +/// attributes' insertion and alignment points, in order. Its kept contexts were written for it +/// then; what it did since moves them. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct KeptPlacement { + pub insert: crate::geom::Vec3, + pub rotation: f64, + pub scale: crate::geom::Vec3, + pub attribs: Vec<(crate::geom::Vec3, crate::geom::Vec3)>, } impl Foreign { @@ -87,6 +101,7 @@ impl Foreign { && self.targets.is_empty() && self.class_order.is_empty() && self.data_store.is_empty() + && self.placements.is_empty() } /// The entities the data store has records for (their 320 handles). diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index f52cd9d07..d25aac64e 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -430,6 +430,17 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { f.records.entry(key).or_insert(x); } } + // Block references whose extension dictionaries are kept (their annotation scale contexts), + // as read. + for e in all_entities(d) { + if let EntityKind::Insert(ins) = &e.kind + && f.entities.get(&e.handle).is_some_and(|x| x.xdict.is_some()) + { + let attribs = ins.attribs.iter().map(|a| (a.text.insert, a.text.align_pt.unwrap_or(a.text.insert))).collect(); + f.placements + .insert(e.handle, cadcraft_doc::foreign::KeptPlacement { insert: ins.insert, rotation: ins.rotation, scale: ins.scale, attribs }); + } + } // The classes of kept objects and of entities of types CADCraft doesn't model. let mut types: HashSet = f.objects.iter().map(|o| up(&o.kind)).collect(); types.extend(all_entities(d).filter_map(|e| match &e.kind { @@ -714,22 +725,36 @@ fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> let mut out = HashMap::new(); for list in by_parent.values() { let Some(first) = list.first() else { continue }; - let Some(EntityKind::Insert(ins)) = owner_entity(&first.handle.hex()).and_then(|h| d.entity(h)).map(|e| &e.kind) else { continue }; - let def = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).unwrap_or(first); - let (Some(x0), Some(y0)) = (num(def, 10), num(def, 20)) else { continue }; - let turn = (ins.rotation.to_degrees() - num(def, 50).unwrap_or(0.0)).to_radians(); - let at0 = cadcraft_doc::geom::Vec2::new(x0, y0); - let ratio = |code: i32, now: f64| num(def, code).filter(|s| s.abs() > 1e-12).map_or(1.0, |s| now / s); - let ratios = [(41, ratio(41, ins.scale.x)), (42, ratio(42, ins.scale.y)), (43, ratio(43, ins.scale.z))]; + let Some(h) = owner_entity(&first.handle.hex()) else { continue }; + let Some(EntityKind::Insert(ins)) = d.entity(h).map(|e| &e.kind) else { continue }; + // The reference as read: kept when it was read, else (data made before that was kept) + // its default context. + let (at0, rot0, scale0) = match f.placements.get(&h) { + Some(p) => (p.insert.xy(), p.rotation, [p.scale.x, p.scale.y, p.scale.z]), + None => { + let def = list.iter().find(|o| is_default(o)).unwrap_or(first); + let (Some(x0), Some(y0)) = (num(def, 10), num(def, 20)) else { continue }; + let s = |code: i32, now: f64| num(def, code).unwrap_or(now); + let rot = num(def, 50).unwrap_or(0.0).to_radians(); + (cadcraft_doc::geom::Vec2::new(x0, y0), rot, [s(41, ins.scale.x), s(42, ins.scale.y), s(43, ins.scale.z)]) + } + }; + let turn = ins.rotation - rot0; + let ratio = |then: f64, now: f64| if then.abs() > 1e-12 { now / then } else { 1.0 }; + let ratios = [(41, ratio(scale0[0], ins.scale.x)), (42, ratio(scale0[1], ins.scale.y)), (43, ratio(scale0[2], ins.scale.z))]; let unchanged = (ins.insert.xy() - at0).len() < 1e-9 && turn.abs() < 1e-12 && ratios.iter().all(|(_, r)| (r - 1.0).abs() < 1e-12); if unchanged || !ratios.iter().all(|(_, r)| r.is_finite()) || !turn.is_finite() { continue; } for c in list { let mut o = (*c).clone(); - // Its offset from the default context turns with the reference. + // Its offset from where the reference was moves as the reference did: back into the + // reference's frame then, scaled (a mirror flips it), turned to its frame now. let at = match (num(c, 10), num(c, 20)) { - (Some(x), Some(y)) => ins.insert.xy() + (cadcraft_doc::geom::Vec2::new(x, y) - at0).rotate(turn), + (Some(x), Some(y)) => { + let off = (cadcraft_doc::geom::Vec2::new(x, y) - at0).rotate(-rot0); + ins.insert.xy() + cadcraft_doc::geom::Vec2::new(off.x * ratios[0].1, off.y * ratios[1].1).rotate(ins.rotation) + } _ => ins.insert.xy(), }; for t in &mut o.tags { @@ -817,19 +842,25 @@ fn attribute_contexts( for (xd, list) in &by_attrib { let Some((r, tag, nth)) = attribs.get(xd) else { continue }; let Some(EntityKind::Insert(ins)) = d.entity(*r).map(|e| &e.kind) else { continue }; - let Some(a) = ins.attribs.iter().filter(|a| up(&a.tag) == *tag).nth(*nth) else { continue }; + let Some((index, a)) = ins.attribs.iter().enumerate().filter(|(_, a)| up(&a.tag) == *tag).nth(*nth) else { continue }; let base = d.block(&ins.block).map(|b| b.base.xy()).unwrap_or_default(); let Some(to_block_now) = ins.transform(base).inverse() else { continue }; - let Some(def) = list.iter().find(|o| o.tags.iter().any(|t| t.code == 290 && t.value.trim() == "1")).or(list.first()) else { continue }; + let Some(def) = list.iter().find(|o| is_default(o)).or(list.first()) else { continue }; let at = |o: &ForeignObject, x: i32| Some(Vec2::new(num(o, x)?, num(o, x + 10)?)); // What the attribute did in the block since: its default context then, the attribute now. let Some(def_place) = text(def, 340).and_then(|s| read.get(&(*r, s))).copied() else { continue }; let Some(to_block_then) = matrix(ins, base, def_place).inverse() else { continue }; let now_ins = to_block_now.apply(a.text.insert.xy()); let now_align = to_block_now.apply(a.text.align_pt.unwrap_or(a.text.insert).xy()); - let (Some(then_ins), Some(then_align)) = (at(def, 10).map(|p| to_block_then.apply(p)), at(def, 11).map(|p| to_block_then.apply(p))) else { - continue; - }; + // The attribute as read, in its reference as read, when that was kept; else its default + // context in the reference's. + let kept = f.placements.get(r).and_then(|p| { + let (ins_then, align_then) = p.attribs.get(index)?; + let then = matrix(ins, base, (p.insert.xy(), p.rotation.to_degrees(), (p.scale.x, p.scale.y))).inverse()?; + Some((then.apply(ins_then.xy()), then.apply(align_then.xy()))) + }); + let then = kept.or_else(|| Some((to_block_then.apply(at(def, 10)?), to_block_then.apply(at(def, 11)?)))); + let Some((then_ins, then_align)) = then else { continue }; let turn = (a.text.rotation.to_degrees() - ins.rotation.to_degrees()) - (num(def, 50).unwrap_or(0.0) - def_place.1); for c in list { let Some(s) = text(c, 340) else { continue }; @@ -864,6 +895,12 @@ fn attribute_contexts( out } +/// Whether a kept context is its object's default one: its first 290 group (of +/// AcDbObjectContextData) is 1. An attribute context has a later 290 group of its own. +fn is_default(o: &ForeignObject) -> bool { + o.tags.iter().find(|t| t.code == 290).is_some_and(|t| t.value.trim() == "1") +} + fn is_blkref_context(kind: &str) -> bool { kind.eq_ignore_ascii_case("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS") } @@ -924,7 +961,6 @@ fn reconcile( let k = f.targets.get(&handle(&norm(&v.value))?)?; (k.0 == "SCALE" && roles.contains_key(k)).then(|| k.1.clone()) }; - let is_default = |o: &ForeignObject| o.tags.iter().find(|t| t.code == 290).is_some_and(|t| t.value.trim() == "1"); let set_default = |o: &mut ForeignObject, on: bool| { if let Some(t) = o.tags.iter_mut().find(|t| t.code == 290) { t.value = if on { "1" } else { "0" }.into(); diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index f3c740d97..0a9746735 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -587,3 +587,84 @@ fn new_contexts_come_from_one_whose_scale_remains() { assert!((actx[1].1 - Vec2::new(12.0, 24.0)).len() < 1e-9, "{actx:?}"); assert_eq!(listed_contexts(&text), 4); } + +/// The written context of the block reference at scale `name`: (insertion, rotation). +fn context_at(text: &str, name: &str) -> (Vec2, f64) { + contexts(text).into_iter().find(|c| c.0 == name).map(|c| (c.2, c.3)).unwrap() +} + +#[test] +fn an_unchanged_reference_keeps_its_contexts_when_its_default_one_is_elsewhere() { + // The reference sits at (11, 20) while its default context says (10, 20): saved unchanged, + // every context is written as read (what moves them is what the reference did since). + let d = read_dxf(dxf(&FIXTURE.replace("2 SIGN\n10 10\n20 20\n30 0\n41 5", "2 SIGN\n10 11\n20 20\n30 0\n41 5")).as_bytes()).unwrap(); + let text = write_dxf(&d); + for scale in ["1:1", "1:5"] { + assert_eq!(context_at(&text, scale).0, Vec2::new(10.0, 20.0), "{scale}"); + } + let mut actx = attribute_contexts(&text); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]); +} + +#[test] +fn a_context_s_own_offset_scales_turns_and_mirrors_with_the_reference() { + // The 1:1 context sits 2 to the right of the reference. Scaled 2 and turned 90°, it is 4 + // above; mirrored (x scale -5), 2 to the left. + let src = FIXTURE.replace("340 51\n50 0\n10 10", "340 51\n50 0\n10 12"); + let edit = |f: &dyn Fn(&mut cadcraft_doc::Insert)| { + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + f(i); + } + }) + .unwrap(); + write_dxf(&d) + }; + let near = |p: Vec2, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9; + let text = edit(&|i| { + i.scale = i.scale * 2.0; + i.rotation = 90f64.to_radians(); + }); + let (at, rot) = context_at(&text, "1:1"); + assert!(near(at, 10.0, 24.0) && (rot - 90.0).abs() < 1e-9, "{at:?} {rot}"); + let text = edit(&|i| i.scale.x = -i.scale.x); + let (at, _) = context_at(&text, "1:1"); + assert!(near(at, 8.0, 20.0), "{at:?}"); +} + +#[test] +fn the_default_context_is_the_one_whose_first_290_is_1() { + // The 1:1 attribute context comes first, turned 10° in its reference, with its own later + // 290 set: the 1:5 one is still the default, so an unchanged save keeps the 10°. + let at = FIXTURE.find("0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS\n5 76").unwrap(); + let end = FIXTURE.find("0 ENDSEC\n0 EOF").unwrap(); + let second = FIXTURE[at..end].replace("50 0\n10 11", "50 10\n10 11").replace("21 22\n290 0", "21 22\n290 1"); + let first = FIXTURE.find("0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS\n5 75").unwrap(); + let src = format!("{}{second}{}{}", &FIXTURE[..first], &FIXTURE[first..at], &FIXTURE[end..]); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + // Moved, so the attribute contexts are brought up to date. + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + for a in &mut i.attribs { + a.text.insert = a.text.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0); + a.text.align_pt = Some(a.text.insert); + } + } + }) + .unwrap(); + let text = write_dxf(&d); + let recs = records(&text); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let rot = recs + .iter() + .filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS") + .find(|(_, t)| get(t, 340).and_then(|h| scales.get(h)) == Some(&"1:1")) + .and_then(|(_, t)| get(t, 50)) + .and_then(|v| v.parse::().ok()) + .unwrap(); + assert!((rot - 10.0).abs() < 1e-9, "{rot}"); +} From 345b5bc7d6131a3574144cd7fa2e128518c693a9 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:20:00 -0600 Subject: [PATCH 010/258] DXF: new reference contexts take handles above every handle in use Upstream now believes handles above 2^48 (AutoCAD writes them), so new annotation contexts can no longer take stand-in handles from 2^48 up: they start above the written handles, $HANDSEED, the kept objects and their targets. Test: a drawing whose reference sits at 2^48 + 1 gains a scale and every written handle stays unique (red with the old 2^48 base). Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 11 ++++-- crates/io/tests/annotative_block_contexts.rs | 39 ++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index d25aac64e..2aaed0276 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -929,8 +929,8 @@ struct Reconciled { /// Contexts not written: their scale is gone from the drawing's scale list, or their /// reference is annotative in CADCraft's model and no longer supports it. dropped: HashSet, - /// New contexts for the scales such a reference supports without a context, with handles - /// above every file handle ([`MAX_HANDLE`]); their dictionaries list them. + /// New contexts for the scales such a reference supports without a context, with stand-in + /// handles above every handle in use (`above`); their dictionaries list them. added: Vec, /// The SCALE objects the added contexts name (group 340): stand-in handle → the scale's role. scales: HashMap, @@ -943,12 +943,15 @@ struct Reconciled { /// supports: one per new scale is made from its default context, scaled by the ratio of the two /// scales about the reference's insertion point (as AutoCAD adds a scale). One context of each /// reference stays the default (290 = 1). Changed dictionaries and contexts go into `contexts`. +/// New objects take stand-in handles above `above` and the kept objects' and targets' handles +/// (AutoCAD writes handles above 2^48, so no range is free by itself). fn reconcile( f: &Foreign, d: &Drawing, owners: &HashMap, roles: &HashMap, contexts: &mut HashMap, + above: u64, ) -> Reconciled { use cadcraft_doc::geom::Vec2; let mut out = Reconciled::default(); @@ -990,7 +993,7 @@ fn reconcile( let Some(reference) = reference else { continue }; groups.entry(parent.clone()).or_insert((reference, attribute, Vec::new())).2.push(contexts.get(&h).unwrap_or(o).clone()); } - let mut next = MAX_HANDLE; + let mut next = f.objects.iter().map(|o| o.handle.0).chain(f.targets.keys().map(|h| h.0)).fold(above, u64::max); let mut fresh = || { next = next.saturating_add(1); format!("{next:X}") @@ -1425,7 +1428,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let attribute = attribute_contexts(f, d, &owners, &contexts); contexts.extend(attribute); // In line with the drawing's scales and each reference's. - let rec = reconcile(f, d, &owners, &roles, &mut contexts); + let rec = reconcile(f, d, &owners, &roles, &mut contexts, seed(tags).max(max_handle(tags))); let all: Vec<&ForeignObject> = f.objects.iter().chain(&rec.added).collect(); for o in &rec.added { if let Some(parent) = o.tags.iter().find(|t| t.code == 330) { diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index 0a9746735..fc5d944fe 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -502,6 +502,45 @@ fn an_annotative_reference_s_contexts_follow_its_scales() { assert!(contexts(&write_dxf(&back)).iter().all(|c| c.0 != "?")); } +/// The fixture with every handle moved up to just past 2^48 (AutoCAD writes handles that high): +/// the reference (40) lands on 2^48 + 1. +fn far_handles(src: &str) -> String { + const SHIFT: u64 = (1 << 48) - 0x3F; + let is_handle = |code: i32| matches!(code, 5 | 105 | 320..=369 | 390..=399 | 480 | 481 | 1005); + let mut out = String::new(); + for line in src.lines() { + let (code, value) = line.trim().split_once(' ').unwrap_or((line.trim(), "")); + let moved = match (code.parse::(), u64::from_str_radix(value, 16)) { + (Ok(c), Ok(h)) if is_handle(c) && h != 0 => format!("{:X}", h + SHIFT), + _ => value.to_string(), + }; + out.push_str(&format!("{code} {moved}\n")); + } + out +} + +#[test] +fn new_contexts_get_their_own_handles_when_the_file_s_are_above_2_pow_48() { + // As in the test above, but every file handle is above 2^48: the new 1:2 contexts and their + // scale take handles no other object has. + let mut d = read_dxf(dxf(&far_handles(FIXTURE)).as_bytes()).unwrap(); + let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0); + d.scales.push(half.clone()); + let five = d.scales.iter().find(|s| s.name == "1:5").cloned().unwrap(); + let reference = Handle::parse_hex("1000000000001").unwrap(); + d.modify_entity(reference, |e| e.common.anno_scales = vec![five, half]).unwrap(); + let text = write_dxf(&d); + let mut names: Vec = contexts(&text).into_iter().map(|c| c.0).collect(); + names.sort(); + assert_eq!(names, ["1:2", "1:5"]); + assert_eq!(attribute_contexts(&text).len(), 2); + let mut handles: Vec = records(&text).iter().filter_map(|(_, t)| get(t, 5).map(str::to_string)).collect(); + let n = handles.len(); + handles.sort(); + handles.dedup(); + assert_eq!(handles.len(), n, "every written handle is unique"); +} + #[test] fn two_attributes_with_one_tag_keep_their_own_contexts() { // A second attribute TAG on the reference, with its own extension dictionary (no contexts From 75d135c9e211157a6ad220bffbb59ca0f7561128 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:33:25 -0600 Subject: [PATCH 011/258] DXF: an attribute as read is found by its tag and place, and keeps its rotation A kept attribute placement was looked up by its index among the reference's attributes now, which differs once they are reordered or replaced (ATTSYNC). It is now found by tag and place among that tag, like the attribute's contexts. The rotation change is measured from the attribute as read too, not from its default context, so an unchanged save no longer turns every context when the ATTRIB (at the current scale) and the default context differ. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/foreign.rs | 17 +++++++-- crates/io/src/dxf_raw.rs | 29 +++++++++++----- crates/io/tests/annotative_block_contexts.rs | 36 ++++++++++++++++++++ 3 files changed, 70 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 84ca2031b..d5c836873 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -81,14 +81,25 @@ pub struct Foreign { } /// A block reference as read: its insertion point, rotation (radians) and scale, and each of its -/// attributes' insertion and alignment points, in order. Its kept contexts were written for it -/// then; what it did since moves them. +/// attributes as read, in order. Its kept contexts were written for it then; what it did since +/// moves them. #[derive(Clone, Debug, Default, PartialEq)] pub struct KeptPlacement { pub insert: crate::geom::Vec3, pub rotation: f64, pub scale: crate::geom::Vec3, - pub attribs: Vec<(crate::geom::Vec3, crate::geom::Vec3)>, + pub attribs: Vec, +} + +/// An attribute of a block reference as read: its tag, insertion and alignment points and +/// rotation (radians). Found again by tag and place among the reference's attributes with that +/// tag, since the attributes can be reordered or replaced (ATTSYNC) after the file is read. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct KeptAttrib { + pub tag: String, + pub insert: crate::geom::Vec3, + pub align: crate::geom::Vec3, + pub rotation: f64, } impl Foreign { diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 2aaed0276..fa6576cf0 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -436,7 +436,16 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { if let EntityKind::Insert(ins) = &e.kind && f.entities.get(&e.handle).is_some_and(|x| x.xdict.is_some()) { - let attribs = ins.attribs.iter().map(|a| (a.text.insert, a.text.align_pt.unwrap_or(a.text.insert))).collect(); + let attribs = ins + .attribs + .iter() + .map(|a| cadcraft_doc::foreign::KeptAttrib { + tag: a.tag.clone(), + insert: a.text.insert, + align: a.text.align_pt.unwrap_or(a.text.insert), + rotation: a.text.rotation, + }) + .collect(); f.placements .insert(e.handle, cadcraft_doc::foreign::KeptPlacement { insert: ins.insert, rotation: ins.rotation, scale: ins.scale, attribs }); } @@ -842,7 +851,7 @@ fn attribute_contexts( for (xd, list) in &by_attrib { let Some((r, tag, nth)) = attribs.get(xd) else { continue }; let Some(EntityKind::Insert(ins)) = d.entity(*r).map(|e| &e.kind) else { continue }; - let Some((index, a)) = ins.attribs.iter().enumerate().filter(|(_, a)| up(&a.tag) == *tag).nth(*nth) else { continue }; + let Some(a) = ins.attribs.iter().filter(|a| up(&a.tag) == *tag).nth(*nth) else { continue }; let base = d.block(&ins.block).map(|b| b.base.xy()).unwrap_or_default(); let Some(to_block_now) = ins.transform(base).inverse() else { continue }; let Some(def) = list.iter().find(|o| is_default(o)).or(list.first()) else { continue }; @@ -852,16 +861,18 @@ fn attribute_contexts( let Some(to_block_then) = matrix(ins, base, def_place).inverse() else { continue }; let now_ins = to_block_now.apply(a.text.insert.xy()); let now_align = to_block_now.apply(a.text.align_pt.unwrap_or(a.text.insert).xy()); - // The attribute as read, in its reference as read, when that was kept; else its default - // context in the reference's. + // The attribute as read (the same tag and place among its tag), in its reference as read, + // when that was kept: its points in the block and its rotation from the reference's + // (degrees). Else its default context in the reference's. let kept = f.placements.get(r).and_then(|p| { - let (ins_then, align_then) = p.attribs.get(index)?; + let k = p.attribs.iter().filter(|k| up(&k.tag) == *tag).nth(*nth)?; let then = matrix(ins, base, (p.insert.xy(), p.rotation.to_degrees(), (p.scale.x, p.scale.y))).inverse()?; - Some((then.apply(ins_then.xy()), then.apply(align_then.xy()))) + Some((then.apply(k.insert.xy()), then.apply(k.align.xy()), k.rotation.to_degrees() - p.rotation.to_degrees())) }); - let then = kept.or_else(|| Some((to_block_then.apply(at(def, 10)?), to_block_then.apply(at(def, 11)?)))); - let Some((then_ins, then_align)) = then else { continue }; - let turn = (a.text.rotation.to_degrees() - ins.rotation.to_degrees()) - (num(def, 50).unwrap_or(0.0) - def_place.1); + let then = + kept.or_else(|| Some((to_block_then.apply(at(def, 10)?), to_block_then.apply(at(def, 11)?), num(def, 50).unwrap_or(0.0) - def_place.1))); + let Some((then_ins, then_align, then_turn)) = then else { continue }; + let turn = (a.text.rotation.to_degrees() - ins.rotation.to_degrees()) - then_turn; for c in list { let Some(s) = text(c, 340) else { continue }; let (Some(was), Some(is)) = (read.get(&(*r, s.clone())).copied(), now.get(&(*r, s)).copied()) else { continue }; diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index fc5d944fe..cbe069eb0 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -707,3 +707,39 @@ fn the_default_context_is_the_one_whose_first_290_is_1() { .unwrap(); assert!((rot - 10.0).abs() < 1e-9, "{rot}"); } + +#[test] +fn an_unchanged_attribute_turned_at_the_current_scale_keeps_its_contexts_rotation() { + // The ATTRIB is turned 20° (it is the attribute at the file's current scale) while its default + // context says 0°: saved unchanged, no context turns (what turns them is what the attribute + // did since it was read). + let d = read_dxf(dxf(&FIXTURE.replace("1 X\n", "1 X\n50 20\n")).as_bytes()).unwrap(); + let text = write_dxf(&d); + let rots: Vec = records(&text) + .iter() + .filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS") + .filter_map(|(_, t)| get(t, 50).and_then(|v| v.parse::().ok())) + .collect(); + assert_eq!(rots.len(), 2, "{rots:?}"); + assert!(rots.iter().all(|r| r.abs() < 1e-9), "{rots:?}"); +} + +#[test] +fn an_attribute_s_contexts_stay_when_the_reference_s_attributes_are_reordered() { + // A second attribute OTHER after TAG, then the reference's attributes reversed (as a block + // redefinition's attribute sync can): TAG is found as read by its tag, so saved otherwise + // unchanged its contexts don't move. + let other = "1 X\n100 AcDbAttribute\n2 TAG\n70 0\n0 ATTRIB\n5 80\n330 40\n100 AcDbEntity\n8 0\n100 AcDbText\n10 1\n20 2\n30 0\n40 1\n1 Y\n100 AcDbAttribute\n2 OTHER\n70 0\n"; + let src = FIXTURE.replacen("1 X\n100 AcDbAttribute\n2 TAG\n70 0\n", other, 1); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + d.modify_entity(Handle::parse_hex("40").unwrap(), |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + assert_eq!(i.attribs.len(), 2); + i.attribs.reverse(); + } + }) + .unwrap(); + let mut actx = attribute_contexts(&write_dxf(&d)); + actx.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]); +} From 0a6d97969b21ba1a825a59b2e7697da6eeeb54ca Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:21:44 -0600 Subject: [PATCH 012/258] DXF: the kept-context code in read and finish moves into helpers main now denies cognitive_complexity over 30 and too_many_arguments over 7. This PR's additions took read to 32 and finish to 31, and retained_objects to 8 arguments: the block-reference and attribute bookkeeping now lives in insert_handles, of_insert, keep_attrib_dictionaries, keep_placements, written_attribs and refreshed_contexts, and retained_objects takes the root and its entries as one pair. Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/dxf_raw.rs | 134 +++++++++++++++--------- crates/io/src/dxf_read/tables.rs | 4 +- crates/io/tests/it/roundtrip/compare.rs | 2 + 3 files changed, 86 insertions(+), 54 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index fa6576cf0..95d3ade50 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -47,6 +47,17 @@ const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCO /// when written ([`block_contexts`]). const CONTEXTS_KEY: &str = "ACDBCONTEXTDATAMANAGER"; +/// The handles of the drawing's block references. +fn insert_handles(d: &Drawing) -> HashSet { + all_entities(d).filter(|e| matches!(e.kind, EntityKind::Insert(_))).map(|e| e.handle.hex()).collect() +} + +/// Whether the object `tags` belongs to a block reference (`inserts`) or one of its attributes +/// (an ATTRIB in `ids`): their extension dictionaries keep annotation scale contexts. +fn of_insert(tags: &[Tag], inserts: &HashSet, ids: &HashMap) -> bool { + head(tags).owner.is_some_and(|o| inserts.contains(&o) || ids.get(&o).is_some_and(|k| k.0 == "ATTRIB")) +} + /// Whether extension dictionary entry `key` is left to CADCraft's model, in the extension /// dictionary of a block reference (`of_insert`) or of something else. fn modelled_xdict_key(key: &str, of_insert: bool) -> bool { @@ -374,8 +385,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { }; // Block references and their attributes (their extension dictionaries keep annotation scale // contexts). - let inserts: HashSet = all_entities(d).filter(|e| matches!(e.kind, EntityKind::Insert(_))).map(|e| e.handle.hex()).collect(); - let of_insert = |t: &[Tag]| head(t).owner.is_some_and(|o| inserts.contains(&o) || ids.get(&o).is_some_and(|k| k.0 == "ATTRIB")); + let inserts = insert_handles(d); let memo = retained_objects(&objects, &ents, &ids, &by_handle, (root.as_deref(), &root_entries), &xdict_of, &inserts); let mut f = Foreign::default(); let mut kept: HashSet = HashSet::new(); @@ -386,7 +396,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { let Some(h) = head(t).handle.and_then(|h| handle(&h)) else { continue }; let mut tags: Vec = t.iter().map(raw).collect(); if is_xdict(i) { - strip_entries(&mut tags, of_insert(t)); + strip_entries(&mut tags, of_insert(t, &inserts, &ids)); } if head(t).owner == root && let Some(key) = root_key(&h.hex()) @@ -416,13 +426,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { } } put_xdata(d, xdata_of); - // Attributes' extension dictionaries (their annotation scale contexts), by attribute. - let attribs: Vec<&[Tag]> = blocks.iter().chain(&entities).filter(|(k, _, _)| k == "ATTRIB").map(|(_, _, t)| *t).collect(); - for (t, key) in attribs.iter().zip(attrib_keys(attribs.iter().copied())) { - if let Some(xd) = head(t).xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)) { - f.records.entry(("ATTRIB".into(), key)).or_insert(ForeignExtra { xdict: Some(xd), ..ForeignExtra::default() }); - } - } + keep_attrib_dictionaries(&mut f, (&blocks, &entities), &kept); for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| k == "BLOCK")) { let Some(key) = head(t).handle.and_then(|h| ids.get(&h).cloned()) else { continue }; let x = extra(kind, t, kind == "BLOCK", false, &kept); @@ -430,26 +434,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { f.records.entry(key).or_insert(x); } } - // Block references whose extension dictionaries are kept (their annotation scale contexts), - // as read. - for e in all_entities(d) { - if let EntityKind::Insert(ins) = &e.kind - && f.entities.get(&e.handle).is_some_and(|x| x.xdict.is_some()) - { - let attribs = ins - .attribs - .iter() - .map(|a| cadcraft_doc::foreign::KeptAttrib { - tag: a.tag.clone(), - insert: a.text.insert, - align: a.text.align_pt.unwrap_or(a.text.insert), - rotation: a.text.rotation, - }) - .collect(); - f.placements - .insert(e.handle, cadcraft_doc::foreign::KeptPlacement { insert: ins.insert, rotation: ins.rotation, scale: ins.scale, attribs }); - } - } + keep_placements(&mut f, d); // The classes of kept objects and of entities of types CADCraft doesn't model. let mut types: HashSet = f.objects.iter().map(|o| up(&o.kind)).collect(); types.extend(all_entities(d).filter_map(|e| match &e.kind { @@ -538,6 +523,39 @@ fn extension_dictionaries( dictionaries } +/// Attributes' extension dictionaries (their annotation scale contexts), by attribute. +fn keep_attrib_dictionaries(f: &mut Foreign, (blocks, entities): (&Recs, &Recs), kept: &HashSet) { + let attribs: Vec<&[Tag]> = blocks.iter().chain(entities).filter(|(k, _, _)| k == "ATTRIB").map(|(_, _, t)| *t).collect(); + for (t, key) in attribs.iter().zip(attrib_keys(attribs.iter().copied())) { + if let Some(xd) = head(t).xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)) { + f.records.entry(("ATTRIB".into(), key)).or_insert(ForeignExtra { xdict: Some(xd), ..ForeignExtra::default() }); + } + } +} + +/// Block references whose extension dictionaries are kept (their annotation scale contexts), as +/// read: where the reference and its attributes were. +fn keep_placements(f: &mut Foreign, d: &Drawing) { + for e in all_entities(d) { + if let EntityKind::Insert(ins) = &e.kind + && f.entities.get(&e.handle).is_some_and(|x| x.xdict.is_some()) + { + let attribs = ins + .attribs + .iter() + .map(|a| cadcraft_doc::foreign::KeptAttrib { + tag: a.tag.clone(), + insert: a.text.insert, + align: a.text.align_pt.unwrap_or(a.text.insert), + rotation: a.text.rotation, + }) + .collect(); + f.placements + .insert(e.handle, cadcraft_doc::foreign::KeptPlacement { insert: ins.insert, rotation: ins.rotation, scale: ins.scale, attribs }); + } + } +} + /// Determine which objects belong to unmodelled dictionary entries or owners. fn retained_objects( objects: &[(String, usize, &[Tag])], @@ -548,9 +566,6 @@ fn retained_objects( xdict_of: &HashMap, inserts: &HashSet, ) -> HashMap { - let of_insert = |tags: &[Tag]| { - head(tags).owner.is_some_and(|owner| inserts.contains(&owner) || records.get(&owner).is_some_and(|key| key.0 == "ATTRIB")) - }; let root_key = |handle: &str| root_entries.iter().find(|(_, entry_handle)| entry_handle == handle).map(|(key, _)| key); let is_xdict = |index: usize| { let Some((_, _, tags)) = objects.get(index) else { return false }; @@ -559,7 +574,7 @@ fn retained_objects( !by_handle.contains_key(&owner) && xdict_of.get(&owner) == Some(&handle) && (entities.contains_key(&owner) || records.contains_key(&owner)) }; let modelled_entry = |tags: &[Tag], handle: &str| { - entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && modelled_xdict_key(key, of_insert(tags))) + entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && modelled_xdict_key(key, of_insert(tags, inserts, records))) }; let mut retained = HashMap::new(); for index in 0..objects.len() { @@ -590,7 +605,7 @@ fn retained_objects( continue; } if is_xdict(current) { - break entries(tags).iter().any(|(key, _)| !modelled_xdict_key(key, of_insert(tags))); + break entries(tags).iter().any(|(key, _)| !modelled_xdict_key(key, of_insert(tags, inserts, records))); } break entities.get(&owner) == Some(&true); }; @@ -1190,6 +1205,35 @@ struct Rec { end: usize, } +/// The written attributes' identities ([`attrib_keys`]), by record start. +fn written_attribs(recs: &[Rec], tags: &[Tag]) -> HashMap { + let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]); + let attrib_recs: Vec<&Rec> = recs.iter().filter(|r| matches!(r.sec.as_str(), "ENTITIES" | "BLOCKS") && r.kind == "ATTRIB").collect(); + attrib_recs.iter().map(|r| r.start).zip(attrib_keys(attrib_recs.iter().map(|r| body(r)))).collect() +} + +/// The kept annotation scale contexts of block references and their attributes, up to date with +/// the references and in line with the drawing's scales ([`reconcile`]); the new objects' owners +/// join `owners`. +fn refreshed_contexts( + f: &Foreign, + d: &Drawing, + owners: &mut HashMap, + roles: &HashMap, + tags: &[Tag], +) -> (HashMap, Reconciled) { + let mut contexts = block_contexts(f, d, owners); + let attribute = attribute_contexts(f, d, owners, &contexts); + contexts.extend(attribute); + let rec = reconcile(f, d, owners, roles, &mut contexts, seed(tags).max(max_handle(tags))); + for o in &rec.added { + if let Some(parent) = o.tags.iter().find(|t| t.code == 330) { + owners.insert(o.handle.hex(), norm(&parent.value)); + } + } + (contexts, rec) +} + fn written_records(tags: &[Tag]) -> Vec { let mut out: Vec = Vec::new(); let mut sec = String::new(); @@ -1406,9 +1450,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let root = objects.first().filter(|(k, _, _)| is_dictionary(k)).map(|(_, s, _)| *s); let root_keys: HashSet = objects.iter().find(|(_, s, _)| Some(*s) == root).map(|(_, _, t)| entries(t).into_iter().map(|(k, _)| up(&k)).collect()).unwrap_or_default(); - // The written attributes' identities, by record. - let attrib_recs: Vec<&Rec> = recs.iter().filter(|r| matches!(r.sec.as_str(), "ENTITIES" | "BLOCKS") && r.kind == "ATTRIB").collect(); - let attribs: HashMap = attrib_recs.iter().map(|r| r.start).zip(attrib_keys(attrib_recs.iter().map(|r| body(r)))).collect(); + let attribs = written_attribs(&recs, tags); // Extension dictionaries that go on a written record (one without its own). let mut block = String::new(); let mut attached: HashSet = HashSet::new(); @@ -1434,18 +1476,8 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { .iter() .filter_map(|o| Some((o.handle.hex(), head(&o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect::>()).owner?))) .collect(); - // Block references' annotation scale contexts, up to date with the references. - let mut contexts = block_contexts(f, d, &owners); - let attribute = attribute_contexts(f, d, &owners, &contexts); - contexts.extend(attribute); - // In line with the drawing's scales and each reference's. - let rec = reconcile(f, d, &owners, &roles, &mut contexts, seed(tags).max(max_handle(tags))); + let (contexts, rec) = refreshed_contexts(f, d, &mut owners, &roles, tags); let all: Vec<&ForeignObject> = f.objects.iter().chain(&rec.added).collect(); - for o in &rec.added { - if let Some(parent) = o.tags.iter().find(|t| t.code == 330) { - owners.insert(o.handle.hex(), norm(&parent.value)); - } - } // Which kept objects are written: those whose owner chain ends at a written owner. let objs: HashMap = all.iter().map(|o| (o.handle.hex(), *o)).collect(); let mut alive_memo: HashMap = HashMap::new(); @@ -1480,9 +1512,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { alive_memo.insert(p, verdict); } } - for h in &rec.dropped { - alive_memo.insert(h.clone(), false); - } + alive_memo.extend(rec.dropped.iter().map(|h| (h.clone(), false))); // New handles for the written kept objects, above every written handle and the seed. let mut next = seed(tags).max(max_handle(tags).saturating_add(1)); let mut alive: HashMap = HashMap::new(); diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index c750ee3ff..3ecb51fcc 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -1,8 +1,8 @@ use super::common::T; use super::objects::MAX_OBJECTS; use super::{ - BlockProps, Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, Vec3, - VportConfig, VportTile, records, + BlockProps, Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, + Vec3, VportConfig, VportTile, records, }; pub(super) fn header(tags: &[Tag], d: &mut Drawing) { diff --git a/crates/io/tests/it/roundtrip/compare.rs b/crates/io/tests/it/roundtrip/compare.rs index d4bd1541a..d6fe2faa0 100644 --- a/crates/io/tests/it/roundtrip/compare.rs +++ b/crates/io/tests/it/roundtrip/compare.rs @@ -29,6 +29,7 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) { let Block { name, annotative, + scale_uniformly, base, entities: contents, description, @@ -42,6 +43,7 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) { } = block.as_ref(); equal(name, &back.name, &path, "name"); equal(annotative, &back.annotative, &path, "annotative"); + equal(scale_uniformly, &back.scale_uniformly, &path, "scale_uniformly"); equal(base, &back.base, &path, "base"); equal(description, &back.description, &path, "description"); equal(xref_overlay, &back.xref_overlay, &path, "xref_overlay"); From 97b9e2a76550fdb495664bfa578d93322dc0302d Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Thu, 15 Oct 2026 10:30:19 -0600 Subject: [PATCH 013/258] DXF/DWG: annotative text, MText and dimensions keep their annotation scales on save AutoCAD keeps an annotative object's size at each annotation scale it supports in scale contexts (extension dictionary AcDbContextDataManager, ACDB_ANNOTATIONSCALES, one *OBJECTCONTEXTDATA_CLASS per scale), with the object's own groups at its default scale. CADCraft dropped AutoCAD's contexts on read, so those objects opened as plain text at the default scale's size and lost their scales on save; its own annotative objects went out with only CADCraft's private record, so AutoCAD showed them at one size at every scale. Text, MText and dimensions in model space and layouts are now written at their default scale (the current one when supported) with AcadAnnotative xdata and a context per scale: text insertion and alignment points, MText width and columns, a dimension's text position and a *D block with its geometry at that scale (sharing the DIMASSOC's extension dictionary when there is one). Scales missing from the list are added. Reading takes the scales from the contexts and the sizes back to paper size. Files before the 2007 format keep CADCraft's record as before. The DWG bridge gives acadrust text contexts its way (marker, radians) and dimension contexts' blocks as BLOCK_RECORD handles, and turns them back. Checked in AutoCAD: it opens the output, keeps both contexts of each object, and draws the dimension at 0.18 / 9.0 text height at 1:1 / 1:50. Co-Authored-By: Claude Opus 5.5 --- crates/dwg/src/lib.rs | 102 ++- crates/io/src/dxf_anno.rs | 452 ++++++++++++++ crates/io/src/dxf_ext.rs | 7 +- crates/io/src/dxf_read.rs | 3 + crates/io/src/dxf_write.rs | 4 + crates/io/src/dxf_write/common.rs | 6 +- crates/io/src/dxf_write/ctx.rs | 15 +- crates/io/src/dxf_write/entity.rs | 21 +- crates/io/src/dxf_write/sections.rs | 128 +++- crates/io/src/lib.rs | 2 + crates/io/tests/annotative_text_contexts.rs | 658 ++++++++++++++++++++ docs/file-format-parity.md | 11 +- docs/gaps.md | 5 +- 13 files changed, 1350 insertions(+), 64 deletions(-) create mode 100644 crates/io/src/dxf_anno.rs create mode 100644 crates/io/tests/annotative_text_contexts.rs diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 39d1f27fa..78278898b 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -121,7 +121,7 @@ mod native { )); } written.map_err(|e| format!("DWG→DXF: {e}"))?; - Ok((add_header_vars(blkref_contexts(&out.buf, false), &doc.header), notes)) + Ok((add_header_vars(contexts(&out.buf, false), &doc.header), notes)) } /// Most record types named in the skipped-records note. @@ -574,52 +574,92 @@ mod native { } } - /// Block reference annotation contexts (`ACDB_BLKREFOBJECTCONTEXTDATA_CLASS`) as acadrust - /// reads and writes them (`to_acadrust`), or back as AutoCAD writes them. AutoCAD's DXF has - /// the rotation (50, degrees), insertion point and scales straight after the context's scale - /// (340); acadrust 0.6.4 looks for them after an `AcDbBlkRefObjectContextData` marker, with - /// the rotation in radians (as DWG holds it), and without the marker reads zeros (an - /// annotative reference at scale 0 draws nothing in AutoCAD). Text that isn't UTF-8, or has - /// no such context, is returned as it is. - pub(crate) fn blkref_contexts(dxf: &[u8], to_acadrust: bool) -> Vec { - const KIND: &str = "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS"; - const MARKER: &str = "AcDbBlkRefObjectContextData"; + /// Annotation scale contexts as acadrust reads and writes them (`to_acadrust`), or back as + /// AutoCAD writes them. Block reference and text contexts + /// (`ACDB_BLKREFOBJECTCONTEXTDATA_CLASS`, `ACDB_TEXTOBJECTCONTEXTDATA_CLASS`): AutoCAD's DXF + /// has their fields straight after the context's scale (340), with the rotation (50) in + /// degrees; acadrust 0.6.4 looks for them after an `AcDbBlkRefObjectContextData` or + /// `AcDbTextObjectContextData` marker, with the rotation in radians (as DWG holds it), and + /// without the marker reads zeros (an annotative reference at scale 0 draws nothing in + /// AutoCAD). Dimension contexts (`ACDB_*DIMOBJECTCONTEXTDATA_CLASS`): AutoCAD names the + /// geometry block in group 2, acadrust reads a BLOCK_RECORD handle there. Text that isn't + /// UTF-8, or has no such context, is returned as it is. + pub(crate) fn contexts(dxf: &[u8], to_acadrust: bool) -> Vec { + const KINDS: [(&str, &str); 2] = [ + ("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS", "AcDbBlkRefObjectContextData"), + ("ACDB_TEXTOBJECTCONTEXTDATA_CLASS", "AcDbTextObjectContextData"), + ]; + let is_dim = |k: &str| k.starts_with("ACDB_") && k.ends_with("DIMOBJECTCONTEXTDATA_CLASS"); let Ok(text) = std::str::from_utf8(dxf) else { return dxf.to_vec() }; - if !text.contains(KIND) { + if !KINDS.iter().any(|(k, _)| text.contains(k)) && !text.contains("DIMOBJECTCONTEXTDATA_CLASS") { return dxf.to_vec(); } let lines: Vec<&str> = text.split('\n').collect(); let eol = |l: &str| if l.ends_with('\r') { "\r" } else { "" }; + // Block records: name (upper case) → handle, and back. + let mut by_name: std::collections::HashMap = std::collections::HashMap::new(); + let mut by_handle: std::collections::HashMap = std::collections::HashMap::new(); + let (mut record, mut h, mut i) = (false, None::, 0); + while let (Some(c), Some(v)) = (lines.get(i), lines.get(i + 1)) { + let (c, v) = (c.trim(), v.trim()); + match c { + "0" => (record, h) = (v == "BLOCK_RECORD", None), + "5" if record => h = Some(v.to_ascii_uppercase()), + "2" if record => { + if let Some(h) = h.take() { + by_name.entry(v.to_ascii_uppercase()).or_insert_with(|| h.clone()); + by_handle.entry(h).or_insert_with(|| v.to_string()); + } + } + _ => {} + } + i += 2; + } let mut out: Vec = Vec::with_capacity(lines.len() + 16); - let (mut inside, mut marked) = (false, false); + // The marker of the context being read (block reference or text), whether it is a + // dimension's, whether its scale (340) was passed and whether its marker was. + let (mut marker, mut dim, mut scaled, mut marked) = (None::<&str>, false, false, false); let mut i = 0; while let (Some(&code_line), Some(&value_line)) = (lines.get(i), lines.get(i + 1)) { let (code, value) = (code_line.trim(), value_line.trim_end_matches('\r')); if code == "0" { - inside = value.trim() == KIND; - marked = false; + let kind = value.trim(); + marker = KINDS.iter().find(|(k, _)| *k == kind).map(|(_, m)| *m); + dim = is_dim(kind); + (scaled, marked) = (false, false); } let mut value = value.to_string(); - if inside { - if code == "100" && value.trim() == MARKER { + if let Some(m) = marker { + if code == "100" && value.trim() == m { marked = true; i += 2; - if !to_acadrust { - continue; + if to_acadrust { + out.push(code_line.to_string()); + out.push(value_line.to_string()); } - out.push(code_line.to_string()); - out.push(value_line.to_string()); continue; } - if code == "50" { - if to_acadrust && !marked { - out.push(format!("100{}", eol(code_line))); - out.push(format!("{MARKER}{}", eol(value_line))); - marked = true; - } - if let Ok(a) = value.trim().parse::() { - value = if to_acadrust { a.to_radians() } else { a.to_degrees() }.to_string(); - } + // The marker goes before the first field after the scale. + if to_acadrust && scaled && !marked && code != "100" { + out.push(format!("100{}", eol(code_line))); + out.push(format!("{m}{}", eol(value_line))); + marked = true; + } + if code == "340" { + scaled = true; + } + if code == "50" + && scaled + && let Ok(a) = value.trim().parse::() + { + value = if to_acadrust { a.to_radians() } else { a.to_degrees() }.to_string(); + } + } + if dim && code == "2" { + let swap = + if to_acadrust { by_name.get(&value.trim().to_ascii_uppercase()) } else { by_handle.get(&value.trim().to_ascii_uppercase()) }; + if let Some(v) = swap { + value = v.clone(); } } out.push(code_line.to_string()); @@ -642,7 +682,7 @@ mod native { mb(Limits::DEFAULT.max_dxf_bytes as u64) )); } - let data = blkref_contexts(dxf, true); + let data = contexts(dxf, true); let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) .map_err(|_| "the DXF→DWG conversion failed".to_string())? .map_err(|e| format!("DXF: {e}"))?; diff --git a/crates/io/src/dxf_anno.rs b/crates/io/src/dxf_anno.rs new file mode 100644 index 000000000..88b02d10c --- /dev/null +++ b/crates/io/src/dxf_anno.rs @@ -0,0 +1,452 @@ +//! Annotative text, MText and dimensions in DXF, as AutoCAD keeps them. An annotative object +//! carries `AcadAnnotative` xdata and, in its extension dictionary under +//! `AcDbContextDataManager`, a dictionary `ACDB_ANNOTATIONSCALES` with one "object context data" +//! object per annotation scale it supports (`*A1`, `*A2`…). Each context names its SCALE object +//! (340), says whether it is the default one (290 = 1, the scale the object's own groups are +//! written at) and holds what changes with the scale: a text's insertion and alignment points, an +//! MText's insertion point, width and columns, a dimension's text position and the anonymous `*D` +//! block with its geometry at that scale. +//! +//! CADCraft keeps an annotative object at paper size with the list of scales it supports +//! ([`cadcraft_doc::Common::anno_scales`]). It writes the object at its default scale with a +//! context per scale ([`plan`], [`objects`]), and reads the scales and paper size back from the +//! contexts ([`resolve`]). An object's position at each scale is the one the scale gives it: +//! AutoCAD lets a context move an object at one scale only, which CADCraft doesn't model. +//! +//! Objects inside block definitions are left alone, and files older than AutoCAD 2007's format +//! (before annotation scaling) don't get contexts. + +use std::collections::{BTreeSet, HashMap}; + +use cadcraft_doc::{AnnoScale, DimKind, Drawing, Entity, EntityKind, HAlign, Handle, MTextColumnType, Text, VAlign}; +use cadcraft_dxf::{Section, Tag}; +use cadcraft_geom::Vec3; + +/// The context classes: (DXF record name, C++ class name). +const TEXT: (&str, &str) = ("ACDB_TEXTOBJECTCONTEXTDATA_CLASS", "AcDbTextObjectContextData"); +const MTEXT: (&str, &str) = ("ACDB_MTEXTOBJECTCONTEXTDATA_CLASS", "AcDbMTextObjectContextData"); +const ALDIM: (&str, &str) = ("ACDB_ALDIMOBJECTCONTEXTDATA_CLASS", "AcDbAlignedDimensionObjectContextData"); +const ANGDIM: (&str, &str) = ("ACDB_ANGDIMOBJECTCONTEXTDATA_CLASS", "AcDbAngularDimensionObjectContextData"); +const RADIM: (&str, &str) = ("ACDB_RADIMOBJECTCONTEXTDATA_CLASS", "AcDbRadialDimensionObjectContextData"); +const DMDIM: (&str, &str) = ("ACDB_DMDIMOBJECTCONTEXTDATA_CLASS", "AcDbDiametricDimensionObjectContextData"); +const ORDDIM: (&str, &str) = ("ACDB_ORDDIMOBJECTCONTEXTDATA_CLASS", "AcDbOrdinateDimensionObjectContextData"); + +/// The extension dictionary entry and the dictionary of contexts. +const MANAGER_KEY: &str = "AcDbContextDataManager"; +const SCALES_KEY: &str = "ACDB_ANNOTATIONSCALES"; + +/// Most contexts read per object (hostile files). +const MAX_CONTEXTS: usize = cadcraft_doc::MAX_SCALES; + +/// Whether `e` (in model space or a layout) is written with annotation scale contexts: annotative +/// text, MText and dimensions. +pub(crate) fn has_contexts(e: &Entity) -> bool { + cadcraft_doc::is_annotative(e) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_)) +} + +/// The scales `e` is written at (valid, each name once) and which of them is the default: the +/// current annotation scale when `e` supports it, else its first. +pub(crate) fn scales(d: &Drawing, e: &Entity) -> (Vec, usize) { + let mut out: Vec = Vec::new(); + for s in e.common.anno_scales.iter().filter(|s| s.is_valid() && !s.name.trim().is_empty()) { + if !out.iter().any(|x| x.name.eq_ignore_ascii_case(&s.name)) { + out.push(s.clone()); + } + } + let current = d.current_anno_scale(); + let default = out.iter().position(|s| s.name.eq_ignore_ascii_case(¤t.name)).unwrap_or(0); + (out, default) +} + +/// Whether text placed by its alignment point (group 11) rather than its start point (10). +fn by_alignment(t: &Text) -> bool { + t.align_pt.is_some() && !matches!((t.halign, t.valign), (HAlign::Left, VAlign::Baseline) | (HAlign::Aligned | HAlign::Fit, _)) +} + +/// `e` at annotation scale `f`, as its groups are written there: sizes scaled (see +/// [`cadcraft_doc::anno_scaled`]) and justified text's start point moved with its size about its +/// alignment point. A dimension's definition gets that scale (DIMSCALE). +pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity { + let mut out = cadcraft_doc::anno_scaled(e, f); + if let (EntityKind::Text(t), EntityKind::Text(paper)) = (&mut out.kind, &e.kind) + && by_alignment(paper) + && let Some(a) = paper.align_pt + { + t.insert = a + (paper.insert - a) * f; + } + out +} + +/// One context: its handle, the SCALE object's handle and the scale. +pub(crate) struct Context { + handle: String, + scale: String, + factor: f64, + default: bool, + /// A dimension's `*D` block at this scale. + block: Option, +} + +/// The objects written for one annotative object. +pub(crate) struct Obj { + /// Its extension dictionary (shared with a dimension's DIMASSOC). + pub xdict: String, + /// Whether the extension dictionary is written here (not with the DIMASSOC). + pub own_xdict: bool, + pub manager: String, + dict: String, + contexts: Vec, +} + +/// The annotative objects of a file being written, by entity handle. +#[derive(Default)] +pub(crate) struct Plan { + pub objs: HashMap, +} + +impl Plan { + /// The context classes the file uses (for its CLASSES section). + pub fn classes(&self, d: &Drawing) -> Vec<(&'static str, &'static str)> { + let mut out = BTreeSet::new(); + for h in self.objs.keys() { + if let Some(e) = d.entity(*h) { + out.insert(class_of(e)); + } + } + out.into_iter().flatten().collect() + } +} + +fn class_of(e: &Entity) -> Option<(&'static str, &'static str)> { + Some(match &e.kind { + EntityKind::Text(_) => TEXT, + EntityKind::MText(_) => MTEXT, + EntityKind::Dimension(dm) => match dm.kind { + DimKind::Linear { .. } | DimKind::Aligned | DimKind::ArcLength => ALDIM, + DimKind::Angular | DimKind::Angular3P => ANGDIM, + DimKind::Radius => RADIM, + DimKind::Diameter => DMDIM, + DimKind::Ordinate { .. } => ORDDIM, + }, + _ => return None, + }) +} + +/// Plan the objects of `e` (annotative, see [`has_contexts`]): `scale_handle` gives each scale's +/// SCALE object, `xdict` the extension dictionary it already has (a dimension's DIMASSOC), +/// `blocks` a dimension's `*D` block at each of [`scales`], and `next` new handles. `None` when +/// no scale has a SCALE object. +pub(crate) fn plan_one( + d: &Drawing, + e: &Entity, + scale_handle: impl Fn(&str) -> Option, + xdict: Option, + blocks: Option<&[String]>, + mut next: impl FnMut() -> String, +) -> Option { + let (scales, default) = scales(d, e); + let mut contexts = Vec::new(); + for (i, s) in scales.iter().enumerate() { + let Some(scale) = scale_handle(&s.name) else { continue }; + let block = blocks.and_then(|b| b.get(i)).cloned(); + contexts.push(Context { handle: String::new(), scale, factor: s.factor(), default: i == default, block }); + } + if contexts.is_empty() { + return None; + } + if !contexts.iter().any(|c| c.default) + && let Some(c) = contexts.first_mut() + { + c.default = true; + } + let own_xdict = xdict.is_none(); + let xdict = xdict.unwrap_or_else(&mut next); + let (manager, dict) = (next(), next()); + for c in &mut contexts { + c.handle = next(); + } + Some(Obj { xdict, own_xdict, manager, dict, contexts }) +} + +/// The factor `e` is written at (its default context's). +pub(crate) fn default_factor(o: &Obj) -> f64 { + o.contexts.iter().find(|c| c.default).map_or(1.0, |c| c.factor) +} + +/// `AcadAnnotative` xdata marking an annotative object. +pub(crate) fn xdata() -> Vec { + vec![Tag::s(1001, "AcadAnnotative"), Tag::s(1000, "AnnotativeData"), Tag::s(1002, "{"), Tag::i(1070, 1), Tag::i(1070, 1), Tag::s(1002, "}")] +} + +/// The extension dictionary entry of `o`'s context manager (key and handle groups). +pub(crate) fn xdict_entry(o: &Obj) -> Vec { + vec![Tag::s(3, MANAGER_KEY), Tag::s(360, o.manager.clone())] +} + +fn p(out: &mut Vec, c: i32, v: Vec3, z: bool) { + out.push(Tag::f(c, v.x)); + out.push(Tag::f(c + 10, v.y)); + if z { + out.push(Tag::f(c + 20, v.z)); + } +} + +/// A dictionary record: handle, reactor and owner `owner`, hard-owner flag 281 = 1, `entries`. +fn dictionary(out: &mut Vec, h: &str, owner: &str, cloning: bool, entries: &[(String, i32, String)]) { + out.push(Tag::s(0, "DICTIONARY")); + out.push(Tag::s(5, h)); + out.extend([Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, owner), Tag::s(102, "}")]); + out.push(Tag::s(330, owner)); + out.push(Tag::s(100, "AcDbDictionary")); + if cloning { + out.push(Tag::i(280, 1)); + } + out.push(Tag::i(281, 1)); + for (k, code, v) in entries { + out.push(Tag::s(3, k.clone())); + out.push(Tag::s(*code, v.clone())); + } +} + +/// The objects of annotative object `e` planned as `o`: its extension dictionary (unless the +/// DIMASSOC's holds the manager), the context manager, the dictionary of contexts and the +/// contexts. +pub(crate) fn objects(d: &Drawing, e: &Entity, o: &Obj) -> Vec { + let mut out = Vec::new(); + let eh = e.handle.hex(); + if o.own_xdict { + dictionary(&mut out, &o.xdict, &eh, true, &[(MANAGER_KEY.to_string(), 360, o.manager.clone())]); + } + dictionary(&mut out, &o.manager, &o.xdict, false, &[(SCALES_KEY.to_string(), 350, o.dict.clone())]); + let keyed: Vec<(String, i32, String)> = o.contexts.iter().enumerate().map(|(i, c)| (format!("*A{}", i + 1), 350, c.handle.clone())).collect(); + dictionary(&mut out, &o.dict, &o.manager, false, &keyed); + let Some((class, _)) = class_of(e) else { return out }; + for c in &o.contexts { + out.push(Tag::s(0, class)); + out.push(Tag::s(5, c.handle.clone())); + out.extend([Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, o.dict.clone()), Tag::s(102, "}")]); + out.push(Tag::s(330, o.dict.clone())); + out.push(Tag::s(100, "AcDbObjectContextData")); + out.push(Tag::i(70, 4)); + out.push(Tag::i(290, i64::from(c.default))); + out.push(Tag::s(100, "AcDbAnnotScaleObjectContextData")); + out.push(Tag::s(340, c.scale.clone())); + context_groups(&mut out, d, &at_scale(e, c.factor), c); + } + out +} + +/// What a context holds of `e` (already at the context's scale). +fn context_groups(out: &mut Vec, d: &Drawing, e: &Entity, c: &Context) { + match &e.kind { + EntityKind::Text(t) => { + let h = match t.halign { + HAlign::Left => 0, + HAlign::Center => 1, + HAlign::Right => 2, + HAlign::Aligned => 3, + HAlign::Middle => 4, + HAlign::Fit => 5, + }; + out.push(Tag::i(70, h)); + out.push(Tag::f(50, t.rotation.to_degrees())); + p(out, 10, t.insert, false); + p(out, 11, t.align_pt.unwrap_or(Vec3::ZERO), false); + } + EntityKind::MText(t) => { + out.push(Tag::i(70, i64::from(t.attach))); + p(out, 10, Vec3::new(t.rotation.cos(), t.rotation.sin(), 0.0), true); + p(out, 11, t.insert, true); + // Reference rectangle (40, 41) and an estimate of the text's extents (42, 43): AutoCAD + // lays the text out again. + let lines = t.contents.split("\\P").count().max(1) as f64; + let longest = t.contents.split("\\P").map(|l| l.chars().count()).max().unwrap_or(1) as f64; + out.push(Tag::f(40, t.width)); + out.push(Tag::f(41, 0.0)); + out.push(Tag::f(42, if t.width > 0.0 { t.width } else { t.height * 0.8 * longest })); + out.push(Tag::f(43, t.height * 1.66 * lines)); + match &t.columns { + None => out.push(Tag::i(71, 0)), + Some(cols) => { + let dynamic = cols.kind == MTextColumnType::Dynamic; + let manual = dynamic && !cols.auto_height; + out.push(Tag::i(71, if dynamic { 2 } else { 1 })); + out.push(Tag::i(72, if manual { cols.heights.len() as i64 } else { i64::from(cols.count.max(1)) })); + out.push(Tag::f(44, t.width)); + out.push(Tag::f(45, cols.gutter)); + out.push(Tag::i(73, i64::from(cols.auto_height))); + out.push(Tag::i(74, i64::from(cols.flow_reversed))); + if manual { + out.extend(cols.heights.iter().map(|h| Tag::f(46, *h))); + } + } + } + } + EntityKind::Dimension(dm) => { + out.push(Tag::s(100, "AcDbDimensionObjectContextData")); + out.push(Tag::s(2, c.block.clone().unwrap_or_default())); + out.push(Tag::i(293, 0)); + let text = if dm.user_text_pos { dm.text_mid } else { cadcraft_render::dimension_in(d, dm).text_pos.to3(0.0) }; + p(out, 10, text, false); + out.push(Tag::i(294, i64::from(!dm.user_text_pos))); + out.push(Tag::f(140, dm.text_rotation)); + for code in [298, 291, 70, 292, 71, 280, 295, 296, 297] { + out.push(Tag::i(code, 0)); + } + let Some((_, sub)) = class_of(e) else { return }; + out.push(Tag::s(100, sub)); + let pts: &[(i32, Vec3)] = match dm.kind { + DimKind::Linear { .. } | DimKind::Aligned | DimKind::ArcLength | DimKind::Angular3P => &[(11, dm.defpt)], + DimKind::Angular => &[(11, dm.p16)], + DimKind::Radius => &[(11, dm.p15)], + DimKind::Diameter => &[(11, dm.p15), (12, dm.defpt)], + DimKind::Ordinate { .. } => &[(11, dm.defpt), (12, dm.p14)], + }; + for (code, v) in pts { + p(out, *code, *v, true); + } + } + _ => {} + } +} + +// --------------------------------------------------------------------------------------------- +// Reading + +/// A record's groups before its xdata. +fn own(tags: &[Tag]) -> &[Tag] { + tags.get(..tags.iter().position(|t| t.code >= 1000).unwrap_or(tags.len())).unwrap_or(&[]) +} + +/// A handle as the key of the maps below. +fn key(s: &str) -> Option { + Handle::parse_hex(s.trim()).filter(|h| h.0 != 0) +} + +/// The extension dictionary of a record (`{ACAD_XDICTIONARY` group). +fn xdict_of(tags: &[Tag]) -> Option { + let i = own(tags).iter().position(|t| t.code == 102 && t.str().trim() == "{ACAD_XDICTIONARY")?; + tags.get(i + 1).filter(|t| t.code == 360).and_then(|t| key(&t.str())) +} + +/// A dictionary's entry `name` (case-insensitive). +fn entry(tags: &[Tag], name: &str) -> Option { + let g = own(tags); + let i = g.iter().position(|t| t.code == 3 && t.str().trim().eq_ignore_ascii_case(name))?; + g.get(i + 1).filter(|t| matches!(t.code, 350 | 360)).and_then(|t| key(&t.str())) +} + +/// Every entry of a dictionary. +fn all_entries(tags: &[Tag]) -> Vec { + own(tags).iter().filter(|t| matches!(t.code, 350 | 360)).filter_map(|t| key(&t.str())).take(MAX_CONTEXTS).collect() +} + +/// Read the annotation scale contexts of the text, MText and dimensions of model space and the +/// layouts: each becomes annotative with the scales of its contexts (in their order), and +/// its sizes are taken back to paper size from the default scale. Contexts of other objects, and +/// contexts whose scale is unknown, are passed over. +pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { + let Some(objects) = secs.iter().find(|s| s.name == "OBJECTS") else { return }; + let mut objs: HashMap = HashMap::new(); + each_record(&objects.tags, |kind, tags| { + if let Some(h) = own(tags).iter().find(|t| t.code == 5).and_then(|t| key(&t.str())) { + objs.entry(h).or_insert((kind.to_ascii_uppercase(), tags)); + } + }); + if !objs.values().any(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) { + return; + } + let scales: HashMap = + objs.iter().filter(|(_, (k, _))| k == "SCALE").filter_map(|(h, (_, t))| Some((*h, crate::dxf_ext::read_scale(own(t))?))).collect(); + // The entities that may have contexts: their extension dictionaries. + let mut found: Vec<(Handle, Handle)> = Vec::new(); + for s in secs.iter().filter(|s| s.name == "ENTITIES" || s.name == "BLOCKS") { + each_record(&s.tags, |kind, tags| { + if !matches!(kind, "TEXT" | "MTEXT" | "DIMENSION" | "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION") { + return; + } + let h = own(tags).iter().find(|t| t.code == 5).and_then(|t| key(&t.str())); + if let (Some(h), Some(x)) = (h, xdict_of(tags)) { + found.push((h, x)); + } + }); + } + for (h, xdict) in found { + let Some(e) = d.entity(h) else { continue }; + if !matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_)) { + continue; + } + let dict = objs + .get(&xdict) + .and_then(|(_, t)| entry(t, MANAGER_KEY)) + .and_then(|m| objs.get(&m)) + .and_then(|(_, t)| entry(t, SCALES_KEY)) + .and_then(|s| objs.get(&s)); + let Some((_, dict)) = dict else { continue }; + let mut list: Vec<(AnnoScale, bool)> = Vec::new(); + for c in all_entries(dict) { + let Some((_, t)) = objs.get(&c).filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) else { continue }; + let g = own(t); + let scale = g.iter().find(|t| t.code == 340).and_then(|t| key(&t.str())).and_then(|s| scales.get(&s)); + let default = g.iter().find(|t| t.code == 290).is_some_and(|t| t.i64() != 0); + if let Some(s) = scale + && !list.iter().any(|(x, _)| x.name.eq_ignore_ascii_case(&s.name)) + { + list.push((s.clone(), default)); + } + } + if list.is_empty() { + continue; + } + // The object's groups were written at the default context's scale. + let f = list.iter().find(|(_, default)| *default).or(list.first()).map_or(1.0, |(s, _)| s.factor()); + let list: Vec = list.into_iter().map(|(s, _)| s).collect(); + let _ = d.modify_entity(h, |e| { + e.common.anno_scales = list; + to_paper(e, f); + }); + } +} + +/// Take an object written at annotation scale `f` back to paper size (the inverse of +/// [`at_scale`]). +fn to_paper(e: &mut Entity, f: f64) { + if !(f.is_finite() && f > 0.0) || (f - 1.0).abs() < 1e-12 { + return; + } + let inv = 1.0 / f; + match &mut e.kind { + EntityKind::Text(t) => { + if by_alignment(t) + && let Some(a) = t.align_pt + { + t.insert = a + (t.insert - a) * inv; + } + t.height *= inv; + } + EntityKind::MText(t) => { + t.height *= inv; + t.width *= inv; + if let Some(c) = &mut t.columns { + c.scale(inv); + } + } + _ => {} + } +} + +/// Call `f` with each record (type, groups after its `0` group) of a section. +fn each_record<'a>(tags: &'a [Tag], mut f: impl FnMut(&str, &'a [Tag])) { + let mut open: Option<(String, usize)> = None; + for (i, t) in tags.iter().enumerate() { + if t.code == 0 { + if let Some((k, s)) = open.take() { + f(&k, tags.get(s..i).unwrap_or(&[])); + } + open = Some((t.str(), i + 1)); + } + } + if let Some((k, s)) = open { + f(&k, tags.get(s..).unwrap_or(&[])); + } +} diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 392ee1400..3fb5e9028 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -799,8 +799,9 @@ struct AnnoObject { const MAX_ANNO_OBJECTS: usize = 1_000_000; /// JSON chunks for the annotative scaling XRECORD, or `None` when nothing differs from a new -/// drawing (1:1, ANNOALLVISIBLE 1, no annotative objects or blocks). -pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing) -> Option> { +/// drawing (1:1, ANNOALLVISIBLE 1, no annotative objects or blocks). With `contexts` the objects +/// written with AutoCAD's annotation scale contexts (`dxf_anno`) are left to them. +pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing, contexts: bool) -> Option> { let cannoscale = d.header.str("CANNOSCALE", "1:1"); let annoallvisible = d.header.i64("ANNOALLVISIBLE", 1); let blocks: Vec = d.blocks.values().filter(|b| b.annotative).map(|b| b.name.clone()).collect(); @@ -808,7 +809,7 @@ pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing) -> Option> { .model .iter() .chain(d.layouts.iter().flat_map(|l| l.entities.iter())) - .filter(|e| cadcraft_doc::is_annotative(e)) + .filter(|e| cadcraft_doc::is_annotative(e) && !(contexts && crate::dxf_anno::has_contexts(e))) .map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone() }) .collect(); if cannoscale == "1:1" && annoallvisible == 1 && blocks.is_empty() && objects.is_empty() { diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index e34e9588d..c1be1fb1f 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -139,6 +139,9 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { objs.apply(&mut d, &rx); crate::dxf_image::resolve(&secs, &mut d); crate::dxf_mline::resolve(&secs, &mut d); + // Annotation scale contexts, after CADCraft's own record (they are newer when AutoCAD edited + // the file since). + crate::dxf_anno::resolve(&secs, &mut d); // Keep handles unique against the header's seed. let seed = d.header.str("HANDSEED", ""); if let Some(h) = own_seed.or_else(|| Handle::parse_hex(&seed)) { diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 8eb3ab91f..0840908bf 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -46,6 +46,9 @@ struct W { /// Persistent reactors of boundary objects: each source object of an associative hatch → /// the hatches (groups `{ACAD_REACTORS 330 …}`), from [`hatch_reactors`]. reactors: HashMap>, + /// Extension dictionaries of annotative objects (their annotation scale contexts, see + /// [`crate::dxf_anno`]), by object; a dimension's DIMASSOC dictionary is written by its own. + xdicts: HashMap, } impl W { @@ -146,6 +149,7 @@ pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec) { pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new(), + xdicts: HashMap::new(), }; let cx = Ctx { target: Version::R2018, legacy_columns: true, ..Ctx::default() }; let paper = d.space_of(e.handle).is_some_and(|s| !matches!(s, cadcraft_doc::Space::Model)); diff --git a/crates/io/src/dxf_write/common.rs b/crates/io/src/dxf_write/common.rs index 88ad71566..f9e6abd61 100644 --- a/crates/io/src/dxf_write/common.rs +++ b/crates/io/src/dxf_write/common.rs @@ -16,7 +16,7 @@ pub(super) fn annotative_xdata(w: &mut W) { /// Override (`ACAD` DSTYLE) and associativity (`CADCRAFT` ASSOC) xdata of a dimension. pub(super) fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) { - let mut ov = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() }; + let mut ov = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new(), xdicts: HashMap::new() }; let mut sah = false; for (k, v) in &dm.overrides { let Some(field) = DimStyle::field_name(k) else { continue }; @@ -83,8 +83,8 @@ pub(super) fn common_x(w: &mut W, e: &Entity, owner: &str, paper: bool, subclass let rs: Vec<&str> = reactors.iter().map(String::as_str).collect(); w.group("ACAD_REACTORS", 330, &rs); } - if let Some(a) = assoc { - w.group("ACAD_XDICTIONARY", 360, &[&a.xdict]); + if let Some(xd) = assoc.map(|a| a.xdict.clone()).or_else(|| w.xdicts.get(&e.handle).cloned()) { + w.group("ACAD_XDICTIONARY", 360, &[&xd]); } w.s(330, owner); w.s(100, "AcDbEntity"); diff --git a/crates/io/src/dxf_write/ctx.rs b/crates/io/src/dxf_write/ctx.rs index 157dcd441..0eb16828e 100644 --- a/crates/io/src/dxf_write/ctx.rs +++ b/crates/io/src/dxf_write/ctx.rs @@ -1,4 +1,4 @@ -use super::{DimVal, Handle, HashMap, K, Vec3, Version, dxf_ext}; +use super::{DimVal, Entity, Handle, HashMap, K, Vec3, Version, W, dxf_ext}; /// The `DIMASSOC` object of an associative dimension (stored in the dimension's extension /// dictionary under `ACAD_DIMASSOC`). @@ -55,6 +55,8 @@ pub(super) struct Ctx { pub(super) target: Version, /// MTEXT columns as the legacy groups 75..79 even from R2018 (the groups AutoLISP lists). pub(super) legacy_columns: bool, + /// Annotative text, MText and dimensions: their annotation scale contexts. + pub(super) anno: crate::dxf_anno::Plan, } impl Ctx { @@ -63,6 +65,17 @@ impl Ctx { pub(super) fn native_mleader(&self) -> bool { self.target >= Version::R2007 } + /// Annotative object `e` as its groups are written: at its default annotation scale (`None`: + /// not written with contexts, as it is). + pub(super) fn at_default(&self, e: &Entity) -> Option { + self.anno.objs.get(&e.handle).map(|o| crate::dxf_anno::at_scale(e, crate::dxf_anno::default_factor(o))) + } + /// `AcadAnnotative` xdata of an object written with contexts. + pub(super) fn anno_xdata(&self, w: &mut W, e: &Entity) { + if self.anno.objs.contains_key(&e.handle) { + w.xdata(crate::dxf_anno::xdata()); + } + } pub(super) fn style(&self, name: &str) -> Option { self.styles.get(&name.to_ascii_uppercase()).cloned() } diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index f5771f106..7e5c18408 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -222,10 +222,16 @@ fn write_basic_entity(w: &mut W, _d: &Drawing, e: &Entity, owner: &str, paper: b fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) { match &e.kind { EntityKind::Text(t) => { + let scaled = cx.at_default(e); + let t = match scaled.as_ref().map(|s| &s.kind) { + Some(EntityKind::Text(s)) => s, + _ => t, + }; w.s(0, "TEXT"); common(w, e, owner, paper, "AcDbText"); thickness(w, e); text_tags(w, d, t, None, None); + cx.anno_xdata(w, e); } // Closed polylines, one per loop (`dxf_region`): REGION's own data is ACIS. EntityKind::Region(r) => { @@ -251,6 +257,11 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo } } EntityKind::MText(t) => { + let scaled = cx.at_default(e); + let t = match scaled.as_ref().map(|s| &s.kind) { + Some(EntityKind::MText(s)) => s, + _ => t, + }; w.s(0, "MTEXT"); common(w, e, owner, paper, "AcDbMText"); w.p(10, t.insert); @@ -277,6 +288,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo w.i(73, if t.line_spacing_exact { 2 } else { 1 }); w.f(44, t.line_spacing); w.t.extend(crate::dxf_read::mtext_dxf::column_tags(t, cx.target >= Version::R2018 && !cx.legacy_columns)); + cx.anno_xdata(w, e); } _ => {} } @@ -338,7 +350,13 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper w.s(2, bname); w.p(10, dm.defpt); let style = d.dim_style(&dm.style).cloned().unwrap_or_default(); - let g = cadcraft_render::dimension_geometry(dm, &style, d.header.f64("DIMSCALE", 1.0)); + // An annotative dimension's text is where its default scale puts it. + let scaled = cx.at_default(e); + let at = match scaled.as_ref().map(|s| &s.kind) { + Some(EntityKind::Dimension(s)) => s, + _ => dm, + }; + let g = cadcraft_render::dimension_geometry(at, &style, d.header.f64("DIMSCALE", 1.0)); w.p(11, if dm.user_text_pos { dm.text_mid } else { g.text_pos.to3(0.0) }); let ty: i64 = match dm.kind { DimKind::Linear { .. } => 0, @@ -408,6 +426,7 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper } } dim_xdata(w, dm, cx); + cx.anno_xdata(w, e); } } diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 48979755a..c1e478a6f 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -243,7 +243,8 @@ fn write_dimstyles(w: &mut W, d: &Drawing, cx: &mut Ctx, version: Version) { w.i(70, 0); let v = serde_json::to_value(s).unwrap_or_default(); let defaults = serde_json::to_value(DimStyle::default()).unwrap_or_default(); - let mut newer = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() }; + let mut newer = + W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new(), xdicts: HashMap::new() }; for (field, code, kind) in dxf_ext::DIM_CODES { let Some(enc) = v.get(*field).and_then(|x| cx.encode(*kind, x)) else { continue }; // DIMPOST is written even when empty: a reader that defaults a missing one to "<>" @@ -313,7 +314,7 @@ fn write_header(w: &mut W, d: &Drawing, version: Version) -> usize { seed_pos } -fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity]) { +fn write_classes(w: &mut W, d: &Drawing, cx: &Ctx, every: &[&Entity]) { w.s(0, "SECTION"); w.s(2, "CLASSES"); let mut classes = vec![ @@ -344,6 +345,9 @@ fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity]) { classes.push(("RASTERVARIABLES", "AcDbRasterVariables", 0, false)); } classes.push(("SCALE", "AcDbScale", 0, false)); + for (dxf_name, cpp) in cx.anno.classes(d) { + classes.push((dxf_name, cpp, 1153, false)); + } for (dxf_name, cpp, proxy, is_entity) in classes { w.s(0, "CLASS"); w.s(1, dxf_name); @@ -685,7 +689,8 @@ fn write_named_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { scale_list(w, scales, scale_dict, root_dict); } -fn write_associative_objects(w: &mut W, cx: &Ctx) { +fn write_associative_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { + let cx = plan.cx; // Dimension associativity: extension dictionary + DIMASSOC per dimension. let mut assoc: Vec<(&Handle, &AssocObj)> = cx.assoc.iter().collect(); assoc.sort_by_key(|(h, _)| **h); @@ -700,6 +705,10 @@ fn write_associative_objects(w: &mut W, cx: &Ctx) { w.i(281, 1); w.s(3, "ACAD_DIMASSOC"); w.s(360, a.handle.clone()); + // An annotative dimension's contexts share the dictionary. + if let Some(o) = cx.anno.objs.get(dim) { + w.t.extend(crate::dxf_anno::xdict_entry(o)); + } w.s(0, "DIMASSOC"); w.s(5, a.handle.clone()); w.group("ACAD_REACTORS", 330, &[&a.xdict]); @@ -729,6 +738,17 @@ fn write_associative_objects(w: &mut W, cx: &Ctx) { } } +/// The annotation scale contexts of annotative text, MText and dimensions. +fn write_annotation_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { + let mut annos: Vec<(&Handle, &crate::dxf_anno::Obj)> = plan.cx.anno.objs.iter().collect(); + annos.sort_by_key(|(h, _)| **h); + for (h, o) in annos { + if let Some(e) = plan.d.entity(*h) { + w.t.extend(crate::dxf_anno::objects(plan.d, e, o)); + } + } +} + fn write_objects(w: &mut W, plan: ObjectWritePlan<'_>) { // Groups (members that still exist) and multileader styles. let group_owner = plan.group_dict.clone(); @@ -739,25 +759,74 @@ fn write_objects(w: &mut W, plan: ObjectWritePlan<'_>) { write_root_group_objects(w, &plan, &groups, &group_owner, &written, &mleader_dict); write_style_objects(w, &plan, &mleader_dict, &mleader_handles); write_named_objects(w, &plan); - write_associative_objects(w, plan.cx); + write_associative_objects(w, &plan); + write_annotation_objects(w, &plan); write_layout_objects(w, &plan); // Raster image definitions. w.t.extend(crate::dxf_image::objects(&plan.cx.images, plan.root_dict)); w.s(0, "ENDSEC"); } +/// The next free `*D` block name at or after `*D{n}`. +fn fresh_dim_name(d: &Drawing, n: &mut usize) -> String { + let mut name = format!("*D{n}"); + while d.block(&name).is_some() { + *n += 1; + name = format!("*D{n}"); + } + *n += 1; + name +} + +type DimDef = (String, String, Vec); + +/// An annotative dimension's blocks, one per annotation scale (its default scale's is the +/// dimension's own); `None` when it has no scales. +fn annotative_dimension_blocks( + d: &Drawing, + e: &Entity, + n: &mut usize, + w: &mut W, + (cx, dim_defs): (&mut Ctx, &mut Vec), +) -> Option> { + let (scales, default) = crate::dxf_anno::scales(d, e); + let mut names = Vec::new(); + for s in &scales { + let at = crate::dxf_anno::at_scale(e, s.factor()); + let ents = match &at.kind { + EntityKind::Dimension(sdm) => dim_block_entities(d, sdm, &e.common.layer), + _ => Vec::new(), + }; + let name = fresh_dim_name(d, n); + dim_defs.push((name.clone(), w.h(), ents)); + names.push(name); + } + cx.dim_blocks.insert(e.handle, names.get(default)?.clone()); + Some(names) +} + +/// The dimensions' anonymous blocks, and the blocks of each annotative dimension by scale (from +/// AutoCAD 2008, the 2007 format: `contexts`). fn dimension_block_definitions( d: &Drawing, all_spaces: &[&EntityStore], - dim_plan: &super::blocks::DimBlockPlan, + (dim_plan, contexts): (&super::blocks::DimBlockPlan, bool), w: &mut W, cx: &mut Ctx, -) -> Vec<(String, String, Vec)> { +) -> (Vec, HashMap>) { let mut dim_defs = Vec::new(); + let mut anno_dim_blocks: HashMap> = HashMap::new(); let mut n = 1; let mut reused_handles = std::collections::HashSet::new(); for st in all_spaces { for e in st.iter() { + if contexts + && crate::dxf_anno::has_contexts(e) + && let Some(names) = annotative_dimension_blocks(d, e, &mut n, w, (cx, &mut dim_defs)) + { + anno_dim_blocks.insert(e.handle, names); + continue; + } if let EntityKind::Dimension(dm) = &e.kind { let reused = dim_plan.reuse.get(&e.handle); let ents: Vec; @@ -778,13 +847,7 @@ fn dimension_block_definitions( } None => { ents = dim_block_entities(d, dm, &e.common.layer); - let mut name = format!("*D{n}"); - while d.block(&name).is_some() { - n += 1; - name = format!("*D{n}"); - } - n += 1; - name + fresh_dim_name(d, &mut n) } }; let brh = w.h(); @@ -793,7 +856,7 @@ fn dimension_block_definitions( } } } - dim_defs + (dim_defs, anno_dim_blocks) } fn arrow_block_definitions( @@ -893,6 +956,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec Vec = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect(); - let mut dim_defs = dimension_block_definitions(d, &all_spaces, &dim_plan, &mut w, &mut cx); + // Annotation scale contexts (from AutoCAD 2008, the 2007 format). + let contexts = target >= Version::R2007; + let (mut dim_defs, anno_dim_blocks) = dimension_block_definitions(d, &all_spaces, (&dim_plan, contexts), &mut w, &mut cx); // Every entity, including block contents (for arrows, tables and overrides). let every: Vec<&Entity> = all_spaces .iter() @@ -958,12 +1024,38 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec = d.scales.iter().filter(|s| s.is_valid()).map(|s| (s, w.h())).collect(); + // Scales annotative objects support that the list lacks are added to it (each context names + // its SCALE object). + let mut extra_scales: Vec = Vec::new(); + for e in all_spaces.iter().flat_map(|s| s.iter()).filter(|e| contexts && crate::dxf_anno::has_contexts(e)) { + for s in crate::dxf_anno::scales(d, e).0 { + let known = |x: &cadcraft_doc::AnnoScale| x.is_valid() && x.name.eq_ignore_ascii_case(&s.name); + if !d.scales.iter().any(known) && !extra_scales.iter().any(known) && extra_scales.len() < cadcraft_doc::MAX_SCALES { + extra_scales.push(s); + } + } + } + let scales: Vec<(&cadcraft_doc::AnnoScale, String)> = + d.scales.iter().filter(|s| s.is_valid()).chain(extra_scales.iter()).map(|s| (s, w.h())).collect(); + // The annotation scale contexts of annotative text, MText and dimensions. + if contexts { + let scale_handle = |name: &str| scales.iter().find(|(s, _)| s.name.eq_ignore_ascii_case(name)).map(|(_, h)| h.clone()); + for e in all_spaces.iter().flat_map(|s| s.iter()).filter(|e| crate::dxf_anno::has_contexts(e)) { + let xdict = cx.assoc.get(&e.handle).map(|a| a.xdict.clone()); + let blocks = anno_dim_blocks.get(&e.handle).map(Vec::as_slice); + if let Some(o) = crate::dxf_anno::plan_one(d, e, scale_handle, xdict, blocks, || w.h()) { + if o.own_xdict { + w.xdicts.insert(e.handle, o.xdict.clone()); + } + cx.anno.objs.insert(e.handle, o); + } + } + } // Plot style names used by layers and objects (Normal always), each a placeholder object. let pstyle_dict = w.h(); let mut pstyle_names: Vec = vec![cadcraft_doc::NORMAL_STYLE.to_string()]; @@ -982,7 +1074,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec 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() +} + +type Rec = (String, Vec<(i32, String)>); + +/// A written file's records: (type, groups). +fn records(text: &str) -> Vec { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out: Vec = Vec::new(); + for pair in lines.chunks(2) { + let (Some(code), Some(value)) = (pair.first().and_then(|c| c.parse::().ok()), pair.get(1)) else { continue }; + if code == 0 { + out.push((value.to_string(), Vec::new())); + } else if let Some((_, tags)) = out.last_mut() { + tags.push((code, value.to_string())); + } + } + out +} + +fn get(tags: &[(i32, String)], code: i32) -> Option<&str> { + tags.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str()) +} + +fn num(tags: &[(i32, String)], code: i32) -> f64 { + get(tags, code).and_then(|v| v.trim().parse::().ok()).unwrap_or(f64::NAN) +} + +/// A written context: (class, scale name, default, groups after the scale). +struct Ctx { + class: String, + scale: String, + default: bool, + tags: Vec<(i32, String)>, +} + +/// The contexts written for the object with handle `owner` (through its extension dictionary, +/// context manager and dictionary of contexts). +fn contexts_of(text: &str, owner: &str) -> Vec { + let recs = records(text); + let by_handle: std::collections::HashMap<&str, &Rec> = recs.iter().filter_map(|r| Some((get(&r.1, 5)?, r))).collect(); + let scales: std::collections::HashMap<&str, &str> = + recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect(); + let entry = |h: &str, key: &str| -> Option { + let t = &by_handle.get(h)?.1; + let i = t.iter().position(|(c, v)| *c == 3 && v.eq_ignore_ascii_case(key))?; + t.get(i + 1).map(|(_, v)| v.clone()) + }; + let Some(ent) = by_handle.get(owner) else { return Vec::new() }; + let xd = ent.1.iter().skip_while(|(c, v)| !(*c == 102 && v == "{ACAD_XDICTIONARY")).nth(1).map(|(_, v)| v.clone()); + let Some(dict) = xd.and_then(|x| entry(&x, "AcDbContextDataManager")).and_then(|m| entry(&m, "ACDB_ANNOTATIONSCALES")) else { + return Vec::new(); + }; + let Some(d) = by_handle.get(dict.as_str()) else { return Vec::new() }; + d.1.iter() + .filter(|(c, _)| *c == 350) + .filter_map(|(_, h)| by_handle.get(h.as_str())) + .map(|(class, t)| { + let at = t.iter().position(|(c, _)| *c == 340).unwrap_or(0); + Ctx { + class: class.clone(), + scale: get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(), + default: get(t, 290) == Some("1"), + tags: t.get(at + 1..).unwrap_or(&[]).to_vec(), + } + }) + .collect() +} + +fn names(d: &Drawing, h: &str) -> Vec { + d.entity(Handle::parse_hex(h).unwrap()).unwrap().common.anno_scales.iter().map(|s| s.name.clone()).collect() +} + +fn read() -> Drawing { + cadcraft_io::read_dxf(dxf(FIXTURE).as_bytes()).unwrap() +} + +fn save(d: &Drawing) -> String { + String::from_utf8(cadcraft_io::write(d, "x.dxf").unwrap()).unwrap() +} + +#[test] +fn contexts_make_text_mtext_and_dimensions_annotative_at_paper_size() { + let d = read(); + for h in ["30", "40", "50"] { + assert_eq!(names(&d, h), ["1:2", "1:10"], "{h}"); + } + let Some(EntityKind::Text(t)) = d.entity(Handle(0x30)).map(|e| &e.kind) else { panic!("text") }; + // 2.5 at 1:2: 1.25 on paper. The start point moves with the size about the alignment point. + assert!((t.height - 1.25).abs() < 1e-12, "{}", t.height); + assert!((t.insert.x - 23.0).abs() < 1e-12, "{:?}", t.insert); + let Some(EntityKind::MText(m)) = d.entity(Handle(0x40)).map(|e| &e.kind) else { panic!("mtext") }; + assert!((m.height - 1.25).abs() < 1e-12 && (m.width - 10.0).abs() < 1e-12, "{} {}", m.height, m.width); +} + +#[test] +fn each_object_is_written_at_its_default_scale_with_a_context_per_scale() { + let text = save(&read()); + let recs = records(&text); + let ent = |h: &str| recs.iter().find(|(_, t)| get(t, 5) == Some(h)).unwrap(); + // The current scale (1:2) is the default: the groups are at its size. + assert_eq!(num(&ent("30").1, 40), 2.5); + assert_eq!(num(&ent("40").1, 40), 2.5); + assert_eq!(num(&ent("40").1, 41), 20.0); + for h in ["30", "40", "50"] { + assert!(ent(h).1.iter().any(|(c, v)| *c == 1001 && v == "AcadAnnotative"), "{h}"); + let ctx = contexts_of(&text, h); + let got: Vec<(&str, bool)> = ctx.iter().map(|c| (c.scale.as_str(), c.default)).collect(); + assert_eq!(got, [("1:2", true), ("1:10", false)], "{h}"); + } + let text_ctx = contexts_of(&text, "30"); + assert!(text_ctx.iter().all(|c| c.class == "ACDB_TEXTOBJECTCONTEXTDATA_CLASS")); + // Right-justified: the alignment point stays, the start point moves with the size. + let starts: Vec<(f64, f64)> = text_ctx.iter().map(|c| (num(&c.tags, 10), num(&c.tags, 11))).collect(); + assert_eq!(starts, [(16.0, 30.0), (-40.0, 30.0)]); + let widths: Vec = contexts_of(&text, "40").iter().map(|c| num(&c.tags, 40)).collect(); + assert_eq!(widths, [20.0, 100.0]); + // A dimension's contexts name its geometry block at each scale; the default one is its own. + let dim = contexts_of(&text, "50"); + assert!(dim.iter().all(|c| c.class == "ACDB_ALDIMOBJECTCONTEXTDATA_CLASS")); + let blocks: Vec = dim.iter().map(|c| get(&c.tags, 2).unwrap().to_string()).collect(); + assert_eq!(get(&ent("50").1, 2), Some(blocks[0].as_str())); + let text_height = |block: &str| { + let start = recs.iter().position(|(k, t)| k == "BLOCK" && get(t, 2) == Some(block)).unwrap(); + let end = start + recs[start..].iter().position(|(k, _)| k == "ENDBLK").unwrap(); + recs[start..end].iter().find(|(k, _)| k == "MTEXT").map(|(_, t)| num(t, 40)).unwrap() + }; + let (h2, h10) = (text_height(&blocks[0]), text_height(&blocks[1])); + assert!((h10 / h2 - 5.0).abs() < 1e-9, "{h2} {h10}"); + // Each context class is declared. + for class in ["ACDB_TEXTOBJECTCONTEXTDATA_CLASS", "ACDB_MTEXTOBJECTCONTEXTDATA_CLASS", "ACDB_ALDIMOBJECTCONTEXTDATA_CLASS"] { + assert!(recs.iter().any(|(k, t)| k == "CLASS" && get(t, 1) == Some(class)), "{class}"); + } +} + +#[test] +fn a_saved_drawing_reads_back_the_same() { + let d = read(); + let back = cadcraft_io::read_dxf(save(&d).as_bytes()).unwrap(); + for h in ["30", "40", "50"] { + let (a, b) = (d.entity(Handle::parse_hex(h).unwrap()).unwrap(), back.entity(Handle::parse_hex(h).unwrap()).unwrap()); + assert_eq!(a.common.anno_scales, b.common.anno_scales, "{h}"); + if !matches!(a.kind, EntityKind::Dimension(_)) { + assert_eq!(a.kind, b.kind, "{h}"); + } + } + // Saved again, the file is the same: nothing piles up. + assert_eq!(contexts_of(&save(&back), "30").len(), 2); +} + +/// A drawing made in CADCraft: text and a dimension at 1:1 and 1:50, 1:50 current. +fn made() -> Drawing { + let mut d = Drawing::default(); + d.header.set_str("CANNOSCALE", "1:50"); + let scales = vec![AnnoScale::new("1:1", 1.0, 1.0), AnnoScale::new("1:50", 1.0, 50.0)]; + let common = Common { anno_scales: scales.clone(), ..Common::default() }; + let t = Text { + insert: Vec3::ZERO, + align_pt: None, + height: 2.5, + value: "NOTE".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + }; + d.add(&Space::Model, common.clone(), EntityKind::Text(t)).unwrap(); + let dm = Dimension { + kind: DimKind::Aligned, + defpt: Vec3::new(100.0, 20.0, 0.0), + text_mid: Vec3::new(50.0, 20.0, 0.0), + p13: Vec3::ZERO, + p14: Vec3::new(100.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 100.0, + text_rotation: 0.0, + user_text_pos: false, + block: None, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + d.add(&Space::Model, common, EntityKind::Dimension(dm)).unwrap(); + d +} + +#[test] +fn objects_made_in_cadcraft_get_contexts_and_read_back() { + let d = made(); + let text = save(&d); + let recs = records(&text); + let handles: Vec = d.model.iter().map(|e| e.handle.hex()).collect(); + let t = recs.iter().find(|(_, t)| get(t, 5) == Some(handles[0].as_str())).unwrap(); + // Written at 1:50, the current scale: 2.5 on paper is 125. + assert_eq!(num(&t.1, 40), 125.0); + for h in &handles { + let got: Vec<(String, bool)> = contexts_of(&text, h).into_iter().map(|c| (c.scale, c.default)).collect(); + assert_eq!(got, [("1:1".to_string(), false), ("1:50".to_string(), true)], "{h}"); + } + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + for (a, b) in d.model.iter().zip(back.model.iter()) { + assert_eq!(a.common.anno_scales, b.common.anno_scales); + } + let Some(EntityKind::Text(t)) = back.model.iter().next().map(|e| &e.kind) else { panic!("text") }; + assert!((t.height - 2.5).abs() < 1e-9, "{}", t.height); +} + +#[test] +fn a_scale_missing_from_the_list_is_added_to_it() { + let mut d = made(); + d.scales.retain(|s| s.name != "1:50"); + let text = save(&d); + assert!(records(&text).iter().any(|(k, t)| k == "SCALE" && get(t, 300) == Some("1:50"))); + let h = d.model.iter().next().unwrap().handle.hex(); + assert_eq!(contexts_of(&text, &h).len(), 2); +} + +#[test] +fn files_older_than_annotation_scaling_keep_cadcraft_s_record() { + let d = made(); + let opts = cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2004), binary: false }; + let bytes = cadcraft_io::write_with(&d, "x.dxf", &opts).unwrap(); + let text = String::from_utf8_lossy(&bytes); + assert!(!text.contains("OBJECTCONTEXTDATA")); + let back = cadcraft_io::read_dxf(&bytes).unwrap(); + for (a, b) in d.model.iter().zip(back.model.iter()) { + assert_eq!(a.common.anno_scales, b.common.anno_scales); + if let (EntityKind::Text(x), EntityKind::Text(y)) = (&a.kind, &b.kind) { + assert_eq!(x.height, y.height); + } + } +} + +#[test] +fn a_dimension_s_associativity_and_contexts_share_its_dictionary() { + let mut d = made(); + let line = + d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(100.0, 0.0, 0.0) })).unwrap(); + let dim = d.model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap().handle; + d.modify_entity(dim, |e| { + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.assoc = vec![ + cadcraft_doc::DimAssoc { point: "p13".into(), handle: line, snap: cadcraft_doc::AssocSnap::Start }, + cadcraft_doc::DimAssoc { point: "p14".into(), handle: line, snap: cadcraft_doc::AssocSnap::End }, + ]; + } + }) + .unwrap(); + let text = save(&d); + let recs = records(&text); + let ent = recs.iter().find(|(k, t)| k == "DIMENSION" && get(t, 5) == Some(dim.hex().as_str())).unwrap(); + let xdicts = ent.1.iter().filter(|(c, v)| *c == 102 && v == "{ACAD_XDICTIONARY").count(); + assert_eq!(xdicts, 1); + assert_eq!(contexts_of(&text, &dim.hex()).len(), 2); + let xd = ent.1.iter().skip_while(|(c, v)| !(*c == 102 && v == "{ACAD_XDICTIONARY")).nth(1).unwrap().1.clone(); + let dict = recs.iter().find(|(_, t)| get(t, 5) == Some(xd.as_str())).unwrap(); + assert!(dict.1.iter().any(|(c, v)| *c == 3 && v == "ACAD_DIMASSOC")); +} + +#[test] +fn hostile_contexts_do_not_panic() { + // Contexts naming no scale, a scale of zero, a missing dictionary and a cycle. + let src = dxf(FIXTURE) + .replace("340\n13\n", "340\n99\n") + .replace("141\n2\n", "141\n0\n") + .replace("360\n42\n", "360\n41\n") + .replace("350\n53\n", "350\n51\n"); + let d = cadcraft_io::read_dxf(src.as_bytes()).unwrap(); + for h in ["30", "40", "50"] { + let n = names(&d, h); + assert!(n.len() <= 1, "{h}: {n:?}"); + } + let _ = save(&d); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn text_mtext_and_dimensions_keep_their_scales_through_dwg() { + let mut d = read(); + // Turned 30° first, so the text context's rotation unit shows (DXF degrees, DWG radians). + d.modify_entity(Handle(0x30), |e| { + if let EntityKind::Text(t) = &mut e.kind { + t.rotation = 30f64.to_radians(); + } + }) + .unwrap(); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + for (h, kind) in [(0x30, "text"), (0x40, "mtext"), (0x50, "dimension")] { + let e = back.model.iter().find(|e| { + matches!((&e.kind, kind), (EntityKind::Text(_), "text") | (EntityKind::MText(_), "mtext") | (EntityKind::Dimension(_), "dimension")) + }); + let e = e.unwrap_or_else(|| panic!("{kind} {h:X}")); + let got: Vec<&str> = e.common.anno_scales.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(got, ["1:2", "1:10"], "{kind}"); + if let EntityKind::Text(t) = &e.kind { + assert!((t.height - 1.25).abs() < 1e-9 && (t.rotation.to_degrees() - 30.0).abs() < 1e-9, "{t:?}"); + } + } + // The DXF the bridge reads back has AutoCAD's layout: rotation in degrees, no marker, and a + // dimension context naming its block. + let dxf = cadcraft_dwg::dwg_to_dxf(&dwg).unwrap(); + let text = String::from_utf8_lossy(&dxf); + let recs = records(&text); + let text_ctx: Vec<&Rec> = recs.iter().filter(|(k, _)| k == "ACDB_TEXTOBJECTCONTEXTDATA_CLASS").collect(); + assert_eq!(text_ctx.len(), 2); + for (_, t) in &text_ctx { + assert!(t.iter().all(|(c, v)| !(*c == 100 && v == "AcDbTextObjectContextData"))); + assert!((num(t.iter().skip_while(|(c, _)| *c != 340).cloned().collect::>().as_slice(), 50) - 30.0).abs() < 1e-9, "{t:?}"); + } + for (_, t) in recs.iter().filter(|(k, _)| k == "ACDB_ALDIMOBJECTCONTEXTDATA_CLASS") { + assert!(get(t, 2).is_some_and(|b| b.starts_with("*D")), "{t:?}"); + } +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d85415123..58d531c85 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-29 · **Change:** minor (R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them; annotative text, MText and dimensions keep their scales on save) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds @@ -75,10 +75,10 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG |---|---|---|---| | LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE (widths, bulges, elevation), SPLINE, RAY, XLINE | yes | yes | round-trip tests | | POLYLINE 2D/3D | yes | yes (as LWPOLYLINE / 3D POLYLINE) | polyface and polygon meshes flattened: lossy | -| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line); changed attribute values refresh justified baselines, including small width changes | ATTDEF prompt kept (#137); unchanged values retain imported-font placement; a justified TEXT's insertion point (group 10, which AutoCAD takes from a DWG as it is) is computed as AutoCAD computes it: Middle (M) centred on the string's own extents, bottom justifications at a TrueType face's descent (#2229) | -| DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written for every associated kind — linear/aligned, angular, radial/diametric, ordinate and arc length — and read back without CADCraft's xdata (#1651) | -| DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written; angular block text honors DIMDSEP, including per-dimension overrides (#1646) | -| DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645) | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | +| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn; annotative text and MText from their annotation scale contexts | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line); annotative text and MText with `AcadAnnotative` and a context per scale (2007 and later); changed attribute values refresh justified baselines, including small width changes | ATTDEF prompt kept (#137); unchanged values retain imported-font placement; a context's own position at one scale (ANNORESET) is not modelled; a justified TEXT's insertion point (group 10, which AutoCAD takes from a DWG as it is) is computed as AutoCAD computes it: Middle (M) centred on the string's own extents, bottom justifications at a TrueType face's descent (#2229) | +| DIMENSION (all 7 kinds) | yes; annotative ones from their scale contexts | yes, with anonymous `*D` blocks; an annotative dimension gets a context and a `*D` block per scale | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written for every associated kind — linear/aligned, angular, radial/diametric, ordinate and arc length — and read back without CADCraft's xdata (#1651) | +| DIMENSION (all 7 kinds) | yes; annotative ones from their scale contexts | yes, with anonymous `*D` blocks; an annotative dimension gets a context and a `*D` block per scale | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written; angular block text honors DIMDSEP, including per-dimension overrides (#1646) | +| DIMENSION (all 7 kinds) | yes; annotative ones from their scale contexts | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645); an annotative dimension gets a context and a `*D` block per scale | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | | LEADER | yes | yes | | | MULTILEADER | yes (#459) | yes, native MULTILEADER with MLEADERSTYLE (#459) | several landings per multileader are folded into one; per-object overrides and annotative scale contexts not kept | | HATCH pattern / solid | yes | yes; associative hatches keep their boundary objects in blocks too, and the boundary carries the hatch reactor (stretched dynamic blocks drag the fill in AutoCAD) | | @@ -150,6 +150,7 @@ our output in AutoCAD black-box. | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | | 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) | +| 2026-10-15 | minor | Annotative text, MText and dimensions read and write AutoCAD's annotation scale contexts (DXF and DWG 2007 and later): written at their default scale with a context per scale, a dimension with a `*D` block per scale; read back at paper size. Before, AutoCAD's were dropped (the objects read as not annotative) and CADCraft's kept only in its own record | | 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 f8ddac941..d24ad1db5 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-30 · **Change:** minor (QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (F12: annotative text, MText and dimensions keep their scales on save) · **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). A PR names the rows it closes in its @@ -34,7 +34,7 @@ do them first. | F10 | MLEADEREDIT (add/remove leader), MLEADERALIGN and MLEADERCOLLECT landed, but a multileader has one landing and one block (a collection keeps the other blocks as block references beside it; MLEADERALIGN has no Options-menu preview); MLEADERSTYLE has 5 fields (block content and spline/no-leader types are per command, not in the style; block content has no attributes) | `annotate.rs`, `cmd/mleader_content.rs`, `tables.rs:417` | Medium | 8–12 | | F9 | MTEXT is typed in an on-canvas editor with a formatting toolbar (font, height, bold, italic, underline, overline, colour, alignment, lists, tab and special characters) and a ruler for indents and tab stops (#532); left: the box does not lay the text out by the indents, tabs, columns or font weights while typing (bold shows wider, overline is not drawn), no justification (attachment) or columns controls in the editor, existing MTEXT cannot be edited (no DDEDIT/MTEDIT), stacked fractions and other codes show as placeholders; no fields (FIELD, UPDATEFIELD) and no spell check (SPELL): open PR #551. Paragraph indents, tabs, bullets, numbering and columns landed (#547) | `ui-egui/mtext_editor.rs`, `engine/mtext_edit.rs` | Medium | 10–18 | | F11 | Tables (cell styles, formulas, TABLEDIT, TABLEEXPORT, table breaking and CSV data links landed, #534): formulas aren't read from or written as AutoCAD FIELD objects (other programs see values); number formats apply to formula results only; cell text doesn't wrap; custom cell styles, breaks and data links travel as CADCraft xdata (not through DWG); data links read CSV only (no Excel ranges, no write-back, not on the web); no cell-style tab in the Table Style dialog | `cmd/table/*`, `io/dxf_table.rs` | Low-medium | 6–10 | -| F12 | Annotative scaling done (#468): scale list (SCALELISTEDIT), CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE/ANNOAUTOSCALE, viewport scale, DXF, status bar list. Left: per-scale positions (ANNORESET is a no-op), a viewport annotation scale apart from its viewport scale, annotative objects inside blocks and old LEADERs, AutoCAD files' per-object scale contexts (read as not annotative) | `cmd/annoscale.rs`, `doc/src/anno.rs` | Low-medium | 4–8 | +| F12 | Annotative scaling done (#468): scale list (SCALELISTEDIT), CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE/ANNOAUTOSCALE, viewport scale, DXF, status bar list. Left: per-scale positions (ANNORESET is a no-op), a viewport annotation scale apart from its viewport scale, annotative objects inside blocks and old LEADERs, scale contexts of hatches and multileaders (text, MText, dimensions and block references read and write AutoCAD's contexts) | `cmd/annoscale.rs`, `doc/src/anno.rs` | Low-medium | 4–8 | | F14 | **[alpha blocker]** Plotting leftovers: binary `.ctb`/`.stb`/`.pc3` files can't be read; model-space PDF plots keep the default margins (a device paper's margins apply to layouts and PNG plots); no system printers (H3); the page setup's "Plot transparency" is not saved in DXF/DWG (the public DXF Reference has no plot layout flag for it), so it lasts for the session and in JSON only. The Plot dialog (#160), Plot Preview and PUBLISH (#186), plot styles (CTB and STB, [plot-styles.md](plot-styles.md), #410) with their end, join and fill styles, plotter devices with paper sizes and printable areas ([plotters.md](plotters.md), #564), and plotted transparency (page setup and Plot dialog option, PLOTTRANSPARENCYOVERRIDE) landed | `io/src/plotter.rs`, `cmd/plotters.rs` | Medium | 4–8 | | 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 | @@ -167,6 +167,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-15 | minor | BREAKLINE (Tools ▸ Express Tools ▸ Break-line Symbol): one polyline between two points with a break symbol, Block/Size/Extension options, size times DIMSCALE: E3 narrowed | | 2026-10-15 | minor | TXT2MTXT (Tools ▸ Express Tools ▸ Convert Text to Mtext): selected TEXT, and MTEXT, combined into one MTEXT top-down or in selection order with optional word wrap, or one MTEXT per TEXT; SEttings remembered for the session: E3 narrowed | | 2026-10-13 | minor | Selection window gesture preference (PICKDRAG 0/2) added to Options ▸ Selection and saved in the profile (U6), with Portuguese and Ukrainian labels | +| 2026-10-15 | minor | F12: annotative text, MText and dimensions keep their annotation scales on save as AutoCAD's scale contexts (AutoCAD files' contexts were dropped) | | 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 0b04db61e3ae3063cd2052b4db570957f4bee14e Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:59:15 -0600 Subject: [PATCH 014/258] DXF test: a justified text's start point is recomputed on save (since #1062) Co-Authored-By: Claude Opus 5.5 --- crates/io/tests/annotative_text_contexts.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/io/tests/annotative_text_contexts.rs b/crates/io/tests/annotative_text_contexts.rs index 8fdafaf72..7ede78f9a 100644 --- a/crates/io/tests/annotative_text_contexts.rs +++ b/crates/io/tests/annotative_text_contexts.rs @@ -479,9 +479,23 @@ fn a_saved_drawing_reads_back_the_same() { for h in ["30", "40", "50"] { let (a, b) = (d.entity(Handle::parse_hex(h).unwrap()).unwrap(), back.entity(Handle::parse_hex(h).unwrap()).unwrap()); assert_eq!(a.common.anno_scales, b.common.anno_scales, "{h}"); - if !matches!(a.kind, EntityKind::Dimension(_)) { - assert_eq!(a.kind, b.kind, "{h}"); + // A justified text's start point is worked out from its alignment point on save, as + // AutoCAD does; the rest reads back as it was. + let mut kind = a.kind.clone(); + if let (EntityKind::Text(t), EntityKind::Text(u)) = (&mut kind, &b.kind) + && t.align_pt.is_some() + { + t.insert = u.insert; } + if !matches!(a.kind, EntityKind::Dimension(_)) { + assert_eq!(kind, b.kind, "{h}"); + } + } + // Saved again, it reads back exactly. + let again = cadcraft_io::read_dxf(save(&back).as_bytes()).unwrap(); + for h in ["30", "40"] { + let h = Handle::parse_hex(h).unwrap(); + assert_eq!(back.entity(h).unwrap().kind, again.entity(h).unwrap().kind); } // Saved again, the file is the same: nothing piles up. assert_eq!(contexts_of(&save(&back), "30").len(), 2); From 3099c82881a1acd54f8f2b08660c9b13ae353c24 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:36:48 -0600 Subject: [PATCH 015/258] DXF: only annotative dimensions get a *D block per scale Annotative text and MText went through the dimension block planning too and left one empty anonymous *D block per scale in every saved file. The hostile contexts test now saves, opens the file again and checks the scales and that every context names a written SCALE. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_write/sections.rs | 10 ++++++---- crates/io/tests/annotative_text_contexts.rs | 17 ++++++++++++++++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index c1e478a6f..90d790d86 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -789,14 +789,16 @@ fn annotative_dimension_blocks( w: &mut W, (cx, dim_defs): (&mut Ctx, &mut Vec), ) -> Option> { + // Only dimensions have a block per scale (text and multileaders have none). + if !matches!(e.kind, EntityKind::Dimension(_)) { + return None; + } let (scales, default) = crate::dxf_anno::scales(d, e); let mut names = Vec::new(); for s in &scales { let at = crate::dxf_anno::at_scale(e, s.factor()); - let ents = match &at.kind { - EntityKind::Dimension(sdm) => dim_block_entities(d, sdm, &e.common.layer), - _ => Vec::new(), - }; + let EntityKind::Dimension(sdm) = &at.kind else { continue }; + let ents = dim_block_entities(d, sdm, &e.common.layer); let name = fresh_dim_name(d, n); dim_defs.push((name.clone(), w.h(), ents)); names.push(name); diff --git a/crates/io/tests/annotative_text_contexts.rs b/crates/io/tests/annotative_text_contexts.rs index 7ede78f9a..46676b543 100644 --- a/crates/io/tests/annotative_text_contexts.rs +++ b/crates/io/tests/annotative_text_contexts.rs @@ -466,6 +466,13 @@ fn each_object_is_written_at_its_default_scale_with_a_context_per_scale() { }; let (h2, h10) = (text_height(&blocks[0]), text_height(&blocks[1])); assert!((h10 / h2 - 5.0).abs() < 1e-9, "{h2} {h10}"); + // Only the dimension has blocks per scale: no empty `*D` block for the text or the MText. + let d_blocks: Vec<&str> = recs.iter().filter(|(k, _)| k == "BLOCK").filter_map(|(_, t)| get(t, 2)).filter(|n| n.starts_with("*D")).collect(); + assert_eq!(d_blocks.len(), 2, "{d_blocks:?}"); + for name in &d_blocks { + let start = recs.iter().position(|(k, t)| k == "BLOCK" && get(t, 2) == Some(name)).unwrap(); + assert_ne!(recs.get(start + 1).map(|(k, _)| k.as_str()), Some("ENDBLK"), "{name} is empty"); + } // Each context class is declared. for class in ["ACDB_TEXTOBJECTCONTEXTDATA_CLASS", "ACDB_MTEXTOBJECTCONTEXTDATA_CLASS", "ACDB_ALDIMOBJECTCONTEXTDATA_CLASS"] { assert!(recs.iter().any(|(k, t)| k == "CLASS" && get(t, 1) == Some(class)), "{class}"); @@ -628,7 +635,15 @@ fn hostile_contexts_do_not_panic() { let n = names(&d, h); assert!(n.len() <= 1, "{h}: {n:?}"); } - let _ = save(&d); + // Saved and opened again: the same scales, every context naming a written SCALE. + let text = save(&d); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + for h in ["30", "40", "50"] { + assert_eq!(names(&back, h), names(&d, h), "{h}"); + for c in contexts_of(&text, h) { + assert_ne!(c.scale, "?", "{h}: a context names a missing SCALE"); + } + } } #[cfg(not(target_arch = "wasm32"))] From 0f094da0ae423cbfe0b9dc1fd868fb0805834c4b Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Thu, 15 Oct 2026 12:19:48 -0600 Subject: [PATCH 016/258] DXF/DWG: annotative multileaders keep their annotation scales on save An annotative multileader's scale context (ACDB_MLEADEROBJECTCONTEXTDATA_CLASS) holds the multileader's whole CONTEXT_DATA body at that scale: overall scale (40), text height, arrowhead size, landing gap, content position and the leaders. CADCraft dropped AutoCAD's on read and wrote none, so annotative multileaders came back plain at the default scale's size, and AutoCAD showed CADCraft's at one size at every scale. Multileaders now go through the annotation scale contexts like text, MText and dimensions: written at the default scale with AcadAnnotative xdata and a context per scale (the entity writer's CONTEXT_DATA at that scale, with its overall scale and landing gap set), read back at paper size. The DWG bridge gives acadrust the CONTEXT_DATA{ group it reads the context after, and takes acadrust's braces and marker out again. Checked in AutoCAD: its own annotative multileader reads back at 1:2 and 1:10 at paper size, and the saved file reopens with text 0.18 / 0.9 as before; one made in CADCraft opens with text 2.5 / 25 at 1:1 / 1:10, the text moved with the scale. Co-Authored-By: Claude Opus 5.5 --- crates/dwg/src/lib.rs | 33 +++++++- crates/io/src/dxf_anno.rs | 61 +++++++++++--- crates/io/src/dxf_write/ctx.rs | 11 ++- crates/io/src/dxf_write/entity.rs | 17 ++-- crates/io/src/dxf_write/sections.rs | 2 +- crates/io/tests/annotative_text_contexts.rs | 90 +++++++++++++++++++++ docs/file-format-parity.md | 5 +- docs/gaps.md | 7 +- 8 files changed, 199 insertions(+), 27 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 78278898b..a63ee504f 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -582,8 +582,11 @@ mod native { /// `AcDbTextObjectContextData` marker, with the rotation in radians (as DWG holds it), and /// without the marker reads zeros (an annotative reference at scale 0 draws nothing in /// AutoCAD). Dimension contexts (`ACDB_*DIMOBJECTCONTEXTDATA_CLASS`): AutoCAD names the - /// geometry block in group 2, acadrust reads a BLOCK_RECORD handle there. Text that isn't - /// UTF-8, or has no such context, is returned as it is. + /// geometry block in group 2, acadrust reads a BLOCK_RECORD handle there. Multileader contexts + /// (`ACDB_MLEADEROBJECTCONTEXTDATA_CLASS`): AutoCAD has the multileader's context groups + /// straight after the scale, acadrust reads them only after a `300 CONTEXT_DATA{` group (and + /// writes them between it and `301 }` after an `AcDbMLeaderObjectContextData` marker). Text + /// that isn't UTF-8, or has no such context, is returned as it is. pub(crate) fn contexts(dxf: &[u8], to_acadrust: bool) -> Vec { const KINDS: [(&str, &str); 2] = [ ("ACDB_BLKREFOBJECTCONTEXTDATA_CLASS", "AcDbBlkRefObjectContextData"), @@ -591,7 +594,8 @@ mod native { ]; let is_dim = |k: &str| k.starts_with("ACDB_") && k.ends_with("DIMOBJECTCONTEXTDATA_CLASS"); let Ok(text) = std::str::from_utf8(dxf) else { return dxf.to_vec() }; - if !KINDS.iter().any(|(k, _)| text.contains(k)) && !text.contains("DIMOBJECTCONTEXTDATA_CLASS") { + const MLEADER: &str = "ACDB_MLEADEROBJECTCONTEXTDATA_CLASS"; + if !KINDS.iter().any(|(k, _)| text.contains(k)) && !text.contains("DIMOBJECTCONTEXTDATA_CLASS") && !text.contains(MLEADER) { return dxf.to_vec(); } let lines: Vec<&str> = text.split('\n').collect(); @@ -619,6 +623,8 @@ mod native { // The marker of the context being read (block reference or text), whether it is a // dimension's, whether its scale (340) was passed and whether its marker was. let (mut marker, mut dim, mut scaled, mut marked) = (None::<&str>, false, false, false); + // In a multileader context: whether its scale was passed and its body opened. + let (mut ml, mut ml_scaled, mut ml_open) = (false, false, false); let mut i = 0; while let (Some(&code_line), Some(&value_line)) = (lines.get(i), lines.get(i + 1)) { let (code, value) = (code_line.trim(), value_line.trim_end_matches('\r')); @@ -627,6 +633,27 @@ mod native { marker = KINDS.iter().find(|(k, _)| *k == kind).map(|(_, m)| *m); dim = is_dim(kind); (scaled, marked) = (false, false); + (ml, ml_scaled, ml_open) = (kind == MLEADER, false, false); + } + if ml { + let v = value.trim(); + // acadrust's braces and marker go. + let theirs = (code == "100" && v == "AcDbMLeaderObjectContextData") + || (code == "300" && v.starts_with("CONTEXT_DATA")) + || (code == "301" && v == "}"); + if theirs && !to_acadrust { + i += 2; + continue; + } + if to_acadrust && ml_scaled && !ml_open { + out.push(format!("300{}", eol(code_line))); + out.push(format!("CONTEXT_DATA{{{}", eol(value_line))); + ml_open = true; + } + // The first 340 is the scale (a later one is the text style). + if code == "340" && !ml_scaled { + ml_scaled = true; + } } let mut value = value.to_string(); if let Some(m) = marker { diff --git a/crates/io/src/dxf_anno.rs b/crates/io/src/dxf_anno.rs index 88b02d10c..9f0a2129a 100644 --- a/crates/io/src/dxf_anno.rs +++ b/crates/io/src/dxf_anno.rs @@ -1,11 +1,12 @@ -//! Annotative text, MText and dimensions in DXF, as AutoCAD keeps them. An annotative object +//! Annotative text, MText, dimensions and multileaders in DXF, as AutoCAD keeps them. An annotative object //! carries `AcadAnnotative` xdata and, in its extension dictionary under //! `AcDbContextDataManager`, a dictionary `ACDB_ANNOTATIONSCALES` with one "object context data" //! object per annotation scale it supports (`*A1`, `*A2`…). Each context names its SCALE object //! (340), says whether it is the default one (290 = 1, the scale the object's own groups are //! written at) and holds what changes with the scale: a text's insertion and alignment points, an //! MText's insertion point, width and columns, a dimension's text position and the anonymous `*D` -//! block with its geometry at that scale. +//! block with its geometry at that scale, a multileader's whole `CONTEXT_DATA{` body at that +//! scale. //! //! CADCraft keeps an annotative object at paper size with the list of scales it supports //! ([`cadcraft_doc::Common::anno_scales`]). It writes the object at its default scale with a @@ -18,7 +19,7 @@ use std::collections::{BTreeSet, HashMap}; -use cadcraft_doc::{AnnoScale, DimKind, Drawing, Entity, EntityKind, HAlign, Handle, MTextColumnType, Text, VAlign}; +use cadcraft_doc::{AnnoScale, DimKind, Drawing, Entity, EntityKind, HAlign, Handle, MLeader, MTextColumnType, Text, VAlign}; use cadcraft_dxf::{Section, Tag}; use cadcraft_geom::Vec3; @@ -30,6 +31,7 @@ const ANGDIM: (&str, &str) = ("ACDB_ANGDIMOBJECTCONTEXTDATA_CLASS", "AcDbAngular const RADIM: (&str, &str) = ("ACDB_RADIMOBJECTCONTEXTDATA_CLASS", "AcDbRadialDimensionObjectContextData"); const DMDIM: (&str, &str) = ("ACDB_DMDIMOBJECTCONTEXTDATA_CLASS", "AcDbDiametricDimensionObjectContextData"); const ORDDIM: (&str, &str) = ("ACDB_ORDDIMOBJECTCONTEXTDATA_CLASS", "AcDbOrdinateDimensionObjectContextData"); +const MLEADER: (&str, &str) = ("ACDB_MLEADEROBJECTCONTEXTDATA_CLASS", "AcDbMLeaderObjectContextData"); /// The extension dictionary entry and the dictionary of contexts. const MANAGER_KEY: &str = "AcDbContextDataManager"; @@ -39,9 +41,9 @@ const SCALES_KEY: &str = "ACDB_ANNOTATIONSCALES"; const MAX_CONTEXTS: usize = cadcraft_doc::MAX_SCALES; /// Whether `e` (in model space or a layout) is written with annotation scale contexts: annotative -/// text, MText and dimensions. +/// text, MText, dimensions and multileaders. pub(crate) fn has_contexts(e: &Entity) -> bool { - cadcraft_doc::is_annotative(e) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_)) + cadcraft_doc::is_annotative(e) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_)) } /// The scales `e` is written at (valid, each name once) and which of them is the default: the @@ -121,6 +123,7 @@ fn class_of(e: &Entity) -> Option<(&'static str, &'static str)> { Some(match &e.kind { EntityKind::Text(_) => TEXT, EntityKind::MText(_) => MTEXT, + EntityKind::MLeader(_) => MLEADER, EntityKind::Dimension(dm) => match dm.kind { DimKind::Linear { .. } | DimKind::Aligned | DimKind::ArcLength => ALDIM, DimKind::Angular | DimKind::Angular3P => ANGDIM, @@ -210,8 +213,8 @@ fn dictionary(out: &mut Vec, h: &str, owner: &str, cloning: bool, entries: /// The objects of annotative object `e` planned as `o`: its extension dictionary (unless the /// DIMASSOC's holds the manager), the context manager, the dictionary of contexts and the -/// contexts. -pub(crate) fn objects(d: &Drawing, e: &Entity, o: &Obj) -> Vec { +/// contexts. `mleader` gives a multileader's groups as the entity writer writes them. +pub(crate) fn objects(d: &Drawing, e: &Entity, o: &Obj, mleader: &dyn Fn(&MLeader) -> Vec) -> Vec { let mut out = Vec::new(); let eh = e.handle.hex(); if o.own_xdict { @@ -231,14 +234,26 @@ pub(crate) fn objects(d: &Drawing, e: &Entity, o: &Obj) -> Vec { out.push(Tag::i(290, i64::from(c.default))); out.push(Tag::s(100, "AcDbAnnotScaleObjectContextData")); out.push(Tag::s(340, c.scale.clone())); - context_groups(&mut out, d, &at_scale(e, c.factor), c); + context_groups(&mut out, d, &at_scale(e, c.factor), c, mleader); } out } /// What a context holds of `e` (already at the context's scale). -fn context_groups(out: &mut Vec, d: &Drawing, e: &Entity, c: &Context) { +fn context_groups(out: &mut Vec, d: &Drawing, e: &Entity, c: &Context, mleader: &dyn Fn(&MLeader) -> Vec) { match &e.kind { + // The multileader's `CONTEXT_DATA{` body, without its braces. + EntityKind::MLeader(m) => { + let mut tags = mleader(m); + mleader_at(&mut tags, c.factor); + let open = tags.iter().position(|t| t.code == 300 && t.str().trim_start().starts_with("CONTEXT_DATA")); + let close = tags.iter().position(|t| t.code == 301); + if let (Some(a), Some(b)) = (open, close) + && a < b + { + out.extend(tags.get(a + 1..b).unwrap_or(&[]).iter().cloned()); + } + } EntityKind::Text(t) => { let h = match t.halign { HAlign::Left => 0, @@ -310,6 +325,28 @@ fn context_groups(out: &mut Vec, d: &Drawing, e: &Entity, c: &Context) { } } +/// A multileader's groups (as [`crate::dxf_mleader::entity_tags`] writes them) at annotation +/// scale `f`: its context's overall scale (40) is `f` and its landing gap (145) is at that scale. +pub(crate) fn mleader_at(tags: &mut [Tag], f: f64) { + let Some(open) = tags.iter().position(|t| t.code == 300 && t.str().trim_start().starts_with("CONTEXT_DATA")) else { return }; + let (mut scale, mut gap) = (false, false); + for t in tags.iter_mut().skip(open + 1) { + match t.code { + // The context's own groups end where its leaders start. + 302 | 301 => break, + 40 if !scale => { + *t = Tag::f(40, f); + scale = true; + } + 145 if !gap => { + *t = Tag::f(145, t.f64() * f); + gap = true; + } + _ => {} + } + } +} + // --------------------------------------------------------------------------------------------- // Reading @@ -362,7 +399,7 @@ pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { let mut found: Vec<(Handle, Handle)> = Vec::new(); for s in secs.iter().filter(|s| s.name == "ENTITIES" || s.name == "BLOCKS") { each_record(&s.tags, |kind, tags| { - if !matches!(kind, "TEXT" | "MTEXT" | "DIMENSION" | "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION") { + if !matches!(kind, "TEXT" | "MTEXT" | "DIMENSION" | "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION" | "MULTILEADER") { return; } let h = own(tags).iter().find(|t| t.code == 5).and_then(|t| key(&t.str())); @@ -373,7 +410,7 @@ pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { } for (h, xdict) in found { let Some(e) = d.entity(h) else { continue }; - if !matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_)) { + if !matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_)) { continue; } let dict = objs @@ -431,6 +468,8 @@ fn to_paper(e: &mut Entity, f: f64) { c.scale(inv); } } + // Its sizes, and its content's place about the landing, scale linearly. + EntityKind::MLeader(_) => e.kind = cadcraft_doc::anno_scaled(e, inv).kind, _ => {} } } diff --git a/crates/io/src/dxf_write/ctx.rs b/crates/io/src/dxf_write/ctx.rs index 0eb16828e..96a51b0c7 100644 --- a/crates/io/src/dxf_write/ctx.rs +++ b/crates/io/src/dxf_write/ctx.rs @@ -1,4 +1,4 @@ -use super::{DimVal, Entity, Handle, HashMap, K, Vec3, Version, W, dxf_ext}; +use super::{DimVal, Drawing, Entity, Handle, HashMap, K, MLeader, Tag, Vec3, Version, W, dxf_ext}; /// The `DIMASSOC` object of an associative dimension (stored in the dimension's extension /// dictionary under `ACAD_DIMASSOC`). @@ -70,6 +70,15 @@ impl Ctx { pub(super) fn at_default(&self, e: &Entity) -> Option { self.anno.objs.get(&e.handle).map(|o| crate::dxf_anno::at_scale(e, crate::dxf_anno::default_factor(o))) } + /// A native MULTILEADER's groups after its `AcDbMLeader` marker. + pub(super) fn mleader_tags(&self, d: &Drawing, m: &MLeader) -> Vec { + let refs = crate::dxf_mleader::Refs { + style: self.mleader_style(&m.style), + text_style: m.text.as_ref().and_then(|t| self.style(&t.style)), + block: m.block.as_ref().and_then(|b| self.block_records.get(&b.block.to_ascii_uppercase()).cloned()), + }; + crate::dxf_mleader::entity_tags(d, m, &refs) + } /// `AcadAnnotative` xdata of an object written with contexts. pub(super) fn anno_xdata(&self, w: &mut W, e: &Entity) { if self.anno.objs.contains_key(&e.handle) { diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 7e5c18408..5d1e28b56 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -504,14 +504,19 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap match &e.kind { EntityKind::MLeader(m) if !cx.native_mleader() => mleader_fallback(w, d, e, m, owner, paper, cx), EntityKind::MLeader(m) => { + let scaled = cx.at_default(e); + let m = match scaled.as_ref().map(|s| &s.kind) { + Some(EntityKind::MLeader(s)) => s, + _ => m, + }; w.s(0, "MULTILEADER"); common(w, e, owner, paper, "AcDbMLeader"); - let refs = crate::dxf_mleader::Refs { - style: cx.mleader_style(&m.style), - text_style: m.text.as_ref().and_then(|t| cx.style(&t.style)), - block: m.block.as_ref().and_then(|b| cx.block_records.get(&b.block.to_ascii_uppercase()).cloned()), - }; - w.t.extend(crate::dxf_mleader::entity_tags(d, m, &refs)); + let mut tags = cx.mleader_tags(d, m); + if let Some(o) = cx.anno.objs.get(&e.handle) { + crate::dxf_anno::mleader_at(&mut tags, crate::dxf_anno::default_factor(o)); + } + w.t.extend(tags); + cx.anno_xdata(w, e); } EntityKind::Leader(l) => { w.s(0, "LEADER"); diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 90d790d86..6aba8f118 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -744,7 +744,7 @@ fn write_annotation_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { annos.sort_by_key(|(h, _)| **h); for (h, o) in annos { if let Some(e) = plan.d.entity(*h) { - w.t.extend(crate::dxf_anno::objects(plan.d, e, o)); + w.t.extend(crate::dxf_anno::objects(plan.d, e, o, &|m| plan.cx.mleader_tags(plan.d, m))); } } } diff --git a/crates/io/tests/annotative_text_contexts.rs b/crates/io/tests/annotative_text_contexts.rs index 46676b543..0a7a91f79 100644 --- a/crates/io/tests/annotative_text_contexts.rs +++ b/crates/io/tests/annotative_text_contexts.rs @@ -685,3 +685,93 @@ fn text_mtext_and_dimensions_keep_their_scales_through_dwg() { assert!(get(t, 2).is_some_and(|b| b.starts_with("*D")), "{t:?}"); } } + +/// A drawing made in CADCraft with an annotative multileader (text 2.5 on paper, 1:1 and 1:10, +/// 1:10 current). +fn with_mleader() -> (Drawing, Handle) { + let mut d = Drawing::default(); + d.header.set_str("CANNOSCALE", "1:10"); + let common = Common { anno_scales: vec![AnnoScale::new("1:1", 1.0, 1.0), AnnoScale::new("1:10", 1.0, 10.0)], ..Common::default() }; + let text = cadcraft_doc::MText { + insert: Vec3::new(10.5, 10.1, 0.0), + height: 2.5, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "Note".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + let m = cadcraft_doc::MLeader { + leaders: vec![vec![Vec3::ZERO]], + landing: Vec3::new(10.0, 10.0, 0.0), + dogleg: 0.36, + text: Some(text), + style: "Standard".into(), + arrow_size: 0.18, + spline: false, + block: None, + }; + let h = d.add(&Space::Model, common, EntityKind::MLeader(m)).unwrap(); + (d, h) +} + +#[test] +fn a_multileader_gets_its_context_data_at_each_scale() { + let (d, h) = with_mleader(); + let text = save(&d); + let recs = records(&text); + let ent = recs.iter().find(|(k, t)| k == "MULTILEADER" && get(t, 5) == Some(h.hex().as_str())).unwrap(); + assert!(ent.1.iter().any(|(c, v)| *c == 1001 && v == "AcadAnnotative")); + // The entity is at 1:10, the current scale: overall scale 10 and text 25. + assert_eq!(num(&ent.1, 40), 10.0); + assert_eq!(num(&ent.1, 41), 25.0); + let ctx = contexts_of(&text, &h.hex()); + let got: Vec<(&str, bool, &str)> = ctx.iter().map(|c| (c.scale.as_str(), c.default, c.class.as_str())).collect(); + assert_eq!(got, [("1:1", false, "ACDB_MLEADEROBJECTCONTEXTDATA_CLASS"), ("1:10", true, "ACDB_MLEADEROBJECTCONTEXTDATA_CLASS")]); + for (c, f) in ctx.iter().zip([1.0, 10.0]) { + // AutoCAD's layout: the context groups straight after the scale, no braces of their own. + assert_eq!(c.tags.first().map(|t| t.0), Some(40), "{:?}", c.tags); + assert!(c.tags.iter().all(|(code, v)| !(*code == 300 && v.starts_with("CONTEXT_DATA")) && *code != 301)); + assert_eq!(num(&c.tags, 40), f); + assert!((num(&c.tags, 41) - 2.5 * f).abs() < 1e-9); + assert!((num(&c.tags, 140) - 0.18 * f).abs() < 1e-9); + // The text keeps its place about the landing, at the scale's size. + assert!((num(&c.tags, 12) - (10.0 + 0.5 * f)).abs() < 1e-9 && (num(&c.tags, 22) - (10.0 + 0.1 * f)).abs() < 1e-9); + } + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let (a, b) = (d.entity(h).unwrap(), back.entity(h).unwrap()); + assert_eq!(a.common.anno_scales, b.common.anno_scales); + let (EntityKind::MLeader(x), EntityKind::MLeader(y)) = (&a.kind, &b.kind) else { panic!("multileader") }; + let (tx, ty) = (x.text.as_ref().unwrap(), y.text.as_ref().unwrap()); + assert!((tx.height - ty.height).abs() < 1e-9 && (tx.insert - ty.insert).len() < 1e-9, "{ty:?}"); + assert!((x.arrow_size - y.arrow_size).abs() < 1e-9 && (x.dogleg - y.dogleg).abs() < 1e-9, "{y:?}"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_multileader_keeps_its_scales_through_dwg() { + let (d, _) = with_mleader(); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + let e = back.model.iter().find(|e| matches!(e.kind, EntityKind::MLeader(_))).unwrap(); + let got: Vec<&str> = e.common.anno_scales.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(got, ["1:1", "1:10"]); + let EntityKind::MLeader(m) = &e.kind else { panic!("multileader") }; + assert!((m.text.as_ref().unwrap().height - 2.5).abs() < 1e-9, "{m:?}"); + // The DXF read back from the DWG has AutoCAD's layout and each context at its scale. + let text = String::from_utf8_lossy(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned(); + let ctx: Vec = records(&text).into_iter().filter(|(k, _)| k == "ACDB_MLEADEROBJECTCONTEXTDATA_CLASS").collect(); + let mut scales: Vec = ctx + .iter() + .map(|(_, t)| { + assert!(t.iter().all(|(c, v)| !(*c == 300 && v.starts_with("CONTEXT_DATA"))), "{t:?}"); + let at = t.iter().position(|(c, _)| *c == 340).unwrap(); + num(&t[at + 1..], 40) + }) + .collect(); + scales.sort_by(f64::total_cmp); + assert_eq!(scales, [1.0, 10.0]); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 58d531c85..a2355bc63 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-29 · **Change:** minor (R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them; annotative text, MText and dimensions keep their scales on save) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them; annotative text, MText, dimensions and multileaders keep their scales on save) · **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 @@ -80,7 +80,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | DIMENSION (all 7 kinds) | yes; annotative ones from their scale contexts | yes, with anonymous `*D` blocks; an annotative dimension gets a context and a `*D` block per scale | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written; angular block text honors DIMDSEP, including per-dimension overrides (#1646) | | DIMENSION (all 7 kinds) | yes; annotative ones from their scale contexts | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645); an annotative dimension gets a context and a `*D` block per scale | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | | LEADER | yes | yes | | -| MULTILEADER | yes (#459) | yes, native MULTILEADER with MLEADERSTYLE (#459) | several landings per multileader are folded into one; per-object overrides and annotative scale contexts not kept | +| MULTILEADER | yes (#459) | yes, native MULTILEADER with MLEADERSTYLE (#459) | several landings per multileader are folded into one; per-object overrides not kept; annotative ones keep their scales as AutoCAD's scale contexts (2007 and later) | | HATCH pattern / solid | yes | yes; associative hatches keep their boundary objects in blocks too, and the boundary carries the hatch reactor (stretched dynamic blocks drag the fill in AutoCAD) | | | HATCH gradient | yes | yes (#162, fixes #80) | | | SOLID, TRACE, 3DFACE | yes | yes | | @@ -150,6 +150,7 @@ our output in AutoCAD black-box. | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | | 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) | +| 2026-10-15 | minor | Annotative multileaders read and write AutoCAD's annotation scale contexts (each context the multileader's `CONTEXT_DATA` at its scale), DXF and DWG | | 2026-10-15 | minor | Annotative text, MText and dimensions read and write AutoCAD's annotation scale contexts (DXF and DWG 2007 and later): written at their default scale with a context per scale, a dimension with a `*D` block per scale; read back at paper size. Before, AutoCAD's were dropped (the objects read as not annotative) and CADCraft's kept only in its own record | | 2026-10-12 | minor | PDF output: object transparency plotted as PDF alpha (`/ExtGState` `/ca` `/CA`) when the page setup's or the plot's "Plot transparency" is on; PNG plots blend it, SVG uses `opacity`; plots without it are unchanged byte for byte | | 2026-10-12 | minor | DXF/DWG save: the Model layout's plot settings are written as CADCraft plots model space, drawing extents scaled to fit (PLOTSETTINGS 74 = 1, 75 = 0), instead of plot type 5 "Layout information", which other programs' Plot dialogs can't use for model space | diff --git a/docs/gaps.md b/docs/gaps.md index d24ad1db5..c5ed8dccd 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 (F12: annotative text, MText and dimensions keep their scales on save) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (F12, FF2: annotative text, MText, dimensions and multileaders keep their scales on save) · **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). A PR names the rows it closes in its @@ -34,7 +34,7 @@ do them first. | F10 | MLEADEREDIT (add/remove leader), MLEADERALIGN and MLEADERCOLLECT landed, but a multileader has one landing and one block (a collection keeps the other blocks as block references beside it; MLEADERALIGN has no Options-menu preview); MLEADERSTYLE has 5 fields (block content and spline/no-leader types are per command, not in the style; block content has no attributes) | `annotate.rs`, `cmd/mleader_content.rs`, `tables.rs:417` | Medium | 8–12 | | F9 | MTEXT is typed in an on-canvas editor with a formatting toolbar (font, height, bold, italic, underline, overline, colour, alignment, lists, tab and special characters) and a ruler for indents and tab stops (#532); left: the box does not lay the text out by the indents, tabs, columns or font weights while typing (bold shows wider, overline is not drawn), no justification (attachment) or columns controls in the editor, existing MTEXT cannot be edited (no DDEDIT/MTEDIT), stacked fractions and other codes show as placeholders; no fields (FIELD, UPDATEFIELD) and no spell check (SPELL): open PR #551. Paragraph indents, tabs, bullets, numbering and columns landed (#547) | `ui-egui/mtext_editor.rs`, `engine/mtext_edit.rs` | Medium | 10–18 | | F11 | Tables (cell styles, formulas, TABLEDIT, TABLEEXPORT, table breaking and CSV data links landed, #534): formulas aren't read from or written as AutoCAD FIELD objects (other programs see values); number formats apply to formula results only; cell text doesn't wrap; custom cell styles, breaks and data links travel as CADCraft xdata (not through DWG); data links read CSV only (no Excel ranges, no write-back, not on the web); no cell-style tab in the Table Style dialog | `cmd/table/*`, `io/dxf_table.rs` | Low-medium | 6–10 | -| F12 | Annotative scaling done (#468): scale list (SCALELISTEDIT), CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE/ANNOAUTOSCALE, viewport scale, DXF, status bar list. Left: per-scale positions (ANNORESET is a no-op), a viewport annotation scale apart from its viewport scale, annotative objects inside blocks and old LEADERs, scale contexts of hatches and multileaders (text, MText, dimensions and block references read and write AutoCAD's contexts) | `cmd/annoscale.rs`, `doc/src/anno.rs` | Low-medium | 4–8 | +| F12 | Annotative scaling done (#468): scale list (SCALELISTEDIT), CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE/ANNOAUTOSCALE, viewport scale, DXF, status bar list. Left: per-scale positions (ANNORESET is a no-op), a viewport annotation scale apart from its viewport scale, annotative objects inside blocks and old LEADERs, scale contexts of hatches (text, MText, dimensions, multileaders and block references read and write AutoCAD's contexts) | `cmd/annoscale.rs`, `doc/src/anno.rs` | Low-medium | 4–8 | | F14 | **[alpha blocker]** Plotting leftovers: binary `.ctb`/`.stb`/`.pc3` files can't be read; model-space PDF plots keep the default margins (a device paper's margins apply to layouts and PNG plots); no system printers (H3); the page setup's "Plot transparency" is not saved in DXF/DWG (the public DXF Reference has no plot layout flag for it), so it lasts for the session and in JSON only. The Plot dialog (#160), Plot Preview and PUBLISH (#186), plot styles (CTB and STB, [plot-styles.md](plot-styles.md), #410) with their end, join and fill styles, plotter devices with paper sizes and printable areas ([plotters.md](plotters.md), #564), and plotted transparency (page setup and Plot dialog option, PLOTTRANSPARENCYOVERRIDE) landed | `io/src/plotter.rs`, `cmd/plotters.rs` | Medium | 4–8 | | 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 | @@ -74,7 +74,7 @@ Detail: [file-format-parity.md](file-format-parity.md). | # | Gap | User impact | Est. | |---|---|---|---| | FF1 | **[alpha blocker]** Round-trip what we don't model. DXF done (#528): unknown entities and objects (with their CLASS records), foreign xdata (hyperlinks included), extension dictionaries, persistent reactors, DICTIONARYVAR and XRECORDs, layer states, colour book colours, references remapped on save; IMAGE, VIEW/UCS, groups, block descriptions, true colours, transparency (#201, #204, #208, #209, #213, #223); WIPEOUT and gradients (#147, #162). Left: through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour book names and reactors; UCS elevation; MTEXT background colours; unknown entities follow only layer edits, and renamed layers and blocks lose their foreign data A user's QSAVE now asks before such a loss and keeps the previous file as `.bak`; the loss itself remains. | High | 6–10 | -| FF2 | Multileader leftovers (native MULTILEADER read/write landed, #459): several landings per multileader (extra leader roots are folded into the lines), per-object overrides (leader colour and linetype, arrowhead symbol, text frame), annotative scale contexts; check the text placement of our MULTILEADER output in AutoCAD | Medium | 3–5 | +| FF2 | Multileader leftovers (native MULTILEADER read/write landed, #459): several landings per multileader (extra leader roots are folded into the lines), per-object overrides (leader colour and linetype, arrowhead symbol, text frame); check the text placement of our MULTILEADER output in AutoCAD | Medium | 3–5 | | FF3 | Save-version leftovers (DXF/DWG 2000–2018, binary DXF, SAVEAS `version`/`binary` and the default save version landed, #421): no R14 DWG or R12 DXF output; the Save dialog can't pick the version per file (the file picker doesn't report the chosen type; File > Default Save Format sets it); no command-line SAVEAS format prompt | Low | 2–4 | | FF4 | Code-page leftovers (pre-2007 DXF read in their `$DWGCODEPAGE` landed, #505): Johab (ANSI_1361) and DOS 855/857/860–865/869 read as ANSI_1252; saving declares `ANSI_1252` instead of the file's code page (the text is pure ASCII, so still correct); acadrust approximates DOS code pages in pre-2007 DWG (DOS437 as 866, DOS850 as 1252) | Low | 1–2 | | FF5 | **[alpha blocker]** Real-file corpus (`storytold/cadcraft-corpus`), open → save → reopen tests, black-box check in AutoCAD | High | 10–15 + human | @@ -167,6 +167,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-15 | minor | BREAKLINE (Tools ▸ Express Tools ▸ Break-line Symbol): one polyline between two points with a break symbol, Block/Size/Extension options, size times DIMSCALE: E3 narrowed | | 2026-10-15 | minor | TXT2MTXT (Tools ▸ Express Tools ▸ Convert Text to Mtext): selected TEXT, and MTEXT, combined into one MTEXT top-down or in selection order with optional word wrap, or one MTEXT per TEXT; SEttings remembered for the session: E3 narrowed | | 2026-10-13 | minor | Selection window gesture preference (PICKDRAG 0/2) added to Options ▸ Selection and saved in the profile (U6), with Portuguese and Ukrainian labels | +| 2026-10-15 | minor | F12, FF2: annotative multileaders keep their annotation scales on save (AutoCAD's scale contexts) | | 2026-10-15 | minor | F12: annotative text, MText and dimensions keep their annotation scales on save as AutoCAD's scale contexts (AutoCAD files' contexts were dropped) | | 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 | From e89ff0832d99e6fe8d17cd70e31c74f17689a39c Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Thu, 15 Oct 2026 12:56:25 -0600 Subject: [PATCH 017/258] DXF: the current annotation scale is AutoCAD's CANNOSCALE variable AutoCAD keeps the current annotation scale in the named object dictionary's AcDbVariableDictionary, as a DICTIONARYVAR CANNOSCALE naming the scale. CADCraft read only its own record, so AutoCAD's drawings opened at 1:1 whatever their scale (annotative objects then showed at their first scale), and the variable was written back as read, so AutoCAD reopened a drawing at its old scale after CADCraft changed it. The variable is read when the scale is in the list (after CADCraft's record: AutoCAD keeps that record as it was, so the variable is the newer one), and the kept variable is written with the drawing's current scale. Annotative objects are written at that scale. Checked in CADCraft and AutoCAD: an AutoCAD drawing at 1:2 opens at 1:2; switched to 1:10 and saved as DXF and DWG, AutoCAD opens both at 1:10. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_anno.rs | 16 +++++++++++++ crates/io/src/dxf_raw.rs | 18 ++++++++++++++ crates/io/tests/annotative_text_contexts.rs | 26 +++++++++++++++++++++ docs/file-format-parity.md | 1 + 4 files changed, 61 insertions(+) diff --git a/crates/io/src/dxf_anno.rs b/crates/io/src/dxf_anno.rs index 9f0a2129a..dc968bcef 100644 --- a/crates/io/src/dxf_anno.rs +++ b/crates/io/src/dxf_anno.rs @@ -390,6 +390,7 @@ pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { objs.entry(h).or_insert((kind.to_ascii_uppercase(), tags)); } }); + current_scale(&objs, d); if !objs.values().any(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) { return; } @@ -445,6 +446,21 @@ pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { } } +/// The current annotation scale as AutoCAD keeps it: in the named object dictionary's +/// `AcDbVariableDictionary`, a DICTIONARYVAR `CANNOSCALE` with the scale's name (group 1). It is +/// newer than CADCraft's own record when AutoCAD saved the file last (AutoCAD keeps that record as +/// it was), and CADCraft writes the two alike. A name the scale list lacks is passed over. +fn current_scale(objs: &HashMap, d: &mut Drawing) { + let root = objs.iter().filter(|(_, (k, t))| k == "DICTIONARY" && own(t).iter().find(|t| t.code == 330).is_some_and(|o| o.str().trim() == "0")); + let Some((_, (_, root))) = root.min_by_key(|(h, _)| h.0) else { return }; + let var = entry(root, "AcDbVariableDictionary").and_then(|v| objs.get(&v)).and_then(|(_, t)| entry(t, "CANNOSCALE")).and_then(|c| objs.get(&c)); + let Some(name) = var.and_then(|(_, t)| own(t).iter().find(|t| t.code == 1).map(Tag::str)) else { return }; + let name = name.trim(); + if d.anno_scale(name).is_some_and(AnnoScale::is_valid) { + d.header.set_str("CANNOSCALE", name); + } +} + /// Take an object written at annotation scale `f` back to paper size (the inverse of /// [`at_scale`]). fn to_paper(e: &mut Entity, f: f64) { diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 95d3ade50..6d96161e6 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -1131,6 +1131,23 @@ fn reconcile( out } +/// AutoCAD's current annotation scale, kept with its variable dictionary (the named object +/// dictionary's `AcDbVariableDictionary`, a DICTIONARYVAR `CANNOSCALE` with the scale's name in +/// group 1), brought up to date with the drawing's: AutoCAD opens the drawing at that scale. +/// `None` when the file had none. +fn current_scale(f: &Foreign, d: &Drawing) -> Option<(String, ForeignObject)> { + let vars = f.dictionary.iter().find(|(k, _)| k.trim().eq_ignore_ascii_case("AcDbVariableDictionary"))?.1; + let object = |h: &str| f.objects.iter().find(|o| o.handle.hex() == norm(h)); + let dict = object(&vars.hex())?; + let at = dict.tags.iter().position(|t| t.code == 3 && t.value.trim().eq_ignore_ascii_case("CANNOSCALE"))?; + let var = dict.tags.get(at + 1).filter(|t| matches!(t.code, 350 | 360))?; + let mut o = object(&var.value)?.clone(); + let name = d.header.str("CANNOSCALE", "1:1"); + let value = o.tags.iter_mut().find(|t| t.code == 1)?; + value.value = name; + Some((o.handle.hex(), o)) +} + /// Drop an extension dictionary's modelled entries (key and handle) from its groups (`of_insert`: /// it is a block reference's). fn strip_entries(tags: &mut Vec, of_insert: bool) { @@ -1225,6 +1242,7 @@ fn refreshed_contexts( let mut contexts = block_contexts(f, d, owners); let attribute = attribute_contexts(f, d, owners, &contexts); contexts.extend(attribute); + contexts.extend(current_scale(f, d)); let rec = reconcile(f, d, owners, roles, &mut contexts, seed(tags).max(max_handle(tags))); for o in &rec.added { if let Some(parent) = o.tags.iter().find(|t| t.code == 330) { diff --git a/crates/io/tests/annotative_text_contexts.rs b/crates/io/tests/annotative_text_contexts.rs index 0a7a91f79..e7ad3e3a7 100644 --- a/crates/io/tests/annotative_text_contexts.rs +++ b/crates/io/tests/annotative_text_contexts.rs @@ -775,3 +775,29 @@ fn a_multileader_keeps_its_scales_through_dwg() { scales.sort_by(f64::total_cmp); assert_eq!(scales, [1.0, 10.0]); } + +/// The fixture with AutoCAD's variable dictionary naming 1:10 as the current annotation scale. +fn with_current_scale() -> String { + dxf(FIXTURE) + .replace("3\nACAD_SCALELIST\n350\n10\n", "3\nACAD_SCALELIST\n350\n10\n3\nAcDbVariableDictionary\n350\n60\n") + .replace( + "0\nENDSEC\n0\nEOF\n", + "0\nDICTIONARY\n5\n60\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nCANNOSCALE\n350\n61\n0\nDICTIONARYVAR\n5\n61\n330\n60\n100\nDictionaryVariables\n280\n0\n1\n1:10\n0\nENDSEC\n0\nEOF\n", + ) +} + +#[test] +fn the_current_scale_is_autocad_s_and_saving_keeps_it_current() { + let mut d = cadcraft_io::read_dxf(with_current_scale().as_bytes()).unwrap(); + assert_eq!(d.header.str("CANNOSCALE", ""), "1:10"); + // Written at the current scale: the 1:10 context is the default one. + let text = save(&d); + let got: Vec<(String, bool)> = contexts_of(&text, "30").into_iter().map(|c| (c.scale, c.default)).collect(); + assert_eq!(got, [("1:2".to_string(), false), ("1:10".to_string(), true)]); + // Changed in CADCraft, AutoCAD's variable says so too. + d.header.set_str("CANNOSCALE", "1:2"); + let recs = records(&save(&d)); + let var = recs.iter().find(|(k, _)| k == "DICTIONARYVAR").unwrap(); + assert_eq!(get(&var.1, 1), Some("1:2")); + assert_eq!(recs.iter().filter(|(k, _)| k == "DICTIONARYVAR").count(), 1); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index a2355bc63..00b40a4e5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -150,6 +150,7 @@ our output in AutoCAD black-box. | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | | 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) | +| 2026-10-15 | minor | The current annotation scale is read from and written to AutoCAD's variable dictionary (`AcDbVariableDictionary` CANNOSCALE), so a drawing opens at its scale in either program | | 2026-10-15 | minor | Annotative multileaders read and write AutoCAD's annotation scale contexts (each context the multileader's `CONTEXT_DATA` at its scale), DXF and DWG | | 2026-10-15 | minor | Annotative text, MText and dimensions read and write AutoCAD's annotation scale contexts (DXF and DWG 2007 and later): written at their default scale with a context per scale, a dimension with a `*D` block per scale; read back at paper size. Before, AutoCAD's were dropped (the objects read as not annotative) and CADCraft's kept only in its own record | | 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 | From 1418607e0648edead52d4d5340faa5bf4618d592 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:46:54 -0600 Subject: [PATCH 018/258] DXF test: an annotative multileader has no *D block Co-Authored-By: Claude Opus 5.5 --- crates/io/tests/annotative_text_contexts.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/io/tests/annotative_text_contexts.rs b/crates/io/tests/annotative_text_contexts.rs index e7ad3e3a7..f468ab99a 100644 --- a/crates/io/tests/annotative_text_contexts.rs +++ b/crates/io/tests/annotative_text_contexts.rs @@ -741,6 +741,8 @@ fn a_multileader_gets_its_context_data_at_each_scale() { // The text keeps its place about the landing, at the scale's size. assert!((num(&c.tags, 12) - (10.0 + 0.5 * f)).abs() < 1e-9 && (num(&c.tags, 22) - (10.0 + 0.1 * f)).abs() < 1e-9); } + // A multileader has no block per scale (only dimensions do). + assert!(!recs.iter().any(|(k, t)| k == "BLOCK" && get(t, 2).is_some_and(|n| n.starts_with("*D")))); let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); let (a, b) = (d.entity(h).unwrap(), back.entity(h).unwrap()); assert_eq!(a.common.anno_scales, b.common.anno_scales); From 3c4c5d4330fce933859d51ad134ca68141317e9e Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:37:47 -0600 Subject: [PATCH 019/258] DXF: AutoCAD's CANNOSCALE names the scale the contexts are written at A CANNOSCALE naming none of the drawing's scales wrote that name to the variable dictionary while the default contexts were written at 1:1; the variable now names the resolved scale too. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 7 ++++--- crates/io/tests/annotative_text_contexts.rs | 5 +++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 6d96161e6..b624ca3a0 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -1133,8 +1133,9 @@ fn reconcile( /// AutoCAD's current annotation scale, kept with its variable dictionary (the named object /// dictionary's `AcDbVariableDictionary`, a DICTIONARYVAR `CANNOSCALE` with the scale's name in -/// group 1), brought up to date with the drawing's: AutoCAD opens the drawing at that scale. -/// `None` when the file had none. +/// group 1), brought up to date with the drawing's: AutoCAD opens the drawing at that scale. It +/// names the scale the contexts are written at ([`Drawing::current_anno_scale`]), 1:1 when the +/// drawing's names none of its scales. `None` when the file had none. fn current_scale(f: &Foreign, d: &Drawing) -> Option<(String, ForeignObject)> { let vars = f.dictionary.iter().find(|(k, _)| k.trim().eq_ignore_ascii_case("AcDbVariableDictionary"))?.1; let object = |h: &str| f.objects.iter().find(|o| o.handle.hex() == norm(h)); @@ -1142,7 +1143,7 @@ fn current_scale(f: &Foreign, d: &Drawing) -> Option<(String, ForeignObject)> { let at = dict.tags.iter().position(|t| t.code == 3 && t.value.trim().eq_ignore_ascii_case("CANNOSCALE"))?; let var = dict.tags.get(at + 1).filter(|t| matches!(t.code, 350 | 360))?; let mut o = object(&var.value)?.clone(); - let name = d.header.str("CANNOSCALE", "1:1"); + let name = d.current_anno_scale().name; let value = o.tags.iter_mut().find(|t| t.code == 1)?; value.value = name; Some((o.handle.hex(), o)) diff --git a/crates/io/tests/annotative_text_contexts.rs b/crates/io/tests/annotative_text_contexts.rs index f468ab99a..5f60111bc 100644 --- a/crates/io/tests/annotative_text_contexts.rs +++ b/crates/io/tests/annotative_text_contexts.rs @@ -802,4 +802,9 @@ fn the_current_scale_is_autocad_s_and_saving_keeps_it_current() { let var = recs.iter().find(|(k, _)| k == "DICTIONARYVAR").unwrap(); assert_eq!(get(&var.1, 1), Some("1:2")); assert_eq!(recs.iter().filter(|(k, _)| k == "DICTIONARYVAR").count(), 1); + // Naming no scale of the drawing's, it is the 1:1 the contexts are written at. + d.header.set_str("CANNOSCALE", "1:999"); + let recs = records(&save(&d)); + let var = recs.iter().find(|(k, _)| k == "DICTIONARYVAR").unwrap(); + assert_eq!(get(&var.1, 1), Some("1:1")); } From b2335c7f2762f937d08a7bc7cbc0b0244f146ab0 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:37:47 -0600 Subject: [PATCH 020/258] DWG: a multileader context's body closes (301 }) before the next record As acadrust writes it; its reader stops at the next record either way. Co-Authored-By: Claude Opus 5.5 --- crates/dwg/src/lib.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index a63ee504f..6495309f3 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -629,6 +629,12 @@ mod native { while let (Some(&code_line), Some(&value_line)) = (lines.get(i), lines.get(i + 1)) { let (code, value) = (code_line.trim(), value_line.trim_end_matches('\r')); if code == "0" { + // An opened multileader context body closes before the next record, as acadrust + // writes it. + if ml_open { + out.push(format!("301{}", eol(code_line))); + out.push(format!("}}{}", eol(value_line))); + } let kind = value.trim(); marker = KINDS.iter().find(|(k, _)| *k == kind).map(|(_, m)| *m); dim = is_dim(kind); @@ -964,6 +970,21 @@ mod tests { assert!(err.contains("the DXF to DWG conversion failed on this file"), "{err}"); } + /// A multileader context read by acadrust has its body between `300 CONTEXT_DATA{` and + /// `301 }`, closed before the next record; back as AutoCAD writes it, both go. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_multileader_context_body_is_closed() { + let ours = " 0\nACDB_MLEADEROBJECTCONTEXTDATA_CLASS\n 5\n90\n340\n51\n 40\n1\n 0\nENDSEC\n"; + let theirs = String::from_utf8(native::contexts(ours.as_bytes(), true)).unwrap(); + let lines: Vec<&str> = theirs.lines().map(str::trim).collect(); + let open = lines.iter().position(|l| *l == "CONTEXT_DATA{").unwrap(); + let close = lines.iter().position(|l| *l == "}").unwrap(); + let next = lines.iter().position(|l| *l == "ENDSEC").unwrap(); + assert!(open < close && close < next && lines.get(close - 1) == Some(&"301"), "{theirs}"); + assert_eq!(String::from_utf8(native::contexts(theirs.as_bytes(), false)).unwrap(), ours); + } + #[test] fn detects_magic() { assert!(is_dwg(b"AC1032\0\0\0\0")); From 555703f0299abda2dfb0e04cbac347fa27460921 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:19:18 -0600 Subject: [PATCH 021/258] 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 | 15 ++++++--------- docs/gaps.md | 8 +++----- 2 files changed, 9 insertions(+), 14 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 00b40a4e5..d85415123 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them; annotative text, MText, dimensions and multileaders keep their scales on save) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds @@ -75,12 +75,12 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG |---|---|---|---| | LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE (widths, bulges, elevation), SPLINE, RAY, XLINE | yes | yes | round-trip tests | | POLYLINE 2D/3D | yes | yes (as LWPOLYLINE / 3D POLYLINE) | polyface and polygon meshes flattened: lossy | -| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn; annotative text and MText from their annotation scale contexts | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line); annotative text and MText with `AcadAnnotative` and a context per scale (2007 and later); changed attribute values refresh justified baselines, including small width changes | ATTDEF prompt kept (#137); unchanged values retain imported-font placement; a context's own position at one scale (ANNORESET) is not modelled; a justified TEXT's insertion point (group 10, which AutoCAD takes from a DWG as it is) is computed as AutoCAD computes it: Middle (M) centred on the string's own extents, bottom justifications at a TrueType face's descent (#2229) | -| DIMENSION (all 7 kinds) | yes; annotative ones from their scale contexts | yes, with anonymous `*D` blocks; an annotative dimension gets a context and a `*D` block per scale | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written for every associated kind — linear/aligned, angular, radial/diametric, ordinate and arc length — and read back without CADCraft's xdata (#1651) | -| DIMENSION (all 7 kinds) | yes; annotative ones from their scale contexts | yes, with anonymous `*D` blocks; an annotative dimension gets a context and a `*D` block per scale | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written; angular block text honors DIMDSEP, including per-dimension overrides (#1646) | -| DIMENSION (all 7 kinds) | yes; annotative ones from their scale contexts | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645); an annotative dimension gets a context and a `*D` block per scale | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | +| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line); changed attribute values refresh justified baselines, including small width changes | ATTDEF prompt kept (#137); unchanged values retain imported-font placement; a justified TEXT's insertion point (group 10, which AutoCAD takes from a DWG as it is) is computed as AutoCAD computes it: Middle (M) centred on the string's own extents, bottom justifications at a TrueType face's descent (#2229) | +| DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written for every associated kind — linear/aligned, angular, radial/diametric, ordinate and arc length — and read back without CADCraft's xdata (#1651) | +| DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written; angular block text honors DIMDSEP, including per-dimension overrides (#1646) | +| DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645) | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | | LEADER | yes | yes | | -| MULTILEADER | yes (#459) | yes, native MULTILEADER with MLEADERSTYLE (#459) | several landings per multileader are folded into one; per-object overrides not kept; annotative ones keep their scales as AutoCAD's scale contexts (2007 and later) | +| MULTILEADER | yes (#459) | yes, native MULTILEADER with MLEADERSTYLE (#459) | several landings per multileader are folded into one; per-object overrides and annotative scale contexts not kept | | HATCH pattern / solid | yes | yes; associative hatches keep their boundary objects in blocks too, and the boundary carries the hatch reactor (stretched dynamic blocks drag the fill in AutoCAD) | | | HATCH gradient | yes | yes (#162, fixes #80) | | | SOLID, TRACE, 3DFACE | yes | yes | | @@ -150,9 +150,6 @@ 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-15 | minor | The current annotation scale is read from and written to AutoCAD's variable dictionary (`AcDbVariableDictionary` CANNOSCALE), so a drawing opens at its scale in either program | -| 2026-10-15 | minor | Annotative multileaders read and write AutoCAD's annotation scale contexts (each context the multileader's `CONTEXT_DATA` at its scale), DXF and DWG | -| 2026-10-15 | minor | Annotative text, MText and dimensions read and write AutoCAD's annotation scale contexts (DXF and DWG 2007 and later): written at their default scale with a context per scale, a dimension with a `*D` block per scale; read back at paper size. Before, AutoCAD's were dropped (the objects read as not annotative) and CADCraft's kept only in its own record | | 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 c5ed8dccd..f8ddac941 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 (F12, FF2: annotative text, MText, dimensions and multileaders keep their scales on save) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first). A PR names the rows it closes in its @@ -34,7 +34,7 @@ do them first. | F10 | MLEADEREDIT (add/remove leader), MLEADERALIGN and MLEADERCOLLECT landed, but a multileader has one landing and one block (a collection keeps the other blocks as block references beside it; MLEADERALIGN has no Options-menu preview); MLEADERSTYLE has 5 fields (block content and spline/no-leader types are per command, not in the style; block content has no attributes) | `annotate.rs`, `cmd/mleader_content.rs`, `tables.rs:417` | Medium | 8–12 | | F9 | MTEXT is typed in an on-canvas editor with a formatting toolbar (font, height, bold, italic, underline, overline, colour, alignment, lists, tab and special characters) and a ruler for indents and tab stops (#532); left: the box does not lay the text out by the indents, tabs, columns or font weights while typing (bold shows wider, overline is not drawn), no justification (attachment) or columns controls in the editor, existing MTEXT cannot be edited (no DDEDIT/MTEDIT), stacked fractions and other codes show as placeholders; no fields (FIELD, UPDATEFIELD) and no spell check (SPELL): open PR #551. Paragraph indents, tabs, bullets, numbering and columns landed (#547) | `ui-egui/mtext_editor.rs`, `engine/mtext_edit.rs` | Medium | 10–18 | | F11 | Tables (cell styles, formulas, TABLEDIT, TABLEEXPORT, table breaking and CSV data links landed, #534): formulas aren't read from or written as AutoCAD FIELD objects (other programs see values); number formats apply to formula results only; cell text doesn't wrap; custom cell styles, breaks and data links travel as CADCraft xdata (not through DWG); data links read CSV only (no Excel ranges, no write-back, not on the web); no cell-style tab in the Table Style dialog | `cmd/table/*`, `io/dxf_table.rs` | Low-medium | 6–10 | -| F12 | Annotative scaling done (#468): scale list (SCALELISTEDIT), CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE/ANNOAUTOSCALE, viewport scale, DXF, status bar list. Left: per-scale positions (ANNORESET is a no-op), a viewport annotation scale apart from its viewport scale, annotative objects inside blocks and old LEADERs, scale contexts of hatches (text, MText, dimensions, multileaders and block references read and write AutoCAD's contexts) | `cmd/annoscale.rs`, `doc/src/anno.rs` | Low-medium | 4–8 | +| F12 | Annotative scaling done (#468): scale list (SCALELISTEDIT), CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE/ANNOAUTOSCALE, viewport scale, DXF, status bar list. Left: per-scale positions (ANNORESET is a no-op), a viewport annotation scale apart from its viewport scale, annotative objects inside blocks and old LEADERs, AutoCAD files' per-object scale contexts (read as not annotative) | `cmd/annoscale.rs`, `doc/src/anno.rs` | Low-medium | 4–8 | | F14 | **[alpha blocker]** Plotting leftovers: binary `.ctb`/`.stb`/`.pc3` files can't be read; model-space PDF plots keep the default margins (a device paper's margins apply to layouts and PNG plots); no system printers (H3); the page setup's "Plot transparency" is not saved in DXF/DWG (the public DXF Reference has no plot layout flag for it), so it lasts for the session and in JSON only. The Plot dialog (#160), Plot Preview and PUBLISH (#186), plot styles (CTB and STB, [plot-styles.md](plot-styles.md), #410) with their end, join and fill styles, plotter devices with paper sizes and printable areas ([plotters.md](plotters.md), #564), and plotted transparency (page setup and Plot dialog option, PLOTTRANSPARENCYOVERRIDE) landed | `io/src/plotter.rs`, `cmd/plotters.rs` | Medium | 4–8 | | 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 | @@ -74,7 +74,7 @@ Detail: [file-format-parity.md](file-format-parity.md). | # | Gap | User impact | Est. | |---|---|---|---| | FF1 | **[alpha blocker]** Round-trip what we don't model. DXF done (#528): unknown entities and objects (with their CLASS records), foreign xdata (hyperlinks included), extension dictionaries, persistent reactors, DICTIONARYVAR and XRECORDs, layer states, colour book colours, references remapped on save; IMAGE, VIEW/UCS, groups, block descriptions, true colours, transparency (#201, #204, #208, #209, #213, #223); WIPEOUT and gradients (#147, #162). Left: through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour book names and reactors; UCS elevation; MTEXT background colours; unknown entities follow only layer edits, and renamed layers and blocks lose their foreign data A user's QSAVE now asks before such a loss and keeps the previous file as `.bak`; the loss itself remains. | High | 6–10 | -| FF2 | Multileader leftovers (native MULTILEADER read/write landed, #459): several landings per multileader (extra leader roots are folded into the lines), per-object overrides (leader colour and linetype, arrowhead symbol, text frame); check the text placement of our MULTILEADER output in AutoCAD | Medium | 3–5 | +| FF2 | Multileader leftovers (native MULTILEADER read/write landed, #459): several landings per multileader (extra leader roots are folded into the lines), per-object overrides (leader colour and linetype, arrowhead symbol, text frame), annotative scale contexts; check the text placement of our MULTILEADER output in AutoCAD | Medium | 3–5 | | FF3 | Save-version leftovers (DXF/DWG 2000–2018, binary DXF, SAVEAS `version`/`binary` and the default save version landed, #421): no R14 DWG or R12 DXF output; the Save dialog can't pick the version per file (the file picker doesn't report the chosen type; File > Default Save Format sets it); no command-line SAVEAS format prompt | Low | 2–4 | | FF4 | Code-page leftovers (pre-2007 DXF read in their `$DWGCODEPAGE` landed, #505): Johab (ANSI_1361) and DOS 855/857/860–865/869 read as ANSI_1252; saving declares `ANSI_1252` instead of the file's code page (the text is pure ASCII, so still correct); acadrust approximates DOS code pages in pre-2007 DWG (DOS437 as 866, DOS850 as 1252) | Low | 1–2 | | FF5 | **[alpha blocker]** Real-file corpus (`storytold/cadcraft-corpus`), open → save → reopen tests, black-box check in AutoCAD | High | 10–15 + human | @@ -167,8 +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-15 | minor | F12, FF2: annotative multileaders keep their annotation scales on save (AutoCAD's scale contexts) | -| 2026-10-15 | minor | F12: annotative text, MText and dimensions keep their annotation scales on save as AutoCAD's scale contexts (AutoCAD files' contexts were dropped) | | 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 9ce077cf51fd191a16127d034f35ad12f0a68943 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:19:22 -0600 Subject: [PATCH 022/258] 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 | 11 +++++------ docs/gaps.md | 5 ++--- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 58d531c85..d85415123 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them; annotative text, MText and dimensions keep their scales on save) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds @@ -75,10 +75,10 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG |---|---|---|---| | LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE (widths, bulges, elevation), SPLINE, RAY, XLINE | yes | yes | round-trip tests | | POLYLINE 2D/3D | yes | yes (as LWPOLYLINE / 3D POLYLINE) | polyface and polygon meshes flattened: lossy | -| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn; annotative text and MText from their annotation scale contexts | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line); annotative text and MText with `AcadAnnotative` and a context per scale (2007 and later); changed attribute values refresh justified baselines, including small width changes | ATTDEF prompt kept (#137); unchanged values retain imported-font placement; a context's own position at one scale (ANNORESET) is not modelled; a justified TEXT's insertion point (group 10, which AutoCAD takes from a DWG as it is) is computed as AutoCAD computes it: Middle (M) centred on the string's own extents, bottom justifications at a TrueType face's descent (#2229) | -| DIMENSION (all 7 kinds) | yes; annotative ones from their scale contexts | yes, with anonymous `*D` blocks; an annotative dimension gets a context and a `*D` block per scale | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written for every associated kind — linear/aligned, angular, radial/diametric, ordinate and arc length — and read back without CADCraft's xdata (#1651) | -| DIMENSION (all 7 kinds) | yes; annotative ones from their scale contexts | yes, with anonymous `*D` blocks; an annotative dimension gets a context and a `*D` block per scale | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written; angular block text honors DIMDSEP, including per-dimension overrides (#1646) | -| DIMENSION (all 7 kinds) | yes; annotative ones from their scale contexts | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645); an annotative dimension gets a context and a `*D` block per scale | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | +| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line); changed attribute values refresh justified baselines, including small width changes | ATTDEF prompt kept (#137); unchanged values retain imported-font placement; a justified TEXT's insertion point (group 10, which AutoCAD takes from a DWG as it is) is computed as AutoCAD computes it: Middle (M) centred on the string's own extents, bottom justifications at a TrueType face's descent (#2229) | +| DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written for every associated kind — linear/aligned, angular, radial/diametric, ordinate and arc length — and read back without CADCraft's xdata (#1651) | +| DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written; angular block text honors DIMDSEP, including per-dimension overrides (#1646) | +| DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645) | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | | LEADER | yes | yes | | | MULTILEADER | yes (#459) | yes, native MULTILEADER with MLEADERSTYLE (#459) | several landings per multileader are folded into one; per-object overrides and annotative scale contexts not kept | | HATCH pattern / solid | yes | yes; associative hatches keep their boundary objects in blocks too, and the boundary carries the hatch reactor (stretched dynamic blocks drag the fill in AutoCAD) | | @@ -150,7 +150,6 @@ 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-15 | minor | Annotative text, MText and dimensions read and write AutoCAD's annotation scale contexts (DXF and DWG 2007 and later): written at their default scale with a context per scale, a dimension with a `*D` block per scale; read back at paper size. Before, AutoCAD's were dropped (the objects read as not annotative) and CADCraft's kept only in its own record | | 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 d24ad1db5..f8ddac941 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 (F12: annotative text, MText and dimensions keep their scales on save) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first). A PR names the rows it closes in its @@ -34,7 +34,7 @@ do them first. | F10 | MLEADEREDIT (add/remove leader), MLEADERALIGN and MLEADERCOLLECT landed, but a multileader has one landing and one block (a collection keeps the other blocks as block references beside it; MLEADERALIGN has no Options-menu preview); MLEADERSTYLE has 5 fields (block content and spline/no-leader types are per command, not in the style; block content has no attributes) | `annotate.rs`, `cmd/mleader_content.rs`, `tables.rs:417` | Medium | 8–12 | | F9 | MTEXT is typed in an on-canvas editor with a formatting toolbar (font, height, bold, italic, underline, overline, colour, alignment, lists, tab and special characters) and a ruler for indents and tab stops (#532); left: the box does not lay the text out by the indents, tabs, columns or font weights while typing (bold shows wider, overline is not drawn), no justification (attachment) or columns controls in the editor, existing MTEXT cannot be edited (no DDEDIT/MTEDIT), stacked fractions and other codes show as placeholders; no fields (FIELD, UPDATEFIELD) and no spell check (SPELL): open PR #551. Paragraph indents, tabs, bullets, numbering and columns landed (#547) | `ui-egui/mtext_editor.rs`, `engine/mtext_edit.rs` | Medium | 10–18 | | F11 | Tables (cell styles, formulas, TABLEDIT, TABLEEXPORT, table breaking and CSV data links landed, #534): formulas aren't read from or written as AutoCAD FIELD objects (other programs see values); number formats apply to formula results only; cell text doesn't wrap; custom cell styles, breaks and data links travel as CADCraft xdata (not through DWG); data links read CSV only (no Excel ranges, no write-back, not on the web); no cell-style tab in the Table Style dialog | `cmd/table/*`, `io/dxf_table.rs` | Low-medium | 6–10 | -| F12 | Annotative scaling done (#468): scale list (SCALELISTEDIT), CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE/ANNOAUTOSCALE, viewport scale, DXF, status bar list. Left: per-scale positions (ANNORESET is a no-op), a viewport annotation scale apart from its viewport scale, annotative objects inside blocks and old LEADERs, scale contexts of hatches and multileaders (text, MText, dimensions and block references read and write AutoCAD's contexts) | `cmd/annoscale.rs`, `doc/src/anno.rs` | Low-medium | 4–8 | +| F12 | Annotative scaling done (#468): scale list (SCALELISTEDIT), CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE/ANNOAUTOSCALE, viewport scale, DXF, status bar list. Left: per-scale positions (ANNORESET is a no-op), a viewport annotation scale apart from its viewport scale, annotative objects inside blocks and old LEADERs, AutoCAD files' per-object scale contexts (read as not annotative) | `cmd/annoscale.rs`, `doc/src/anno.rs` | Low-medium | 4–8 | | F14 | **[alpha blocker]** Plotting leftovers: binary `.ctb`/`.stb`/`.pc3` files can't be read; model-space PDF plots keep the default margins (a device paper's margins apply to layouts and PNG plots); no system printers (H3); the page setup's "Plot transparency" is not saved in DXF/DWG (the public DXF Reference has no plot layout flag for it), so it lasts for the session and in JSON only. The Plot dialog (#160), Plot Preview and PUBLISH (#186), plot styles (CTB and STB, [plot-styles.md](plot-styles.md), #410) with their end, join and fill styles, plotter devices with paper sizes and printable areas ([plotters.md](plotters.md), #564), and plotted transparency (page setup and Plot dialog option, PLOTTRANSPARENCYOVERRIDE) landed | `io/src/plotter.rs`, `cmd/plotters.rs` | Medium | 4–8 | | 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 | @@ -167,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-15 | minor | F12: annotative text, MText and dimensions keep their annotation scales on save as AutoCAD's scale contexts (AutoCAD files' contexts were dropped) | | 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 f0ab3e94e53fe7cd6f597c399c9fd7a530ac3b65 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:48:37 -0600 Subject: [PATCH 023/258] Block attributes: Enhanced Attribute Editor, an Attributes group in Properties, REFEDIT on dynamic blocks - Edit Attributes (ATTEDIT/EATTEDIT typed or from a menu) with one block reference selected opens the Enhanced Attribute Editor: tag, prompt and value of each attribute; Apply and OK run `attedit {handle, values}` with the values changed, one undo step each. With nothing selected ATTEDIT asks at the command line as before, and now takes a selected reference at once. - The Properties palette lists a block reference's attributes in an Attributes group; values can be edited there (multiline values with line breaks and constant attributes read-only). - `attedit` JSON: refuses objects that aren't block references, references on locked layers and values over 64 KiB; leaves constant attributes alone and reports them as `constantTags`. - `cadcraft_engine::attributes` gives the rows the palette and dialog show (prompt from the attribute definition when the attribute has none). - REFEDIT on a dynamic block reference names the dynamic block and points to BEDIT or Edit Attributes, instead of "*U1 is generated geometry". - Shortcut menu: Edit Attributes only when some attribute can be changed. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/blocks.rs | 2 +- crates/engine/src/cmd/blocks/attedit.rs | 72 ++++++- crates/engine/src/cmd/blocks/refedit.rs | 10 + crates/engine/src/lib.rs | 1 + crates/engine/tests/it/attedit_prompts.rs | 44 ++++ crates/engine/tests/it/dynamic_block_data.rs | 42 +++- crates/ui-egui/src/attedit.rs | 207 +++++++++++++++++++ crates/ui-egui/src/context_menu.rs | 2 +- crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/menus.rs | 3 + crates/ui-egui/src/palettes.rs | 24 +++ crates/ui-egui/tests/attedit_dialog.rs | 114 ++++++++++ docs/gaps.md | 5 +- docs/ui-parity.md | 3 +- 16 files changed, 525 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/src/attedit.rs create mode 100644 crates/ui-egui/tests/attedit_dialog.rs diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 258594ff0..06219a81d 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -18,7 +18,7 @@ use super::has_doc; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; mod attdef; -mod attedit; +pub(crate) mod attedit; mod burst; mod description; mod dyngrip; diff --git a/crates/engine/src/cmd/blocks/attedit.rs b/crates/engine/src/cmd/blocks/attedit.rs index be59474c5..ef1392d70 100644 --- a/crates/engine/src/cmd/blocks/attedit.rs +++ b/crates/engine/src/cmd/blocks/attedit.rs @@ -19,7 +19,7 @@ pub(super) fn attedit_spec() -> CommandSpec { CommandSpec::new("attedit", "Single...", run) .menu(&["Modify", "Object", "Attribute", "Single..."]) .alias(&["ate", "eattedit"]) - .params("{handle, values: {TAG: value} (tags in any case)} → {changed, unknownTags?}") + .params("{handle, values: {TAG: value} (tags in any case; constant attributes are left alone)} → {changed, unknownTags?, constantTags?}") .interactive(|_| Ok(Box::new(AtteditM::default()))) } @@ -62,10 +62,21 @@ pub(super) fn with_unknown_tags(s: &Session, h: Handle, values: &Map Result { let h = targets(s, p)?.first().copied().ok_or_else(|| bad("attedit", "`handle` is required"))?; let vals = p.get("values").and_then(Value::as_object).cloned().unwrap_or_default(); + let Some(EntityKind::Insert(ins)) = s.doc()?.entity(h).map(|e| &e.kind) else { + return Err(bad("attedit", format!("{} is not a block reference", h.hex()))); + }; + if super::super::curves::is_locked(s, h) { + return Err(bad("attedit", "the reference is on a locked layer")); + } + // Constant attributes keep their definition's value. + let constant: Vec = ins.attribs.iter().filter(|a| a.constant && value_for(&vals, &a.tag).is_some()).map(|a| a.tag.clone()).collect(); + if let Some(a) = ins.attribs.iter().find(|a| value_for(&vals, &a.tag).is_some_and(|v| v.len() > MAX_VALUE)) { + return Err(bad("attedit", format!("the value for {} is longer than {MAX_VALUE} bytes", a.tag))); + } let mut n = 0; s.doc_mut()?.modify_entity(h, |e| { if let EntityKind::Insert(i) = &mut e.kind { - for a in &mut i.attribs { + for a in i.attribs.iter_mut().filter(|a| !a.constant) { if let Some(v) = value_for(&vals, &a.tag) { set_value(&mut a.text, v); n += 1; @@ -73,7 +84,54 @@ fn run(s: &mut Session, p: &Value) -> Result { } } })?; - Ok(with_unknown_tags(s, h, &vals, json!({ "changed": n }))) + let mut r = with_unknown_tags(s, h, &vals, json!({ "changed": n })); + if !constant.is_empty() + && let Some(o) = r.as_object_mut() + { + o.insert("constantTags".into(), json!(constant)); + } + Ok(r) +} + +/// One attribute of a block reference, as the Properties palette and the Edit Attributes dialog +/// list it. +#[derive(Clone, Debug, PartialEq)] +pub struct AttributeRow { + pub tag: String, + /// The definition's prompt (the tag when it has none). + pub prompt: String, + pub value: String, + /// Not constant: the value can be changed. + pub editable: bool, + pub invisible: bool, + /// A multiline attribute: its value may hold line breaks. + pub multiline: bool, +} + +/// The attributes of block reference `h`, in order (empty for other objects). The prompt comes +/// from the attribute, else from its definition in the reference's block. +pub fn attributes(d: &cadcraft_doc::Drawing, h: Handle) -> Vec { + let Some(EntityKind::Insert(ins)) = d.entity(h).map(|e| &e.kind) else { return Vec::new() }; + let block = d.block(&ins.block); + let def_prompt = |tag: &str| { + block.and_then(|b| { + b.entities.iter().find_map(|e| match &e.kind { + EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag) && !ad.prompt.is_empty() => Some(ad.prompt.clone()), + _ => None, + }) + }) + }; + ins.attribs + .iter() + .map(|a| AttributeRow { + tag: a.tag.clone(), + prompt: if a.prompt.is_empty() { def_prompt(&a.tag).unwrap_or_else(|| a.tag.clone()) } else { a.prompt.clone() }, + value: a.text.value.clone(), + editable: !a.constant, + invisible: a.invisible, + multiline: a.multiline.is_some(), + }) + .collect() } /// A block name, tag or value specification: comma-separated wildcard patterns, any case. For @@ -247,6 +305,14 @@ impl Interactive for AtteditM { fn name(&self) -> &'static str { "ATTEDIT" } + /// A selected block reference is taken at once (Edit Attributes from the shortcut menu). + fn begin(&mut self, s: &mut Session) -> Result { + let pre = s.selection(); + if s.settings.pickfirst && !pre.is_empty() && self.pick(s, &pre).is_ok() { + s.set_selection(Vec::new()); + } + Ok(Step::Continue) + } fn prompt(&self, _s: &Session) -> Prompt { match self.attribs.get(self.values.len()) { Some((_, tag, cur)) if self.block.is_some() => Prompt::new(format!("Enter value for {tag}"), Accept::TEXT).default(cur.clone()), diff --git a/crates/engine/src/cmd/blocks/refedit.rs b/crates/engine/src/cmd/blocks/refedit.rs index 18d0d436b..e3ea619ea 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -119,6 +119,16 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { ), )); } + // A dynamic block reference shows an anonymous copy (`*U12`) made for its values. + if let Some(r) = cadcraft_doc::dynblock::reference(d, ih) { + return Err(bad( + "refedit", + format!( + "\"{}\" is a dynamic block: edit it in the Block Editor (BEDIT), or its attributes with Edit Attributes (ATTEDIT); editing dynamic blocks in place is not available yet", + r.definition + ), + )); + } if blk.name.starts_with('*') || blk.array.is_some() { return Err(bad("refedit", format!("\"{}\" is generated geometry and can't be edited in place", blk.name))); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8f84b35d7..666b8980d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -47,6 +47,7 @@ pub use cadcraft_doc as doc; pub use cadcraft_fonts as fonts; pub use cadcraft_geom as geom; pub use cadcraft_render as render; +pub use cmd::blocks::attedit::{AttributeRow, attributes}; 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}; diff --git a/crates/engine/tests/it/attedit_prompts.rs b/crates/engine/tests/it/attedit_prompts.rs index 61452cbd1..37f6fcdfc 100644 --- a/crates/engine/tests/it/attedit_prompts.rs +++ b/crates/engine/tests/it/attedit_prompts.rs @@ -109,3 +109,47 @@ fn attribute_tags_match_in_any_case_and_unknown_tags_are_reported() { let r = s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "four"}})).unwrap(); assert_eq!(r, json!({"changed": 1})); } + +#[test] +fn attedit_takes_a_selected_block_reference_at_once() { + let mut s = with_block(); + let h = handle(&insert(&mut s, 100.0, json!({}))); + s.set_selection(vec![h]); + s.cmdline("attedit").unwrap(); + assert!(s.prompt_text().contains("Enter value for T "), "{}", s.prompt_text()); + type_lines(&mut s, &["picked", ""]); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!((value(&s, h, "T"), value(&s, h, "U")), ("picked".into(), "u".into())); +} + +#[test] +fn attedit_leaves_constant_attributes_and_locked_references_alone() { + let mut s = with_block(); + let h = handle(&insert(&mut s, 100.0, json!({}))); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + i.attribs[1].constant = true; + } + }) + .unwrap(); + let rows = cadcraft_engine::attributes(s.doc().unwrap(), h); + assert_eq!(rows.iter().map(|r| (r.tag.as_str(), r.editable)).collect::>(), [("T", true), ("U", false)]); + + let r = s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "t2", "U": "u2"}})).unwrap(); + assert_eq!((r["changed"].clone(), r["constantTags"].clone()), (json!(1), json!(["U"]))); + assert_eq!((value(&s, h, "T"), value(&s, h, "U")), ("t2".into(), "u".into())); + // One undo step. + s.undo().unwrap(); + assert_eq!(value(&s, h, "T"), "one"); + + // Not a block reference, a value too long, a locked layer. + let line = s.execute("line", &json!({"points": [[0, 50], [10, 50]]})).unwrap()["handles"][0].clone(); + assert!(s.execute("attedit", &json!({"handle": line, "values": {"T": "x"}})).is_err()); + assert!(s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "x".repeat(70_000)}})).is_err()); + s.execute("layer.set", &json!({"name": "0", "locked": true})).unwrap(); + let e = s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "x"}})).unwrap_err().to_string(); + assert!(e.contains("locked"), "{e}"); + assert_eq!(value(&s, h, "T"), "one"); +} diff --git a/crates/engine/tests/it/dynamic_block_data.rs b/crates/engine/tests/it/dynamic_block_data.rs index 5b4cb11e3..4fb7a7b8e 100644 --- a/crates/engine/tests/it/dynamic_block_data.rs +++ b/crates/engine/tests/it/dynamic_block_data.rs @@ -14,10 +14,19 @@ fn obj(handle: u64, kind: &str, tags: &[(i32, &str)]) -> ForeignObject { /// A session whose block "Door" has a visibility parameter with two states. fn session() -> Session { + session_with(false) +} + +/// [`session`], with an attribute NO (default "1") in Door when `attribute`. +fn session_with(attribute: bool) -> Session { let mut s = Session::new(); - let l = s.execute("line", &json!({ "points": [[0, 0], [1, 0]] })).unwrap()["handles"][0].clone(); - s.execute("block", &json!({ "name": "Door", "base": [0, 0], "handles": [l] })).unwrap(); - let line = s.doc().unwrap().block("Door").unwrap().entities.handles()[0].hex(); + let mut hs = vec![s.execute("line", &json!({ "points": [[0, 0], [1, 0]] })).unwrap()["handles"][0].clone()]; + if attribute { + hs.push(s.execute("attdef", &json!({ "tag": "NO", "prompt": "Door number", "default": "1", "at": [0, 1] })).unwrap()["handle"].clone()); + } + s.execute("block", &json!({ "name": "Door", "base": [0, 0], "handles": hs })).unwrap(); + let b = s.doc().unwrap().block("Door").unwrap().clone(); + let line = b.entities.iter().find(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::Line(_))).unwrap().handle.hex(); let mut f = Foreign::default(); f.records.insert(("BLOCK_RECORD".into(), "DOOR".into()), ForeignExtra { xdict: Some(Handle(0xF00)), ..Default::default() }); f.objects.push(obj(0xF00, "DICTIONARY", &[(100, "AcDbDictionary"), (3, "ACAD_ENHANCEDBLOCK"), (360, "F01")])); @@ -138,3 +147,30 @@ fn a_visibility_state_is_changed_in_one_undo_step() { assert!(s.execute("blocks.reference.set", &p).is_err(), "{p}"); } } + +#[test] +fn a_dynamic_block_references_attributes_are_edited_and_refedit_says_why_not() { + let mut s = session_with(true); + let insert = s.doc().unwrap().model.handles()[0]; + let value = |s: &Session| match s.doc().unwrap().entity(insert).map(|e| e.kind.clone()) { + Some(cadcraft_engine::doc::EntityKind::Insert(i)) => (i.block, i.attribs.iter().map(|a| a.text.value.clone()).collect::>()), + other => panic!("{other:?}"), + }; + assert_eq!(value(&s).1, ["1"]); + // A visibility state change makes the reference show an anonymous copy (*U). + s.execute("blocks.reference.set", &json!({ "handle": insert.hex(), "name": "Visibility1", "value": "Closed" })).unwrap(); + assert!(value(&s).0.starts_with("*U")); + let rows = cadcraft_engine::attributes(s.doc().unwrap(), insert); + assert_eq!((rows[0].tag.as_str(), rows[0].prompt.as_str(), rows[0].editable), ("NO", "Door number", true)); + + let r = s.execute("attedit", &json!({ "handle": insert.hex(), "values": { "no": "12" } })).unwrap(); + assert_eq!(r["changed"], 1); + assert_eq!(value(&s).1, ["12"]); + // The value stays through another change of state. + s.execute("blocks.reference.set", &json!({ "handle": insert.hex(), "name": "Visibility1", "value": "Open" })).unwrap(); + assert_eq!(value(&s).1, ["12"]); + + // REFEDIT names the dynamic block and where to edit it instead of "*U… is generated geometry". + let e = s.execute("refedit", &json!({ "handles": [insert.hex()] })).unwrap_err().to_string(); + assert!(e.contains("\"Door\" is a dynamic block") && e.contains("BEDIT"), "{e}"); +} diff --git a/crates/ui-egui/src/attedit.rs b/crates/ui-egui/src/attedit.rs new file mode 100644 index 000000000..b291b8d39 --- /dev/null +++ b/crates/ui-egui/src/attedit.rs @@ -0,0 +1,207 @@ +//! The Edit Attributes dialog (Enhanced Attribute Editor): ATTEDIT / EATTEDIT typed or started +//! from a menu while one block reference with attributes is selected. It lists each attribute's +//! tag, prompt and value; Apply and OK run `attedit {handle, values}` with the values changed (one +//! undo step each). With nothing suitable selected ATTEDIT asks at the command line instead, and +//! JSON calls never open the dialog. + +use cadcraft_engine::doc::{Drawing, EntityKind, Handle}; +use egui::{RichText, vec2}; +use serde_json::{Map, Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// One attribute row: what the drawing had when the dialog opened, and what is typed now. +#[derive(Clone, Debug)] +pub struct Row { + pub tag: String, + pub prompt: String, + pub value: String, + pub editable: bool, + pub invisible: bool, + pub multiline: bool, + pub typed: String, +} + +/// The dialog's state while it is open. +#[derive(Default)] +pub struct State { + /// The block reference edited. + pub handle: Option, + /// Its block's name (the dynamic block's for a dynamic block reference). + pub block: String, + pub rows: Vec, + /// Why the last Apply failed. + pub error: Option, +} + +/// The block reference the dialog edits: the selection when it is exactly one block reference +/// with an attribute that can be changed. +fn selected_reference(app: &CadApp) -> Option { + let st = app.session.state().ok()?; + let [h] = st.selection.as_slice() else { return None }; + matches!(st.doc.entity(*h).map(|e| &e.kind), Some(EntityKind::Insert(_))).then_some(*h)?; + cadcraft_engine::attributes(&st.doc, *h).iter().any(|a| a.editable).then_some(*h) +} + +/// The name shown for block reference `h`: its dynamic block's, not its anonymous copy's. +fn block_name(d: &Drawing, h: Handle) -> String { + if let Some(r) = cadcraft_engine::doc::dynblock::reference(d, h) { + return r.definition; + } + match d.entity(h).map(|e| &e.kind) { + Some(EntityKind::Insert(i)) => i.block.clone(), + _ => String::new(), + } +} + +/// Load the rows of block reference `h`. +fn load(app: &mut CadApp, h: Handle) { + let Ok(st) = app.session.state() else { return }; + let rows = cadcraft_engine::attributes(&st.doc, h) + .into_iter() + .map(|a| Row { + typed: a.value.clone(), + tag: a.tag, + prompt: a.prompt, + value: a.value, + editable: a.editable, + invisible: a.invisible, + multiline: a.multiline, + }) + .collect(); + app.attedit = State { handle: Some(h), block: block_name(&st.doc, h), rows, error: None }; +} + +/// ATTEDIT / EATTEDIT typed or from a menu without parameters opens the dialog when one block +/// reference with attributes is selected; otherwise the command runs at the command line. +pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option> { + if !matches!(id, "attedit" | "ate" | "eattedit") || !params.is_null() { + return None; + } + let h = selected_reference(app)?; + app.session.echo(format!("Command: {}", id.to_ascii_uppercase())); + load(app, h); + app.ui.dialog = Some("attedit".into()); + Some(Ok(Value::Null)) +} + +/// The values typed that differ from the drawing's, as `attedit`'s `values`. +fn changed(rows: &[Row]) -> Map { + rows.iter().filter(|r| r.editable && r.typed != r.value).map(|r| (r.tag.clone(), Value::String(r.typed.clone()))).collect() +} + +/// Apply: run `attedit` with the changed values; true when it went through (or nothing changed). +pub fn apply(app: &mut CadApp) -> bool { + let Some(h) = app.attedit.handle else { return false }; + let values = changed(&app.attedit.rows); + if values.is_empty() { + return true; + } + match app.run("attedit", json!({ "handle": h.hex(), "values": values })) { + Ok(_) => { + load(app, h); + true + } + Err(e) => { + app.attedit.error = Some(e); + false + } + } +} + +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + // The reference went away (undo, erase from the command line): nothing to edit. + let alive = app.attedit.handle.is_some_and(|h| app.session.state().ok().is_some_and(|st| st.doc.entity(h).is_some())); + if !alive { + *open = false; + return; + } + let t = Tokens::get(); + let mut choice: Option<&str> = None; + let st = &mut app.attedit; + egui::Window::new(crate::tl!("Enhanced Attribute Editor")) + .id(egui::Id::new("Enhanced Attribute Editor")) + .open(open) + .collapsible(false) + .resizable(true) + .default_width(460.0) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(crate::tl!("Block:")).color(t.text_dim)); + ui.label(&st.block); + }); + ui.add_space(6.0); + egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { + egui::Grid::new("attedit-rows").num_columns(3).striped(true).spacing(vec2(12.0, 4.0)).show(ui, |ui| { + ui.label(RichText::new(crate::tl!("Tag")).color(t.text_dim)); + ui.label(RichText::new(crate::tl!("Prompt")).color(t.text_dim)); + ui.label(RichText::new(crate::tl!("Value")).color(t.text_dim)); + ui.end_row(); + for r in &mut st.rows { + let tag = if r.invisible { format!("{} ({})", r.tag, crate::i18n::t("invisible")) } else { r.tag.clone() }; + ui.label(tag); + ui.label(&r.prompt); + let edit = if r.multiline { + egui::TextEdit::multiline(&mut r.typed).desired_rows(2) + } else { + egui::TextEdit::singleline(&mut r.typed) + }; + let resp = ui.add_enabled(r.editable, edit.desired_width(220.0)); + if !r.editable { + let _ = resp.on_disabled_hover_text(crate::tl!("Constant")); + } + ui.end_row(); + } + }); + }); + if let Some(e) = &st.error { + ui.add_space(4.0); + ui.colored_label(t.warn, e); + } + ui.add_space(8.0); + ui.horizontal(|ui| { + let dirty = !changed(&st.rows).is_empty(); + if ui.button(crate::tl!("OK")).clicked() { + choice = Some("ok"); + } + if ui.button(crate::tl!("Cancel")).clicked() { + choice = Some("cancel"); + } + if ui.add_enabled(dirty, egui::Button::new(crate::tl!("Apply"))).clicked() { + choice = Some("apply"); + } + }); + }); + match choice { + Some("ok") => { + if apply(app) { + *open = false; + } + } + Some("apply") => { + apply(app); + } + Some(_) => *open = false, + None => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn row(tag: &str, value: &str, typed: &str, editable: bool) -> Row { + Row { tag: tag.into(), prompt: String::new(), value: value.into(), editable, invisible: false, multiline: false, typed: typed.into() } + } + + #[test] + fn only_changed_editable_values_are_sent() { + let rows = [row("A", "1", "1", true), row("B", "2", "3", true), row("C", "x", "y", false)]; + let v = changed(&rows); + assert_eq!(v.len(), 1); + assert_eq!(v.get("B"), Some(&json!("3"))); + } +} diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index bbaf48df3..0bef1565b 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -137,7 +137,7 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> { EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) => vec![("textedit", None)], EntityKind::Insert(_) => { let mut v = vec![("bedit", None), ("refedit", None)]; - if ents.iter().any(|e| matches!(&e.kind, EntityKind::Insert(i) if !i.attribs.is_empty())) { + if ents.iter().any(|e| matches!(&e.kind, EntityKind::Insert(i) if i.attribs.iter().any(|a| !a.constant))) { v.push(("attedit", Some("Edit Attributes..."))); } v diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index acdddb552..3fbe2ac16 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -27,6 +27,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "preview" => crate::exchange::dialog(app, ctx, &mut open), "commands" => commands(app, ctx, &mut open), "blocks" => blocks(app, ctx, &mut open), + "attedit" => crate::attedit::dialog(app, ctx, &mut open), "bedit" => crate::bedit::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), "stylesmanager" => crate::plotstyles::dialog(app, ctx, &mut open), diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bbb70e489..db14e0359 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1377,3 +1377,5 @@ CADCraft is up to date. Встановлено найновішу версію CADCraft. Could not check for updates. Не вдалося перевірити оновлення. Save changes to block "{name}"? Зберегти зміни в блоці «{name}»? + Constant Константа + Multiline: edit it with Edit Attributes Багаторядковий: змінюйте в «Редагувати атрибути» diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 142a589a3..7d0502c8b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -19,6 +19,7 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App { pub mod aliasdlg; pub mod animation; +pub mod attedit; pub mod autosave; pub mod bedit; pub mod canvas; @@ -309,6 +310,8 @@ pub struct CadApp { pub alias_dlg: Option, /// The Hatch and Gradient dialog while open or picking ([`hatchdlg`]). pub hatch_dlg: Option, + /// The Edit Attributes dialog ([`attedit`]). + pub attedit: attedit::State, /// The Edit Block Definition dialog ([`bedit`]). pub bedit: bedit::State, /// The startup update check and its prompt (desktop; [`updates_ui`]). @@ -366,6 +369,7 @@ impl CadApp { gpu_notice: None, alias_dlg: None, hatch_dlg: None, + attedit: attedit::State::default(), bedit: bedit::State::default(), #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 55d058811..f46ad5d39 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -94,6 +94,9 @@ fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value) -> Option = sel.iter().map(|h| h.hex()).collect(); let mut set: Option = None; let mut custom_set: Option = None; + let mut att_set: Option = None; let group = |ui: &mut egui::Ui, title: &str| { let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::hover()); ui.painter().rect_filled(r.shrink2(vec2(6.0, 1.0)), 2.0, t.chrome_dark); @@ -1156,6 +1157,26 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); } } + let atts = cadcraft_engine::attributes(d, e.handle); + if !atts.is_empty() { + group(ui, "Attributes"); + for a in &atts { + prop_row(ui, &a.tag, |ui| { + // A value with line breaks is edited in the Edit Attributes dialog; + // a single-line field would join its lines. + if !a.editable || a.value.contains('\n') { + let r = value_box(ui, &a.value.replace('\n', " "), false, false); + r.on_hover_text(if a.editable { + crate::tl!("Multiline: edit it with Edit Attributes") + } else { + crate::tl!("Constant") + }); + } else if let Some(v) = edit_field(ui, ui.id().with(("attval", e.handle, &a.tag)), a.value.clone()) { + att_set = Some(json!({ "handle": e.handle.hex(), "values": { a.tag.clone(): v } })); + } + }); + } + } } _ => {} } @@ -1174,6 +1195,9 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { if let Some(p) = custom_set { let _ = app.run("blocks.reference.set", p); } + if let Some(p) = att_set { + let _ = app.run("attedit", p); + } } #[cfg(test)] diff --git a/crates/ui-egui/tests/attedit_dialog.rs b/crates/ui-egui/tests/attedit_dialog.rs new file mode 100644 index 000000000..41fc0b9a6 --- /dev/null +++ b/crates/ui-egui/tests/attedit_dialog.rs @@ -0,0 +1,114 @@ +//! Block attributes from the UI: Edit Attributes on a selected block reference opens the Enhanced +//! Attribute Editor, and the Properties palette lists the attributes in their own group. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Handle}; +use cadcraft_ui_egui::{CadApp, Services, attedit, context_menu, menus}; +use serde_json::json; + +/// A block "Tag" with attributes NO (prompt "Number") and NOTE, and one reference to it. +fn app_with_reference() -> (CadApp, Handle) { + let mut app = CadApp::new(Session::new(), Services::default()); + let mut hs = vec![app.run("line", json!({ "points": [[0, 0], [10, 0]] })).unwrap()["handles"][0].clone()]; + hs.push(app.run("attdef", json!({ "tag": "NO", "prompt": "Number", "default": "1", "at": [0, 1] })).unwrap()["handle"].clone()); + hs.push(app.run("attdef", json!({ "tag": "NOTE", "default": "n", "at": [0, 2] })).unwrap()["handle"].clone()); + app.run("block", json!({ "name": "Tag", "base": [0, 0], "handles": hs, "keep": "delete" })).unwrap(); + let r = app.run("insert", json!({ "name": "Tag", "at": [100, 0], "attribs": { "NO": "7" } })).unwrap(); + let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); + app.session.set_selection(vec![h]); + (app, h) +} + +fn value(app: &CadApp, h: Handle, tag: &str) -> String { + match app.session.doc().unwrap().entity(h).map(|e| &e.kind) { + Some(EntityKind::Insert(i)) => i.attribs.iter().find(|a| a.tag == tag).unwrap().text.value.clone(), + other => panic!("{other:?}"), + } +} + +/// The text painted in one frame. +fn painted(app: &mut CadApp, ctx: &egui::Context) -> String { + fn collect(shape: &egui::Shape, text: &mut String) { + match shape { + egui::Shape::Text(s) => { + text.push_str(s.galley.text()); + text.push('\n'); + } + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, text)), + _ => {} + } + } + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| app.ui(ui)); + output.textures_delta.clear(); + let mut text = String::new(); + for s in &output.shapes { + collect(&s.shape, &mut text); + } + text +} + +#[test] +fn edit_attributes_on_a_selected_reference_opens_the_dialog() { + let (mut app, h) = app_with_reference(); + let labels: Vec<_> = context_menu::object_entries(&app) + .into_iter() + .filter_map(|e| match e { + menus::Entry::Item { label, .. } => Some(label), + menus::Entry::Sub { .. } => None, + }) + .collect(); + assert!(labels.iter().any(|l| l == "Edit Attributes..."), "{labels:?}"); + + menus::activate(&mut app, "attedit"); + assert_eq!(app.ui.dialog.as_deref(), Some("attedit")); + assert_eq!(app.attedit.block, "Tag"); + let rows: Vec<_> = app.attedit.rows.iter().map(|r| (r.tag.as_str(), r.prompt.as_str(), r.value.as_str())).collect(); + assert_eq!(rows, [("NO", "Number", "7"), ("NOTE", "NOTE", "n")]); + assert!(app.session.running.is_none(), "the dialog, not the command-line prompts"); + + let ctx = egui::Context::default(); + app.logic(&ctx); + painted(&mut app, &ctx); + let text = painted(&mut app, &ctx); + for s in ["Enhanced Attribute Editor", "Number", "NOTE", "OK", "Apply"] { + assert!(text.contains(s), "{s} missing from:\n{text}"); + } + + // Apply changes only what was typed, in one undo step, and keeps the dialog open. + app.attedit.rows[1].typed = "a note".into(); + assert!(attedit::apply(&mut app)); + assert_eq!((value(&app, h, "NO"), value(&app, h, "NOTE")), ("7".into(), "a note".into())); + assert_eq!(app.attedit.rows[1].value, "a note", "rows reload after Apply"); + app.run("undo", json!({})).unwrap(); + assert_eq!(value(&app, h, "NOTE"), "n"); +} + +#[test] +fn without_a_selected_reference_attedit_asks_at_the_command_line() { + let (mut app, _) = app_with_reference(); + app.session.set_selection(Vec::new()); + app.start("eattedit"); + assert!(app.ui.dialog.is_none()); + assert!(app.session.prompt_text().contains("Select block reference"), "{}", app.session.prompt_text()); + app.session.cancel(); + + // JSON calls never open the dialog. + let (mut app, h) = app_with_reference(); + app.run("attedit", json!({ "handle": h.hex(), "values": { "NO": "9" } })).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(value(&app, h, "NO"), "9"); +} + +#[test] +fn the_properties_palette_lists_the_attributes() { + let (mut app, _) = app_with_reference(); + let ctx = egui::Context::default(); + app.logic(&ctx); + painted(&mut app, &ctx); + let text = painted(&mut app, &ctx); + // (Text fields' contents are not painted shapes here, so only the labels are checked.) + for s in ["Attributes", "NO", "NOTE"] { + assert!(text.lines().any(|l| l == s), "{s} missing from:\n{text}"); + } +} diff --git a/docs/gaps.md b/docs/gaps.md index f8ddac941..b4801dba4 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-30 · **Change:** minor (QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks: F3 updated; Enhanced Attribute Editor and the Properties palette's Attributes group: 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). A PR names the rows it closes in its @@ -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; the Enhanced Attribute Editor lists and edits a selected reference's values, and the Properties palette has an Attributes group): the editor has no Text Options or Properties tabs; no verify, preset or lock-position modes, and multiline attributes (read, drawn and saved since 2026-10-12) can't be created or switched in BATTMAN; data extraction covers block references and attribute values (CSV or a table) only — no wizard, nested blocks, other objects' properties, `.dxe` templates or spreadsheet output | `cmd/blocks/battman.rs`, `cmd/blocks/extract.rs` | Low | 4–6 | | F19 | MATCHPROP Settings is a keyword prompt (no dialog) and has no material, shadow or centre-object settings; TEXTTOFRONT and HATCHTOBACK act on the current space only; OVERKILL doesn't compare polyline segments with other objects (picker and Settings, DRAWORDER Above/Under, TEXTTOFRONT, HATCHTOBACK, OVERKILL tolerance/ignore/overlap/end-to-end options landed, #439) | `props/matchprop.rs`, `draworder.rs`, `overkill.rs` | Low | 2–4 | | F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Left: right-click customization, the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export Open and Save has the backup copy checkbox (ISAVEBAK). | `ui-egui/src/options/` | Low | 2–4 | | F21 | MLINE, REGION and HELIX are objects since #510, with gaps: MLEDIT tees trim square; UNION/SUBTRACT/INTERSECT only combine regions whose boundaries don't meet; regions are saved as closed polylines (no ACIS data) | `draw2/mline.rs`, `inquiry/regions.rs`, `dxf_region.rs` | Low | 6–10 | @@ -170,6 +170,7 @@ Detail: [localization-parity.md](localization-parity.md). | 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 | +| 2026-10-13 | minor | F17: Edit Attributes (ATTEDIT/EATTEDIT with a selected block reference) opens the Enhanced Attribute Editor; the Properties palette lists and edits attribute values; REFEDIT on a dynamic block reference says to use BEDIT or Edit Attributes | | 2026-10-13 | minor | STRETCH takes crossing and window polygons (CP, WP), BOX and a fence (F), typed and as JSON (`polygon`, `fence`): F1 narrowed | | 2026-10-12 | minor | Property-based and hostile-input tests for geometry numerics landed (deterministic xorshift generator, no new dependency; known answers at 1e6–1e7 coordinates): S6 removed | | 2026-10-12 | trivial | F13: HATCHEDIT refuses a bad scale or angle before editing (#724) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3522b5091..b31787587 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -159,7 +159,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)); once a menu is open, pointing at another title opens that menu (#1567) | | Tool Bar, File tabs, Start tab, layout tabs | yes | yes | | Tool Sets palette (Drafting, Modeling, … with flyouts) | yes | yes for 2D groups | -| Properties Inspector, Quick Properties | yes | yes (every control acts or is visibly unavailable, #182); block references show read-only Position X/Y/Z from their stored insertion point; coordinate editing is still missing | +| 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 and an Attributes group whose values can be edited; coordinate editing is still missing | | Layer Properties Manager (filters, states, VP overrides) | yes | yes | | Blocks palette, Content | yes | Blocks window (click to insert, #28) | | Status bar toggles | ~25 | most toggles; Annotation Visibility and Workspace do nothing | @@ -217,6 +217,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | 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) | +| 2026-10-13 | minor | Block references list their attributes in the Properties Inspector (editable values); Edit Attributes opens the Enhanced Attribute Editor | | 2026-10-12 | minor | Block references now show their stored insertion X/Y/Z in the Properties Inspector, including nonzero Z; fields are read-only | | 2026-10-11 | minor | Isometric drafting (#556): isometric snap and grid, ISODRAFT, ISOPLANE (F5), ortho along isoplane axes, ELLIPSE Isocircle | | 2026-10-11 | minor | Object snap tracking, Extension, Parallel, Apparent Intersection, additional polar angles (#379): tracking 30% → 70%, object snaps 40% → 45%; total 43% → 48% | From 9f518ba001df2195e008f462ef208e155a0d56f4 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:58:26 -0600 Subject: [PATCH 024/258] Enhanced Attribute Editor: tied to the drawing it was opened for The dialog kept only the reference's handle, and handles repeat across drawings: with another drawing's tab chosen, it stayed open and Apply or OK changed that drawing's reference with the same handle. It now records the drawing (DocState::uid), closes when another is active, and Apply does nothing there. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/attedit.rs | 21 +++++++++++++---- crates/ui-egui/tests/attedit_dialog.rs | 32 +++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/attedit.rs b/crates/ui-egui/src/attedit.rs index b291b8d39..3bc0a8333 100644 --- a/crates/ui-egui/src/attedit.rs +++ b/crates/ui-egui/src/attedit.rs @@ -28,6 +28,9 @@ pub struct Row { pub struct State { /// The block reference edited. pub handle: Option, + /// The drawing it is in (`DocState::uid`): handles repeat across drawings, and the dialog + /// doesn't stop another drawing's tab from being chosen. + pub doc: Option, /// Its block's name (the dynamic block's for a dynamic block reference). pub block: String, pub rows: Vec, @@ -70,7 +73,15 @@ fn load(app: &mut CadApp, h: Handle) { multiline: a.multiline, }) .collect(); - app.attedit = State { handle: Some(h), block: block_name(&st.doc, h), rows, error: None }; + app.attedit = State { handle: Some(h), doc: Some(st.uid), block: block_name(&st.doc, h), rows, error: None }; +} + +/// The block reference the dialog edits, while the drawing it was opened for is the active one +/// and still has it. +fn edited(app: &CadApp) -> Option { + let h = app.attedit.handle?; + let st = app.session.state().ok()?; + (Some(st.uid) == app.attedit.doc && st.doc.entity(h).is_some()).then_some(h) } /// ATTEDIT / EATTEDIT typed or from a menu without parameters opens the dialog when one block @@ -93,7 +104,7 @@ fn changed(rows: &[Row]) -> Map { /// Apply: run `attedit` with the changed values; true when it went through (or nothing changed). pub fn apply(app: &mut CadApp) -> bool { - let Some(h) = app.attedit.handle else { return false }; + let Some(h) = edited(app) else { return false }; let values = changed(&app.attedit.rows); if values.is_empty() { return true; @@ -111,9 +122,9 @@ pub fn apply(app: &mut CadApp) -> bool { } pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { - // The reference went away (undo, erase from the command line): nothing to edit. - let alive = app.attedit.handle.is_some_and(|h| app.session.state().ok().is_some_and(|st| st.doc.entity(h).is_some())); - if !alive { + // The reference went away (undo, erase from the command line) or another drawing is active: + // nothing to edit. + if edited(app).is_none() { *open = false; return; } diff --git a/crates/ui-egui/tests/attedit_dialog.rs b/crates/ui-egui/tests/attedit_dialog.rs index 41fc0b9a6..81d9c3ebe 100644 --- a/crates/ui-egui/tests/attedit_dialog.rs +++ b/crates/ui-egui/tests/attedit_dialog.rs @@ -9,6 +9,12 @@ use serde_json::json; /// A block "Tag" with attributes NO (prompt "Number") and NOTE, and one reference to it. fn app_with_reference() -> (CadApp, Handle) { let mut app = CadApp::new(Session::new(), Services::default()); + let h = add_reference(&mut app); + (app, h) +} + +/// Block "Tag" and its reference, as [`app_with_reference`], in the active drawing (selected). +fn add_reference(app: &mut CadApp) -> Handle { let mut hs = vec![app.run("line", json!({ "points": [[0, 0], [10, 0]] })).unwrap()["handles"][0].clone()]; hs.push(app.run("attdef", json!({ "tag": "NO", "prompt": "Number", "default": "1", "at": [0, 1] })).unwrap()["handle"].clone()); hs.push(app.run("attdef", json!({ "tag": "NOTE", "default": "n", "at": [0, 2] })).unwrap()["handle"].clone()); @@ -16,7 +22,7 @@ fn app_with_reference() -> (CadApp, Handle) { let r = app.run("insert", json!({ "name": "Tag", "at": [100, 0], "attribs": { "NO": "7" } })).unwrap(); let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); app.session.set_selection(vec![h]); - (app, h) + h } fn value(app: &CadApp, h: Handle, tag: &str) -> String { @@ -112,3 +118,27 @@ fn the_properties_palette_lists_the_attributes() { assert!(text.lines().any(|l| l == s), "{s} missing from:\n{text}"); } } + +/// The dialog belongs to the drawing it was opened for: with another drawing's tab chosen (where +/// the same handle is a reference with the same tags), Apply changes nothing and the dialog +/// closes. +#[test] +fn the_dialog_closes_in_another_drawing() { + let (mut app, h) = app_with_reference(); + menus::activate(&mut app, "attedit"); + assert_eq!(app.ui.dialog.as_deref(), Some("attedit")); + app.attedit.rows[1].typed = "a note".into(); + + app.session.new_drawing(false); + assert_eq!(add_reference(&mut app), h, "the same handle in the other drawing"); + assert!(!attedit::apply(&mut app)); + assert_eq!(value(&app, h, "NOTE"), "n", "the other drawing's reference is untouched"); + let ctx = egui::Context::default(); + app.logic(&ctx); + painted(&mut app, &ctx); + assert!(app.ui.dialog.is_none(), "closed"); + + // Back in the first drawing, its reference is as it was too. + app.session.active = 0; + assert_eq!(value(&app, h, "NOTE"), "n"); +} From 5134098c571cadfe3ae01d38fe88c29558aa0f23 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:57:59 -0600 Subject: [PATCH 025/258] Enhanced Attribute Editor: open it on a reference with one attribute current attedit::open(app, handle, current) opens the dialog on a block reference of the active drawing with the given attribute (an index in cadcraft_engine::attributes order) current: its tag is bold, and its value box takes the focus and scrolls into view in the first frame. Without one, or for one that can't be changed, the first editable attribute is current. It returns false, and opens nothing, for anything but a block reference with an attribute that can be changed. ATTEDIT/EATTEDIT from a menu go through it, and Apply keeps the current attribute. This is what a double-click on an attribute needs (#1790). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/attedit.rs | 44 ++++++++++++++++++++++---- crates/ui-egui/tests/attedit_dialog.rs | 35 ++++++++++++++++++++ 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/attedit.rs b/crates/ui-egui/src/attedit.rs index 3bc0a8333..c4ab8b63d 100644 --- a/crates/ui-egui/src/attedit.rs +++ b/crates/ui-egui/src/attedit.rs @@ -34,6 +34,11 @@ pub struct State { /// Its block's name (the dynamic block's for a dynamic block reference). pub block: String, pub rows: Vec, + /// The row that is current: shown in bold, and its value box takes the focus when the + /// dialog opens (the attribute double-clicked). + pub current: Option, + /// The current row's value box still has to take the focus. + pub focus: bool, /// Why the last Apply failed. pub error: Option, } @@ -73,7 +78,27 @@ fn load(app: &mut CadApp, h: Handle) { multiline: a.multiline, }) .collect(); - app.attedit = State { handle: Some(h), doc: Some(st.uid), block: block_name(&st.doc, h), rows, error: None }; + let current = app.attedit.current; + app.attedit = State { handle: Some(h), doc: Some(st.uid), block: block_name(&st.doc, h), rows, current, focus: false, error: None }; +} + +/// Open the dialog on block reference `h` of the active drawing, with attribute `current` (an +/// index into its attributes, in `cadcraft_engine::attributes` order) current; without one, or +/// when that attribute can't be changed, the first one that can. False, and nothing opens, when +/// `h` is not a block reference with an attribute that can be changed. +pub fn open(app: &mut CadApp, h: Handle, current: Option) -> bool { + let Ok(st) = app.session.state() else { return false }; + if !matches!(st.doc.entity(h).map(|e| &e.kind), Some(EntityKind::Insert(_))) { + return false; + } + let attribs = cadcraft_engine::attributes(&st.doc, h); + let Some(first) = attribs.iter().position(|a| a.editable) else { return false }; + let current = current.filter(|i| attribs.get(*i).is_some_and(|a| a.editable)).unwrap_or(first); + app.attedit.current = Some(current); + load(app, h); + app.attedit.focus = true; + app.ui.dialog = Some("attedit".into()); + true } /// The block reference the dialog edits, while the drawing it was opened for is the active one @@ -92,9 +117,7 @@ pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option Date: Sun, 25 Oct 2026 14:35:49 -0600 Subject: [PATCH 026/258] Enhanced Attribute Editor: egui ids without the APIs this egui deprecates Id::unique for the window, Ui::scope_id for the palette's value fields, as the rest of the UI does since main's egui update. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/attedit.rs | 2 +- crates/ui-egui/src/palettes.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/attedit.rs b/crates/ui-egui/src/attedit.rs index c4ab8b63d..c681c4bee 100644 --- a/crates/ui-egui/src/attedit.rs +++ b/crates/ui-egui/src/attedit.rs @@ -155,7 +155,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let mut choice: Option<&str> = None; let st = &mut app.attedit; egui::Window::new(crate::tl!("Enhanced Attribute Editor")) - .id(egui::Id::new("Enhanced Attribute Editor")) + .id(egui::Id::unique("Enhanced Attribute Editor")) .open(open) .collapsible(false) .resizable(true) diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 0762b024e..361b921a2 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -1171,7 +1171,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } else { crate::tl!("Constant") }); - } else if let Some(v) = edit_field(ui, ui.id().with(("attval", e.handle, &a.tag)), a.value.clone()) { + } else if let Some(v) = edit_field(ui, ui.scope_id().with(("attval", e.handle, &a.tag)), a.value.clone()) { att_set = Some(json!({ "handle": e.handle.hex(), "values": { a.tag.clone(): v } })); } }); From 37cd9089d35e2f43c7cbd64814e1144aa3cb8cce Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:44:40 -0600 Subject: [PATCH 027/258] Enhanced Attribute Editor: edits go by attribute place, so a repeated tag changes one row attedit takes `at: {index: value}` beside `values`: one attribute by its place in the reference (indexes checked against its attributes). The Edit Attributes dialog and the Properties palette send their edits that way, so on a reference with two attributes sharing a tag (a DXF may carry them) editing one row no longer overwrites the other. `values` still changes every attribute with the tag. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/blocks/attedit.rs | 33 ++++++++++++++++++----- crates/engine/tests/it/attedit_prompts.rs | 30 +++++++++++++++++++++ crates/ui-egui/src/attedit.rs | 11 ++++---- crates/ui-egui/src/palettes.rs | 7 ++--- 4 files changed, 67 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/blocks/attedit.rs b/crates/engine/src/cmd/blocks/attedit.rs index ef1392d70..125ae50a5 100644 --- a/crates/engine/src/cmd/blocks/attedit.rs +++ b/crates/engine/src/cmd/blocks/attedit.rs @@ -19,7 +19,7 @@ pub(super) fn attedit_spec() -> CommandSpec { CommandSpec::new("attedit", "Single...", run) .menu(&["Modify", "Object", "Attribute", "Single..."]) .alias(&["ate", "eattedit"]) - .params("{handle, values: {TAG: value} (tags in any case; constant attributes are left alone)} → {changed, unknownTags?, constantTags?}") + .params("{handle, values?: {TAG: value} (tags in any case; every attribute with the tag), at?: {index: value} (one attribute, by its place in the reference, for repeated tags); constant attributes are left alone} → {changed, unknownTags?, constantTags?}") .interactive(|_| Ok(Box::new(AtteditM::default()))) } @@ -34,7 +34,11 @@ pub(super) fn dash_attedit_spec() -> CommandSpec { /// The value `values` gives for `tag`, matching the tag in any case. Numbers and booleans count /// as their text. pub(super) fn value_for(values: &Map, tag: &str) -> Option { - let v = values.get(tag).or_else(|| values.iter().find(|(k, _)| k.eq_ignore_ascii_case(tag)).map(|(_, v)| v))?; + text_of(values.get(tag).or_else(|| values.iter().find(|(k, _)| k.eq_ignore_ascii_case(tag)).map(|(_, v)| v))?) +} + +/// A value given for an attribute as its text (numbers and booleans count as their text). +fn text_of(v: &Value) -> Option { match v { Value::String(t) => Some(t.clone()), Value::Number(n) => Some(n.to_string()), @@ -68,16 +72,33 @@ fn run(s: &mut Session, p: &Value) -> Result { if super::super::curves::is_locked(s, h) { return Err(bad("attedit", "the reference is on a locked layer")); } + // Values by place (`at`): one attribute each, where a tag repeats (a DXF reference may carry + // two attributes with one tag; `values` changes both). + let mut at: Vec<(usize, String)> = Vec::new(); + if let Some(m) = p.get("at").filter(|v| !v.is_null()) { + let m = m.as_object().ok_or_else(|| bad("attedit", "`at` must be an object of {index: value}"))?; + for (k, v) in m { + let i = k + .trim() + .parse::() + .ok() + .filter(|i| *i < ins.attribs.len()) + .ok_or_else(|| bad("attedit", format!("`at`: {k} is not the index of one of the reference's attributes")))?; + at.push((i, text_of(v).ok_or_else(|| bad("attedit", format!("`at`: the value for {k} must be text")))?)); + } + } + let given = |i: usize, tag: &str| at.iter().find(|(j, _)| *j == i).map(|(_, v)| v.clone()).or_else(|| value_for(&vals, tag)); // Constant attributes keep their definition's value. - let constant: Vec = ins.attribs.iter().filter(|a| a.constant && value_for(&vals, &a.tag).is_some()).map(|a| a.tag.clone()).collect(); - if let Some(a) = ins.attribs.iter().find(|a| value_for(&vals, &a.tag).is_some_and(|v| v.len() > MAX_VALUE)) { + let constant: Vec = + ins.attribs.iter().enumerate().filter(|(i, a)| a.constant && given(*i, &a.tag).is_some()).map(|(_, a)| a.tag.clone()).collect(); + if let Some((_, a)) = ins.attribs.iter().enumerate().find(|(i, a)| given(*i, &a.tag).is_some_and(|v| v.len() > MAX_VALUE)) { return Err(bad("attedit", format!("the value for {} is longer than {MAX_VALUE} bytes", a.tag))); } let mut n = 0; s.doc_mut()?.modify_entity(h, |e| { if let EntityKind::Insert(i) = &mut e.kind { - for a in i.attribs.iter_mut().filter(|a| !a.constant) { - if let Some(v) = value_for(&vals, &a.tag) { + for (j, a) in i.attribs.iter_mut().enumerate().filter(|(_, a)| !a.constant) { + if let Some(v) = given(j, &a.tag) { set_value(&mut a.text, v); n += 1; } diff --git a/crates/engine/tests/it/attedit_prompts.rs b/crates/engine/tests/it/attedit_prompts.rs index 37f6fcdfc..7a5207968 100644 --- a/crates/engine/tests/it/attedit_prompts.rs +++ b/crates/engine/tests/it/attedit_prompts.rs @@ -153,3 +153,33 @@ fn attedit_leaves_constant_attributes_and_locked_references_alone() { assert!(e.contains("locked"), "{e}"); assert_eq!(value(&s, h, "T"), "one"); } + +#[test] +fn attedit_at_changes_one_of_two_attributes_sharing_a_tag() { + let mut s = with_block(); + let h = handle(&insert(&mut s, 100.0, json!({}))); + // As a DXF reference may carry them: the second attribute's tag is T too. + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + i.attribs[1].tag = "T".into(); + } + }) + .unwrap(); + let values = |s: &Session| -> Vec { + let EntityKind::Insert(i) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") }; + i.attribs.iter().map(|a| a.text.value.clone()).collect() + }; + let r = s.execute("attedit", &json!({"handle": h.hex(), "at": {"1": "second"}})).unwrap(); + assert_eq!(r, json!({"changed": 1})); + assert_eq!(values(&s), ["one", "second"]); + // By tag, every attribute with it, as before. + s.execute("attedit", &json!({"handle": h.hex(), "values": {"t": "both"}})).unwrap(); + assert_eq!(values(&s), ["both", "both"]); + // Hostile places are refused and change nothing. + for at in [json!({"2": "x"}), json!({"-1": "x"}), json!({"one": "x"}), json!({"0": [1]}), json!([1]), json!({"18446744073709551616": "x"})] { + assert!(s.execute("attedit", &json!({"handle": h.hex(), "at": at})).is_err(), "{at}"); + } + assert_eq!(values(&s), ["both", "both"]); +} diff --git a/crates/ui-egui/src/attedit.rs b/crates/ui-egui/src/attedit.rs index c681c4bee..ab466c5ad 100644 --- a/crates/ui-egui/src/attedit.rs +++ b/crates/ui-egui/src/attedit.rs @@ -1,6 +1,6 @@ //! The Edit Attributes dialog (Enhanced Attribute Editor): ATTEDIT / EATTEDIT typed or started //! from a menu while one block reference with attributes is selected. It lists each attribute's -//! tag, prompt and value; Apply and OK run `attedit {handle, values}` with the values changed (one +//! tag, prompt and value; Apply and OK run `attedit {handle, at}` with the values changed (one //! undo step each). With nothing suitable selected ATTEDIT asks at the command line instead, and //! JSON calls never open the dialog. @@ -120,9 +120,10 @@ pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option Map { - rows.iter().filter(|r| r.editable && r.typed != r.value).map(|r| (r.tag.clone(), Value::String(r.typed.clone()))).collect() + rows.iter().enumerate().filter(|(_, r)| r.editable && r.typed != r.value).map(|(i, r)| (i.to_string(), Value::String(r.typed.clone()))).collect() } /// Apply: run `attedit` with the changed values; true when it went through (or nothing changed). @@ -132,7 +133,7 @@ pub fn apply(app: &mut CadApp) -> bool { if values.is_empty() { return true; } - match app.run("attedit", json!({ "handle": h.hex(), "values": values })) { + match app.run("attedit", json!({ "handle": h.hex(), "at": values })) { Ok(_) => { load(app, h); true @@ -245,6 +246,6 @@ mod tests { let rows = [row("A", "1", "1", true), row("B", "2", "3", true), row("C", "x", "y", false)]; let v = changed(&rows); assert_eq!(v.len(), 1); - assert_eq!(v.get("B"), Some(&json!("3"))); + assert_eq!(v.get("1"), Some(&json!("3"))); } } diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 361b921a2..b77d37bdd 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -1160,7 +1160,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { let atts = cadcraft_engine::attributes(d, e.handle); if !atts.is_empty() { group(ui, "Attributes"); - for a in &atts { + for (i, a) in atts.iter().enumerate() { prop_row(ui, &a.tag, |ui| { // A value with line breaks is edited in the Edit Attributes dialog; // a single-line field would join its lines. @@ -1171,8 +1171,9 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } else { crate::tl!("Constant") }); - } else if let Some(v) = edit_field(ui, ui.scope_id().with(("attval", e.handle, &a.tag)), a.value.clone()) { - att_set = Some(json!({ "handle": e.handle.hex(), "values": { a.tag.clone(): v } })); + } else if let Some(v) = edit_field(ui, ui.scope_id().with(("attval", e.handle, i)), a.value.clone()) { + // By place: another attribute may share the tag. + att_set = Some(json!({ "handle": e.handle.hex(), "at": { i.to_string(): v } })); } }); } From aaadba7b117bea79f8bd53dfc58718e7aed445e4 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:17:46 -0600 Subject: [PATCH 028/258] Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them) Co-Authored-By: Claude Sonnet 5.5 --- docs/gaps.md | 5 ++--- docs/ui-parity.md | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index b4801dba4..f8ddac941 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; Enhanced Attribute Editor and the Properties palette's Attributes group: F17 narrowed) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first). A PR names the rows it closes in its @@ -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; the Enhanced Attribute Editor lists and edits a selected reference's values, and the Properties palette has an Attributes group): the editor has no Text Options or Properties tabs; 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): no verify, preset or lock-position modes, and multiline attributes (read, drawn and saved since 2026-10-12) can't be created or switched in BATTMAN; data extraction covers block references and attribute values (CSV or a table) only — no wizard, nested blocks, other objects' properties, `.dxe` templates or spreadsheet output | `cmd/blocks/battman.rs`, `cmd/blocks/extract.rs` | Low | 4–6 | | F19 | MATCHPROP Settings is a keyword prompt (no dialog) and has no material, shadow or centre-object settings; TEXTTOFRONT and HATCHTOBACK act on the current space only; OVERKILL doesn't compare polyline segments with other objects (picker and Settings, DRAWORDER Above/Under, TEXTTOFRONT, HATCHTOBACK, OVERKILL tolerance/ignore/overlap/end-to-end options landed, #439) | `props/matchprop.rs`, `draworder.rs`, `overkill.rs` | Low | 2–4 | | F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Left: right-click customization, the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export Open and Save has the backup copy checkbox (ISAVEBAK). | `ui-egui/src/options/` | Low | 2–4 | | F21 | MLINE, REGION and HELIX are objects since #510, with gaps: MLEDIT tees trim square; UNION/SUBTRACT/INTERSECT only combine regions whose boundaries don't meet; regions are saved as closed polylines (no ACIS data) | `draw2/mline.rs`, `inquiry/regions.rs`, `dxf_region.rs` | Low | 6–10 | @@ -170,7 +170,6 @@ Detail: [localization-parity.md](localization-parity.md). | 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 | -| 2026-10-13 | minor | F17: Edit Attributes (ATTEDIT/EATTEDIT with a selected block reference) opens the Enhanced Attribute Editor; the Properties palette lists and edits attribute values; REFEDIT on a dynamic block reference says to use BEDIT or Edit Attributes | | 2026-10-13 | minor | STRETCH takes crossing and window polygons (CP, WP), BOX and a fence (F), typed and as JSON (`polygon`, `fence`): F1 narrowed | | 2026-10-12 | minor | Property-based and hostile-input tests for geometry numerics landed (deterministic xorshift generator, no new dependency; known answers at 1e6–1e7 coordinates): S6 removed | | 2026-10-12 | trivial | F13: HATCHEDIT refuses a bad scale or angle before editing (#724) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b31787587..3522b5091 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -159,7 +159,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)); once a menu is open, pointing at another title opens that menu (#1567) | | Tool Bar, File tabs, Start tab, layout tabs | yes | yes | | Tool Sets palette (Drafting, Modeling, … with flyouts) | yes | yes for 2D groups | -| Properties Inspector, Quick Properties | yes | yes (every control acts or is visibly unavailable, #182); block references show read-only Position X/Y/Z from their stored insertion point and an Attributes group whose values can be edited; coordinate editing is still missing | +| 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 | | Blocks palette, Content | yes | Blocks window (click to insert, #28) | | Status bar toggles | ~25 | most toggles; Annotation Visibility and Workspace do nothing | @@ -217,7 +217,6 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | 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) | -| 2026-10-13 | minor | Block references list their attributes in the Properties Inspector (editable values); Edit Attributes opens the Enhanced Attribute Editor | | 2026-10-12 | minor | Block references now show their stored insertion X/Y/Z in the Properties Inspector, including nonzero Z; fields are read-only | | 2026-10-11 | minor | Isometric drafting (#556): isometric snap and grid, ISODRAFT, ISOPLANE (F5), ortho along isoplane axes, ELLIPSE Isocircle | | 2026-10-11 | minor | Object snap tracking, Extension, Parallel, Apparent Intersection, additional polar angles (#379): tracking 30% → 70%, object snaps 40% → 45%; total 43% → 48% | From a174177b4b8e52058ff0d98284bbdd4529b14d5c Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:03:55 -0600 Subject: [PATCH 029/258] Enhanced Attribute Editor: pending edits stay with their drawing and attribute layout The Properties attribute field's edit buffer is now keyed by the drawing's uid as well as the handle and place, so text typed in one drawing is not committed in another drawing's reference that has the same handle. Apply in the dialog checks that the reference still has the attributes (tag and value, in the same places) the dialog listed. If another command or an undo changed them, nothing is written: the rows are reloaded and the dialog says so, instead of the typed value landing on whichever attribute now has that place. Regression tests: a_stale_dialog_does_not_overwrite_another_attribute, a_pending_properties_value_does_not_follow_a_drawing_switch. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/attedit.rs | 15 +++++++ crates/ui-egui/src/palettes.rs | 5 ++- crates/ui-egui/tests/attedit_dialog.rs | 58 ++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/attedit.rs b/crates/ui-egui/src/attedit.rs index ab466c5ad..c36dc24e1 100644 --- a/crates/ui-egui/src/attedit.rs +++ b/crates/ui-egui/src/attedit.rs @@ -126,6 +126,14 @@ fn changed(rows: &[Row]) -> Map { rows.iter().enumerate().filter(|(_, r)| r.editable && r.typed != r.value).map(|(i, r)| (i.to_string(), Value::String(r.typed.clone()))).collect() } +/// True while the reference's attributes are still the ones the dialog listed (tag and value, in +/// the same places). +fn rows_unchanged(app: &CadApp, h: Handle) -> bool { + let Ok(st) = app.session.state() else { return false }; + let now = cadcraft_engine::attributes(&st.doc, h); + now.len() == app.attedit.rows.len() && now.iter().zip(&app.attedit.rows).all(|(a, r)| a.tag == r.tag && a.value == r.value) +} + /// Apply: run `attedit` with the changed values; true when it went through (or nothing changed). pub fn apply(app: &mut CadApp) -> bool { let Some(h) = edited(app) else { return false }; @@ -133,6 +141,13 @@ pub fn apply(app: &mut CadApp) -> bool { if values.is_empty() { return true; } + if !rows_unchanged(app, h) { + // Another command reordered, renamed or edited the attributes while the dialog was open: + // a row index would address a different attribute now. Show what the drawing has. + load(app, h); + app.attedit.error = Some(crate::tl!("The attributes changed while this dialog was open. Review them and apply again.").into()); + return false; + } match app.run("attedit", json!({ "handle": h.hex(), "at": values })) { Ok(_) => { load(app, h); diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index b77d37bdd..9cbb19580 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -710,6 +710,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); properties_header(app, ui); let sel = app.session.selection(); + let uid = app.session.state().ok().map(|st| st.uid); let Ok(d) = app.session.doc() else { return }; ui.add_space(4.0); let h = &d.header; @@ -1162,6 +1163,8 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { group(ui, "Attributes"); for (i, a) in atts.iter().enumerate() { prop_row(ui, &a.tag, |ui| { + // The buffer is the drawing's too: handles repeat across drawings, and a + // pending value must not follow a tab switch. // A value with line breaks is edited in the Edit Attributes dialog; // a single-line field would join its lines. if !a.editable || a.value.contains('\n') { @@ -1171,7 +1174,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } else { crate::tl!("Constant") }); - } else if let Some(v) = edit_field(ui, ui.scope_id().with(("attval", e.handle, i)), a.value.clone()) { + } else if let Some(v) = edit_field(ui, ui.scope_id().with(("attval", uid, e.handle, i)), a.value.clone()) { // By place: another attribute may share the tag. att_set = Some(json!({ "handle": e.handle.hex(), "at": { i.to_string(): v } })); } diff --git a/crates/ui-egui/tests/attedit_dialog.rs b/crates/ui-egui/tests/attedit_dialog.rs index 43efb03e3..13dea6da4 100644 --- a/crates/ui-egui/tests/attedit_dialog.rs +++ b/crates/ui-egui/tests/attedit_dialog.rs @@ -177,3 +177,61 @@ fn the_dialog_closes_in_another_drawing() { app.session.active = 0; assert_eq!(value(&app, h, "NOTE"), "n"); } + +/// Rows are addressed by place, so a dialog opened before the attributes were reordered must not +/// write its typed value into whichever attribute now has that place: Apply reloads and says so. +#[test] +fn a_stale_dialog_does_not_overwrite_another_attribute() { + let (mut app, h) = app_with_reference(); + menus::activate(&mut app, "attedit"); + app.attedit.rows[1].typed = "EG".into(); + app.run("battman", json!({ "name": "Tag", "action": "order", "order": ["NOTE", "NO"] })).unwrap(); + assert!(!attedit::apply(&mut app)); + assert_eq!((value(&app, h, "NO"), value(&app, h, "NOTE")), ("7".into(), "n".into()), "nothing was written"); + assert!(app.attedit.error.is_some()); + let rows: Vec<_> = app.attedit.rows.iter().map(|r| (r.tag.as_str(), r.typed.as_str())).collect(); + assert_eq!(rows, [("NOTE", "n"), ("NO", "7")], "the dialog shows the drawing's current order"); + + // Typing again after the reload applies to the right attribute. + app.attedit.rows[0].typed = "EG".into(); + assert!(attedit::apply(&mut app)); + assert_eq!((value(&app, h, "NO"), value(&app, h, "NOTE")), ("7".into(), "EG".into())); + + // The same through undo: the dialog opens on the reordered attributes, then the order is undone. + menus::activate(&mut app, "attedit"); + app.attedit.rows[0].typed = "again".into(); + app.run("undo", json!({})).unwrap(); + app.run("undo", json!({})).unwrap(); + assert!(!attedit::apply(&mut app)); + assert_eq!(value(&app, h, "NO"), "7"); +} + +/// The Properties palette's pending text is the drawing's: typed in one drawing and committed +/// after another (with the same handle and tags) is chosen, it must not be applied there. +#[test] +fn a_pending_properties_value_does_not_follow_a_drawing_switch() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + let (app, h) = app_with_reference(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + harness.run(); + let field = harness.get_all_by_role(egui::accesskit::Role::TextInput).find(|n| n.value().as_deref() == Some("n")).expect("the NOTE field"); + field.focus(); + harness.run(); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text("EG".into())); + harness.run(); + + harness.state_mut().session.new_drawing(false); + assert_eq!(add_reference(harness.state_mut()), h); + harness.run(); + harness.key_press(egui::Key::Enter); + harness.run(); + assert_eq!(value(harness.state(), h, "NOTE"), "n", "the other drawing's reference is untouched"); +} From 7d1a7e4fc812ca7b38e4ae7089ceeda00e32c22f Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:28:33 -0600 Subject: [PATCH 030/258] Annotative text contexts test: Dimension gains insertion_point on main Co-Authored-By: Claude Sonnet 5.5 --- crates/io/tests/annotative_text_contexts.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/io/tests/annotative_text_contexts.rs b/crates/io/tests/annotative_text_contexts.rs index 46676b543..7c9e7d9a0 100644 --- a/crates/io/tests/annotative_text_contexts.rs +++ b/crates/io/tests/annotative_text_contexts.rs @@ -541,6 +541,7 @@ fn made() -> Drawing { text_rotation: 0.0, user_text_pos: false, block: None, + insertion_point: Vec3::ZERO, overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), From 227e3c385b20129cf525775e3d9cbe78b722b3bb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 9 Nov 2026 06:29:44 -0500 Subject: [PATCH 031/258] Release 0.19.0 --- Cargo.lock | 32 ++++++++++++++++---------------- Cargo.toml | 2 +- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 334acd517..54ba163b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -614,7 +614,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cadcraft" -version = "0.17.0" +version = "0.19.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -644,7 +644,7 @@ dependencies = [ [[package]] name = "cadcraft-cli" -version = "0.17.0" +version = "0.19.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -660,14 +660,14 @@ dependencies = [ [[package]] name = "cadcraft-color" -version = "0.17.0" +version = "0.19.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-constraints" -version = "0.17.0" +version = "0.19.0" dependencies = [ "cadcraft-doc", "cadcraft-geom", @@ -677,7 +677,7 @@ dependencies = [ [[package]] name = "cadcraft-doc" -version = "0.17.0" +version = "0.19.0" dependencies = [ "cadcraft-color", "cadcraft-geom", @@ -688,7 +688,7 @@ dependencies = [ [[package]] name = "cadcraft-dwg" -version = "0.17.0" +version = "0.19.0" dependencies = [ "acadrust", "log", @@ -696,7 +696,7 @@ dependencies = [ [[package]] name = "cadcraft-dxf" -version = "0.17.0" +version = "0.19.0" dependencies = [ "encoding_rs", "log", @@ -705,7 +705,7 @@ dependencies = [ [[package]] name = "cadcraft-engine" -version = "0.17.0" +version = "0.19.0" dependencies = [ "cadcraft-color", "cadcraft-constraints", @@ -726,7 +726,7 @@ dependencies = [ [[package]] name = "cadcraft-fonts" -version = "0.17.0" +version = "0.19.0" dependencies = [ "cadcraft-dxf", "cadcraft-geom", @@ -739,14 +739,14 @@ dependencies = [ [[package]] name = "cadcraft-geom" -version = "0.17.0" +version = "0.19.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-io" -version = "0.17.0" +version = "0.19.0" dependencies = [ "acadrust", "cadcraft-color", @@ -768,7 +768,7 @@ dependencies = [ [[package]] name = "cadcraft-mcp" -version = "0.17.0" +version = "0.19.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -782,7 +782,7 @@ dependencies = [ [[package]] name = "cadcraft-render" -version = "0.17.0" +version = "0.19.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -796,7 +796,7 @@ dependencies = [ [[package]] name = "cadcraft-ui-egui" -version = "0.17.0" +version = "0.19.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -823,7 +823,7 @@ dependencies = [ [[package]] name = "cadcraft-web" -version = "0.17.0" +version = "0.19.0" dependencies = [ "cadcraft-engine", "cadcraft-fonts", @@ -5991,7 +5991,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.17.0" +version = "0.19.0" dependencies = [ "chrono", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 78309ded4..32204493c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] # default-members [workspace.package] -version = "0.17.0" +version = "0.19.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 51f5bbcc21fb7aef216f0768cc59fa730809416c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:49:24 +0100 Subject: [PATCH 032/258] Fonts: the MTEXT strip test expects a short \U+ escape to keep its digits (#2954) (#3024) strips_formatting expected `\U+12` to strip to nothing. plain_mtext dropped every unknown code up to the next `;` when that assertion was written. #1036 limits this to the codes in takes_arg, and `\U` is not one of them, so plain_mtext returns `+12`. The layout and paragraph paths give the same text, and unicode_escapes_are_decoded_in_every_parser already expects it. The test has failed on main since both changes merged, and the failure stops the gate at its test step. The test module now also checks the short escape in both layout paths. (cherry picked from commit 6f0f1fefa81d08031bde56a8b3d5b1556810f397) Co-authored-by: .CooCoo --- crates/fonts/src/mtext.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index e2ff9a3f9..9fe7aa47e 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -904,7 +904,7 @@ mod tests { assert_eq!(plain_mtext("\\H2.5x;Big"), "Big"); assert_eq!(plain_mtext("unterminated \\H2"), "unterminated "); assert_eq!(plain_mtext("\\U+0041B \\U+00E8"), "AB è"); - assert_eq!(plain_mtext("\\U+12"), "", "a short escape is a code with an argument"); + assert_eq!(plain_mtext("\\U+12"), "+12", "a short escape loses only the backslash and the code"); } #[test] @@ -928,6 +928,8 @@ mod tests { assert_eq!(plain_mtext("\\M+5BCFE x;y"), "\u{4ef6} x;y"); // Malformed escapes lose only the backslash and the code. assert_eq!(plain_mtext("a\\U+12 b"), "a+12 b"); + assert_eq!(lay("a\\U+12 b", 0.0).lines, vec!["a+12 b"]); + assert_eq!(lay("\\pxql;a\\U+12 b", 0.0).lines, vec!["a+12 b"]); assert_eq!(plain_mtext("a\\M+ b"), "a+ b"); } From 21c984ed5c797b0126c081d11a3133434e7d106c Mon Sep 17 00:00:00 2001 From: cdwilson127 Date: Wed, 11 Nov 2026 11:17:26 +1300 Subject: [PATCH 033/258] INSERT of a drawing file whose block exists no longer asks to redefine it when EXPERT is 2 or more (fixes #2995) EXPERT 2 or more answers the "already exists. Redefine it?" question Yes without asking, so a routine that inserts the same file repeatedly finishes each INSERT. EXPERT below 2 still asks. --- crates/engine/src/cmd/blocks/insert_file.rs | 5 +++-- crates/engine/tests/insert_file.rs | 23 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index 7a0492fad..667bc12a1 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -29,9 +29,10 @@ pub(super) struct FileRef { } impl FileRef { - /// Whether to ask before redefining: a plain path whose block already exists. + /// Whether to ask before redefining: a plain path whose block already exists. EXPERT 2 or + /// more answers Yes without asking. pub fn ask_redefine(&self, s: &Session) -> bool { - !self.explicit && s.doc().is_ok_and(|d| d.block(&self.name).is_some()) + !self.explicit && s.doc().is_ok_and(|d| d.block(&self.name).is_some() && d.header.i64("EXPERT", 0) < 2) } /// Read the file and (re)define its block. Returns the block's name. diff --git a/crates/engine/tests/insert_file.rs b/crates/engine/tests/insert_file.rs index 23e5d5581..839694000 100644 --- a/crates/engine/tests/insert_file.rs +++ b/crates/engine/tests/insert_file.rs @@ -150,6 +150,29 @@ fn a_drawing_file_becomes_a_block_with_its_insbase_and_tables() { assert_eq!(inserts(&s).len(), n); } +#[test] +fn expert_two_or_more_redefines_a_file_block_without_asking() { + // #2995: with EXPERT 2 or more the "already exists. Redefine it?" question is not asked; it + // is answered Yes, so the next INSERT of the same file finishes and the block is redefined + // from the file as it is now. + hooks(); + let dir = TempDir::new("insert-file-expert"); + let bolt = dir.file("bolt.dxf", "10,10"); + let mut s = Session::new(); + s.script(&format!("-INSERT {bolt} 0,0 1 1 0\n")).unwrap(); + s.execute("setvar", &json!({ "name": "EXPERT", "value": 2 })).unwrap(); + dir.file("bolt.dxf", "0,0"); + s.script(&format!("-INSERT {bolt} 20,0 1 1 0\n")).unwrap(); + assert!(s.running.is_none(), "INSERT finished: {}", s.prompt_text()); + assert_eq!(inserts(&s).len(), 2); + assert_eq!(s.doc().unwrap().block("bolt").unwrap().base, Vec3::ZERO, "redefined from the file"); + + // EXPERT 1 still asks. + s.execute("setvar", &json!({ "name": "EXPERT", "value": 1 })).unwrap(); + s.cmdline(&format!("-INSERT {bolt}")).unwrap(); + assert!(s.prompt_text().contains("Redefine"), "{}", s.prompt_text()); +} + #[test] fn exploded_json_insert_is_one_undo_step() { for params in [json!({ "name": "*B", "at": [5, 5] }), json!({ "name": "B", "at": [5, 5], "explode": true })] { From 161af2a8dabc3b716f50af9ce18b4cf01345de38 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 14:27:14 -0500 Subject: [PATCH 034/258] Release 0.20.1: repair Flatpak update checks and self-updates (#3078) * Release 0.20.1: fix Flatpak update permissions * test: avoid unchecked option parsing in Flatpak regression --- Cargo.lock | 32 +++++++++---------- Cargo.toml | 2 +- crates/ui-egui/tests/flatpak_updates.rs | 27 ++++++++++++++++ .../ai.storyteller.cadcraft.bundle.yml | 2 ++ .../linux/flatpak/ai.storyteller.cadcraft.yml | 2 ++ 5 files changed, 48 insertions(+), 17 deletions(-) create mode 100644 crates/ui-egui/tests/flatpak_updates.rs diff --git a/Cargo.lock b/Cargo.lock index 148dd3705..5dcec2532 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -614,7 +614,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cadcraft" -version = "0.20.0" +version = "0.20.1" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -645,7 +645,7 @@ dependencies = [ [[package]] name = "cadcraft-cli" -version = "0.20.0" +version = "0.20.1" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -661,14 +661,14 @@ dependencies = [ [[package]] name = "cadcraft-color" -version = "0.20.0" +version = "0.20.1" dependencies = [ "serde", ] [[package]] name = "cadcraft-constraints" -version = "0.20.0" +version = "0.20.1" dependencies = [ "cadcraft-doc", "cadcraft-geom", @@ -678,7 +678,7 @@ dependencies = [ [[package]] name = "cadcraft-doc" -version = "0.20.0" +version = "0.20.1" dependencies = [ "cadcraft-color", "cadcraft-geom", @@ -689,7 +689,7 @@ dependencies = [ [[package]] name = "cadcraft-dwg" -version = "0.20.0" +version = "0.20.1" dependencies = [ "acadrust", "log", @@ -697,7 +697,7 @@ dependencies = [ [[package]] name = "cadcraft-dxf" -version = "0.20.0" +version = "0.20.1" dependencies = [ "encoding_rs", "log", @@ -706,7 +706,7 @@ dependencies = [ [[package]] name = "cadcraft-engine" -version = "0.20.0" +version = "0.20.1" dependencies = [ "cadcraft-color", "cadcraft-constraints", @@ -727,7 +727,7 @@ dependencies = [ [[package]] name = "cadcraft-fonts" -version = "0.20.0" +version = "0.20.1" dependencies = [ "cadcraft-dxf", "cadcraft-geom", @@ -740,14 +740,14 @@ dependencies = [ [[package]] name = "cadcraft-geom" -version = "0.20.0" +version = "0.20.1" dependencies = [ "serde", ] [[package]] name = "cadcraft-io" -version = "0.20.0" +version = "0.20.1" dependencies = [ "acadrust", "cadcraft-color", @@ -769,7 +769,7 @@ dependencies = [ [[package]] name = "cadcraft-mcp" -version = "0.20.0" +version = "0.20.1" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -784,7 +784,7 @@ dependencies = [ [[package]] name = "cadcraft-render" -version = "0.20.0" +version = "0.20.1" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -798,7 +798,7 @@ dependencies = [ [[package]] name = "cadcraft-ui-egui" -version = "0.20.0" +version = "0.20.1" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -825,7 +825,7 @@ dependencies = [ [[package]] name = "cadcraft-web" -version = "0.20.0" +version = "0.20.1" dependencies = [ "cadcraft-engine", "cadcraft-fonts", @@ -5993,7 +5993,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index e7241a93e..eba807670 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] # default-members [workspace.package] -version = "0.20.0" +version = "0.20.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/crates/ui-egui/tests/flatpak_updates.rs b/crates/ui-egui/tests/flatpak_updates.rs new file mode 100644 index 000000000..1362e8148 --- /dev/null +++ b/crates/ui-egui/tests/flatpak_updates.rs @@ -0,0 +1,27 @@ +//! Release and source Flatpaks must allow release checks and host update helpers. +fn finish_args(manifest: &str) -> Vec<&str> { + manifest + .split("finish-args:") + .nth(1) + .unwrap_or_default() + .lines() + .take_while(|line| line.is_empty() || line.starts_with(' ') || line.starts_with('#')) + .filter_map(|line| line.trim().strip_prefix("- ")) + .map(|arg| arg.trim_matches(['\'', '"'])) + .collect() +} + +#[test] +fn flatpak_update_permissions() { + let manifests = [ + include_str!("../../../packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml"), + include_str!("../../../packaging/linux/flatpak/ai.storyteller.cadcraft.yml"), + ]; + let args = manifests.map(finish_args); + assert_eq!(args[0], args[1], "source and release permissions must agree"); + for permissions in args { + for required in ["--share=network", "--talk-name=org.freedesktop.Flatpak"] { + assert!(permissions.contains(&required), "missing update permission: {required}"); + } + } +} diff --git a/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml index 448ba058d..118f11e49 100644 --- a/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml @@ -17,6 +17,8 @@ runtime-version: '26.08' sdk: org.freedesktop.Sdk command: cadcraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland diff --git a/packaging/linux/flatpak/ai.storyteller.cadcraft.yml b/packaging/linux/flatpak/ai.storyteller.cadcraft.yml index e4b19cb81..08ccdffde 100644 --- a/packaging/linux/flatpak/ai.storyteller.cadcraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.cadcraft.yml @@ -18,6 +18,8 @@ sdk-extensions: - org.freedesktop.Sdk.Extension.rust-stable command: cadcraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland From 1ba86d461b7e7a165c4b2a8749c63516f4e38675 Mon Sep 17 00:00:00 2001 From: FredApps Date: Sat, 14 Nov 2026 21:44:50 +0100 Subject: [PATCH 035/258] Release: CADCraft v0.21.0 --- Cargo.lock | 28 ++++++++++++++-------------- Cargo.toml | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index de9acea4c..41e541936 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -614,7 +614,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cadcraft" -version = "0.20.1" +version = "0.21.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -645,7 +645,7 @@ dependencies = [ [[package]] name = "cadcraft-cli" -version = "0.20.1" +version = "0.21.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -661,14 +661,14 @@ dependencies = [ [[package]] name = "cadcraft-color" -version = "0.20.1" +version = "0.21.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-constraints" -version = "0.20.1" +version = "0.21.0" dependencies = [ "cadcraft-doc", "cadcraft-geom", @@ -678,7 +678,7 @@ dependencies = [ [[package]] name = "cadcraft-doc" -version = "0.20.1" +version = "0.21.0" dependencies = [ "cadcraft-color", "cadcraft-geom", @@ -689,7 +689,7 @@ dependencies = [ [[package]] name = "cadcraft-engine" -version = "0.20.1" +version = "0.21.0" dependencies = [ "cadcraft-color", "cadcraft-constraints", @@ -710,7 +710,7 @@ dependencies = [ [[package]] name = "cadcraft-fonts" -version = "0.20.1" +version = "0.21.0" dependencies = [ "cadcraft-geom", "craft-dxf", @@ -723,14 +723,14 @@ dependencies = [ [[package]] name = "cadcraft-geom" -version = "0.20.1" +version = "0.21.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-io" -version = "0.20.1" +version = "0.21.0" dependencies = [ "acadrust", "cadcraft-color", @@ -752,7 +752,7 @@ dependencies = [ [[package]] name = "cadcraft-mcp" -version = "0.20.1" +version = "0.21.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -767,7 +767,7 @@ dependencies = [ [[package]] name = "cadcraft-render" -version = "0.20.1" +version = "0.21.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -781,7 +781,7 @@ dependencies = [ [[package]] name = "cadcraft-ui-egui" -version = "0.20.1" +version = "0.21.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -809,7 +809,7 @@ dependencies = [ [[package]] name = "cadcraft-web" -version = "0.20.1" +version = "0.21.0" dependencies = [ "cadcraft-engine", "cadcraft-fonts", @@ -5997,7 +5997,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.20.1" +version = "0.21.0" dependencies = [ "chrono", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 0cee71d26..b22766049 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] # default-members [workspace.package] -version = "0.20.1" +version = "0.21.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From a9576755120c488d1150a81060eb90751686f9b7 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sun, 15 Nov 2026 10:12:49 +0000 Subject: [PATCH 036/258] DXF: mirror a mirrored HATCH's pattern lines with its boundary (#3120) A HATCH with extrusion (0,0,-1) had its boundary and hatch angle mirrored into the world, but the pattern definition lines read from the file kept their OCS direction, base point and offset. Lines at an angle other than the hatch's were drawn on the wrong slant (ANSI31 at 45 instead of 135) and multi-line patterns lost their alignment. Mirror each line the same way. --- crates/io/src/dxf_read/entities.rs | 2 ++ crates/io/src/dxf_read/hatch.rs | 24 ++++++++++++++++++++++++ crates/io/src/tests.rs | 25 +++++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 2e4b6ff14..e31cd75ab 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -273,7 +273,9 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef v.p.x = -v.p.x; v.bulge = -v.bulge; } + let ocs_angle = h.angle; h.angle = cadcraft_geom::norm_angle(std::f64::consts::PI - h.angle); + super::hatch::mirror_pattern_lines(&mut h.pattern_lines, h.origin, h.scale, ocs_angle, h.angle); } k } diff --git a/crates/io/src/dxf_read/hatch.rs b/crates/io/src/dxf_read/hatch.rs index 13013a85d..9cd0f5729 100644 --- a/crates/io/src/dxf_read/hatch.rs +++ b/crates/io/src/dxf_read/hatch.rs @@ -291,6 +291,30 @@ fn pattern_definition(tags: &[Tag], scale: f64, angle: f64, origin: Vec2) -> Vec .collect() } +/// The pattern lines of a hatch read in a mirrored OCS (extrusion (0,0,-1)) turned into the world +/// frame its boundary was mirrored into: each line as the file drew it (angle, base point and +/// offset at hatch angle `ocs_angle`) is mirrored in x, then kept the library's way for the +/// mirrored hatch angle `world_angle`. Without this, lines at an angle other than the hatch's +/// kept their unmirrored direction and position against a mirrored boundary (issue #3120). +pub(super) fn mirror_pattern_lines(lines: &mut [cadcraft_doc::library::PatternLine], origin: Vec2, scale: f64, ocs_angle: f64, world_angle: f64) { + // The same fallbacks as `pattern_definition` used when it stored the lines. + let scale = if scale.is_finite() && scale > 1e-9 { scale } else { 1.0 }; + let ocs_angle = if ocs_angle.is_finite() { ocs_angle } else { 0.0 }; + let world_angle = if world_angle.is_finite() { world_angle } else { 0.0 }; + let mirror = |v: Vec2| Vec2::new(-v.x, v.y); + for line in lines { + let file_angle = line.angle.to_radians() + ocs_angle; + let base = mirror(origin + Vec2::new(line.origin.0, line.origin.1).rotate(ocs_angle) * scale); + let offset = mirror(Vec2::new(line.delta.0, line.delta.1).rotate(file_angle) * scale); + let angle = std::f64::consts::PI - file_angle; + let local = (base - origin).rotate(-world_angle) * (1.0 / scale); + let delta = offset.rotate(-angle) * (1.0 / scale); + line.angle = (angle - world_angle).to_degrees(); + line.origin = (local.x, local.y); + line.delta = (delta.x, delta.y); + } +} + /// Hatch origin and background colour from `CADCRAFT` xdata: `1000 HATCH`, `1011` origin, /// `1000` background colour name (empty for none). Defaults when absent. fn hatch_xdata(tags: &[Tag]) -> (Vec2, Option) { diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 34a8c8de4..5b0fd7f49 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2641,6 +2641,31 @@ fn mirrored_hatch_extrusion_flips_boundary() { } } +/// Issue #3120: a mirrored HATCH's pattern lines mirror with its boundary. The file draws one +/// line at 55° from (1, 0.5) with offset (-0.2, 0.3) in its OCS; under extrusion (0,0,-1) that +/// is a line at 125° from (-1, 0.5) with offset (0.2, 0.3) in the world. Before, only the hatch +/// angle was mirrored and the line stayed at 55° - 10° + 170° = 215° (35°), off its true slant. +#[test] +fn mirrored_hatch_mirrors_its_pattern_lines() { + let text = "0\nSECTION\n2\nENTITIES\n0\nHATCH\n8\n0\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n-1\n2\nMYPAT\n70\n0\n71\n0\n91\n1\n\ + 92\n2\n72\n0\n73\n1\n93\n4\n10\n1\n20\n0\n10\n3\n20\n0\n10\n3\n20\n2\n10\n1\n20\n2\n97\n0\n75\n0\n76\n1\n\ + 52\n10\n41\n2\n77\n0\n78\n1\n53\n55\n43\n1\n44\n0.5\n45\n-0.2\n46\n0.3\n79\n2\n49\n0.5\n49\n-0.25\n98\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "h.dxf").unwrap(); + let h = first(&d, |k| if let EntityKind::Hatch(h) = k { Some(h.clone()) } else { None }); + assert!((h.angle.to_degrees() - 170.0).abs() < 1e-9, "hatch angle {}", h.angle.to_degrees()); + let [l] = h.pattern_lines.as_slice() else { panic!("one pattern line: {:?}", h.pattern_lines) }; + // The line in the world, the way the renderer and the writer place it. + let ang = l.angle.to_radians() + h.angle; + let base = h.origin + Vec2::new(l.origin.0, l.origin.1).rotate(h.angle) * h.scale; + let offset = Vec2::new(l.delta.0, l.delta.1).rotate(ang) * h.scale; + let dir = cadcraft_geom::norm_angle(ang).to_degrees(); + assert!((dir - 125.0).abs() < 1e-9, "line direction {dir}"); + assert!(base.near(Vec2::new(-1.0, 0.5), 1e-9), "base point {base:?}"); + assert!(offset.near(Vec2::new(0.2, 0.3), 1e-9), "offset {offset:?}"); + let dashes: Vec = l.dashes.iter().map(|d| d * h.scale).collect(); + assert_eq!(dashes, vec![0.5, -0.25]); +} + /// Issue #1886: a HATCH in a tilted plane (a terrain face) is drawn as seen from above, not turned /// about the origin. With extrusion (0, 0.5, -√3/2) the OCS axes are x = (-1,0,0) and /// y = (0, √3/2, 1/2): the square (1,0)..(3,2) lies over (-3,0)..(-1,√3), from z 0 up to z 1. From f3a9ecdce98dbd8636bd0d2dfa1273b46d8de80d Mon Sep 17 00:00:00 2001 From: V1dalTheAbidal <97257872+V1dalTheAbidal@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:54:04 +0200 Subject: [PATCH 037/258] Selection through a viewport leaves out block parts on its frozen layers (#3126) Through an MSPACE viewport a block reference on a layer the viewport draws was hit on a part whose layer is frozen in that viewport, and that part took room in the box a window tests. The viewport does not draw the part. - doc: ViewportBounds measures an entity as one layout viewport draws it, without the block contents on the viewport's frozen layers. - render: build_entities_in_viewport builds loose entities as a viewport that freezes the given layers draws them. - engine: a pick, selection cycling's list, a window, a crossing window, a fence and the polygons test a reference against that box and that geometry. The spatial index is unchanged: the viewport's box is never larger than the indexed one. - ui: the highlight of a reference inside the active viewport is built the same way. A clipped reference (XCLIP) stays selected by its boundary whatever the viewport draws inside it, as AutoCAD 2022 selects it: it keeps the box the drawing gives it. Nothing changes where no layer is frozen in the active viewport. --- crates/doc/src/extents.rs | 304 ++++++- crates/doc/src/lib.rs | 4 +- crates/engine/src/select.rs | 77 +- crates/engine/tests/it/main.rs | 1 + .../tests/it/viewport_frozen_block_parts.rs | 825 ++++++++++++++++++ crates/render/src/lib.rs | 2 +- crates/render/src/pipeline.rs | 11 +- crates/render/src/tests.rs | 28 + crates/ui-egui/src/canvas/tests.rs | 31 + crates/ui-egui/src/canvas/viewport.rs | 10 +- 10 files changed, 1233 insertions(+), 60 deletions(-) create mode 100644 crates/engine/tests/it/viewport_frozen_block_parts.rs diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 9f29c07b6..0d3128d7e 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -270,15 +270,56 @@ fn text_box(t: &crate::Text, len: usize) -> Bounds2 { /// entities a visibility state hides are invisible this way, and they sit far from the block's /// geometry in real drawings. Layer "0" takes the insert's layer, which the caller has checked. /// `off_counts`: a layer turned off counts too, as in the drawing's extents ([`extent_bounds`]). -fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool) -> bool { +/// `frozen`: the layers frozen in the layout viewport measured through ([`ViewportBounds`]). +fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool, frozen: &[String]) -> bool { // Attribute definitions are not drawn in an insert (its attribs are, see below). - !matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts) + !matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts, frozen) } /// Whether what lies on `layer` inside an insert counts: layer "0" takes the insert's layer, which /// the caller has checked; a frozen layer never counts, one turned off only with `off_counts`. -fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool { - layer == "0" || d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) +/// Nor does one of the layers in `frozen`, those frozen in the layout viewport measured through, +/// which does not draw them (the names compared as the renderer compares them). +fn layer_counts(d: &Drawing, layer: &str, off_counts: bool, frozen: &[String]) -> bool { + layer == "0" || (d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) && !frozen.iter().any(|f| f.eq_ignore_ascii_case(layer))) +} + +/// The box of the contents of the block `blk`, referenced at `depth`, in the block's coordinates: +/// the parts that count there ([`in_block_visible`]). It is read from `blocks`, or measured and +/// kept there, so a block is measured once per depth and not again for every reference to it +/// ([`bounds_in`] says what the maps hold and why the depth is part of the key). +fn block_contents_box<'a>( + d: &'a Drawing, + blk: &'a crate::Block, + depth: usize, + blocks: &mut HashMap<(&'a str, usize), Bounds2>, + in_drawing: &mut HashMap<(&'a str, usize), Bounds2>, + off_counts: bool, + frozen: &[String], +) -> Bounds2 { + if let Some(known) = blocks.get(&(blk.name.as_str(), depth)) { + return *known; + } + let mut inner = Bounds2::EMPTY; + for be in blk.entities.iter().filter(|be| in_block_visible(d, be, off_counts, frozen)) { + inner = inner.union(&bounds_in(d, be, depth + 1, blocks, in_drawing, off_counts, frozen)); + } + blocks.insert((blk.name.as_str(), depth), inner); + inner +} + +/// The box of the contents of the block `blk`, referenced at `depth`, as the drawing shows them: +/// no viewport's frozen layers are left out. For a clipped reference measured through a viewport +/// ([`bounds_in`]). `in_drawing` keeps these boxes, apart from that viewport's own block bounds. +fn drawing_block_box<'a>( + d: &'a Drawing, + blk: &'a crate::Block, + depth: usize, + off_counts: bool, + in_drawing: &mut HashMap<(&'a str, usize), Bounds2>, +) -> Bounds2 { + // With no layer left out, the measure never asks for the drawing's boxes itself. + block_contents_box(d, blk, depth, in_drawing, &mut HashMap::new(), off_counts, &[]) } /// The layer an insert's attribute draws on, as the renderer takes it: its own, else its @@ -327,13 +368,13 @@ fn mtext_box(t: &crate::MText) -> Bounds2 { /// The box of what `e` draws (block contents on layers turned off left out). pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 { - bounds_of(d, e, depth, false, &mut HashMap::new()) + bounds_of(d, e, depth, false, &[], &mut HashMap::new(), &mut HashMap::new()) } /// The box `e` takes in the drawing's extents: as [`entity_bounds`], but block contents on a layer /// turned off count, as AutoCAD 2024's ZOOM Extents counts them (a frozen layer's do not). pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 { - bounds_of(d, e, 0, true, &mut HashMap::new()) + bounds_of(d, e, 0, true, &[], &mut HashMap::new(), &mut HashMap::new()) } /// The bounds of block contents measured so far, kept across the entities of one unchanged @@ -351,24 +392,69 @@ pub struct BlockBoundsCache<'a> { /// [`entity_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`. pub fn entity_bounds_cached<'a>(d: &'a Drawing, e: &Entity, depth: usize, cache: &mut BlockBoundsCache<'a>) -> Bounds2 { - bounds_of(d, e, depth, false, &mut cache.drawn) + bounds_of(d, e, depth, false, &[], &mut cache.drawn, &mut HashMap::new()) } /// [`extent_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`. pub fn extent_bounds_cached<'a>(d: &'a Drawing, e: &Entity, cache: &mut BlockBoundsCache<'a>) -> Bounds2 { - bounds_of(d, e, 0, true, &mut cache.extents) + bounds_of(d, e, 0, true, &[], &mut cache.extents, &mut HashMap::new()) } -fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blocks: &mut HashMap<(&'a str, usize), Bounds2>) -> Bounds2 { +/// The boxes of what one layout viewport draws: [`entity_bounds`] with the block contents on the +/// layers frozen in that viewport left out, as the viewport leaves them out when it draws. It +/// keeps the block bounds it has measured, as a [`BlockBoundsCache`] does, so use one only while +/// the drawing it measured is unchanged. The layers belong to it, so the bounds measured through +/// one viewport never answer for another. One thing a selection counts whatever the viewport +/// draws stays in: a clipped reference (XCLIP) is selected by its boundary, so it keeps the box +/// the drawing gives it. +pub struct ViewportBounds<'a> { + /// The layers frozen in the viewport. + frozen: &'a [String], + /// By block name and depth, the box of the block contents the viewport draws. + blocks: HashMap<(&'a str, usize), Bounds2>, + /// The same with no layer of the viewport left out: the box the drawing gives the contents, + /// which a clipped reference keeps. + in_drawing: HashMap<(&'a str, usize), Bounds2>, +} + +impl<'a> ViewportBounds<'a> { + /// For a viewport that freezes the layers in `frozen` (none: the drawing as it shows anywhere). + pub fn new(frozen: &'a [String]) -> Self { + ViewportBounds { frozen, blocks: HashMap::new(), in_drawing: HashMap::new() } + } + + /// The layers frozen in the viewport. + pub fn frozen(&self) -> &'a [String] { + self.frozen + } + + /// The box of what the viewport draws of `e`. Like [`entity_bounds`] it does not look at the + /// layer `e` itself is on: whether the viewport draws `e` at all is the caller's to check. + pub fn entity_bounds(&mut self, d: &'a Drawing, e: &Entity) -> Bounds2 { + bounds_of(d, e, 0, false, self.frozen, &mut self.blocks, &mut self.in_drawing) + } +} + +/// The box of `e` at `depth` with the block bounds in `blocks` and `in_drawing`: [`bounds_in`], a +/// top-level annotative object measured as it draws. +fn bounds_of<'a>( + d: &'a Drawing, + e: &Entity, + depth: usize, + off_counts: bool, + frozen: &[String], + blocks: &mut HashMap<(&'a str, usize), Bounds2>, + in_drawing: &mut HashMap<(&'a str, usize), Bounds2>, +) -> Bounds2 { // A top-level annotative object measures as it draws at the current annotation scale. if depth == 0 { match d.anno_draw(e) { crate::AnnoDraw::Plain => {} crate::AnnoDraw::Hidden => return Bounds2::EMPTY, - crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, off_counts), + crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen), } } - bounds_in(d, e, depth, blocks, off_counts) + bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen) } /// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed, @@ -376,8 +462,20 @@ fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blo /// expanding the block again, so nested or self-referencing blocks cost at most one pass over each /// definition per depth instead of one per reference (which grows exponentially with the nesting /// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its -/// bounds must not stand in for a shallower reference to the same block (#706). -fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Bounds2>, off_counts: bool) -> Bounds2 { +/// bounds must not stand in for a shallower reference to the same block (#706). The bounds in +/// `blocks` depend on `off_counts` and on `frozen` (see [`layer_counts`]), so one map goes with +/// one value of each. `in_drawing` is the map that goes with the same `off_counts` and no frozen +/// layer: a measure through a viewport takes from it the box the drawing gives the block of a +/// clipped reference ([`drawing_block_box`]). A measure with no frozen layer does not use it. +fn bounds_in<'a>( + d: &'a Drawing, + e: &Entity, + depth: usize, + blocks: &mut HashMap<(&'a str, usize), Bounds2>, + in_drawing: &mut HashMap<(&'a str, usize), Bounds2>, + off_counts: bool, + frozen: &[String], +) -> Bounds2 { match &e.kind { EntityKind::Table(t) if t.is_broken() => t.bounds(), EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY, @@ -400,17 +498,16 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< let mut b = Bounds2::EMPTY; if let Some(blk) = d.block(&ins.block) { let m = ins.transform(blk.base.xy()); - let inner = match blocks.get(&(blk.name.as_str(), depth)) { - Some(b) => *b, - None => { - let mut inner = Bounds2::EMPTY; - for be in blk.entities.iter().filter(|be| in_block_visible(d, be, off_counts)) { - inner = inner.union(&bounds_in(d, be, depth + 1, blocks, off_counts)); - } - blocks.insert((blk.name.as_str(), depth), inner); - inner - } - }; + let mut inner = block_contents_box(d, blk, depth, blocks, in_drawing, off_counts, frozen); + // XCLIP: the reference app selects a clipped reference by its boundary whatever a + // viewport draws inside it, so a clipped reference keeps the box the drawing gives it. + // One that is not inverted and has a part drawn gets the boundary's box below as it is. + if !frozen.is_empty() + && let Some(c) = ins.clip.as_ref().filter(|c| c.active()) + && (c.inverted || inner.is_empty()) + { + inner = drawing_block_box(d, blk, depth, off_counts, in_drawing); + } b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) }; // XCLIP: the reference app takes the boundary's box, also where it reaches past the // block or misses it (an inverted clip can show anything, so it keeps the block's). @@ -432,7 +529,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< } } for a in &ins.attribs { - if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) { + if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts, frozen) { b = b.union(&match a.multiline_text() { Some(m) => mtext_box(&m), None => text_box(&a.text, a.text.value.chars().count()), @@ -469,17 +566,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< // Reuse the shared block-bounds cache (as the Insert branch does) so a dimension // block with branching or self-referencing children costs one pass per definition // per depth, not one per reference (which grows exponentially) (CWE-400). - let inner = match blocks.get(&(blk.name.as_str(), depth)) { - Some(cached) => *cached, - None => { - let mut inner = Bounds2::EMPTY; - for be in blk.entities.iter().filter(|be| in_block_visible(d, be, off_counts)) { - inner = inner.union(&bounds_in(d, be, depth + 1, blocks, off_counts)); - } - blocks.insert((blk.name.as_str(), depth), inner); - inner - } - }; + let inner = block_contents_box(d, blk, depth, blocks, in_drawing, off_counts, frozen); // The block draws translated by the insertion point (group 12), so its bounds // move with it (#2634); the cache above keeps the block's own bounds. let off = dm.insertion_point.xy(); @@ -498,7 +585,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< } if let Some(ins) = &m.block { let be = Entity { handle: e.handle, common: e.common.clone(), kind: EntityKind::Insert(ins.clone()) }; - b = b.union(&bounds_in(d, &be, depth, blocks, off_counts)); + b = b.union(&bounds_in(d, &be, depth, blocks, in_drawing, off_counts, frozen)); } b } @@ -798,6 +885,149 @@ mod tests { } } + /// Through a layout viewport the block contents on a layer frozen in it take no room: a part + /// of a reference, a part two blocks deep, a nested reference that is itself on that layer + /// (with everything in it), an attribute, the parts of the block a dimension or a multileader + /// draws (a reference nested in a dimension's block too), and the parts of an annotative + /// reference. A clipped reference (XCLIP) keeps the box the drawing gives it, whatever is drawn + /// of it. The layer's name is matched whatever its case. With no layer frozen + /// the box is the one [`entity_bounds`] gives, and one [`ViewportBounds`] gives every entity + /// the box a fresh one gives it. + #[test] + fn a_viewport_leaves_out_block_contents_on_the_layers_frozen_in_it() { + let line = |handle: u64, y: f64, layer: &str| { + let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }); + let mut e = Entity::new(crate::Handle(handle), kind); + e.common.layer = layer.into(); + e + }; + let reference = |block: &str| crate::Insert { block: block.into(), ..crate::Insert::default() }; + let ins = |block: &str, layer: &str| { + let mut e = Entity::new(crate::Handle(2), EntityKind::Insert(reference(block))); + e.common.layer = layer.into(); + e + }; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + let mut add = |name: &str, parts: Vec| { + let mut b = crate::Block::new(name); + for part in parts { + b.entities.push(part); + } + d.blocks.insert(name.into(), std::sync::Arc::new(b)); + }; + // B: a line on layer 0 along y = 0 and one on "Hidden" along y = 50. N nests B. Z holds a + // reference to B that is itself on "Hidden", and a line along y = 90. H is all on "Hidden". + add("B", vec![line(1, 0.0, "0"), line(3, 50.0, "Hidden")]); + add("N", vec![ins("B", "0")]); + add("Z", vec![ins("B", "Hidden"), line(1, 90.0, "0")]); + add("H", vec![line(1, 50.0, "Hidden")]); + // A reference to B with an attribute on "Hidden" at y = 70. + let mut tagged = ins("B", "0"); + if let EntityKind::Insert(i) = &mut tagged.kind { + i.attribs.push(crate::Attrib { + tag: "T".into(), + text: Text { insert: Vec3::new(0.0, 70.0, 0.0), align_pt: None, ..text(HAlign::Left, VAlign::Baseline) }, + invisible: false, + constant: false, + prompt: String::new(), + props: crate::AttribProps { layer: Some("Hidden".into()), ..Default::default() }, + multiline: None, + modes: Default::default(), + }); + } + // References to H clipped to a boundary around its line, and with that clip inverted: no + // part of either is drawn where "Hidden" is frozen in the viewport. And a reference to B + // with the inverted clip: its line along y = 0 is drawn there. + let clip = |block: &str, inverted: bool| { + let mut e = ins(block, "0"); + if let EntityKind::Insert(i) = &mut e.kind { + let boundary = crate::ClipBoundary::new(vec![Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0)]); + i.clip = Some(crate::ClipBoundary { inverted, ..boundary }); + } + e + }; + let (clipped, clipped_inverted, clipped_partly) = (clip("H", false), clip("H", true), clip("B", true)); + // An annotative reference to B: measured as it draws at the annotation scale, here 1:1. + let mut scaled = ins("B", "0"); + scaled.common.anno_scales = vec![crate::AnnoScale::unit()]; + // Dimensions that draw B and N, and a multileader that draws B. + let dimension = |block: &str| { + let kind = EntityKind::Dimension(crate::Dimension { + kind: crate::DimKind::Aligned, + defpt: Vec3::new(5.0, 1.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::ZERO, + p14: Vec3::new(10.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some(block.into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }); + Entity::new(crate::Handle(3), kind) + }; + let (dim, dim_nested) = (dimension("B"), dimension("N")); + let leader = Entity::new( + crate::Handle(4), + EntityKind::MLeader(crate::MLeader { + leaders: vec![vec![Vec3::ZERO]], + landing: Vec3::new(1.0, 0.0, 0.0), + dogleg: 0.45, + text: None, + style: "Standard".into(), + arrow_size: 1.0, + spline: false, + block: Some(reference("B")), + }), + ); + let frozen = ["HIDDEN".to_string()]; + let mut view = ViewportBounds::new(&frozen); + let ys = |b: Bounds2| (b.min.y, b.max.y); + assert_eq!(ys(entity_bounds(&d, &ins("B", "0"), 0)), (0.0, 50.0)); + assert_eq!(ys(view.entity_bounds(&d, &ins("B", "0"))), (0.0, 0.0), "a part on the frozen layer"); + assert_eq!(ys(view.entity_bounds(&d, &ins("N", "0"))), (0.0, 0.0), "a part two blocks deep"); + assert_eq!(ys(entity_bounds(&d, &ins("Z", "0"), 0)), (0.0, 90.0)); + assert_eq!(ys(view.entity_bounds(&d, &ins("Z", "0"))), (90.0, 90.0), "a nested reference on the frozen layer"); + assert!(!entity_bounds(&d, &ins("H", "0"), 0).is_empty()); + assert!(view.entity_bounds(&d, &ins("H", "0")).is_empty(), "nothing of it is drawn"); + let boundary = (Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0)); + let (drawn, seen) = (entity_bounds(&d, &clipped, 0), view.entity_bounds(&d, &clipped)); + assert_eq!((drawn.min, drawn.max), boundary); + assert_eq!((seen.min, seen.max), boundary, "a clipped reference no part of which is drawn keeps its boundary"); + assert_eq!(ys(entity_bounds(&d, &clipped_inverted, 0)), (50.0, 50.0)); + assert_eq!(ys(view.entity_bounds(&d, &clipped_inverted)), (50.0, 50.0), "and one clipped the other way its block's box"); + assert_eq!(ys(entity_bounds(&d, &clipped_partly, 0)), (0.0, 50.0)); + assert_eq!(ys(view.entity_bounds(&d, &clipped_partly)), (0.0, 50.0), "with a part drawn too"); + assert!(entity_bounds(&d, &tagged, 0).max.y >= 70.0); + assert_eq!(ys(view.entity_bounds(&d, &tagged)), (0.0, 0.0), "an attribute on the frozen layer"); + assert_eq!(ys(entity_bounds(&d, &scaled, 0)), (0.0, 50.0)); + assert_eq!(ys(view.entity_bounds(&d, &scaled)), (0.0, 0.0), "an annotative reference"); + assert_eq!(entity_bounds(&d, &dim, 0).max.y, 50.0); + assert!(view.entity_bounds(&d, &dim).max.y < 50.0, "the block a dimension draws"); + assert_eq!(entity_bounds(&d, &dim_nested, 0).max.y, 50.0); + assert!(view.entity_bounds(&d, &dim_nested).max.y < 50.0, "a reference nested in the block a dimension draws"); + assert_eq!(entity_bounds(&d, &leader, 0).max.y, 50.0); + assert!(view.entity_bounds(&d, &leader).max.y < 50.0, "the block a multileader draws"); + let clips = [clipped, clipped_inverted, clipped_partly]; + let all = [ins("B", "0"), ins("N", "0"), ins("Z", "0"), ins("H", "0"), tagged, scaled, dim, dim_nested, leader].into_iter().chain(clips); + let all: Vec = all.collect(); + let mut plain = ViewportBounds::new(&[]); + for e in &all { + let (shared, fresh) = (view.entity_bounds(&d, e), ViewportBounds::new(&frozen).entity_bounds(&d, e)); + assert_eq!((shared.min, shared.max), (fresh.min, fresh.max)); + let (unfrozen, drawn) = (plain.entity_bounds(&d, e), entity_bounds(&d, e, 0)); + assert_eq!((unfrozen.min, unfrozen.max), (drawn.min, drawn.max)); + } + } + /// A turned array of references reaches its side copies, not only the first and the last; /// a hostile count measures only the copies that are drawn. #[test] diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 873e83b83..a67b8614e 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -30,8 +30,8 @@ pub use cadcraft_geom as geom; pub use constraint::*; pub use entity::*; pub use extents::{ - BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, ole_frame_accepts, - ole_frame_transform, + BlockBoundsCache, MAX_BLOCK_DEPTH, ViewportBounds, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, + ole_frame_accepts, ole_frame_transform, }; pub use format::Format; pub use gdt::*; diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 56403f8fa..710ee864a 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -1,6 +1,6 @@ //! Hit testing and window/crossing selection. -use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, entity_bounds}; +use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, ViewportBounds, entity_bounds}; use cadcraft_geom::{Bounds2, Line, Vec2, point_in_polygon}; use crate::spatial::{self, SpatialIndex}; @@ -8,6 +8,14 @@ use crate::{Accept, Prompt}; /// Polylines approximating an entity for hit testing, tessellated at `tol`. pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec> { + hit_polylines_in(d, e, &mut ViewportBounds::new(&[]), tol) +} + +/// [`hit_polylines`] through the layout viewport `view`: the parts of a block reference on the +/// layers frozen in that viewport are not drawn there, so they are not hit, and the box around +/// the reference is the box around the parts that are drawn ([`bounds_in`]). A clipped +/// reference's box stays, as [`ViewportBounds`] says. +fn hit_polylines_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a>, tol: f64) -> Vec> { match &e.kind { EntityKind::Text(_) | EntityKind::MText(_) @@ -19,17 +27,18 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec> { | EntityKind::MLeader(_) | EntityKind::Image(_) => { // Text-like objects are hit inside their box. - let b = entity_bounds(d, e, 0); + let b = bounds_in(d, e, None, view); if b.is_empty() { return Vec::new(); } let c = b.corners(); let mut v = vec![vec![c[0], c[1], c[2], c[3], c[0]]]; if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::Insert(_) | EntityKind::MLeader(_)) { - let list = cadcraft_render::build_entities( + let list = cadcraft_render::build_entities_in_viewport( d, std::iter::once(e), &cadcraft_render::Options { tolerance: tol, text: false, linetypes: false, ..Default::default() }, + view.frozen(), ); v = list.prims.iter().map(|p| list.points(p).to_vec()).collect(); v.push(vec![c[0], c[1], c[2], c[3], c[0]]); @@ -93,7 +102,13 @@ fn dist_to_polyline(pts: &[Vec2], p: Vec2) -> f64 { /// Distance from `p` to the entity (0 inside text boxes and solid fills). pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 { - let polys = hit_polylines(d, e, tol); + entity_distance_in(d, e, &mut ViewportBounds::new(&[]), p, tol) +} + +/// [`entity_distance`] through the layout viewport `view`: to what that viewport draws of the +/// entity ([`hit_polylines_in`]). +fn entity_distance_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a>, p: Vec2, tol: f64) -> f64 { + let polys = hit_polylines_in(d, e, view, tol); 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(_)); @@ -183,6 +198,16 @@ pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option) -> Boun known.unwrap_or_else(|| entity_bounds(d, e, 0)) } +/// The box a selection made through the layout viewport `view` tests `e` against: the box of +/// what that viewport draws of it. `known` is the box the spatial index holds, of what the +/// drawing shows; it stands unless the viewport freezes layers and `e` draws a block (a block +/// reference, a dimension, a multileader), whose contents on those layers the viewport leaves +/// out. That box is never larger than `known`, so the index still finds every candidate. +fn bounds_in<'a>(d: &'a Drawing, e: &Entity, known: Option, view: &mut ViewportBounds<'a>) -> Bounds2 { + let draws_a_block = matches!(e.kind, EntityKind::Insert(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_)); + if draws_a_block && !view.frozen().is_empty() { view.entity_bounds(d, e) } else { bounds_of(d, e, known) } +} + pub(crate) fn is_infinite(e: &Entity) -> bool { matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) } @@ -235,16 +260,17 @@ pub(crate) fn pick_with( aperture: f64, ) -> Option { let probe = Bounds2::new(p, p).expand(aperture); + let mut view = ViewportBounds::new(frozen); // Candidates come topmost first: the first within the aperture is the one. for (e, known) in candidates(d, space, ix, &probe.expand(aperture), true, true)? { if !selectable(d, e, frozen) { continue; } let infinite = is_infinite(e); - if !infinite && !bounds_of(d, e, known).expand(aperture).intersects(&probe) { + if !infinite && !bounds_in(d, e, known, &mut view).expand(aperture).intersects(&probe) { continue; } - if entity_distance(d, e, p, aperture / 4.0) <= aperture { + if entity_distance_in(d, e, &mut view, p, aperture / 4.0) <= aperture { return Some(e.handle); } } @@ -262,9 +288,13 @@ pub fn pick_all_in(d: &Drawing, space: &Space, frozen: &[String], p: Vec2, apert let ix = spatial::index(d, space); let probe = Bounds2::new(p, p).expand(aperture); let Some(cands) = candidates(d, space, &ix, &probe.expand(aperture), true, true) else { return Vec::new() }; + let mut view = ViewportBounds::new(frozen); cands - .filter(|(e, known)| selectable(d, e, frozen) && (is_infinite(e) || bounds_of(d, e, *known).expand(aperture).intersects(&probe))) - .filter(|(e, _)| entity_distance(d, e, p, aperture / 4.0) <= aperture) + .filter(|(e, known)| { + selectable(d, e, frozen) + && (is_infinite(e) || bounds_in(d, e, *known, &mut view).expand(aperture).intersects(&probe)) + && entity_distance_in(d, e, &mut view, p, aperture / 4.0) <= aperture + }) .map(|(e, _)| e.handle) .collect() } @@ -311,7 +341,8 @@ pub(crate) fn select_window_with( ) -> Vec { let Some(cands) = candidates(d, space, ix, &bx, crossing, false) else { return Vec::new() }; let tol = window_tol(&bx); - cands.filter(|(e, known)| selectable(d, e, frozen) && in_window(d, e, *known, &bx, crossing, tol)).map(|(e, _)| e.handle).collect() + let mut view = ViewportBounds::new(frozen); + cands.filter(|(e, known)| selectable(d, e, frozen) && in_window_in(d, e, *known, &mut view, &bx, crossing, tol)).map(|(e, _)| e.handle).collect() } /// The tessellation tolerance window and crossing tests use for a box. @@ -322,15 +353,29 @@ pub(crate) fn window_tol(bx: &Bounds2) -> f64 { /// Whether a window box (`crossing` false: entirely inside) or a crossing box (inside or /// touching its geometry, not just its bounding box) selects `e`. pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option, bx: &Bounds2, crossing: bool, tol: f64) -> bool { + in_window_in(d, e, known, &mut ViewportBounds::new(&[]), bx, crossing, tol) +} + +/// [`in_window`] through the layout viewport `view`: a block reference is inside the box, or +/// touches it, by the parts that viewport draws ([`bounds_in`], [`hit_polylines_in`]). +fn in_window_in<'a>( + d: &'a Drawing, + e: &Entity, + known: Option, + view: &mut ViewportBounds<'a>, + bx: &Bounds2, + crossing: bool, + tol: f64, +) -> bool { let infinite = is_infinite(e); - let eb = bounds_of(d, e, known); + let eb = bounds_in(d, e, known, view); if !infinite && bx.contains_box(&eb) { return true; } if !crossing || (!infinite && !eb.intersects(bx)) { return false; } - let polys = hit_polylines(d, e, tol); + let polys = hit_polylines_in(d, e, view, tol); let hit = polys.iter().any(|pl| { if pl.len() == 1 { pl.first().is_some_and(|p| bx.contains(*p)) @@ -378,13 +423,14 @@ pub(crate) fn select_fence_with( let tol = (fb.width() + fb.height()).max(1e-9) / 2000.0; let probe = fb.expand(tol); let Some(cands) = candidates(d, space, ix, &probe, true, false) else { return Vec::new() }; + let mut view = ViewportBounds::new(frozen); let mut out = Vec::new(); for (e, known) in cands { // Infinite objects have no useful bounds; like window selection, test their geometry directly. - if !selectable(d, e, frozen) || (!is_infinite(e) && !bounds_of(d, e, known).intersects(&probe)) { + if !selectable(d, e, frozen) || (!is_infinite(e) && !bounds_in(d, e, known, &mut view).intersects(&probe)) { continue; } - let polys = hit_polylines(d, e, tol); + let polys = hit_polylines_in(d, e, &mut view, tol); let hit = fence.windows(2).any(|f| { let (Some(a), Some(b)) = (f.first(), f.get(1)) else { return false }; let fl = Line::new(*a, *b); @@ -415,17 +461,18 @@ pub fn select_polygon_in(d: &Drawing, space: &Space, frozen: &[String], poly: &[ let Some(cands) = candidates(d, space, &ix, &pb, crossing, false) else { return Vec::new() }; let edges: Vec = poly.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?))).chain(poly.last().map(|l| Line::new(*l, *first))).collect(); + let mut view = ViewportBounds::new(frozen); let mut out = Vec::new(); for (e, known) in cands { let infinite = is_infinite(e); if !selectable(d, e, frozen) || (infinite && !crossing) { continue; } - let eb = bounds_of(d, e, known); + let eb = bounds_in(d, e, known, &mut view); if !infinite && if crossing { !eb.intersects(&pb) } else { !pb.contains_box(&eb) } { continue; } - let polys = hit_polylines(d, e, tol); + let polys = hit_polylines_in(d, e, &mut view, tol); let crosses = polys.iter().any(|pl| { pl.windows(2).any(|w| { w.first().zip(w.get(1)).is_some_and(|(p, q)| edges.iter().any(|f| cadcraft_geom::line_line(f, &Line::new(*p, *q)).is_some())) diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 2c706838b..adf34772d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -167,6 +167,7 @@ mod trim_extend_options; mod undo_count; mod undo_layout_tab; mod viewport_clip; +mod viewport_frozen_block_parts; mod viewport_frozen_selection; mod vplayer_prompts; mod vports; diff --git a/crates/engine/tests/it/viewport_frozen_block_parts.rs b/crates/engine/tests/it/viewport_frozen_block_parts.rs new file mode 100644 index 000000000..6bb19274e --- /dev/null +++ b/crates/engine/tests/it/viewport_frozen_block_parts.rs @@ -0,0 +1,825 @@ +//! A block reference on a layer the active MSPACE viewport draws, with parts on a layer frozen in +//! that viewport ("VP Freeze"): the viewport does not draw those parts, so a selection made +//! through it does not hit the reference on them, and they take no room in the box a window +//! tests. AutoCAD 2022 was given the same objects and answers the cases asserted on them one by +//! one the same way through a viewport. Where it differs is what is taken through the rectangle +//! around a reference (#2991): the grid test only compares that between a layer frozen in the +//! viewport and one frozen for the whole drawing. In a viewport that does not freeze the layer +//! and on the Model tab everything is as before. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::Handle; +use cadcraft_engine::geom::{Bounds2, Vec2}; +use cadcraft_engine::select; +use serde_json::json; + +/// Draws a line from `a` to `b` on layer 0, or on "Hidden" when `hidden`, and returns its handle. +fn line(s: &mut Session, a: [f64; 2], b: [f64; 2], hidden: bool) -> Handle { + let r = s.execute("line", &json!({ "points": [a, b] })).unwrap(); + let h = Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap(); + if hidden { + to_hidden(s, h); + } + h +} + +/// Puts `h` on the layer "Hidden". +fn to_hidden(s: &mut Session, h: Handle) { + s.execute("properties.set", &json!({ "handles": [h.hex()], "layer": "Hidden" })).unwrap(); + assert_eq!(s.doc().unwrap().entity(h).unwrap().common.layer, "Hidden"); +} + +/// Makes the block `name` of the objects `parts`, with its base at `base`, and returns the +/// reference to it that takes their place, on layer 0. +fn block(s: &mut Session, name: &str, base: [f64; 2], parts: &[Handle]) -> Handle { + let hs: Vec = parts.iter().map(|h| h.hex()).collect(); + let r = s.execute("block", &json!({ "name": name, "base": base, "handles": hs })).unwrap(); + let h = Handle::parse_hex(r["insert"].as_str().unwrap()).unwrap(); + assert_eq!(s.doc().unwrap().entity(h).unwrap().common.layer, "0"); + h +} + +/// Inserts the block `name` at `at` and returns the reference. +fn insert(s: &mut Session, name: &str, at: [f64; 2]) -> Handle { + let r = s.execute("insert", &json!({ "name": name, "at": at })).unwrap(); + Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap() +} + +/// Makes `viewport` the active MSPACE viewport. +fn enter(s: &mut Session, viewport: &str) { + s.execute("mspace", &json!({ "handle": viewport })).unwrap(); +} + +/// `hs` in handle order. +fn sorted(mut hs: Vec) -> Vec { + hs.sort_by_key(|h| h.0); + hs +} + +/// Five block references on layer 0 and two viewports, as AutoCAD was given them. +struct Parts { + /// The session, on the layout that holds the two viewports, in paper space. + s: Session, + /// One line on layer 0 from (0, 0) to (10, 0) and one on "Hidden" from (0, 5) to (10, 5). + r: Handle, + /// One line, on "Hidden", from (20, 5) to (30, 5): nothing of it is drawn where the layer is + /// frozen. The last object made. + h: Handle, + /// A reference to the block of `r` nested in another block: its lines run from (40, 0) to + /// (50, 0) on layer 0 and from (40, 5) to (50, 5) on "Hidden". + n: Handle, + /// A block of a reference to the block of `r` that is itself on "Hidden" (lines from (60, 0) + /// to (70, 0) and from (60, 5) to (70, 5), neither drawn where the layer is frozen) and of a + /// line on layer 0 from (60, 10) to (70, 10). + z: Handle, + /// Two lines on layer 0, from (80, 0) to (90, 0) and from (80, 10) to (90, 10), and between + /// them one on "Hidden" from (80, 5) to (90, 5): a part that is not drawn where the layer is + /// frozen, inside the box around the parts that are. + q: Handle, + /// The viewport that freezes "Hidden". + a: String, + /// The viewport that freezes nothing. + b: String, +} + +/// The drawing of [`Parts`], in paper space. With `crowded`, model space also holds enough lines, +/// far from the references, for selections to go through the spatial index instead of scanning +/// the space. +fn parts(crowded: bool) -> Parts { + let mut s = Session::new(); + s.execute("layer.new", &json!({ "name": "Hidden" })).unwrap(); + let on_0 = line(&mut s, [0.0, 0.0], [10.0, 0.0], false); + let on_hidden = line(&mut s, [0.0, 5.0], [10.0, 5.0], true); + let r = block(&mut s, "BP", [0.0, 0.0], &[on_0, on_hidden]); + let nested = insert(&mut s, "BP", [40.0, 0.0]); + let n = block(&mut s, "BN", [40.0, 0.0], &[nested]); + let child = insert(&mut s, "BP", [60.0, 0.0]); + to_hidden(&mut s, child); + let own = line(&mut s, [60.0, 10.0], [70.0, 10.0], false); + let z = block(&mut s, "BZ", [60.0, 0.0], &[child, own]); + let low = line(&mut s, [80.0, 0.0], [90.0, 0.0], false); + let high = line(&mut s, [80.0, 10.0], [90.0, 10.0], false); + let between = line(&mut s, [80.0, 5.0], [90.0, 5.0], true); + let q = block(&mut s, "BQ", [80.0, 0.0], &[low, high, between]); + if crowded { + let far: Vec<[f64; 2]> = (0..=cadcraft_engine::spatial::MIN_INDEXED).map(|i| [1000.0 + i as f64, 1000.0 + (i % 2) as f64]).collect(); + s.execute("line", &json!({ "points": far })).unwrap(); + } + let only_hidden = line(&mut s, [20.0, 5.0], [30.0, 5.0], true); + let h = block(&mut s, "BH", [20.0, 5.0], &[only_hidden]); + assert_eq!(s.doc().unwrap().model.len() >= cadcraft_engine::spatial::MIN_INDEXED, crowded, "whether model space is indexed"); + s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap(); + let v = s.execute("mview", &json!({ "count": 2, "p1": [20, 20], "p2": [220, 120] })).unwrap(); + let (a, b) = (v["viewports"][0].as_str().unwrap().to_string(), v["viewports"][1].as_str().unwrap().to_string()); + s.execute("vplayer", &json!({ "handles": [a], "freeze": ["Hidden"] })).unwrap(); + Parts { s, r, h, n, z, q, a, b } +} + +/// What a pick at `p` finds where the session is: through the active viewport, or on its tab. +fn pick(s: &Session, p: [f64; 2]) -> Option { + let st = s.state().unwrap(); + select::pick_in(&st.doc, &st.edit_space(), st.viewport_frozen(), Vec2::new(p[0], p[1]), 0.2) +} + +/// Every object a pick at `p` finds where the session is, as selection cycling lists them. +fn pick_all(s: &Session, p: [f64; 2]) -> Vec { + let st = s.state().unwrap(); + sorted(select::pick_all_in(&st.doc, &st.edit_space(), st.viewport_frozen(), Vec2::new(p[0], p[1]), 0.2)) +} + +/// What a window from `a` to `b` takes where the session is (a crossing window with `crossing`). +fn window(s: &Session, a: [f64; 2], b: [f64; 2], crossing: bool) -> Vec { + let st = s.state().unwrap(); + let bx = Bounds2::new(Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1])); + sorted(select::select_window_in(&st.doc, &st.edit_space(), st.viewport_frozen(), bx, crossing)) +} + +/// The objects of the selection set the AutoLISP `code` returns (none for nil), in handle order. +fn lisp_set(s: &mut Session, code: &str) -> Vec { + use cadcraft_engine::lisp::value::Value as Lisp; + match s.lisp_eval(code, false, true, Vec::new()).unwrap() { + Some(Ok(Lisp::PickSet(set))) => sorted(set.items.lock().unwrap().clone()), + Some(Ok(Lisp::Nil)) => Vec::new(), + other => panic!("`{code}` returned {other:?}"), + } +} + +/// What a fence along `pts` takes where the session is. +fn fence(s: &Session, pts: &[[f64; 2]]) -> Vec { + let st = s.state().unwrap(); + let pts: Vec = pts.iter().map(|p| Vec2::new(p[0], p[1])).collect(); + sorted(select::select_fence_in(&st.doc, &st.edit_space(), st.viewport_frozen(), &pts)) +} + +/// What a window polygon through `pts` takes where the session is (a crossing polygon with +/// `crossing`). +fn polygon(s: &Session, pts: &[[f64; 2]], crossing: bool) -> Vec { + let st = s.state().unwrap(); + let pts: Vec = pts.iter().map(|p| Vec2::new(p[0], p[1])).collect(); + sorted(select::select_polygon_in(&st.doc, &st.edit_space(), st.viewport_frozen(), &pts, crossing)) +} + +/// A pick, selection cycling's list, a crossing window, a fence and a crossing polygon on the part +/// the viewport does not draw find nothing; neither does a pick on the side of the box around both parts, nor a +/// crossing window in the empty middle of that box, where the viewport draws nothing of the +/// reference. The part it draws is hit as before, and the other viewport hits both parts. The +/// same with and without the spatial index. +#[test] +fn a_reference_is_not_hit_on_a_part_the_viewport_does_not_draw() { + for crowded in [false, true] { + let Parts { mut s, r, a, b, .. } = parts(crowded); + let around = [[4.0, 4.0], [6.0, 4.0], [6.0, 6.0], [4.0, 6.0]]; + enter(&mut s, &a); + assert_eq!(pick(&s, [5.0, 5.0]), None, "a pick on the part that is not drawn (indexed: {crowded})"); + assert_eq!(pick_all(&s, [5.0, 5.0]), [], "selection cycling's list there (indexed: {crowded})"); + assert_eq!(window(&s, [4.0, 4.0], [6.0, 6.0], true), [], "a crossing window over it (indexed: {crowded})"); + assert_eq!(fence(&s, &[[5.0, 4.0], [5.0, 6.0]]), [], "a fence across it (indexed: {crowded})"); + assert_eq!(polygon(&s, &around, true), [], "a crossing polygon over it (indexed: {crowded})"); + assert_eq!(pick(&s, [0.0, 2.5]), None, "a pick on the side of the box around both parts (indexed: {crowded})"); + assert_eq!(window(&s, [4.0, 2.0], [6.0, 3.0], true), [], "a crossing window between the parts (indexed: {crowded})"); + assert_eq!(pick(&s, [5.0, 0.0]), Some(r), "the part that is drawn (indexed: {crowded})"); + enter(&mut s, &b); + assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "this viewport draws the part (indexed: {crowded})"); + assert_eq!(pick_all(&s, [5.0, 5.0]), [r]); + assert_eq!(window(&s, [4.0, 4.0], [6.0, 6.0], true), [r]); + assert_eq!(fence(&s, &[[5.0, 4.0], [5.0, 6.0]]), [r]); + assert_eq!(polygon(&s, &around, true), [r]); + } +} + +/// A window and a window polygon around the drawn part alone take the reference: the part that +/// is not drawn takes no room in its box. A window around that part alone takes nothing. The +/// other viewport needs both parts inside the window, as before. +#[test] +fn a_window_takes_a_reference_by_the_parts_the_viewport_draws() { + for crowded in [false, true] { + let Parts { mut s, r, a, b, .. } = parts(crowded); + let around = [[-1.0, -1.0], [11.0, -1.0], [11.0, 1.0], [-1.0, 1.0]]; + enter(&mut s, &a); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [r], "around the drawn part alone (indexed: {crowded})"); + assert_eq!(polygon(&s, &around, false), [r], "a window polygon around the drawn part alone (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, 4.0], [11.0, 6.0], false), [], "around the part that is not drawn (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 6.0], false), [r], "around both (indexed: {crowded})"); + enter(&mut s, &b); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [], "this viewport draws both parts (indexed: {crowded})"); + assert_eq!(polygon(&s, &around, false), []); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 6.0], false), [r]); + } +} + +/// A reference whose every part is on the frozen layer has nothing drawn in the viewport: no +/// pick, window, crossing window or fence finds it there, and a window around it and three others +/// takes those three. It is still on a layer the viewport draws, so Select All takes it, and +/// Last takes such a reference when it is the last object made, as AutoCAD's All and Last do. The +/// other viewport finds it. +#[test] +fn a_reference_with_nothing_drawn_in_the_viewport_is_not_selected_there() { + for crowded in [false, true] { + let Parts { mut s, r, h, n, z, a, b, .. } = parts(crowded); + enter(&mut s, &a); + assert_eq!(pick(&s, [25.0, 5.0]), None, "a pick on its line (indexed: {crowded})"); + assert_eq!(window(&s, [24.0, 4.0], [26.0, 6.0], true), [], "a crossing window over its line (indexed: {crowded})"); + assert_eq!(fence(&s, &[[25.0, 4.0], [25.0, 6.0]]), [], "a fence across its line (indexed: {crowded})"); + assert_eq!(window(&s, [19.0, 4.0], [31.0, 6.0], false), [], "a window around it (indexed: {crowded})"); + assert_eq!(window(&s, [-2.0, -2.0], [72.0, 12.0], false), sorted(vec![r, n, z]), "a window around the four (indexed: {crowded})"); + assert_eq!(window(&s, [-2.0, -2.0], [72.0, 12.0], true), sorted(vec![r, n, z]), "a crossing window over the four (indexed: {crowded})"); + s.execute("selectall", &json!({})).unwrap(); + assert!(s.selection().contains(&h), "its own layer is drawn: Select All takes it (indexed: {crowded})"); + s.set_selection(Vec::new()); + // Another reference to that block, made through this viewport: the last object made. + let last = insert(&mut s, "BH", [20.0, 15.0]); + assert_eq!(pick(&s, [25.0, 15.0]), None, "nothing of it is drawn here either (indexed: {crowded})"); + assert_eq!(lisp_set(&mut s, "(ssget \"L\")"), [last], "its own layer is drawn: Last takes it (indexed: {crowded})"); + enter(&mut s, &b); + assert_eq!(pick(&s, [25.0, 5.0]), Some(h), "this viewport draws it (indexed: {crowded})"); + assert_eq!(window(&s, [19.0, 4.0], [31.0, 6.0], false), [h]); + assert_eq!(window(&s, [-2.0, -2.0], [72.0, 12.0], false), sorted(vec![r, h, n, z])); + } +} + +/// The same inside a nested reference: a part on the frozen layer two blocks deep is not hit and +/// takes no room, and a nested reference that is itself on the frozen layer brings none of its +/// lines, whatever their layers, while the rest of the block around it is hit and measured. +#[test] +fn a_nested_reference_follows_the_viewport_too() { + for crowded in [false, true] { + let Parts { mut s, n, z, a, b, .. } = parts(crowded); + enter(&mut s, &a); + assert_eq!(pick(&s, [45.0, 5.0]), None, "the nested part that is not drawn (indexed: {crowded})"); + assert_eq!(window(&s, [44.0, 4.0], [46.0, 6.0], true), [], "a crossing window over it (indexed: {crowded})"); + assert_eq!(pick(&s, [45.0, 0.0]), Some(n), "the nested part that is drawn (indexed: {crowded})"); + assert_eq!(window(&s, [39.0, -1.0], [51.0, 1.0], false), [n], "a window around the drawn nested part (indexed: {crowded})"); + assert_eq!(pick(&s, [65.0, 0.0]), None, "the layer 0 line of a nested reference on the frozen layer (indexed: {crowded})"); + assert_eq!(pick(&s, [65.0, 5.0]), None, "its other line (indexed: {crowded})"); + assert_eq!(window(&s, [64.0, -1.0], [66.0, 6.0], true), [], "a crossing window over that nested reference (indexed: {crowded})"); + assert_eq!(pick(&s, [65.0, 10.0]), Some(z), "the line beside it in the block (indexed: {crowded})"); + assert_eq!(window(&s, [59.0, 9.0], [71.0, 11.0], false), [z], "a window around that line alone (indexed: {crowded})"); + assert_eq!(window(&s, [59.0, -1.0], [71.0, 11.0], false), [z], "a window around the whole block (indexed: {crowded})"); + enter(&mut s, &b); + assert_eq!(pick(&s, [45.0, 5.0]), Some(n), "this viewport draws every part (indexed: {crowded})"); + assert_eq!(window(&s, [39.0, -1.0], [51.0, 1.0], false), []); + assert_eq!(pick(&s, [65.0, 0.0]), Some(z)); + assert_eq!(window(&s, [59.0, 9.0], [71.0, 11.0], false), []); + } +} + +/// A part that is not drawn can lie inside the box around the parts that are. A pick, selection +/// cycling's list and a fence on it find nothing there, although they are within that box; the drawn parts are hit, and a +/// window takes the reference when it holds both of them, not one alone. The hit geometry is what +/// decides here, not the box: without the viewport's layers in it the part is hit. +#[test] +fn a_part_that_is_not_drawn_is_not_hit_inside_the_box_of_the_drawn_parts() { + for crowded in [false, true] { + let Parts { mut s, q, a, b, .. } = parts(crowded); + enter(&mut s, &a); + assert_eq!(pick(&s, [85.0, 5.0]), None, "a pick on the part that is not drawn (indexed: {crowded})"); + assert_eq!(pick_all(&s, [85.0, 5.0]), [], "selection cycling's list there (indexed: {crowded})"); + assert_eq!(fence(&s, &[[85.0, 4.0], [85.0, 6.0]]), [], "a fence across it (indexed: {crowded})"); + assert_eq!(pick(&s, [85.0, 10.0]), Some(q), "a drawn part (indexed: {crowded})"); + assert_eq!(window(&s, [79.0, -1.0], [91.0, 11.0], false), [q], "a window around both drawn parts (indexed: {crowded})"); + assert_eq!(window(&s, [79.0, -1.0], [91.0, 1.0], false), [], "a window around one of them (indexed: {crowded})"); + enter(&mut s, &b); + assert_eq!(pick(&s, [85.0, 5.0]), Some(q), "this viewport draws the part (indexed: {crowded})"); + assert_eq!(pick_all(&s, [85.0, 5.0]), [q]); + assert_eq!(fence(&s, &[[85.0, 4.0], [85.0, 6.0]]), [q]); + } +} + +/// Freezing the layer in the viewport the session is in, and thawing it again, changes what the +/// next pick and the next window find: nothing is kept from before the change. With the spatial +/// index too, which is not rebuilt for a layer frozen in a viewport. +#[test] +fn freezing_and_thawing_the_layer_in_the_viewport_changes_what_is_hit_at_once() { + for crowded in [false, true] { + let Parts { mut s, r, b, .. } = parts(crowded); + enter(&mut s, &b); + assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "drawn here (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), []); + s.execute("vplayer", &json!({ "handles": [b], "freeze": ["Hidden"] })).unwrap(); + assert_eq!(pick(&s, [5.0, 5.0]), None, "frozen in this viewport now (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [r], "the part takes no room any more (indexed: {crowded})"); + s.execute("vplayer", &json!({ "handles": [b], "thaw": ["Hidden"] })).unwrap(); + assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "thawed again (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [], "and it takes its room again (indexed: {crowded})"); + } +} + +/// What a user does goes through the same tests. A click on the part the viewport does not draw +/// is a click on nothing: it starts a selection window. A window dragged around the drawn part +/// alone takes the reference, and so does a click on that part. The `select` command's pick and +/// window answer the same way. +#[test] +fn clicks_and_the_select_command_see_the_parts_the_viewport_draws() { + for crowded in [false, true] { + let Parts { mut s, r, a, .. } = parts(crowded); + enter(&mut s, &a); + s.idle_click(Vec2::new(5.0, 5.0), false).unwrap(); + assert!(s.pending_window.is_some(), "a click on the part that is not drawn must be a click on nothing (indexed: {crowded})"); + // The other corner of that window, left to right around nothing. + s.idle_click(Vec2::new(6.0, 6.0), false).unwrap(); + assert_eq!(s.selection(), [], "a click on the part that is not drawn (indexed: {crowded})"); + s.idle_click(Vec2::new(-1.0, -1.0), false).unwrap(); + s.idle_click(Vec2::new(11.0, 1.0), false).unwrap(); + assert_eq!(s.selection(), [r], "a window dragged around the drawn part alone (indexed: {crowded})"); + s.set_selection(Vec::new()); + s.idle_click(Vec2::new(5.0, 0.0), false).unwrap(); + assert_eq!(s.selection(), [r], "a click on the drawn part (indexed: {crowded})"); + s.set_selection(Vec::new()); + s.execute("select", &json!({ "at": [5, 5], "aperture": 0.5 })).unwrap(); + assert_eq!(s.selection(), [], "select at a point on the part that is not drawn (indexed: {crowded})"); + s.execute("select", &json!({ "window": [[-1, -1], [11, 1]] })).unwrap(); + assert_eq!(s.selection(), [r], "select by a window around the drawn part (indexed: {crowded})"); + } +} + +/// A clipped reference (XCLIP) with every part on the frozen layer is still selected by its clip +/// boundary, as AutoCAD 2022 selects it: a pick, a crossing window and a fence on the boundary +/// and a window around it take the reference, a pick on the part that is not drawn does not, and +/// a window must hold the whole boundary. Hiding the frames (XCLIPFRAME 0) changes none of that. +/// The viewport draws the frame and nothing else of the reference. The viewport that draws the +/// layer selects it on its part too. +#[test] +fn a_clipped_reference_with_no_part_drawn_is_selected_by_its_boundary() { + /// [`parts`] with one more reference to the block of `h`, at (20, 20), where its line runs + /// from (20, 20) to (30, 20), clipped to the rectangle from (18, 18) to (32, 22). The session + /// is left in the viewport that freezes nothing. + fn clipped(crowded: bool) -> (Parts, Handle) { + let mut p = parts(crowded); + enter(&mut p.s, &p.b); + let c = insert(&mut p.s, "BH", [20.0, 20.0]); + p.s.execute("xclip", &json!({ "handle": c.hex(), "rectangle": [[18, 18], [32, 22]] })).unwrap(); + (p, c) + } + /// What six selections find: a pick on the reference's line, a pick on its boundary, a + /// crossing window and a fence over the boundary, a window around all of it, and a window + /// around the line alone, inside the boundary. + fn found(s: &Session) -> [Vec; 6] { + [ + pick(s, [25.0, 20.0]).into_iter().collect(), + pick(s, [18.0, 20.0]).into_iter().collect(), + window(s, [17.0, 19.0], [19.0, 21.0], true), + fence(s, &[[17.0, 20.0], [19.0, 20.0]]), + window(s, [15.0, 15.0], [35.0, 25.0], false), + window(s, [19.0, 19.0], [31.0, 21.0], false), + ] + } + /// Whether `v` lies on a side of the clip rectangle. + fn on_the_frame(v: Vec2) -> bool { + [v.x - 18.0, v.x - 32.0, v.y - 18.0, v.y - 22.0].iter().any(|d| d.abs() < 1e-9) + } + for crowded in [false, true] { + let (Parts { mut s, a, .. }, c) = clipped(crowded); + assert_eq!(found(&s), [vec![c], vec![c], vec![c], vec![c], vec![c], vec![]], "where the layer is drawn (indexed: {crowded})"); + enter(&mut s, &a); + let by_its_boundary = [vec![], vec![c], vec![c], vec![c], vec![c], vec![]]; + assert_eq!(found(&s), by_its_boundary, "through the viewport that freezes the layer (indexed: {crowded})"); + // That viewport draws the frame, and only the frame. + { + let st = s.state().unwrap(); + let reference = st.doc.entity(c).unwrap(); + let drawn = cadcraft_engine::render::build_entities_in_viewport( + &st.doc, + std::iter::once(&**reference), + &Default::default(), + st.viewport_frozen(), + ); + assert!(!drawn.verts.is_empty(), "the frame is drawn (indexed: {crowded})"); + assert!(drawn.verts.iter().all(|v| on_the_frame(Vec2::new(v.x, v.y))), "nothing but the frame is drawn (indexed: {crowded})"); + } + // With the frames hidden the boundary selects all the same. + s.execute("xclipframe", &json!({ "value": 0 })).unwrap(); + assert_eq!(found(&s), by_its_boundary, "with the frames hidden (indexed: {crowded})"); + } +} + +/// A clipped reference with a part on each layer, the clip showing a piece of both, with the +/// coordinates AutoCAD 2022 was given (here 100 to the right) and its answers. Through the +/// viewport the piece on the frozen layer is not hit; the drawn piece and the boundary are, the +/// part of the block the clip cuts away is not, and a window must hold the whole boundary. +#[test] +fn a_clipped_reference_with_a_part_drawn_is_selected_by_its_boundary_and_that_part() { + for crowded in [false, true] { + let Parts { mut s, a, b, .. } = parts(crowded); + enter(&mut s, &b); + // A line on layer 0 from (130, 30) to (160, 30) and one on "Hidden" 4 above it, clipped to + // the rectangle from (138, 27) to (152, 37). + let on_0 = line(&mut s, [130.0, 30.0], [160.0, 30.0], false); + let on_hidden = line(&mut s, [130.0, 34.0], [160.0, 34.0], true); + let c = block(&mut s, "BK", [130.0, 30.0], &[on_0, on_hidden]); + s.execute("xclip", &json!({ "handle": c.hex(), "rectangle": [[138, 27], [152, 37]] })).unwrap(); + assert_eq!(pick(&s, [145.0, 34.0]), Some(c), "where the layer is drawn (indexed: {crowded})"); + enter(&mut s, &a); + assert_eq!(pick(&s, [145.0, 34.0]), None, "the piece that is not drawn (indexed: {crowded})"); + assert_eq!(pick(&s, [145.0, 30.0]), Some(c), "the drawn piece (indexed: {crowded})"); + assert_eq!(pick(&s, [133.0, 30.0]), None, "the layer 0 part where the clip cuts it away (indexed: {crowded})"); + assert_eq!(pick(&s, [145.0, 27.0]), Some(c), "the bottom side of the boundary (indexed: {crowded})"); + assert_eq!(pick(&s, [145.0, 37.0]), Some(c), "the top side of the boundary (indexed: {crowded})"); + assert_eq!(window(&s, [144.0, 26.0], [146.0, 28.0], true), [c], "a crossing window over the bottom side (indexed: {crowded})"); + assert_eq!(window(&s, [137.0, 26.0], [153.0, 38.0], false), [c], "a window around the boundary (indexed: {crowded})"); + assert_eq!(window(&s, [137.5, 29.0], [152.5, 31.0], false), [], "a window around the drawn piece alone (indexed: {crowded})"); + assert_eq!(window(&s, [137.0, 26.0], [153.0, 33.0], false), [], "a window around the lower half of the boundary (indexed: {crowded})"); + assert_eq!(window(&s, [128.0, 26.0], [162.0, 38.0], false), [c], "a window around the whole block (indexed: {crowded})"); + } +} + +/// A reference with an inverted clip keeps the box the drawing gives it as well, so its frame, +/// which the viewport draws, here beside a part it does not draw, is still hit there: by a pick +/// and by a fence, neither of which comes near a side of that box. AutoCAD 2022 selects such a +/// reference by its frame too, and answers the pick on the drawn part and the two windows the +/// same way. The shape is the one AutoCAD was given, 80 to the right. This test passes without +/// the change as well: it holds what the change must leave alone, and fails when a clipped +/// reference is measured through the viewport like any other. +#[test] +fn an_inverted_clip_is_hit_on_its_frame_through_the_viewport() { + for crowded in [false, true] { + let Parts { mut s, a, b, .. } = parts(crowded); + enter(&mut s, &b); + // The block of `r` at (100, 20): a line on layer 0 from (100, 20) to (110, 20) and one on + // "Hidden" 5 above it. The clip hides what is inside the rectangle from (103, 23) to + // (107, 27), so the bottom side of its frame runs between the two lines. + let c = insert(&mut s, "BP", [100.0, 20.0]); + s.execute("xclip", &json!({ "handle": c.hex(), "rectangle": [[103, 23], [107, 27]], "invert": true })).unwrap(); + assert_eq!(pick(&s, [105.0, 23.0]), Some(c), "where the layer is drawn (indexed: {crowded})"); + enter(&mut s, &a); + assert_eq!(pick(&s, [105.0, 23.0]), Some(c), "the bottom side of the frame (indexed: {crowded})"); + assert_eq!(fence(&s, &[[105.0, 22.5], [105.0, 23.5]]), [c], "a fence across it (indexed: {crowded})"); + assert_eq!(pick(&s, [101.0, 20.0]), Some(c), "the layer 0 part outside the boundary (indexed: {crowded})"); + assert_eq!(window(&s, [99.0, 19.0], [111.0, 21.0], false), [], "a window around the drawn part alone (indexed: {crowded})"); + assert_eq!(window(&s, [99.0, 19.0], [111.0, 28.5], false), [c], "a window around both parts and the frame (indexed: {crowded})"); + } +} + +/// What a pick at `p` finds in the model space of `d` through a viewport that freezes the layers +/// in `frozen`, or on the Model tab with no layer. +fn picked(d: &cadcraft_engine::doc::Drawing, frozen: &[String], p: [f64; 2]) -> Option { + select::pick_in(d, &cadcraft_engine::doc::Space::Model, frozen, Vec2::new(p[0], p[1]), 0.2) +} + +/// What a window from `a` to `b` takes there ([`picked`]). +fn windowed(d: &cadcraft_engine::doc::Drawing, frozen: &[String], a: [f64; 2], b: [f64; 2]) -> Vec { + let area = Bounds2::new(Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1])); + select::select_window_in(d, &cadcraft_engine::doc::Space::Model, frozen, area, false) +} + +/// What a crossing window from `a` to `b` takes there ([`picked`]). +fn crossed(d: &cadcraft_engine::doc::Drawing, frozen: &[String], a: [f64; 2], b: [f64; 2]) -> Vec { + let area = Bounds2::new(Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1])); + select::select_window_in(d, &cadcraft_engine::doc::Space::Model, frozen, area, true) +} + +/// What a fence from `a` to `b` takes there ([`picked`]). +fn fenced(d: &cadcraft_engine::doc::Drawing, frozen: &[String], a: [f64; 2], b: [f64; 2]) -> Vec { + select::select_fence_in(d, &cadcraft_engine::doc::Space::Model, frozen, &[Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1])]) +} + +/// Other objects that draw a block, built by hand in model space with the coordinates AutoCAD +/// 2022 was given. +struct BlockDrawers { + /// The drawing that holds them. + d: cadcraft_engine::doc::Drawing, + /// A 2 x 2 array of references (MINSERT) from (0, -30), its rows 12 and its columns 15 apart. + array: Handle, + /// A reference at (70, 30) with an attribute on "Hidden" 4 above its line. + tagged: Handle, + /// An annotative reference at the origin, at the drawing's annotation scale. + scaled: Handle, + /// A multileader from (110, -20) to (130, 0) whose content is a block (here 100 to the + /// right of where AutoCAD had it). + leader: Handle, + /// A dimension along (150, -10) to (160, -10) whose block nests a reference, as the block of + /// a dimension with an arrowhead block does in AutoCAD. + dim: Handle, +} + +/// The drawing of [`BlockDrawers`]: every block has a line on layer 0 and, above it, one on +/// "Hidden", but for the one with the attribute, where the attribute is on "Hidden". +fn block_drawers() -> BlockDrawers { + use cadcraft_engine::doc::{ + AnnoScale, Attrib, AttribProps, Block, Common, DimKind, Dimension, Drawing, Entity, EntityKind, HAlign, Insert, Line, MLeader, Space, Text, + VAlign, + }; + use cadcraft_engine::geom::Vec3; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + let line = |handle: u64, a: [f64; 2], b: [f64; 2], layer: &str| { + let mut part = Entity::new(Handle(handle), EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) })); + part.common.layer = layer.into(); + part + }; + let reference = |block: &str, at: [f64; 2]| Insert { block: block.into(), insert: Vec3::new(at[0], at[1], 0.0), ..Insert::default() }; + let mut define = |name: &str, parts: Vec| { + let mut block = Block::new(name); + for part in parts { + block.entities.push(part); + } + d.blocks.insert(name.into(), std::sync::Arc::new(block)); + }; + // BP: a line on layer 0 and, 5 above it, one on "Hidden". BM: the same, 8 apart. BA: one line. + define("BP", vec![line(1, [0.0, 0.0], [10.0, 0.0], "0"), line(2, [0.0, 5.0], [10.0, 5.0], "Hidden")]); + define("BM", vec![line(1, [0.0, 0.0], [6.0, 0.0], "0"), line(2, [0.0, 8.0], [6.0, 8.0], "Hidden")]); + define("BA", vec![line(1, [0.0, 0.0], [10.0, 0.0], "0")]); + // *D9: what a dimension draws, here a reference to BP at (150, 0) and a line of its own. + let mut nested = Entity::new(Handle(1), EntityKind::Insert(reference("BP", [150.0, 0.0]))); + nested.common.layer = "0".into(); + define("*D9", vec![nested, line(2, [150.0, -10.0], [160.0, -10.0], "0")]); + let model = Space::Model; + // A 2 x 2 array of BP from (0, -30), its rows 12 and its columns 15 apart. + let grid = Insert { cols: 2, rows: 2, col_spacing: 15.0, row_spacing: 12.0, ..reference("BP", [0.0, -30.0]) }; + let array = d.add(&model, Common::default(), EntityKind::Insert(grid)).unwrap(); + // BA at (70, 30) with an attribute on "Hidden" 4 above its line. + let value = Text { + insert: Vec3::new(70.0, 34.0, 0.0), + align_pt: None, + height: 1.5, + value: "HHHH".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + }; + let attribute = Attrib { + tag: "TAG".into(), + text: value, + invisible: false, + constant: false, + prompt: String::new(), + props: AttribProps { layer: Some("Hidden".into()), ..Default::default() }, + multiline: None, + modes: Default::default(), + }; + let tagged = d.add(&model, Common::default(), EntityKind::Insert(Insert { attribs: vec![attribute], ..reference("BA", [70.0, 30.0]) })).unwrap(); + // An annotative reference to BP at the origin, at the drawing's annotation scale. + let annotative = Common { anno_scales: vec![AnnoScale::unit()], ..Common::default() }; + let scaled = d.add(&model, annotative, EntityKind::Insert(reference("BP", [0.0, 0.0]))).unwrap(); + // A multileader from (110, -20) to (130, 0) with BM at (127.36, -4), where AutoCAD put it. + let leader = MLeader { + leaders: vec![vec![Vec3::new(110.0, -20.0, 0.0)]], + landing: Vec3::new(130.0, 0.0, 0.0), + dogleg: 0.36, + text: None, + style: "Standard".into(), + arrow_size: 0.18, + spline: false, + block: Some(reference("BM", [127.36, -4.0])), + }; + let leader = d.add(&model, Common::default(), EntityKind::MLeader(leader)).unwrap(); + // A dimension along (150, -10) to (160, -10) that draws *D9. + let dimension = Dimension { + kind: DimKind::Aligned, + defpt: Vec3::new(160.0, -10.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::new(150.0, -10.0, 0.0), + p14: Vec3::new(160.0, -10.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some("*D9".into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + let dim = d.add(&model, Common::default(), EntityKind::Dimension(dimension)).unwrap(); + BlockDrawers { d, array, tagged, scaled, leader, dim } +} + +/// An array of references (MINSERT) and a reference with an attribute on the frozen layer follow +/// the viewport as a plain reference does: the parts and the attribute on the frozen layer are +/// not hit and take no room in a window. They have the coordinates AutoCAD 2022 was given and its +/// answers. The frozen layers are given to the selection as a viewport gives them. +#[test] +fn arrays_and_attributes_follow_the_viewport() { + let BlockDrawers { d, array, tagged, .. } = block_drawers(); + let through = ["Hidden".to_string()]; + // The array: the "Hidden" part of no copy is hit, and a window needs the layer 0 parts only. + assert_eq!(picked(&d, &through, [5.0, -30.0]), Some(array), "the layer 0 part of the first copy"); + assert_eq!(picked(&d, &through, [5.0, -25.0]), None, "the part of the first copy that is not drawn"); + assert_eq!(picked(&d, &through, [20.0, -13.0]), None, "the part of the last copy that is not drawn"); + assert_eq!(picked(&d, &through, [20.0, -18.0]), Some(array), "the layer 0 part of the last copy"); + assert_eq!(crossed(&d, &through, [19.0, -14.0], [21.0, -12.0]), [], "a crossing window over the last copy's part that is not drawn"); + assert_eq!(windowed(&d, &through, [-1.0, -31.0], [26.0, -17.0]), [array], "a window around all but the upper row's parts that are not drawn"); + assert_eq!(picked(&d, &[], [20.0, -13.0]), Some(array), "where the layer is drawn"); + assert_eq!(windowed(&d, &[], [-1.0, -31.0], [26.0, -17.0]), []); + assert_eq!(windowed(&d, &[], [-1.0, -31.0], [26.0, -12.0]), [array]); + + // The attribute: not hit, and no room taken. + assert_eq!(picked(&d, &through, [75.0, 30.0]), Some(tagged)); + assert_eq!(crossed(&d, &through, [70.0, 33.5], [76.0, 36.0]), [], "a crossing window over the attribute that is not drawn"); + assert_eq!(fenced(&d, &through, [71.0, 33.0], [71.0, 37.0]), [], "a fence across it"); + assert_eq!(windowed(&d, &through, [69.0, 29.0], [81.0, 31.0]), [tagged], "a window around the line alone"); + assert_eq!(crossed(&d, &[], [70.0, 33.5], [76.0, 36.0]), [tagged], "where the layer is drawn"); + assert_eq!(windowed(&d, &[], [69.0, 29.0], [81.0, 31.0]), []); + assert_eq!(windowed(&d, &[], [69.0, 29.0], [81.0, 37.0]), [tagged]); +} + +/// An annotative reference, a multileader whose content is a block and a dimension whose block +/// nests a reference follow the viewport too: their parts on the frozen layer are not hit and +/// take no room in a window. The first two have the coordinates AutoCAD 2022 was given and its +/// answers. The frozen layers are given to the selection as a viewport gives them. +#[test] +fn annotative_references_multileaders_and_dimensions_follow_the_viewport() { + let BlockDrawers { d, scaled, leader, dim, .. } = block_drawers(); + let through = ["Hidden".to_string()]; + // The annotative reference. + assert_eq!(picked(&d, &through, [5.0, 5.0]), None, "the part of the annotative reference that is not drawn"); + assert_eq!(picked(&d, &through, [5.0, 0.0]), Some(scaled)); + assert_eq!(crossed(&d, &through, [4.0, 4.0], [6.0, 6.0]), []); + assert_eq!(fenced(&d, &through, [5.0, 4.0], [5.0, 6.0]), []); + assert_eq!(windowed(&d, &through, [-1.0, -1.0], [11.0, 1.0]), [scaled], "a window around its layer 0 part alone"); + assert_eq!(picked(&d, &[], [5.0, 5.0]), Some(scaled), "where the layer is drawn"); + assert_eq!(windowed(&d, &[], [-1.0, -1.0], [11.0, 1.0]), []); + + // The multileader: its block's part on "Hidden" lies from (127.36, 4) to (133.36, 4). + assert_eq!(picked(&d, &through, [130.36, 4.0]), None, "the part of the multileader's block that is not drawn"); + assert_eq!(picked(&d, &through, [130.36, -4.0]), Some(leader), "the layer 0 part of its block"); + assert_eq!(picked(&d, &through, [120.0, -10.0]), Some(leader), "its leader line"); + assert_eq!(crossed(&d, &through, [129.65, 3.29], [131.07, 4.71]), []); + assert_eq!(fenced(&d, &through, [130.36, 3.0], [130.36, 5.0]), []); + assert_eq!(windowed(&d, &through, [108.0, -22.0], [135.36, 2.0]), [leader], "a window around its leader and the layer 0 part"); + assert_eq!(picked(&d, &[], [130.36, 4.0]), Some(leader), "where the layer is drawn"); + assert_eq!(windowed(&d, &[], [108.0, -22.0], [135.36, 2.0]), []); + assert_eq!(windowed(&d, &[], [108.0, -22.0], [135.36, 6.0]), [leader]); + + // The dimension: the nested reference's part on "Hidden" lies from (150, 5) to (160, 5). + assert_eq!(picked(&d, &through, [155.0, 5.0]), None, "the part of the reference nested in the dimension's block that is not drawn"); + assert_eq!(crossed(&d, &through, [154.0, 4.0], [156.0, 6.0]), []); + assert_eq!(picked(&d, &through, [155.0, 0.0]), Some(dim), "the layer 0 part of that reference"); + assert_eq!(picked(&d, &[], [155.0, 5.0]), Some(dim), "where the layer is drawn"); +} + +/// A drawing, built by hand with the coordinates AutoCAD 2022 was given, whose model space holds +/// one reference, and that reference: to a block with a line on layer 0 from (60, 36) to (70, 36) +/// and a reference to a block of one line on "Hidden", from (60, 30) to (70, 30), clipped (XCLIP) +/// to the rectangle from (58, 27) to (72, 33). +fn framed_reference() -> (cadcraft_engine::doc::Drawing, Handle) { + use cadcraft_engine::doc::{Block, ClipBoundary, Common, Drawing, Entity, EntityKind, Insert, Line, Space}; + use cadcraft_engine::geom::Vec3; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + let line = |a: [f64; 2], b: [f64; 2]| EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) }); + let reference = |block: &str, at: [f64; 2]| Insert { block: block.into(), insert: Vec3::new(at[0], at[1], 0.0), ..Insert::default() }; + let mut define = |name: &str, parts: Vec<(EntityKind, &str)>| { + let mut block = Block::new(name); + for (i, (kind, layer)) in parts.into_iter().enumerate() { + let mut part = Entity::new(Handle(i as u64 + 1), kind); + part.common.layer = layer.into(); + block.entities.push(part); + } + d.blocks.insert(name.into(), std::sync::Arc::new(block)); + }; + // BC2: one line, on "Hidden". BNC: a reference to it, clipped to a rectangle given in the + // coordinates of BC2, and a line on layer 0. + define("BC2", vec![(line([0.0, 0.0], [10.0, 0.0]), "Hidden")]); + let boundary = ClipBoundary::new(vec![Vec2::new(-2.0, -3.0), Vec2::new(12.0, 3.0)]); + let inner = Insert { clip: Some(boundary), ..reference("BC2", [60.0, 30.0]) }; + define("BNC", vec![(EntityKind::Insert(inner), "0"), (line([60.0, 36.0], [70.0, 36.0]), "0")]); + let framed = d.add(&Space::Model, Common::default(), EntityKind::Insert(reference("BNC", [0.0, 0.0]))).unwrap(); + (d, framed) +} + +/// A clipped reference (XCLIP) that is a part of a block keeps its boundary as well: AutoCAD 2022 +/// selects the outer reference by a pick or a crossing window on the boundary of the clipped one +/// with every part inside it on a layer frozen in the viewport, and a window must hold that +/// boundary. A pick on the part that is not drawn takes nothing. The pick on the top side of the +/// boundary holds the hit geometry: it lies inside the outer reference's box, away from its +/// sides. The shape is the one AutoCAD was given. The frozen layers are given to the selection +/// as a viewport gives them. +#[test] +fn a_clipped_reference_inside_a_block_is_selected_by_its_boundary() { + let (d, framed) = framed_reference(); + let through = ["Hidden".to_string()]; + assert_eq!(picked(&d, &through, [58.0, 30.0]), Some(framed), "the left side of the nested clip boundary"); + assert_eq!(picked(&d, &through, [65.0, 33.0]), Some(framed), "its top side"); + assert_eq!(crossed(&d, &through, [57.0, 29.0], [59.0, 31.0]), [framed], "a crossing window over its left side"); + assert_eq!(picked(&d, &through, [65.0, 30.0]), None, "the clipped reference's line, which is not drawn"); + assert_eq!(picked(&d, &through, [65.0, 36.0]), Some(framed), "the outer reference's own line"); + assert_eq!(windowed(&d, &through, [59.0, 35.0], [71.0, 37.0]), [], "a window around its own line alone"); + assert_eq!(windowed(&d, &through, [56.0, 25.0], [74.0, 38.0]), [framed], "a window around its own line and the boundary"); + assert_eq!(picked(&d, &[], [65.0, 30.0]), Some(framed), "where the layer is drawn"); +} + +/// A dimension is drawn from its block, and a crossing window inside the rectangle around a +/// dimension does not take it as one inside a block reference's does (#2991), so a dimension +/// shows what a crossing window itself tests. Over a part of that block the viewport does not +/// draw, between two parts it draws, the window takes nothing, and neither do a pick and a +/// fence; over a drawn part they take the dimension. The frozen layers are given to the +/// selection as a viewport gives them. +#[test] +fn a_crossing_window_tests_the_parts_the_viewport_draws() { + use cadcraft_engine::doc::{Block, Common, DimKind, Dimension, Drawing, Entity, EntityKind, Line, Space}; + use cadcraft_engine::geom::Vec3; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + let mut block = Block::new("*D1"); + for (handle, y, layer) in [(1, 0.0, "0"), (2, 10.0, "0"), (3, 5.0, "Hidden")] { + let mut part = Entity::new(Handle(handle), EntityKind::Line(Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) })); + part.common.layer = layer.into(); + block.entities.push(part); + } + d.blocks.insert("*D1".into(), std::sync::Arc::new(block)); + let dimension = Dimension { + kind: DimKind::Aligned, + defpt: Vec3::new(5.0, 1.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::ZERO, + p14: Vec3::new(10.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some("*D1".into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + let dim = d.add(&Space::Model, Common::default(), EntityKind::Dimension(dimension)).unwrap(); + let frozen = ["Hidden".to_string()]; + let (model, hidden_part, drawn_part) = (Space::Model, Vec2::new(5.0, 5.0), Vec2::new(5.0, 10.0)); + let over = |p: Vec2| Bounds2::new(Vec2::new(p.x - 1.0, p.y - 1.0), Vec2::new(p.x + 1.0, p.y + 1.0)); + let across = |p: Vec2| [Vec2::new(p.x, p.y - 1.0), Vec2::new(p.x, p.y + 1.0)]; + assert_eq!(select::select_window_in(&d, &model, &frozen, over(hidden_part), true), [], "a crossing window over the part that is not drawn"); + assert_eq!(select::pick_in(&d, &model, &frozen, hidden_part, 0.2), None, "a pick on it"); + assert_eq!(select::select_fence_in(&d, &model, &frozen, &across(hidden_part)), [], "a fence across it"); + assert_eq!(select::select_window_in(&d, &model, &frozen, over(drawn_part), true), [dim], "a crossing window over a drawn part"); + assert_eq!(select::pick_in(&d, &model, &frozen, drawn_part, 0.2), Some(dim)); + assert_eq!(select::select_window_in(&d, &model, &[], over(hidden_part), true), [dim], "where the layer is drawn"); + assert_eq!(select::pick_in(&d, &model, &[], hidden_part, 0.2), Some(dim)); + assert_eq!(select::select_fence_in(&d, &model, &[], &across(hidden_part)), [dim]); +} + +/// The selections of a grid across the five references, with what each finds: at every point a +/// pick, selection cycling's list, a crossing window, a fence, two windows and the two polygons. +fn probes(s: &Session) -> Vec<(String, Vec)> { + let mut out = Vec::new(); + for xi in -2..=92 { + for yi in -2..=12 { + let (x, y) = (f64::from(xi), f64::from(yi)); + out.push((format!("pick at ({x}, {y})"), pick(s, [x, y]).into_iter().collect())); + out.push((format!("cycling list at ({x}, {y})"), pick_all(s, [x, y]))); + out.push((format!("crossing window from ({x}, {y})"), window(s, [x, y], [x + 2.0, y + 2.0], true))); + out.push((format!("fence through ({x}, {y})"), fence(s, &[[x, y - 1.0], [x, y + 1.0]]))); + out.push((format!("low window from ({x}, {y})"), window(s, [x, y], [x + 13.0, y + 2.0], false))); + out.push((format!("tall window from ({x}, {y})"), window(s, [x, y], [x + 13.0, y + 12.0], false))); + out.push((format!("window polygon from ({x}, {y})"), polygon(s, &[[x, y], [x + 13.0, y], [x + 6.0, y + 3.0]], false))); + out.push((format!("crossing polygon from ({x}, {y})"), polygon(s, &[[x, y], [x + 2.0, y], [x + 1.0, y + 2.0]], true))); + } + } + out +} + +/// Through a viewport that freezes a layer every selection answers as it does on the Model tab +/// with that layer frozen for the whole drawing: each selection of a grid across the references, +/// with and without the spatial index. That holds for what is taken through the rectangle around +/// a reference too (#2991): it is the rectangle around the drawn parts in both, and a part that is +/// not drawn changes nothing inside it. +#[test] +fn a_layer_frozen_in_the_viewport_selects_as_one_frozen_for_the_drawing_does() { + for crowded in [false, true] { + let Parts { mut s, r, h, n, z, q, a, .. } = parts(crowded); + enter(&mut s, &a); + let through_the_viewport = probes(&s); + let Parts { s: mut model, r: r2, h: h2, n: n2, z: z2, q: q2, .. } = parts(crowded); + assert_eq!([r, h, n, z, q], [r2, h2, n2, z2, q2], "the two drawings must be made alike"); + model.execute("layout.set", &json!({ "name": "Model" })).unwrap(); + model.execute("layer.set", &json!({ "name": "Hidden", "frozen": true })).unwrap(); + let frozen_for_the_drawing = probes(&model); + assert_eq!(through_the_viewport.len(), frozen_for_the_drawing.len()); + for (through, frozen) in through_the_viewport.iter().zip(&frozen_for_the_drawing) { + assert_eq!(through, frozen, "through the viewport, then with the layer frozen for the drawing (indexed: {crowded})"); + } + // The grid does select: each reference with a drawn part many times, the one without never. + let times = |x: Handle| through_the_viewport.iter().filter(|(_, hs)| hs.contains(&x)).count(); + assert!([r, n, z, q].iter().all(|x| times(*x) > 50), "taken {:?} times (indexed: {crowded})", [r, n, z, q].map(times)); + assert_eq!(times(h), 0, "a reference with nothing drawn was selected (indexed: {crowded})"); + } +} + +/// Nothing changes where no viewport freezes the layer: on the Model tab both parts are hit and +/// both take room, and with the layer frozen for the whole drawing the part is left out there +/// as it always was. +#[test] +fn the_model_tab_and_a_layer_frozen_for_the_drawing_are_as_before() { + for crowded in [false, true] { + let Parts { mut s, r, h, .. } = parts(crowded); + s.execute("layout.set", &json!({ "name": "Model" })).unwrap(); + assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "the Model tab draws both parts (indexed: {crowded})"); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), []); + assert_eq!(pick(&s, [25.0, 5.0]), Some(h)); + s.execute("layer.set", &json!({ "name": "Hidden", "frozen": true })).unwrap(); + assert_eq!(pick(&s, [5.0, 5.0]), None, "frozen for the whole drawing (indexed: {crowded})"); + assert_eq!(window(&s, [4.0, 4.0], [6.0, 6.0], true), []); + assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [r]); + assert_eq!(pick(&s, [25.0, 5.0]), None); + assert_eq!(pick(&s, [5.0, 0.0]), Some(r)); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 7d5da3358..ad116174c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -387,7 +387,7 @@ mod viewports; pub use dim_draw::{dim_text, dimension_in}; pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha}; -pub use pipeline::{Options, build, build_entities, build_plot}; +pub use pipeline::{Options, build, build_entities, build_entities_in_viewport, build_plot}; use props::{default_lineweight, resolve_common}; use text_entity::text_style; pub use text_entity::{layout_mtext_entity, place_text_entity, style_font, text_align}; diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 3fc72f518..c1ad58943 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -196,6 +196,15 @@ pub(crate) fn with_point_view(d: &Drawing, space: &Space, opts: &Options) -> Opt /// Build the display list for a set of loose entities (previews, rubber bands). pub fn build_entities<'a, I: IntoIterator>(d: &Drawing, ents: I, opts: &Options) -> DisplayList { + build_entities_in_viewport(d, ents, opts, &[]) +} + +/// [`build_entities`] as a selection through a layout viewport that freezes the layers in +/// `frozen` sees them: what is on one of those layers is left out, as the viewport does not draw +/// it, the parts of a block reference too. Picking through the viewport tests objects against +/// this, so a part the viewport does not draw is not hit, and the highlight of an object seen +/// through the viewport is built from it. +pub fn build_entities_in_viewport<'a, I: IntoIterator>(d: &Drawing, ents: I, opts: &Options, frozen: &[String]) -> DisplayList { let ents: Vec<&Entity> = ents.into_iter().collect(); // Only previews holding points need the model extents for relative point sizes. let with_view; @@ -207,7 +216,7 @@ pub fn build_entities<'a, I: IntoIterator>(d: &Drawing, ents: }; let mut b = Builder { list: DisplayList::default(), opts, plotting: false, styles: None, named: None, shared_budget: None, transparency: 0 }; for e in ents { - entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e); + entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, frozen, &[]), e); } b.list } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index dd98aadd8..e8ef7798a 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -34,6 +34,34 @@ fn linetype_dashes_line() { assert!(l.prims.len() > 10); } +/// Loose entities built as a layout viewport draws them leave out what is on a layer frozen in +/// it, the part of a block reference on that layer too, whatever the case of the layer's name. +/// With no such layer the list is the one [`build_entities`] gives. +#[test] +fn loose_entities_built_for_a_viewport_leave_out_its_frozen_layers() { + let line = |handle: u64, y: f64, layer: &str| { + let kind = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }); + let mut e = cadcraft_doc::Entity::new(Handle(handle), kind); + e.common.layer = layer.into(); + e + }; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + let mut b = cadcraft_doc::Block::new("B"); + for part in [line(1, 0.0, "0"), line(2, 5.0, "Hidden")] { + b.entities.push(part); + } + d.blocks.insert("B".into(), std::sync::Arc::new(b)); + let reference = cadcraft_doc::Insert { block: "B".into(), ..Default::default() }; + let ents = [cadcraft_doc::Entity::new(Handle(3), EntityKind::Insert(reference)), line(4, 5.0, "Hidden"), line(5, 8.0, "0")]; + let ys = |l: &DisplayList| -> Vec { l.prims.iter().map(|p| l.points(p)[0].y).collect() }; + let opts = Options::default(); + let frozen = ["HIDDEN".to_string()]; + assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &frozen)), [0.0, 8.0]); + assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &[])), [0.0, 5.0, 5.0, 8.0]); + assert_eq!(ys(&build_entities(&d, &ents, &opts)), [0.0, 5.0, 5.0, 8.0]); +} + #[test] fn frozen_layer_hidden() { let mut d = sample(); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index a742d8c95..56694ad49 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -367,6 +367,37 @@ fn the_viewport_highlight_leaves_out_objects_the_viewport_does_not_draw() { assert_eq!(outlined(&app, &mut highlight, both), both); } +/// The highlight of a block reference inside the active viewport shows the parts that viewport +/// draws: not its part on a layer frozen there, which the other viewport's highlight shows. +#[test] +fn the_viewport_highlight_of_a_reference_leaves_out_the_parts_the_viewport_does_not_draw() { + let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default()); + for y in [0, 30] { + app.run("line", serde_json::json!({ "points": [[0, y], [100, y]] })).unwrap(); + } + let lines = app.session.doc().unwrap().model.handles(); + let (a, b) = viewports_freezing_hidden(&mut app); + // Inside a viewport the block's reference is made in model space, where the lines are. + app.session.execute("mspace", &serde_json::json!({ "handle": b })).unwrap(); + app.session.execute("properties.set", &serde_json::json!({ "handles": [lines[1].hex()], "layer": "Hidden" })).unwrap(); + let parts: Vec = lines.iter().map(|h| h.hex()).collect(); + let made = app.session.execute("block", &serde_json::json!({ "name": "B", "base": [0, 0], "handles": parts })).unwrap(); + let reference = Handle::parse_hex(made["insert"].as_str().unwrap()).unwrap(); + assert_eq!(app.session.doc().unwrap().model.handles(), [reference], "the reference must be the one object in model space"); + /// The heights at which `highlight` draws something for the reference. + fn heights(app: &CadApp, highlight: &mut VpHighlight, reference: Handle) -> Vec { + highlight.update(app.session.state().unwrap(), &[reference], 10.0); + let mut ys: Vec = highlight.list.prims.iter().map(|p| highlight.list.points(p)[0].y).collect(); + ys.sort_by(f64::total_cmp); + ys + } + let mut highlight = VpHighlight::default(); + app.session.execute("mspace", &serde_json::json!({ "handle": b })).unwrap(); + assert_eq!(heights(&app, &mut highlight, reference), [0.0, 30.0], "this viewport draws both parts"); + app.session.execute("mspace", &serde_json::json!({ "handle": a })).unwrap(); + assert_eq!(heights(&app, &mut highlight, reference), [0.0], "a part the viewport does not draw was highlighted"); +} + /// Selection cycling's badge beside a resting pointer follows the layers frozen in the active /// viewport: over two overlapping lines it shows while the viewport draws both, goes when the /// layer of one of them is frozen there, and comes back when the layer is thawed. diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index 43471f61a..1cff39ba1 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -273,7 +273,8 @@ pub(super) fn viewport_highlight_tolerance(scale: f64) -> f64 { /// the hover are kept apart, so moving the cursor over objects doesn't tessellate the selection /// again; each is rebuilt only when the drawing, the objects, the zoom band or the layers frozen /// in the viewport change. An object on one of those layers is not drawn in the viewport, so it -/// is not highlighted there either. +/// is not highlighted there either, and neither are the parts of a block reference on them +/// ([`cadcraft_render::build_entities_in_viewport`]). #[derive(Default)] pub(super) struct VpHighlight { key: Option, @@ -285,18 +286,19 @@ pub(super) struct VpHighlight { impl VpHighlight { pub(super) fn update(&mut self, st: &cadcraft_engine::DocState, handles: &[Handle], scale: f64) { let tolerance = viewport_highlight_tolerance(scale); + // Entering another viewport changes what is drawn without changing the drawing. + let frozen = st.viewport_frozen(); let key = { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); - // Entering another viewport changes what is drawn without changing the drawing. - let frozen = st.viewport_frozen(); (st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, tolerance.to_bits(), handles, frozen, super::list::font_generation()) .hash(&mut h); h.finish() }; if self.key != Some(key) { let ents = handles.iter().filter_map(|h| st.doc.model.get(*h)).filter(|e| !st.hidden_in_viewport(e)).map(|e| e.as_ref()); - self.list = cadcraft_render::build_entities(&st.doc, ents, &cadcraft_render::Options { tolerance, ..Default::default() }); + self.list = + cadcraft_render::build_entities_in_viewport(&st.doc, ents, &cadcraft_render::Options { tolerance, ..Default::default() }, frozen); self.key = Some(key); self.list_gen = self.list_gen.wrapping_add(1); } From fa44f8541a818db02bc9be505ba6f909467d60a2 Mon Sep 17 00:00:00 2001 From: V1dalTheAbidal <97257872+V1dalTheAbidal@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:27:32 +0200 Subject: [PATCH 038/258] A dimension is not picked on block text the viewport does not draw (#3126) A dimension is hit anywhere inside the box of its text. That box was read from the dimension's block without the viewport, so through an MSPACE viewport a pick in the box of text on a layer frozen in that viewport still took the dimension, although the viewport does not draw the text. AutoCAD 2022 picks nothing there. - doc: ViewportBounds::leaves_out tells whether a viewport leaves a part of a block out for its layer, by the comparison its boxes already use. - engine: the text test of a pick and of selection cycling's list skips the text the viewport leaves out. Not changed: the rectangle around a dimension is still hit along its sides (#2991). With the text not drawn its top side runs through the box of the text, so a pick within pick distance of that side and a crossing window over it still take the dimension, where AutoCAD takes nothing. Nothing changes where no layer is frozen in the active viewport: text on a layer frozen for the whole drawing or turned off is tested as before. --- crates/doc/src/extents.rs | 39 +++++++- crates/engine/src/select.rs | 10 ++- .../tests/it/viewport_frozen_block_parts.rs | 88 +++++++++++++++++++ 3 files changed, 132 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 0d3128d7e..30efe6e17 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -281,7 +281,13 @@ fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool, frozen: &[String] /// Nor does one of the layers in `frozen`, those frozen in the layout viewport measured through, /// which does not draw them (the names compared as the renderer compares them). fn layer_counts(d: &Drawing, layer: &str, off_counts: bool, frozen: &[String]) -> bool { - layer == "0" || (d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) && !frozen.iter().any(|f| f.eq_ignore_ascii_case(layer))) + layer == "0" || (d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) && !frozen_in(frozen, layer)) +} + +/// Whether `layer` is one of the layers in `frozen`, those frozen in a layout viewport (the names +/// compared as the renderer compares them). +fn frozen_in(frozen: &[String], layer: &str) -> bool { + frozen.iter().any(|f| f.eq_ignore_ascii_case(layer)) } /// The box of the contents of the block `blk`, referenced at `depth`, in the block's coordinates: @@ -428,6 +434,16 @@ impl<'a> ViewportBounds<'a> { self.frozen } + /// Whether the viewport leaves `part` out for its layer. `part` is an entity of the block + /// that an object the viewport draws is drawn from (a block reference, a dimension, a + /// multileader), and it is left out when its layer is frozen in the viewport, as in the + /// boxes above. A part on layer 0 never is: it takes the layer of the object, which the + /// caller has checked. What the drawing itself hides (a layer frozen for the whole drawing + /// or turned off) is not looked at here. + pub fn leaves_out(&self, part: &Entity) -> bool { + part.common.layer != "0" && frozen_in(self.frozen, &part.common.layer) + } + /// The box of what the viewport draws of `e`. Like [`entity_bounds`] it does not look at the /// layer `e` itself is on: whether the viewport draws `e` at all is the caller's to check. pub fn entity_bounds(&mut self, d: &'a Drawing, e: &Entity) -> Bounds2 { @@ -885,6 +901,27 @@ mod tests { } } + /// A viewport leaves a part of a block out for its layer when that layer is frozen in the + /// viewport, its name matched whatever its case. A part on layer 0 is never left out, also + /// where the viewport freezes layer 0: it takes the layer of the object drawn from the block. + /// A layer the drawing itself hides (frozen for the whole drawing, or turned off) is not the + /// viewport's to leave out, and a viewport that freezes no layer leaves nothing out. + #[test] + fn a_viewport_leaves_out_the_parts_on_its_frozen_layers() { + let part = |layer: &str| { + let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) }); + let mut e = Entity::new(crate::Handle(1), kind); + e.common.layer = layer.into(); + e + }; + let frozen = ["hidden".to_string(), "0".to_string()]; + let (through, plain) = (ViewportBounds::new(&frozen), ViewportBounds::new(&[])); + assert!(through.leaves_out(&part("Hidden")), "a layer frozen in the viewport, its name in another case"); + assert!(!plain.leaves_out(&part("Hidden")), "the same part where no layer is frozen"); + assert!(!through.leaves_out(&part("0")), "layer 0 takes the object's layer"); + assert!(!through.leaves_out(&part("Other")), "a layer the viewport does not freeze"); + } + /// Through a layout viewport the block contents on a layer frozen in it take no room: a part /// of a reference, a part two blocks deep, a nested reference that is itself on that layer /// (with everything in it), an attribute, the parts of the block a dimension or a multileader diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 710ee864a..b769a0974 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -112,7 +112,7 @@ fn entity_distance_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds< 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 && entity_bounds(d, e, 0).contains(p)) || in_text(d, e, view, p) { best = 0.0; } // A solid hatch fills its loops with odd parity under its island style, as it is drawn, not @@ -133,8 +133,10 @@ fn entity_distance_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds< /// Whether `p` is on the text of a dimension or multileader: inside the box around its words, /// turned with the text, as plain text is hit anywhere inside its box. Their other geometry is /// hit along its lines, so without this the cursor found the object only between the letters' -/// edges and the lines. -fn in_text(d: &Drawing, e: &Entity, p: Vec2) -> bool { +/// edges and the lines. Text in a dimension's block that `view` leaves out +/// ([`ViewportBounds::leaves_out`]) does not count: the viewport does not draw text on a layer +/// frozen in it, and a pick in its box finds nothing there, as in AutoCAD. +fn in_text(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, p: Vec2) -> bool { match &e.kind { // A dimension with a block (as AutoCAD saves them) is drawn from that block: its text is // the text there, not the text the dimension's own geometry would place. @@ -142,7 +144,7 @@ fn in_text(d: &Drawing, e: &Entity, p: Vec2) -> bool { // The block draws translated by the insertion point (group 12): test there (#2634). Some(blk) => { let p = p - dm.insertion_point.xy(); - blk.entities.iter().any(|be| match &be.kind { + blk.entities.iter().filter(|be| !view.leaves_out(be)).any(|be| match &be.kind { EntityKind::MText(t) => in_box(cadcraft_render::layout_mtext_entity(d, t).strokes.into_iter().flatten(), t.rotation, p), EntityKind::Text(_) => entity_bounds(d, be, 0).contains(p), _ => false, diff --git a/crates/engine/tests/it/viewport_frozen_block_parts.rs b/crates/engine/tests/it/viewport_frozen_block_parts.rs index 6bb19274e..b015856c9 100644 --- a/crates/engine/tests/it/viewport_frozen_block_parts.rs +++ b/crates/engine/tests/it/viewport_frozen_block_parts.rs @@ -757,6 +757,94 @@ fn a_crossing_window_tests_the_parts_the_viewport_draws() { assert_eq!(select::select_fence_in(&d, &model, &[], &across(hidden_part)), [dim]); } +/// A dimension is picked anywhere inside the box of its text, and that text is a part of its +/// block. Through a viewport that freezes the text's layer the text is not drawn: a pick in its +/// box finds nothing there and selection cycling lists nothing, while the lines of the dimension +/// are picked as before and a window around all of it takes it. Where the text is drawn a pick +/// in its middle takes the dimension. AutoCAD 2022 was given this dimension, with the text of +/// its block moved to "Hidden", and answers every case asserted here the same way. The block is +/// the one it made, without the arrowheads and the definition points. The frozen layers are +/// given to the selection as a viewport gives them. +/// +/// Some answers of AutoCAD are not matched and not asserted. It picks nothing at any of the 27 +/// points of its grid inside the box of the text and takes nothing with a crossing window inside +/// that box; here the nine points of the top row and that crossing window still take the +/// dimension, through the top side of the rectangle around it, which is hit as the rectangle +/// around a block reference is (#2991). And with the layer frozen for the whole drawing or turned +/// off it picks nothing in that box either, where CADCraft picks the dimension as it did before +/// this change, which leaves what a drawing-wide layer state does alone. +#[test] +fn a_dimension_is_not_picked_on_text_that_is_not_drawn() { + use cadcraft_engine::doc::{Block, Common, DimKind, Dimension, Drawing, Entity, EntityKind, Line, MText, Space}; + use cadcraft_engine::geom::Vec3; + let mut d = Drawing::new_metric(); + d.ensure_layer("Hidden"); + // A horizontal dimension from (0, 5) and (40, 15) with its line along y = 40 and text 3 high: + // two extension lines, the two halves of the dimension line, and the text between them. + let mut block = Block::new("*D5"); + let lines = [([0.0, 5.063], [0.0, 40.18]), ([40.0, 15.063], [40.0, 40.18]), ([2.0, 40.0], [12.462, 40.0]), ([38.0, 40.0], [27.538, 40.0])]; + for (handle, (a, b)) in (1..).zip(lines) { + let mut part = Entity::new(Handle(handle), EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) })); + part.common.layer = "0".into(); + block.entities.push(part); + } + let words = MText { + insert: Vec3::new(20.0, 40.0, 0.0), + height: 3.0, + width: 0.0, + attach: 5, + rotation: 0.0, + style: "Standard".into(), + contents: "\\A1;40.0000".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + let mut text = Entity::new(Handle(5), EntityKind::MText(words)); + text.common.layer = "Hidden".into(); + block.entities.push(text); + d.blocks.insert("*D5".into(), std::sync::Arc::new(block)); + let dimension = Dimension { + kind: DimKind::Linear { rotation: 0.0 }, + defpt: Vec3::new(40.0, 40.0, 0.0), + text_mid: Vec3::new(20.0, 40.0, 0.0), + p13: Vec3::new(0.0, 5.0, 0.0), + p14: Vec3::new(40.0, 15.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some("*D5".into()), + insertion_point: Vec3::ZERO, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + let dim = d.add(&Space::Model, Common::default(), EntityKind::Dimension(dimension)).unwrap(); + let through = ["Hidden".to_string()]; + let (middle, dimension_line, extension_line) = ([20.0, 40.0], [3.0, 40.0], [0.0, 20.0]); + let cycled = |frozen: &[String], p: [f64; 2]| select::pick_all_in(&d, &Space::Model, frozen, Vec2::new(p[0], p[1]), 0.2); + // AutoCAD was picked at a grid of 27 points inside the box of the text (14.896 by 3.063 + // there) and took nothing at any of them. Its two lower rows are asserted: 18 points, each + // more than 2 away from the lines. The top row, 0.613 above the dimension line, is not: it is + // 0.163 from the top side of the rectangle around the dimension, which lies 0.45 above that + // line, so inside the pick distance of 0.2, and that side still takes the dimension (#2991). + let grid: Vec<[f64; 2]> = (0..9).flat_map(|i| (0..2).map(move |j| [14.704 + 1.324 * f64::from(i), 39.387 + 0.613 * f64::from(j)])).collect(); + assert_eq!(picked(&d, &[], middle), Some(dim), "where the text is drawn"); + assert_eq!(cycled(&[], middle), [dim]); + assert_eq!(picked(&d, &through, middle), None, "a pick in the middle of the text that is not drawn"); + assert_eq!(cycled(&through, middle), [], "selection cycling there"); + for p in grid { + assert_eq!(picked(&d, &through, p), None, "a pick inside the box of the text at {p:?}"); + } + assert_eq!(picked(&d, &through, dimension_line), Some(dim), "the dimension line"); + assert_eq!(picked(&d, &through, extension_line), Some(dim), "an extension line"); + assert_eq!(windowed(&d, &through, [-2.0, 3.0], [42.0, 43.0]), [dim], "a window around all of it"); +} + /// The selections of a grid across the five references, with what each finds: at every point a /// pick, selection cycling's list, a crossing window, a fence, two windows and the two polygons. fn probes(s: &Session) -> Vec<(String, Vec)> { From 5f3fbd636ddddd1264527cb245f64ef514179ef9 Mon Sep 17 00:00:00 2001 From: vantruong-dang Date: Mon, 16 Nov 2026 21:55:16 +0700 Subject: [PATCH 039/258] fix(engine): frame layout extents on initial tab switch (#3219) --- crates/engine/src/cmd/layout/tests.rs | 23 +++++++++++++++++++++++ crates/engine/src/cmd/view.rs | 19 ++++++++++++++----- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layout/tests.rs b/crates/engine/src/cmd/layout/tests.rs index 57d52a7ef..7a7cefb10 100644 --- a/crates/engine/src/cmd/layout/tests.rs +++ b/crates/engine/src/cmd/layout/tests.rs @@ -372,3 +372,26 @@ fn plot_path_extension_picks_the_format_like_export() { assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree"); std::fs::remove_dir_all(&dir).ok(); } + +#[test] +fn layout_set_frames_extents_away_from_origin() { + let mut s = Session::new(); + s.doc_mut().unwrap().layouts.push(cadcraft_doc::Layout::new("COVER", 2)); + let paper = Space::Paper("COVER".into()); + s.doc_mut() + .unwrap() + .add( + &paper, + cadcraft_doc::Common::default(), + cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { + a: cadcraft_geom::Vec3::new(12049.0, 4307.0, 0.0), + b: cadcraft_geom::Vec3::new(12449.0, 4594.0, 0.0), + }), + ) + .unwrap(); + s.execute("layout.set", &json!({"name": "COVER"})).unwrap(); + let v = s.state().unwrap().view(); + assert!((v.center.x - 12249.0).abs() < 1e-6, "center.x={}", v.center.x); + assert!((v.center.y - 4450.5).abs() < 1e-6, "center.y={}", v.center.y); + assert!(v.height >= 287.0, "height={}", v.height); +} diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 7161308df..3592100e6 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -315,6 +315,7 @@ fn run_layout_set(s: &mut Session, p: &Value) -> Result { Space::Paper(l.name.clone()) }; s.pending_window = None; + let (vw, vh) = s.viewport_px; let st = s.state_mut()?; st.space = space.clone(); st.mspace = None; @@ -322,11 +323,19 @@ fn run_layout_set(s: &mut Session, p: &Value) -> Result { if let Space::Paper(n) = &space && !st.views.iter().any(|(sp, _)| sp == &space) { - // Default paper view: the sheet. - let page = st.doc.layout(n).map(|l| l.page.clone()).unwrap_or_default(); - let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) }; - let unit = if st.doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 }; - st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15, twist: 0.0 }); + let ext = st.doc.extents(&space); + if !ext.is_empty() && ext.width().is_finite() && ext.height().is_finite() { + let aspect = st.zoom_aspect(vw / vh.max(1.0)); + let (center, bw, bh) = View::twisted_box(ext, 0.0); + let height = bh.max(bw / aspect.max(1e-6)).max(1e-6) * 1.15; + st.set_view_quiet(View { center, height, twist: 0.0 }); + } else { + // Default paper view: the sheet. + let page = st.doc.layout(n).map(|l| l.page.clone()).unwrap_or_default(); + let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) }; + let unit = if st.doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 }; + st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15, twist: 0.0 }); + } } s.touch(); ok() From d12e08b1c94a4456b2a2f1295f2676703d90b9bf Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:07:05 -0600 Subject: [PATCH 040/258] io: dxf_anno uses craft_dxf, as main's DXF crate now is Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_anno.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/dxf_anno.rs b/crates/io/src/dxf_anno.rs index 88b02d10c..e13ac95ba 100644 --- a/crates/io/src/dxf_anno.rs +++ b/crates/io/src/dxf_anno.rs @@ -19,7 +19,7 @@ use std::collections::{BTreeSet, HashMap}; use cadcraft_doc::{AnnoScale, DimKind, Drawing, Entity, EntityKind, HAlign, Handle, MTextColumnType, Text, VAlign}; -use cadcraft_dxf::{Section, Tag}; +use craft_dxf::{Section, Tag}; use cadcraft_geom::Vec3; /// The context classes: (DXF record name, C++ class name). From 86898c0e1af99db0ec3dc7c8ed6c73e720b5e373 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:07:07 -0600 Subject: [PATCH 041/258] io: dxf_anno uses craft_dxf, as main's DXF crate now is Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_anno.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/dxf_anno.rs b/crates/io/src/dxf_anno.rs index dc968bcef..f2a3e4086 100644 --- a/crates/io/src/dxf_anno.rs +++ b/crates/io/src/dxf_anno.rs @@ -20,7 +20,7 @@ use std::collections::{BTreeSet, HashMap}; use cadcraft_doc::{AnnoScale, DimKind, Drawing, Entity, EntityKind, HAlign, Handle, MLeader, MTextColumnType, Text, VAlign}; -use cadcraft_dxf::{Section, Tag}; +use craft_dxf::{Section, Tag}; use cadcraft_geom::Vec3; /// The context classes: (DXF record name, C++ class name). From 24312f63cf8ea70ddcb62671d72c24435335a579 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:39:49 -0600 Subject: [PATCH 042/258] fmt: dxf_anno's craft_dxf import in order Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_anno.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/dxf_anno.rs b/crates/io/src/dxf_anno.rs index e13ac95ba..4bab1941b 100644 --- a/crates/io/src/dxf_anno.rs +++ b/crates/io/src/dxf_anno.rs @@ -19,8 +19,8 @@ use std::collections::{BTreeSet, HashMap}; use cadcraft_doc::{AnnoScale, DimKind, Drawing, Entity, EntityKind, HAlign, Handle, MTextColumnType, Text, VAlign}; -use craft_dxf::{Section, Tag}; use cadcraft_geom::Vec3; +use craft_dxf::{Section, Tag}; /// The context classes: (DXF record name, C++ class name). const TEXT: (&str, &str) = ("ACDB_TEXTOBJECTCONTEXTDATA_CLASS", "AcDbTextObjectContextData"); From bc0363df596ec4c79517682aa21f66bd3054bd2a Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:39:56 -0600 Subject: [PATCH 043/258] fmt: dxf_anno's craft_dxf import in order Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_anno.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/dxf_anno.rs b/crates/io/src/dxf_anno.rs index f2a3e4086..d1126ddf3 100644 --- a/crates/io/src/dxf_anno.rs +++ b/crates/io/src/dxf_anno.rs @@ -20,8 +20,8 @@ use std::collections::{BTreeSet, HashMap}; use cadcraft_doc::{AnnoScale, DimKind, Drawing, Entity, EntityKind, HAlign, Handle, MLeader, MTextColumnType, Text, VAlign}; -use craft_dxf::{Section, Tag}; use cadcraft_geom::Vec3; +use craft_dxf::{Section, Tag}; /// The context classes: (DXF record name, C++ class name). const TEXT: (&str, &str) = ("ACDB_TEXTOBJECTCONTEXTDATA_CLASS", "AcDbTextObjectContextData"); From 485892d8d1cc940f80b6d41a4830d62528f6ca3c Mon Sep 17 00:00:00 2001 From: vantruong-dang Date: Thu, 19 Nov 2026 13:40:11 +0700 Subject: [PATCH 044/258] perf(gpu): stabilize deep-zoom vertex origin with power-of-two grid and hysteresis --- crates/ui-egui/src/canvas/draw.rs | 14 +++-- crates/ui-egui/src/canvas/viewport.rs | 9 ++-- crates/ui-egui/src/gpu.rs | 75 +++++++++++++++++++++++++-- 3 files changed, 88 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/canvas/draw.rs b/crates/ui-egui/src/canvas/draw.rs index 17da084f7..a0a9154bf 100644 --- a/crates/ui-egui/src/canvas/draw.rs +++ b/crates/ui-egui/src/canvas/draw.rs @@ -169,13 +169,16 @@ pub(super) fn draw_highlight_gpu( stencil: crate::gpu::Stencil, ) { let (hl_key, hl_slot, hl_origin, hl_infinite) = hl; - let origin = crate::gpu::choose_origin(&list.bounds, xf.center, f64::from(xf.rect.height()) / xf.scale.max(1e-300)); - let key = { + let hl_hash = |o: Vec2| { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); - (list_gen, sel, origin.x.to_bits(), origin.y.to_bits(), color.to_array(), look.width.to_bits(), look.dashed).hash(&mut h); + (list_gen, sel, o.x.to_bits(), o.y.to_bits(), color.to_array(), look.width.to_bits(), look.dashed).hash(&mut h); h.finish() }; + let view_height = f64::from(xf.rect.height()) / xf.scale.max(1e-300); + let reuse = *hl_key == Some(hl_hash(*hl_origin)) && crate::gpu::origin_usable(*hl_origin, &list.bounds, xf.center, view_height); + let origin = if reuse { *hl_origin } else { crate::gpu::choose_origin(&list.bounds, xf.center, view_height) }; + let key = hl_hash(origin); if *hl_key != Some(key) { let prims = prims(); let mesh = crate::gpu::build_highlight_mesh(list, &prims, origin, color.to_array(), look.width, look.dashed); @@ -279,7 +282,10 @@ pub(super) fn list_mesh_key(key: &ListKey, list_gen: u64, origin: Vec2, bg: Rgb, /// the infinite lines, which are clipped to the view on the CPU every frame. pub(super) fn draw_list_gpu(c: &mut CanvasState, p: &egui::Painter, xf: &Xf, bg: Rgb, lwdisplay: bool) { let Some(list) = &c.list else { return }; - let origin = crate::gpu::choose_origin(&list.bounds, xf.center, f64::from(xf.rect.height()) / xf.scale.max(1e-300)); + let view_height = f64::from(xf.rect.height()) / xf.scale.max(1e-300); + let reuse = c.mesh_key == Some(list_mesh_key(&c.key, c.list_gen, c.mesh_origin, bg, lwdisplay)) + && crate::gpu::origin_usable(c.mesh_origin, &list.bounds, xf.center, view_height); + let origin = if reuse { c.mesh_origin } else { crate::gpu::choose_origin(&list.bounds, xf.center, view_height) }; let key = list_mesh_key(&c.key, c.list_gen, origin, bg, lwdisplay); if c.mesh_key != Some(key) { let t0 = crate::now_ms(); diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index 43471f61a..4a44efaf4 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -174,13 +174,16 @@ pub(super) fn draw_vp_content(c: &mut VpContent, gpu: bool, p: &egui::Painter, f draw_vp_mask(c, p, outline, xf_paper); stencil = crate::gpu::Stencil::Inside; } - let origin = crate::gpu::choose_origin(&c.list.bounds, xf.center, f64::from(xf.rect.height()) / xf.scale.max(1e-300)); - let key = { + let mesh_hash = |o: Vec2| { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); - (c.builds, origin.x.to_bits(), origin.y.to_bits(), bg.0, bg.1, bg.2, lwdisplay).hash(&mut h); + (c.builds, o.x.to_bits(), o.y.to_bits(), bg.0, bg.1, bg.2, lwdisplay).hash(&mut h); h.finish() }; + let view_height = f64::from(xf.rect.height()) / xf.scale.max(1e-300); + let reuse = c.mesh_key == Some(mesh_hash(c.mesh_origin)) && crate::gpu::origin_usable(c.mesh_origin, &c.list.bounds, xf.center, view_height); + let origin = if reuse { c.mesh_origin } else { crate::gpu::choose_origin(&c.list.bounds, xf.center, view_height) }; + let key = mesh_hash(origin); if c.mesh_key != Some(key) { let mesh = crate::gpu::build_mesh(&c.list, origin, bg, lwdisplay); if let Ok(mut slot) = c.mesh_slot.lock() { diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 095c2d192..782facf04 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -295,9 +295,13 @@ pub fn build_highlight_mesh(list: &DisplayList, prims: &[usize], origin: Vec2, c m } +/// Maximum drift of a cached vertex origin from `view_center` (in multiples of `view_height`) +/// before re-centering to preserve `f32` GPU vertex precision. +const MAX_ORIGIN_DRIFT_FACTOR: f64 = 512.0; + /// The vertex origin for a display list seen at `view_center` / `view_height`: the list's centre /// normally; at deep zoom (the view much smaller than the drawing) a point near the view, snapped -/// to a coarse grid so panning re-uploads only every few dozen screens. +/// to a coarse power-of-two grid so consecutive zoom steps and panning re-upload rarely. pub fn choose_origin(bounds: &Bounds2, view_center: Vec2, view_height: f64) -> Vec2 { let size = bounds.width().max(bounds.height()); if bounds.is_empty() @@ -307,8 +311,34 @@ pub fn choose_origin(bounds: &Bounds2, view_center: Vec2, view_height: f64) -> V { return if bounds.is_empty() { Vec2::ZERO } else { bounds.center() }; } - let step = view_height * 64.0; - Vec2::new((view_center.x / step).round() * step, (view_center.y / step).round() * step) + let raw = view_height * 64.0; + if !raw.is_finite() || raw <= 0.0 { + return bounds.center(); + } + let exp = raw.log2().floor().clamp(-1000.0, 1000.0) as i32; + let step = 2.0_f64.powi(exp); + if !step.is_finite() || step <= 0.0 { + return bounds.center(); + } + let o = Vec2::new((view_center.x / step).round() * step, (view_center.y / step).round() * step); + if o.is_finite() { o } else { bounds.center() } +} + +/// Whether an already uploaded mesh's `origin` is still close enough to `view_center` for `f32` +/// vertex precision at `view_height`, avoiding needless GPU mesh rebuilds while zooming or panning. +pub fn origin_usable(origin: Vec2, bounds: &Bounds2, view_center: Vec2, view_height: f64) -> bool { + if !origin.is_finite() { + return false; + } + if bounds.is_empty() || !view_center.is_finite() || view_height.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) { + return true; + } + let size = bounds.width().max(bounds.height()); + if view_height * 2000.0 >= size && origin == bounds.center() { + return true; + } + let d = (view_center.x - origin.x).abs().max((view_center.y - origin.y).abs()); + d.is_finite() && d <= view_height * MAX_ORIGIN_DRIFT_FACTOR } /// Pending upload shared between the canvas (producer) and the paint callback (consumer). @@ -970,6 +1000,45 @@ mod tests { assert_eq!(choose_origin(&b, Vec2::new(f64::NAN, 0.0), 1.0), b.center()); } + #[test] + fn choose_origin_is_stable_across_small_zoom_steps() { + let b = Bounds2::new(Vec2::new(0.0, 0.0), Vec2::new(1e6, 1e6)); + let center = Vec2::new(123_456.7, 654_321.2); + let base = choose_origin(&b, center, 1.0); + for h in [1.1, 1.25, 1.5, 1.9] { + assert_eq!(choose_origin(&b, center, h), base, "view_height {h} changed origin within 2x band"); + } + // Panning far away or zooming across much larger/smaller scales still tracks the camera. + let panned = choose_origin(&b, Vec2::new(900_000.0, 900_000.0), 1.0); + assert_ne!(panned, base); + assert!((panned.x - 900_000.0).abs() <= 32.0); + let zoomed_out = choose_origin(&b, center, 64.0); + assert!((zoomed_out.x - center.x).abs() <= 2048.0); + let zoomed_in = choose_origin(&b, Vec2::new(123_456.789, 654_321.123), 1e-3); + assert!((zoomed_in.x - 123_456.789).abs() <= 0.1); + // Degenerate view heights and extreme scales fall back cleanly without panicking or NaN. + assert_eq!(choose_origin(&b, center, 0.0), b.center()); + assert_eq!(choose_origin(&b, center, -1.0), b.center()); + assert_eq!(choose_origin(&b, center, f64::NAN), b.center()); + assert!(choose_origin(&b, center, 1e-300).is_finite()); + assert_eq!(choose_origin(&b, center, 1e300), b.center()); + } + + #[test] + fn origin_usable_keeps_origin_within_precision_budget() { + let b = Bounds2::new(Vec2::new(0.0, 0.0), Vec2::new(1e6, 1e6)); + let center = Vec2::new(123_456.7, 654_321.2); + let o = choose_origin(&b, center, 1.0); + // Small pans and zooming out or moderately in keep the uploaded origin valid. + assert!(origin_usable(o, &b, center + Vec2::new(100.0, -200.0), 1.0)); + assert!(origin_usable(o, &b, center, 10.0)); + assert!(origin_usable(o, &b, o + Vec2::new(256.0, -256.0), 0.5)); + // Exceeding 512 * view_height or non-finite origins force a recenter. + assert!(!origin_usable(o, &b, o + Vec2::new(513.0, 0.0), 1.0)); + assert!(!origin_usable(o, &b, o + Vec2::new(60.0, 0.0), 0.1)); + assert!(!origin_usable(Vec2::new(f64::NAN, 0.0), &b, center, 1.0)); + } + #[test] fn wipeout_masks_start_a_draw_order_group() { let mut l = list(); From 573488d5a39a4b0fd2b37ecbd0a8282e9b6583fb Mon Sep 17 00:00:00 2001 From: vantruong-dang Date: Thu, 19 Nov 2026 14:00:12 +0700 Subject: [PATCH 045/258] fix(cmd): support SCALE Reference Points and Copy, disable pointer boxes on numeric prompts, and scale heights in grip SCALE --- crates/engine/src/cmd/gripcmds.rs | 10 +- crates/engine/src/cmd/griphot.rs | 67 ++++++++--- crates/engine/src/cmd/modify.rs | 2 +- crates/engine/src/cmd/modify/select_then.rs | 122 +++++++++++++------- crates/engine/src/tests.rs | 91 +++++++++++++++ crates/ui-egui/src/cmdline.rs | 7 +- crates/ui-egui/src/grip_dyn.rs | 43 ++++++- 7 files changed, 269 insertions(+), 73 deletions(-) diff --git a/crates/engine/src/cmd/gripcmds.rs b/crates/engine/src/cmd/gripcmds.rs index a7ba2cdd6..d7e5933b8 100644 --- a/crates/engine/src/cmd/gripcmds.rs +++ b/crates/engine/src/cmd/gripcmds.rs @@ -253,14 +253,16 @@ fn run_grip_rotate(s: &mut Session, p: &Value) -> Result { fn run_grip_scale(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; let base = base_point(s, "grip.scale", p, &hs)?; - let m = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) { - Some(f) if f > 0.0 => Mat3::scale_about(base, f), + let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) { + Some(f) if f > 1e-12 => f, Some(_) => return Err(bad("grip.scale", "factor must be positive")), None => { - mode_matrix(GripMode::Scale, base, point_req("grip.scale", p, "to")?).ok_or_else(|| bad("grip.scale", "scale factor would be zero"))? + let f = base.dist(point_req("grip.scale", p, "to")?); + if f.is_finite() && f > 1e-12 { f } else { return Err(bad("grip.scale", "scale factor would be zero")) } } }; - apply(s, &hs, &m, bool_or(p, "copy", false)) + let r = super::modify::scale_entities(s, &hs, super::modify::at_elevation(s, base), f, bool_or(p, "copy", false))?; + Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::>() })) } fn run_grip_mirror(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/griphot.rs b/crates/engine/src/cmd/griphot.rs index 9234d981c..6f8349bc6 100644 --- a/crates/engine/src/cmd/griphot.rs +++ b/crates/engine/src/cmd/griphot.rs @@ -14,7 +14,7 @@ use cadcraft_geom::{Mat3, Vec2}; use super::gripcmds::stretch_grips; use super::helpers::line; use super::machines::number; -use super::modify::transform_entities; +use super::modify::{at_elevation, scale_entities, transform_entities}; use crate::grips::{GripAction, GripMode, grip_action, grip_actions, mode_matrix}; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step}; @@ -220,14 +220,7 @@ impl GripEdit { } } - /// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes). - fn edit(&mut self, s: &mut Session, to: Vec2, m: Option) -> Result { - let before = s.state()?.doc.clone(); - let changed = match (self.mode, m) { - (GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(), - (_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(), - (_, None) => return Err(other("Invalid point.")), - }; + fn finish_edit(&mut self, before: Arc, changed: bool) -> Result { if !changed { return Err(other("The objects can't be edited that way (locked, or the result would be degenerate).")); } @@ -240,6 +233,27 @@ impl GripEdit { } } + /// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes). + fn edit(&mut self, s: &mut Session, to: Vec2, m: Option) -> Result { + let before = s.state()?.doc.clone(); + let changed = match (self.mode, m) { + (GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(), + (_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(), + (_, None) => return Err(other("Invalid point.")), + }; + self.finish_edit(before, changed) + } + + /// Scale `targets` uniformly about `base` in 3D, scaling text heights, elevations and thickness. + fn edit_scale(&mut self, s: &mut Session, f: f64) -> Result { + if !f.is_finite() || f <= 1e-12 { + return Err(other("Invalid point.")); + } + let before = s.state()?.doc.clone(); + let changed = !scale_entities(s, &self.targets, at_elevation(s, self.base), f, self.copy)?.is_empty(); + self.finish_edit(before, changed) + } + fn mode_input(&mut self, s: &mut Session, i: Input) -> Result { match i { Input::Keyword(k) => match k.as_str() { @@ -286,12 +300,20 @@ impl GripEdit { Ok(Step::Continue) } Input::Point(p) => { - let m = self.matrix(p); - self.edit(s, p, m) + if self.mode == GripMode::Scale { + self.edit_scale(s, self.base.dist(p)) + } else { + let m = self.matrix(p); + self.edit(s, p, m) + } } Input::Deferred(d) => { - let m = self.matrix(d.at); - self.edit(s, d.at, m) + if self.mode == GripMode::Scale { + self.edit_scale(s, self.base.dist(d.at)) + } else { + let m = self.matrix(d.at); + self.edit(s, d.at, m) + } } Input::Text(t) => match self.mode { GripMode::Rotate => { @@ -300,7 +322,7 @@ impl GripEdit { } GripMode::Scale => { let f = positive(number(&t))?; - self.edit(s, self.base, Some(Mat3::scale_about(self.base, f))) + self.edit_scale(s, f) } _ => Err(other("Requires a point or an option keyword.")), }, @@ -327,14 +349,21 @@ impl GripEdit { (Ask::RefFirst, Input::Text(t)) => self.ask = Ask::RefNew(value(&t)?), (Ask::RefFirst, Input::Enter) => self.ask = Ask::RefNew(if rotate { 0.0 } else { 1.0 }), (Ask::RefSecond(a), Input::Point(p)) => self.ask = Ask::RefNew(between(a, p)?), - (Ask::RefNew(_), Input::Point(p)) => { - let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?; - return self.edit(s, p, Some(m)); + (Ask::RefNew(r), Input::Point(p)) => { + if rotate { + let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?; + return self.edit(s, p, Some(m)); + } + let f = positive(Some(self.base.dist(p) / r))?; + return self.edit_scale(s, f); } (Ask::RefNew(r), Input::Text(t)) => { let v = value(&t)?; - let m = if rotate { Mat3::rotate_about(self.base, v - r) } else { Mat3::scale_about(self.base, positive(Some(v / r))?) }; - return self.edit(s, self.base, Some(m)); + if rotate { + return self.edit(s, self.base, Some(Mat3::rotate_about(self.base, v - r))); + } + let f = positive(Some(v / r))?; + return self.edit_scale(s, f); } (_, Input::Enter) => self.ask = Ask::Mode, _ => {} diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 367dacc65..ec3559eea 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -35,7 +35,7 @@ use oops::run_oops; pub(crate) use oops::{Erased, erase_kept}; use select_then::{DisplaceM, Op, SelectThen}; use stretch::{StretchM, run_stretch}; -pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities}; +pub(crate) use transform::{at_elevation, holds_ole_frame, ole_refusal, refuse_ole_frames, scale_entities, transform_entities}; use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale}; pub(crate) use trim::{Edges, extend, trim}; diff --git a/crates/engine/src/cmd/modify/select_then.rs b/crates/engine/src/cmd/modify/select_then.rs index 009a95281..45cdf0533 100644 --- a/crates/engine/src/cmd/modify/select_then.rs +++ b/crates/engine/src/cmd/modify/select_then.rs @@ -26,12 +26,11 @@ pub(super) struct SelectThen { objs: Vec, pts: Vec, reference: bool, - /// ROTATE Reference: the reference angle (radians), once known. Its first point, and the - /// first of the two new-angle points, are kept in `ref_from`. + /// ROTATE Reference: the reference angle (radians), once known. ref_angle: Option, - /// ROTATE Reference: the new angle is given by two points (the `Points` option). + /// ROTATE/SCALE Reference: the new angle/length is given by two points (the `Points` option). ref_points: bool, - /// SCALE Reference: first point of a reference length given by two points. + /// ROTATE/SCALE Reference: first point of a reference or `Points` pair given by two points. ref_from: Option, /// SCALE Reference: the reference length, once known. ref_len: Option, @@ -126,30 +125,47 @@ impl SelectThen { } } - /// SCALE Reference: reference length (typed, or two points), then new length (typed, or a - /// point measured from the base point). The scale factor is new length / reference length. + /// SCALE Reference: reference length (typed, or two points), then new length (typed, a point + /// measured from the base point, or two points after `Points`). The scale factor is new length / + /// reference length. fn scale_reference(&mut self, s: &mut Session, i: Input) -> Result { let Some(base) = self.pts.first().copied() else { return Ok(Step::Done) }; - match (self.ref_len, self.ref_from, i) { - (None, None, Input::Point(p)) => { + if matches!(&i, Input::Keyword(k) if k == "Copy") { + self.copy_mode = true; + s.echo("Scaling a copy of the selected objects."); + return Ok(Step::Continue); + } + let Some(r) = self.ref_len else { + match (self.ref_from, i) { + (None, Input::Point(p)) => self.ref_from = Some(p), + (None, Input::Text(t)) => self.ref_len = Some(require_length(number(&t))?), + (None, Input::Enter) => self.ref_len = Some(1.0), + (Some(a), Input::Point(p)) => { + self.ref_len = Some(require_length(Some(a.dist(p)))?); + self.ref_from = None; + } + (_, Input::Enter) => return Ok(Step::Done), + _ => {} + } + return Ok(Step::Continue); + }; + match (self.ref_points, self.ref_from, i) { + (false, _, Input::Keyword(k)) if k == "Points" => { + self.ref_points = true; + self.ref_from = None; + Ok(Step::Continue) + } + (false, _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r), + (false, _, Input::Text(t)) => { + let n = require_length(number(&t))?; + self.scale_by(s, base, n / r) + } + (true, None, Input::Point(p)) => { self.ref_from = Some(p); Ok(Step::Continue) } - (None, None, Input::Text(t)) => { - self.ref_len = Some(require_length(number(&t))?); - Ok(Step::Continue) - } - (None, None, Input::Enter) => { - self.ref_len = Some(1.0); - Ok(Step::Continue) - } - (None, Some(a), Input::Point(p)) => { - self.ref_len = Some(require_length(Some(a.dist(p)))?); - Ok(Step::Continue) - } - (Some(r), _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r), - (Some(r), _, Input::Text(t)) => { - let n = require_length(number(&t))?; + (true, Some(a), Input::Point(p)) => { + let n = require_length(Some(a.dist(p)))?; self.scale_by(s, base, n / r) } (_, _, Input::Enter) => Ok(Step::Done), @@ -157,6 +173,26 @@ impl SelectThen { } } + /// The prompt while SCALE Reference collects its lengths. + fn scale_reference_prompt(&self) -> Prompt { + let base = self.pts.first().copied(); + match (self.ref_len, self.ref_points, self.ref_from) { + (None, _, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).kw(&["Copy"]).default("1"), + (None, _, Some(p)) | (Some(_), true, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p), + (Some(_), false, _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).kw(&["Points", "Copy"]).base_opt(base), + (Some(_), true, None) => Prompt::new("Specify first point", Accept::POINT), + } + } + + /// Live factor and rubber-band anchor while SCALE Reference previews with the cursor at `c`. + fn scale_reference_factor(&self, base: Vec2, c: Vec2) -> Option<(f64, Vec2)> { + match (self.ref_len, self.ref_points, self.ref_from) { + (Some(r), false, _) => positive_length(Some(base.dist(c) / r)).map(|f| (f, base)), + (Some(r), true, Some(a)) => positive_length(Some(a.dist(c) / r)).map(|f| (f, a)), + _ => None, + } + } + /// ROTATE Reference: reference angle (typed, or two points), then the new angle (typed, a /// point measured from the base point, or two points after `Points`). The objects turn by the /// new angle minus the reference angle. @@ -314,11 +350,7 @@ impl Interactive for SelectThen { let k = self.pts.len(); let base = self.pts.first().copied(); if self.op == Op::Scale && self.reference { - return match (self.ref_len, self.ref_from) { - (Some(_), _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).base_opt(base), - (None, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p), - (None, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).default("1"), - }; + return self.scale_reference_prompt(); } if self.op == Op::Rotate && self.reference { return self.rotate_reference_prompt(); @@ -464,16 +496,15 @@ impl Interactive for SelectThen { return Vec::new(); } let Some(base) = self.pts.first().copied() else { return Vec::new() }; - let m = match self.op { - Op::Move | Op::Copy => Mat3::translate(c - base), - Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)), - Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)), - Op::Scale => match self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r))) { - Some(f) => Mat3::scale_about(base, f), - None if self.ref_len.is_some() => return Vec::new(), + let (m, rubber_from) = match self.op { + Op::Move | Op::Copy => (Mat3::translate(c - base), base), + Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base), + Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base), + Op::Scale => match self.scale_reference_factor(base, c) { + Some((f, from)) => (Mat3::scale_about(base, f), from), None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(), }, - Op::Mirror if !self.ask_erase => Mat3::mirror(base, c), + Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base), _ => return Vec::new(), }; let Ok(d) = s.doc() else { return Vec::new() }; @@ -488,7 +519,7 @@ impl Interactive for SelectThen { k }) .collect(); - out.push(line(base, c)); + out.push(line(rubber_from, c)); out } fn drag(&self, s: &Session, c: Vec2) -> Option { @@ -496,15 +527,18 @@ impl Interactive for SelectThen { return None; } let base = self.pts.first().copied()?; - let matrix = match self.op { - Op::Move | Op::Copy => Mat3::translate(c - base), - Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)), - Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)), - Op::Scale => Mat3::scale_about(base, self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r)))?), - Op::Mirror if !self.ask_erase => Mat3::mirror(base, c), + let (matrix, rubber_from) = match self.op { + Op::Move | Op::Copy => (Mat3::translate(c - base), base), + Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base), + Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base), + Op::Scale => { + let (f, from) = self.scale_reference_factor(base, c)?; + (Mat3::scale_about(base, f), from) + } + Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base), _ => return None, }; - let mut extra = vec![line(base, c)]; + let mut extra = vec![line(rubber_from, c)]; if self.op != Op::Mirror { return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false }); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 205faa273..d9fefc6b9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -532,6 +532,97 @@ fn scale_reference_typed_and_picked() { assert!(end(&s).near(Vec2::new(50.0, 0.0), 1e-9)); } +#[test] +fn scale_reference_points_and_copy() { + fn line_ends(s: &Session) -> Vec { + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Line(l) => Some(l.b.xy()), + _ => None, + }) + .collect() + } + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + // Reference 10 via two points, then Points option with two points of length 30 -> (30, 0). + for t in ["scale", "all", "", "0,0", "r", "0,0", "10,0"] { + s.cmdline(t).unwrap(); + } + let p = s.current_prompt().unwrap(); + assert_eq!(p.message, "Specify new length"); + assert!(p.keywords.contains(&"Points".to_string())); + assert!(p.keywords.contains(&"Copy".to_string())); + s.cmdline("p").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Specify first point"); + s.cmdline("5,5").unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Specify second point"); + s.cmdline("5,35").unwrap(); + assert!(s.running.is_none()); + assert!(line_ends(&s)[0].near(Vec2::new(30.0, 0.0), 1e-9)); + + // Coinciding Points are rejected without leaving the second-point prompt; a valid point completes. + for t in ["scale", "all", "", "0,0", "r", "30", "p", "5,5", "5,5"] { + s.cmdline(t).unwrap(); + } + assert!(s.running.is_some()); + assert_eq!(s.current_prompt().unwrap().message, "Specify second point"); + s.cmdline("5,25").unwrap(); + assert!(s.running.is_none()); + assert!(line_ends(&s)[0].near(Vec2::new(20.0, 0.0), 1e-9)); + + // Copy entered inside Reference mode before reference length keeps the original and adds a scaled copy. + for t in ["scale", "all", "", "0,0", "r", "c", "20", "40"] { + s.cmdline(t).unwrap(); + } + assert!(s.running.is_none()); + let ends = line_ends(&s); + assert_eq!(ends.len(), 2); + assert!(ends.iter().any(|p| p.near(Vec2::new(20.0, 0.0), 1e-9))); + assert!(ends.iter().any(|p| p.near(Vec2::new(40.0, 0.0), 1e-9))); + + // Copy entered at "Specify new length" combined with Points scales a copy. + for t in ["scale", "l", "", "0,0", "r", "40", "c", "p", "0,0", "10,0"] { + s.cmdline(t).unwrap(); + } + assert!(s.running.is_none()); + let ends = line_ends(&s); + assert_eq!(ends.len(), 3); + assert!(ends.iter().any(|p| p.near(Vec2::new(10.0, 0.0), 1e-9))); +} + +#[test] +fn hot_grip_scale_scales_heights_and_thickness() { + let mut s = Session::new(); + let r = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap(); + let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + e.common.thickness = 3.0; + if let EntityKind::Text(t) = &mut e.kind { + t.insert.z = 5.0; + } + }) + .unwrap(); + s.set_selection(vec![h]); + s.start_grip_edit(&[(h, 0)]).unwrap(); + // STRETCH -> MOVE -> ROTATE -> SCALE + for _ in 0..3 { + s.input(Input::Enter).unwrap(); + } + assert!(s.current_prompt().unwrap().message.contains("** SCALE **")); + s.cmdline("2").unwrap(); + assert!(s.running.is_none()); + let e = s.doc().unwrap().entity(h).unwrap(); + assert_eq!(e.common.thickness, 6.0); + let EntityKind::Text(t) = &e.kind else { panic!("expected text") }; + assert_eq!(t.height, 4.0); + assert_eq!(t.insert.z, 10.0); +} + #[test] fn layers_and_properties() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index f926ae31c..3ec903212 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -49,14 +49,15 @@ pub struct CmdLine { pub const MAX_LINES: usize = 12; const LINE_H: f32 = 16.0; -/// The Dynamic Input frame for the prompt on screen, or `None` when the value boxes are not live -/// (Dynamic Input off, no point prompt or a pending selection window). +/// The Dynamic Input pointer-input frame for the prompt on screen, or `None` when the pointer +/// value boxes are not live (Dynamic Input off, a selection window pending, not a point prompt, or +/// a prompt that also takes a scalar number like SCALE's factor or ROTATE's angle). pub fn dyn_frame(app: &CadApp) -> Option { let st = &app.session.settings; if !st.dynmode || app.session.pending_window.is_some() { return None; } - let p = app.session.current_prompt().filter(cadcraft_engine::pointmod::accepts)?; + let p = app.session.current_prompt().filter(|p| cadcraft_engine::pointmod::accepts(p) && !p.accept.number)?; Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute }) } diff --git a/crates/ui-egui/src/grip_dyn.rs b/crates/ui-egui/src/grip_dyn.rs index 35714b5c7..2a885de55 100644 --- a/crates/ui-egui/src/grip_dyn.rs +++ b/crates/ui-egui/src/grip_dyn.rs @@ -32,16 +32,26 @@ pub struct GripDyn { pub locked: Vec<(usize, String)>, } +/// The active prompt eligible for grip or distance dimensional input (`dynmode` enabled, not in a +/// selection window, accepting a point). +fn dyn_prompt(app: &CadApp) -> Option { + let st = &app.session.settings; + if !st.dynmode || app.session.pending_window.is_some() { + return None; + } + app.session.current_prompt().filter(cadcraft_engine::pointmod::accepts) +} + /// The base of the prompt on show when it asks for a distance from it (a circle's radius, a /// polyline arc's): its one field is that distance. fn distance_base(app: &CadApp) -> Option { - crate::cmdline::dyn_frame(app).and_then(|_| app.session.current_prompt()).filter(|p| p.distance).and_then(|p| p.base) + dyn_prompt(app).filter(|p| p.distance).and_then(|p| p.base) } /// The dimensions on show, after bringing the fields' state up to date with the prompt (empty when /// no grip is stretched, no distance is asked for, or the value boxes aren't live). pub fn dims(app: &mut CadApp) -> Vec { - let grip = crate::cmdline::dyn_frame(app).and_then(|_| app.session.current_prompt()).and_then(|p| p.grip); + let grip = dyn_prompt(app).and_then(|p| p.grip); let base = distance_base(app); let st = &mut app.canvas.grip_dyn; if st.grip != grip || st.base != base { @@ -359,4 +369,33 @@ mod tests { assert!(arch(c.len()) != arch(c.x) && arch(c.len()) != arch(c.y), "{c:?}"); assert!(text.contains(&arch(c.len())), "no {} in:\n{text}", arch(c.len())); } + + /// Prompts like SCALE factor (`Accept::POINT_OR_NUMBER` without `Prompt::distance`) must not + /// open the two-box pointer input (`dyn_frame`) so typing a factor + Tab/Enter stays a plain + /// numeric scale factor instead of becoming polar/Cartesian coordinates. + #[test] + fn scale_factor_prompt_does_not_open_pointer_boxes() { + let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default()); + app.session.settings.dynmode = true; + app.session.execute("line", &serde_json::json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let ctx = egui::Context::default(); + run_frame(&mut app, &ctx, Vec::new()); + let at = app.canvas.rect.map_or(pos2(700.0, 450.0), |r| r.center() + vec2(120.0, -60.0)); + run_frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); + + for t in ["scale", "all", "", "0,0"] { + app.session.cmdline(t).unwrap(); + } + run_frame(&mut app, &ctx, vec![Event::PointerMoved(at)]); + assert_eq!(app.session.current_prompt().unwrap().message, "Specify scale factor"); + assert!(crate::cmdline::dyn_frame(&app).is_none()); + + run_frame(&mut app, &ctx, vec![Event::Text("0.5".into())]); + run_frame(&mut app, &ctx, vec![Event::Text("\t".into())]); + assert_eq!(app.cmd.buffer, "0.5"); + run_frame(&mut app, &ctx, key(egui::Key::Enter)); + assert!(app.session.running.is_none()); + let b = line_end(&app); + assert!(b.near(Vec2::new(5.0, 0.0), 1e-9), "{b:?}"); + } } From 573823767ca2eb03dcf326c6d625c8df681ad467 Mon Sep 17 00:00:00 2001 From: HolyZephyros Date: Thu, 19 Nov 2026 16:16:01 +0300 Subject: [PATCH 046/258] i18n(tr): complete Turkish UI catalog --- crates/ui-egui/src/i18n/tr.tsv | 870 +++++++++++++++++++++++++++++++++ 1 file changed, 870 insertions(+) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index fd51400af..7294b3717 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1394,3 +1394,873 @@ menu View Görünüm # ArtCraft feature naming Additional Tools Ek Araçlar + (1, 2, 4, 8, 16, 32, 64, 128, or 256) (1, 2, 4, 8, 16, 32, 64, 128 veya 256) + 2D Wireframe 2B Tel Kafes + 3D Views 3B Görünümler + <Öteleme> +