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 01/43] 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 02/43] 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 03/43] 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 04/43] 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 05/43] 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 06/43] 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 07/43] 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 08/43] 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 09/43] 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 10/43] 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 11/43] 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 12/43] 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 13/43] 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 14/43] 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 15/43] 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 16/43] 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 17/43] 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 18/43] 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 19/43] 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 20/43] 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 21/43] 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 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 22/43] 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 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 23/43] 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 24/43] 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 25/43] 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 26/43] 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 0f40e91e825c5681b244f8c93680209eaf57c46b Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:43:00 -0600 Subject: [PATCH 27/43] io: dxf_anno reads main's borrowed DXF sections (SectionRef) Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_anno.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/io/src/dxf_anno.rs b/crates/io/src/dxf_anno.rs index 4bab1941b..619a3426f 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, MTextColumnType, Text, VAlign}; use cadcraft_geom::Vec3; -use craft_dxf::{Section, Tag}; +use craft_dxf::{SectionRef, Tag}; /// The context classes: (DXF record name, C++ class name). const TEXT: (&str, &str) = ("ACDB_TEXTOBJECTCONTEXTDATA_CLASS", "AcDbTextObjectContextData"); @@ -345,10 +345,10 @@ fn all_entries(tags: &[Tag]) -> Vec { /// 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) { +pub(crate) fn resolve(secs: &[SectionRef<'_>], 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| { + 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)); } @@ -361,7 +361,7 @@ pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { // 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| { + each_record(s.tags, |kind, tags| { if !matches!(kind, "TEXT" | "MTEXT" | "DIMENSION" | "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION") { return; } From 56dc8fb4101dc2f2fe43be7e7f746ffb4d24ab24 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:52:37 -0600 Subject: [PATCH 28/43] DXF writer: annotation scale planning in two helpers (main's tags_kept_for passed the complexity limit) Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_write/sections.rs | 61 +++++++++++++++++++---------- 1 file changed, 40 insertions(+), 21 deletions(-) diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 8c356cf31..259d12732 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -893,6 +893,44 @@ fn annotative_dimension_blocks( } /// The dimensions' anonymous blocks, and the blocks of each annotative dimension by scale (from +/// The scales annotative text, MText and dimensions support that the drawing's scale list lacks +/// (each context names its SCALE object, so they are added to the list written). +fn missing_anno_scales(d: &Drawing, all_spaces: &[&EntityStore]) -> Vec { + let mut extra: Vec = Vec::new(); + for e in all_spaces.iter().flat_map(|s| s.iter()).filter(|e| 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.iter().any(known) && extra.len() < cadcraft_doc::MAX_SCALES { + extra.push(s); + } + } + } + extra +} + +/// Plan the annotation scale contexts of annotative text, MText and dimensions: their objects in +/// `cx.anno`, and the extension dictionaries made for them in `w.xdicts`. +fn plan_anno_contexts( + d: &Drawing, + all_spaces: &[&EntityStore], + scales: &[(&cadcraft_doc::AnnoScale, String)], + anno_dim_blocks: &HashMap>, + w: &mut W, + cx: &mut Ctx, +) { + 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); + } + } +} + /// AutoCAD 2008, the 2007 format: `contexts`). fn dimension_block_definitions( d: &Drawing, @@ -1158,30 +1196,11 @@ pub(super) fn tags_kept_for( let scale_dict = w.h(); // 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 extra_scales = if contexts { missing_anno_scales(d, &all_spaces) } else { Vec::new() }; 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); - } - } + plan_anno_contexts(d, &all_spaces, &scales, &anno_dim_blocks, &mut w, &mut cx); } // Plot style names used by layers and objects (Normal always), each a placeholder object; in // a drawing of named plot styles also those of the layers of saved layer states, which name From 896fe05886d052428c9f165631b8fccc10fd0759 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:00:43 -0600 Subject: [PATCH 29/43] DXF: a block reference moved in elevation takes its contexts along, at their own heights block_contexts compared the reference with the one read in X and Y only, so a reference moved only in Z kept its contexts at their old heights; and any other change set every context's group 30 to the reference's Z, losing a context's own height. Z is part of the change check now, and each context keeps its offset from the reference as read, scaled with the reference's Z scale as X and Y follow theirs. FredApps on #1244. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 21 +++++++--- crates/io/tests/annotative_block_contexts.rs | 40 ++++++++++++++++++++ 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 9fe1430fa..d4ef99153 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -933,20 +933,29 @@ fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> 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]), + let (at0, z0, rot0, scale0) = match f.placements.get(&h) { + Some(p) => (p.insert.xy(), p.insert.z, 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)]) + ( + cadcraft_doc::geom::Vec2::new(x0, y0), + num(def, 30).unwrap_or(0.0), + 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); + // A move in elevation alone is a change too. + let unchanged = (ins.insert.xy() - at0).len() < 1e-9 + && (ins.insert.z - z0).abs() < 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; } @@ -961,11 +970,13 @@ fn block_contexts(f: &Foreign, d: &Drawing, owners: &HashMap) -> } _ => ins.insert.xy(), }; + // Its height above or below the reference as read is kept, scaled with it. + let z = num(c, 30).map_or(ins.insert.z, |cz| ins.insert.z + (cz - z0) * ratios[2].1); for t in &mut o.tags { let v = match t.code { 10 => Some(at.x), 20 => Some(at.y), - 30 => Some(ins.insert.z), + 30 => Some(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, diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/annotative_block_contexts.rs index 80eb8ad6b..ec96e7ebe 100644 --- a/crates/io/tests/annotative_block_contexts.rs +++ b/crates/io/tests/annotative_block_contexts.rs @@ -744,3 +744,43 @@ fn an_attribute_s_contexts_stay_when_the_reference_s_attributes_are_reordered() 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))]); } + +/// Each written block reference context's elevation (group 30), by scale name. +fn context_heights(text: &str) -> Vec<(String, 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 mut out: Vec<(String, f64)> = 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, 30).and_then(|v| v.parse::().ok()).unwrap_or(f64::NAN)) + }) + .collect(); + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +#[test] +fn a_reference_moved_only_in_elevation_takes_its_contexts_along_at_their_own_heights() { + // The 1:1 context 2 units above the reference, as read. + let src = FIXTURE.replace("10 10\n20 20\n30 0\n41 1\n", "10 10\n20 20\n30 2\n41 1\n"); + assert_ne!(src, FIXTURE); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let r = Handle::parse_hex("40").unwrap(); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.insert.z += 3.0; + } + }) + .unwrap(); + let written = write_dxf(&d); + let near = |h: &[(String, f64)], scale: &str, z: f64| h.iter().any(|(s, v)| s == scale && (v - z).abs() < 1e-9); + let h = context_heights(&written); + assert!(near(&h, "1:5", 3.0) && near(&h, "1:1", 5.0), "both rise by 3, the 1:1 one staying 2 above: {h:?}"); + // Saved and opened again, then saved unchanged: the heights stay. + let again = write_dxf(&read_dxf(written.as_bytes()).unwrap()); + let h = context_heights(&again); + assert!(near(&h, "1:5", 3.0) && near(&h, "1:1", 5.0), "{h:?}"); +} From f718f0f7f9b277b50a7bc1c02524bc6ecc98ca3c Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:58:58 -0600 Subject: [PATCH 30/43] Tests: the annotative block context tests join the io test binary (AGENTS.md rule 30) Co-Authored-By: Claude Opus 5.5 --- crates/io/tests/{ => it}/annotative_block_contexts.rs | 0 crates/io/tests/it/main.rs | 1 + 2 files changed, 1 insertion(+) rename crates/io/tests/{ => it}/annotative_block_contexts.rs (100%) diff --git a/crates/io/tests/annotative_block_contexts.rs b/crates/io/tests/it/annotative_block_contexts.rs similarity index 100% rename from crates/io/tests/annotative_block_contexts.rs rename to crates/io/tests/it/annotative_block_contexts.rs diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index c45a57658..c45dfed62 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -2,6 +2,7 @@ mod acad_interop; #[cfg(not(target_arch = "wasm32"))] mod acis_data_store; mod angle_header; +mod annotative_block_contexts; mod annotative_orientation; mod annotative_roundtrip; mod assoc_array_roundtrip; From 05530e5e96c3b7e6f08f50367409b13e4929c190 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:59:20 -0600 Subject: [PATCH 31/43] Tests: the annotative text context tests join the io test binary (AGENTS.md rule 30) Co-Authored-By: Claude Opus 5.5 --- crates/io/tests/{ => it}/annotative_text_contexts.rs | 0 crates/io/tests/it/main.rs | 1 + 2 files changed, 1 insertion(+) rename crates/io/tests/{ => it}/annotative_text_contexts.rs (100%) diff --git a/crates/io/tests/annotative_text_contexts.rs b/crates/io/tests/it/annotative_text_contexts.rs similarity index 100% rename from crates/io/tests/annotative_text_contexts.rs rename to crates/io/tests/it/annotative_text_contexts.rs diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index c45dfed62..12db80bff 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -5,6 +5,7 @@ mod angle_header; mod annotative_block_contexts; mod annotative_orientation; mod annotative_roundtrip; +mod annotative_text_contexts; mod assoc_array_roundtrip; mod assoc_dependency_prune; mod attdef_insert_dwg; From b076ec4c9fd1ce6f8e7e9a8f4ae5188a5e0e6fe5 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:43:44 -0600 Subject: [PATCH 32/43] DWG: block reference contexts and the block's annotative flag stay DXF-only until the bridge converts them The DWG bridge doesn't carry annotation scale contexts into a DWG yet (storytold/craft-libs#2005): the DWG reader read them back as zeros, a reference at scale 0 at its other scales. A save through the bridge now leaves the kept block reference and attribute contexts out, as before they were kept, and the block's AcadAnnotative flag too (without its references' contexts AutoCAD would scale them by the annotation scale once more). DXF keeps both. The DWG round-trip test that waited for craft-libs#2005 (ignored, a_reference_s_contexts_survive_dwg) is replaced by one that runs: a DWG save leaves the contexts out and the reference reads back at its own scale. The round trip of the contexts through DWG follows once the bridge converts them. FredApps on #1362 (rule 31). Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 41 ++++++++++++++++++- crates/io/src/dxf_write/sections.rs | 8 ++-- .../io/tests/it/annotative_block_contexts.rs | 34 +++++++-------- 3 files changed, 60 insertions(+), 23 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index d4ef99153..e0a82a4b8 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -1322,6 +1322,38 @@ fn reconcile( out } +/// The kept annotation scale context objects (each `AcDbContextDataManager` an extension +/// dictionary lists, and everything owned below it), by handle: what a DWG save leaves out. The +/// dictionaries that list them drop the entry when the manager isn't written. +fn kept_context_objects(f: &Foreign, own: &HashMap>) -> HashSet { + let mut managers: HashSet = HashSet::new(); + for o in f.objects.iter().filter(|o| is_dictionary(&o.kind)) { + for w in o.tags.windows(2) { + if let [k, v] = w + && k.code == 3 + && up(&k.value) == CONTEXTS_KEY + && matches!(v.code, 350 | 360) + { + managers.insert(norm(&v.value)); + } + } + } + let under = |h: &str| { + let mut cur = h.to_string(); + for _ in 0..MAX_DEPTH { + if managers.contains(&cur) { + return true; + } + match own.get(&cur).cloned().flatten() { + Some(o) => cur = o, + None => return false, + } + } + false + }; + f.objects.iter().map(|o| o.handle.hex()).filter(|h| under(h)).collect() +} + /// 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) { @@ -1749,6 +1781,7 @@ pub(crate) fn finish( modern: bool, target_modern: bool, strings: bool, + bridge: bool, ) -> HashSet { let f = d.foreign.as_ref(); let unknown = unknown_handles(d); @@ -1827,7 +1860,10 @@ pub(crate) fn finish( // Annotation scale contexts brought up to date follow owner chains by group 330, and give the // records they add an owner. let mut owners: HashMap = own.iter().filter_map(|(h, o)| Some((h.clone(), o.clone()?))).collect(); - let (contexts, rec) = refreshed_contexts(f, d, &mut owners, &roles, tags); + // The DWG bridge doesn't carry annotation scale contexts through to a DWG yet + // (storytold/craft-libs#2005): a DWG save leaves the kept block reference and attribute + // contexts out, as before they were kept. + let (contexts, rec) = if bridge { (HashMap::new(), Reconciled::default()) } else { refreshed_contexts(f, d, &mut owners, &roles, tags) }; for o in &rec.added { own.insert(o.handle.hex(), owners.get(&o.handle.hex()).cloned()); } @@ -1876,6 +1912,9 @@ pub(crate) fn finish( alive_memo }); alive_memo.extend(rec.dropped.iter().map(|h| (h.clone(), false))); + if bridge { + alive_memo.extend(kept_context_objects(f, &own).into_iter().map(|h| (h, false))); + } // Drop kept AcDbAssocDependency objects whose dependentOnObject is no longer written. Also drop // the kept objects whose owner, as [`owner_of`] finds it, is a dropped dependency. Leaving an // active dependency with its group 330 remapped to "0" breaks the associative reactor invariant. diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 19f00b1c8..993db299d 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -1213,12 +1213,14 @@ pub(super) fn tags_kept_for( w.s(340, layout.unwrap_or("0")); // User blocks: insertion units (70), explodability (280), uniform scaling (281) and // whether references are annotative (`AcadAnnotative` xdata: without it AutoCAD scales - // the references by their units instead of the annotation scale). + // the references by their units instead of the annotation scale). Not in a DWG yet: the + // bridge drops the references' contexts, and the flag alone would have AutoCAD scale them + // by the annotation scale once more (storytold/craft-libs#2005). if let Some(b) = blk { w.i(70, i64::from(b.units)); w.i(280, i64::from(b.explodable)); w.i(281, i64::from(b.scale_uniformly)); - if b.annotative { + if b.annotative && !bridge { annotative_xdata(w); } if let Some(a) = &b.array { @@ -1354,7 +1356,7 @@ pub(super) fn tags_kept_for( // no data store, so a solid whose geometry is only there is left out of it. // The DWG bridge keeps proxies in the DWG's own layout. let strings = bridge || version >= Version::R2007; - let kept = crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013, target >= Version::R2013, strings); + let kept = crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013, target >= Version::R2013, strings, bridge); // Kept constraint groups go in the order their reader expects: a DXF's own version. The // bridge's R2000 text is read as the version its kept groups came from when that is newer // (craft-dwg's `encode_kept_noted` declares it), so there they stay as read. diff --git a/crates/io/tests/it/annotative_block_contexts.rs b/crates/io/tests/it/annotative_block_contexts.rs index ec96e7ebe..545d8b7ba 100644 --- a/crates/io/tests/it/annotative_block_contexts.rs +++ b/crates/io/tests/it/annotative_block_contexts.rs @@ -418,28 +418,24 @@ fn kept_contexts(d: &Drawing) -> Vec<(f64, f64)> { d.foreign.objects.iter().filter(|o| o.kind == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS").map(|o| (num(o, 50), num(o, 41))).collect() } +/// A DWG save leaves the reference's contexts out, and the block's annotative flag with them: +/// the DWG bridge doesn't convert block reference contexts yet (storytold/craft-libs#2005), and +/// the flag without them would have AutoCAD scale the reference by the annotation scale once +/// more. The reference comes back at its own scale; DXF keeps both. #[cfg(not(target_arch = "wasm32"))] #[test] -#[ignore = "needs the DWG bridge's annotation context conversion (storytold/craft-libs#2005) in the pinned craft-dwg"] -fn a_reference_s_contexts_survive_dwg() { - // Turned 30° first, so the rotation's unit shows (DXF degrees, DWG radians). - let mut d = read(); +fn a_dwg_save_leaves_the_reference_s_contexts_out() { + cadcraft_io::dwg_worker::allow_in_process(); + let 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:?}"); - } + let scale = |d: &Drawing| match d.entity(r).map(|e| &e.kind) { + Some(cadcraft_doc::EntityKind::Insert(i)) => i.scale.x, + _ => f64::NAN, + }; + let back = cadcraft_io::read(&cadcraft_io::write(&d, "x.dwg").unwrap(), "x.dwg").unwrap(); + assert!(kept_contexts(&back).is_empty(), "{:?}", kept_contexts(&back)); + assert!((scale(&back) - scale(&d)).abs() < 1e-9, "{} vs {}", scale(&back), scale(&d)); + assert!(!kept_contexts(&read_dxf(write_dxf(&d).as_bytes()).unwrap()).is_empty(), "DXF keeps them"); } /// Every written ACDB_ANNOTATIONSCALES dictionary entry names a written context, and every From 91f1e0c0c0db5220cce04a777789c39de1330cd8 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:47:06 -0600 Subject: [PATCH 33/43] DWG: annotative text, MText and dimensions keep their scales in CADCraft's record until the bridge converts contexts A save through the DWG bridge writes no annotation scale contexts now: the bridge doesn't convert them yet (storytold/craft-libs#2005), so CADCraft's own record carries the scales, as for an older format. DXF from 2007 on writes the contexts as before. The DWG test that waited for craft-libs#2005 (ignored) now runs: the scales, paper height and rotation come back through DWG from the record, and the DWG holds no contexts. The contexts' own round trip through DWG follows with the bridge. FredApps on #1362 (rule 31). Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_write/sections.rs | 6 +++-- .../io/tests/it/annotative_text_contexts.rs | 26 +++++++------------ 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 5214ddd7f..effd13501 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -1223,8 +1223,10 @@ pub(super) fn tags_kept_for( let mut cx = Ctx { paper_views: paper_views(d), target, frozen_341, modern_table_values: !bridge && version >= Version::R2007, ..Ctx::default() }; cx.block_records = user_blocks.iter().map(|(n, h, _)| (n.to_ascii_uppercase(), h.clone())).collect(); let all_spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect(); - // Annotation scale contexts (from AutoCAD 2008, the 2007 format). - let contexts = target >= Version::R2007; + // Annotation scale contexts (from AutoCAD 2008, the 2007 format). Not through the DWG bridge + // yet, which doesn't convert them (storytold/craft-libs#2005): a DWG keeps CADCraft's own + // record of the scales instead, as an older format does. + let contexts = target >= Version::R2007 && !bridge; 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 diff --git a/crates/io/tests/it/annotative_text_contexts.rs b/crates/io/tests/it/annotative_text_contexts.rs index 0dd0131bc..39415bb54 100644 --- a/crates/io/tests/it/annotative_text_contexts.rs +++ b/crates/io/tests/it/annotative_text_contexts.rs @@ -647,12 +647,15 @@ fn hostile_contexts_do_not_panic() { } } +/// A DWG keeps the objects' scales in CADCraft's own record, not in AutoCAD's contexts: the DWG +/// bridge doesn't convert those yet (storytold/craft-libs#2005). The scales, the paper sizes and +/// a turned text's rotation come back; the contexts' round trip through DWG follows with the +/// bridge. #[cfg(not(target_arch = "wasm32"))] #[test] -#[ignore = "needs the DWG bridge's annotation context conversion (storytold/craft-libs#2005) in the pinned craft-dwg"] fn text_mtext_and_dimensions_keep_their_scales_through_dwg() { + cadcraft_io::dwg_worker::allow_in_process(); 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(); @@ -661,29 +664,18 @@ fn text_mtext_and_dimensions_keep_their_scales_through_dwg() { .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")] { + for kind in ["text", "mtext", "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 e = e.unwrap_or_else(|| panic!("{kind}")); 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 = craft_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:?}"); - } + let recs = records(&String::from_utf8_lossy(&dxf)); + assert!(!recs.iter().any(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")), "no contexts in the DWG"); } From d3a7097e9967c9f91cce5b2c98de911b60ebdc4e Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:49:17 -0600 Subject: [PATCH 34/43] Tests: the multileader's DWG round trip runs, through CADCraft's record The multileader DWG test that waited for craft-libs#2005 (ignored) now runs: its scales and paper text height come back through DWG from CADCraft's own record, and the DWG holds no multileader contexts. The contexts' round trip through DWG follows with the bridge. FredApps on #1362 (rule 31). Co-Authored-By: Claude Opus 5.5 --- crates/io/tests/it/annotative_text_contexts.rs | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/crates/io/tests/it/annotative_text_contexts.rs b/crates/io/tests/it/annotative_text_contexts.rs index 7da67261f..d7fb04991 100644 --- a/crates/io/tests/it/annotative_text_contexts.rs +++ b/crates/io/tests/it/annotative_text_contexts.rs @@ -746,10 +746,13 @@ fn a_multileader_gets_its_context_data_at_each_scale() { assert!((x.arrow_size - y.arrow_size).abs() < 1e-9 && (x.dogleg - y.dogleg).abs() < 1e-9, "{y:?}"); } +/// A multileader's scales come back through DWG from CADCraft's own record (the DWG bridge +/// doesn't convert contexts yet, storytold/craft-libs#2005), at its paper size; the DWG holds no +/// multileader contexts. #[cfg(not(target_arch = "wasm32"))] #[test] -#[ignore = "needs the DWG bridge's annotation context conversion (storytold/craft-libs#2005) in the pinned craft-dwg"] fn a_multileader_keeps_its_scales_through_dwg() { + cadcraft_io::dwg_worker::allow_in_process(); let (d, _) = with_mleader(); let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); @@ -758,19 +761,8 @@ fn a_multileader_keeps_its_scales_through_dwg() { 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(&craft_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]); + assert!(!records(&text).iter().any(|(k, _)| k == "ACDB_MLEADEROBJECTCONTEXTDATA_CLASS"), "no contexts in the DWG"); } /// The fixture with AutoCAD's variable dictionary naming 1:10 as the current annotation scale. From c12a1c12cad6d6a23309df2b619d7fac162c8283 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:05:25 -0600 Subject: [PATCH 35/43] DXF writer: the DWG bridge's context choice in contexts_for (finish passed the complexity limit) Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index e0a82a4b8..2bbb2ff72 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -1459,6 +1459,23 @@ fn refreshed_contexts( (contexts, rec) } +/// The kept annotation scale contexts as [`finish`] writes them: brought up to date +/// ([`refreshed_contexts`]), or for the DWG bridge, which doesn't carry them into a DWG yet +/// (storytold/craft-libs#2005), all of them dropped, as before they were kept. +fn contexts_for( + f: &Foreign, + d: &Drawing, + (owners, own): (&mut HashMap, &HashMap>), + roles: &HashMap, + tags: &[Tag], + bridge: bool, +) -> (HashMap, Reconciled) { + if bridge { + return (HashMap::new(), Reconciled { dropped: kept_context_objects(f, own), ..Reconciled::default() }); + } + refreshed_contexts(f, d, owners, roles, tags) +} + fn written_records(tags: &[Tag]) -> Vec { let mut out: Vec = Vec::new(); let mut sec = String::new(); @@ -1860,10 +1877,7 @@ pub(crate) fn finish( // Annotation scale contexts brought up to date follow owner chains by group 330, and give the // records they add an owner. let mut owners: HashMap = own.iter().filter_map(|(h, o)| Some((h.clone(), o.clone()?))).collect(); - // The DWG bridge doesn't carry annotation scale contexts through to a DWG yet - // (storytold/craft-libs#2005): a DWG save leaves the kept block reference and attribute - // contexts out, as before they were kept. - let (contexts, rec) = if bridge { (HashMap::new(), Reconciled::default()) } else { refreshed_contexts(f, d, &mut owners, &roles, tags) }; + let (contexts, rec) = contexts_for(f, d, (&mut owners, &own), &roles, tags, bridge); for o in &rec.added { own.insert(o.handle.hex(), owners.get(&o.handle.hex()).cloned()); } @@ -1912,9 +1926,6 @@ pub(crate) fn finish( alive_memo }); alive_memo.extend(rec.dropped.iter().map(|h| (h.clone(), false))); - if bridge { - alive_memo.extend(kept_context_objects(f, &own).into_iter().map(|h| (h, false))); - } // Drop kept AcDbAssocDependency objects whose dependentOnObject is no longer written. Also drop // the kept objects whose owner, as [`owner_of`] finds it, is a dropped dependency. Leaving an // active dependency with its group 330 remapped to "0" breaks the associative reactor invariant. From 02461788e6127f7992d932d10b08b81d431c2f15 Mon Sep 17 00:00:00 2001 From: Moritz Boelling <131036780+mbolling@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:51:34 +0000 Subject: [PATCH 36/43] PDF plots write a filled primitive as the outline of its triangles, not one subpath per triangle (#3459) (#3614) A solid hatch, wide polyline, wipeout mask or filled glyph reached the PDF writer as a triangle list, and each triangle became its own closed subpath. The writer now cancels edges that two triangles share in opposite directions and chains what is left into closed loops, written as one nonzero fill. The winding number at every point depends only on the net directed edges, so the filled area is the same for overlapping, mixed- orientation, zero-area and T-junction triangles; vertices are matched by the exact bits of the f32 coordinates written. O(n log n) time, O(n) memory, no recursion. For a 400-vertex solid hatch with a square island the page content stream goes from 30,086 to 9,922 bytes (457 to 3 subpaths) and the compressed file from 5,874 to 4,223 bytes. Co-authored-by: Claude Opus 5.5 --- crates/io/src/pdf.rs | 11 +- crates/io/src/pdf/outline.rs | 202 +++++++++++++++++++++++++ crates/io/tests/it/main.rs | 1 + crates/io/tests/it/pdf_fill_outline.rs | 89 +++++++++++ 4 files changed, 299 insertions(+), 4 deletions(-) create mode 100644 crates/io/src/pdf/outline.rs create mode 100644 crates/io/tests/it/pdf_fill_outline.rs diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 7fed3ce9a..e97f81a64 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -36,6 +36,7 @@ use kr::text::{GlyphId, KrillaGlyph}; use crate::{IoError, Result}; mod fonts; +mod outline; /// PDF points per millimetre. const PT_PER_MM: f64 = 72.0 / 25.4; @@ -867,7 +868,7 @@ fn krilla_failure(e: KrillaError) -> Failure { /// transparent primitive is stroked on its own (one path is painted once), so where /// primitives overlap they build up, as in PNG plots and on screen. Block contents and /// viewport contents share their reference's handle, so this goes by primitive, not by object. -/// Each filled primitive is one path of its triangles. +/// Each filled primitive is one path: the outline of its triangles. /// /// Primitives that stand for a glyph in an embeddable font (see [`fonts::Fonts`]) are written /// as text instead: the glyph at font size 1 under its glyph matrix (the matrix axes are one @@ -983,14 +984,16 @@ fn stroke_run(s: &mut Surface<'_>, batch: &mut Option<(StrokeStyle, PathBuilder) } } -/// Fill a set of triangles, clipped to the plot area. +/// Fill a set of triangles, clipped to the plot area, as the loops of their outline (see +/// [`outline`]), which fill the same as the triangles with far less path data. fn fill_tris(s: &mut Surface<'_>, p: &SheetPage, raw: &[Vec2], rgb: Rgb, t: u8) { let mapped: Vec = raw.iter().map(|q| p.map.pt(*q)).collect(); // With a vertex out of range, keep the parts inside the plot area. let tris = if mapped.iter().all(|q| coord(*q).is_some()) { mapped } else { clip::clip_triangles(&mapped, &p.clip_pt) }; + let tris: Vec<[outline::Pt; 3]> = tris.as_chunks::<3>().0.iter().filter_map(|[a, b, c]| Some([coord(*a)?, coord(*b)?, coord(*c)?])).collect(); + let rings = outline::loops(&tris).unwrap_or_else(|| tris.iter().map(|t| t.to_vec()).collect()); let mut pb = PathBuilder::new(); - for tri in tris.as_chunks::<3>().0 { - let Some(v) = tri.iter().map(|q| coord(*q)).collect::>>() else { continue }; + for v in &rings { for (j, (x, y)) in v.iter().enumerate() { if j == 0 { pb.move_to(*x, *y); diff --git a/crates/io/src/pdf/outline.rs b/crates/io/src/pdf/outline.rs new file mode 100644 index 000000000..91b32dded --- /dev/null +++ b/crates/io/src/pdf/outline.rs @@ -0,0 +1,202 @@ +//! The outline of a set of filled triangles: closed loops that fill, under the nonzero rule, +//! exactly what the triangles fill as one path of one subpath each. +//! +//! A filled path's nonzero winding number at a point is the sum, over its directed edges, of +//! the crossings of a ray from the point. So it depends only on how many times each directed +//! edge occurs, less the times it occurs reversed. An edge shared by two neighbouring +//! triangles in opposite directions cancels, and so does a zero-length edge. What is left +//! enters each vertex as often as it leaves it (each triangle does, and a cancelled pair takes +//! one entry and one exit from both its ends), so it splits into closed loops, and any such +//! split winds the same as the triangles everywhere off the edges. This holds for overlapping +//! triangles, mixed orientations, zero-area triangles and T-junctions alike: edges that do not +//! pair stay in the outline, which is then larger but still fills the same. +//! +//! Vertices are matched by the exact bits of the `f32` coordinates that are written, never by a +//! tolerance, so two distinct written points are never merged. + +/// A written vertex. +pub(super) type Pt = (f32, f32); + +/// The bits of a vertex, the key it is matched by. +fn key(p: Pt) -> u64 { + (u64::from(p.0.to_bits()) << 32) | u64::from(p.1.to_bits()) +} + +/// The loops (each closed back to its first vertex) whose nonzero fill is that of `tris`, or +/// `None` when they cannot be traced (which the reasoning above rules out; the caller then +/// writes the triangles). Time is `O(n log n)` and memory `O(n)` in the triangle count. +pub(super) fn loops(tris: &[[Pt; 3]]) -> Option>> { + let mut keys: Vec = tris.iter().flatten().map(|p| key(*p)).collect(); + keys.sort_unstable(); + keys.dedup(); + let pts: Vec = keys.iter().map(|k| (f32::from_bits((k >> 32) as u32), f32::from_bits(*k as u32))).collect(); + let id = |p: &Pt| keys.binary_search(&key(*p)).ok().and_then(|i| u32::try_from(i).ok()); + // Each edge as (lower id, higher id, +1 when it runs from the lower to the higher). + let mut undirected: Vec<(u32, u32, i8)> = Vec::with_capacity(tris.len().saturating_mul(3)); + for t in tris { + let v = [id(&t[0])?, id(&t[1])?, id(&t[2])?]; + for (a, b) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])] { + match a.cmp(&b) { + std::cmp::Ordering::Less => undirected.push((a, b, 1)), + std::cmp::Ordering::Greater => undirected.push((b, a, -1)), + std::cmp::Ordering::Equal => {} + } + } + } + undirected.sort_unstable_by_key(|e| (e.0, e.1)); + // What is left of each edge once opposite directions cancel, by start vertex. + let mut edges: Vec<(u32, u32)> = Vec::new(); + for run in undirected.chunk_by(|x, y| (x.0, x.1) == (y.0, y.1)) { + let Some(&(a, b, _)) = run.first() else { continue }; + let net: i64 = run.iter().map(|e| i64::from(e.2)).sum(); + let e = if net > 0 { (a, b) } else { (b, a) }; + edges.extend(std::iter::repeat_n(e, usize::try_from(net.unsigned_abs()).ok()?)); + } + drop(undirected); + edges.sort_unstable(); + // `next[v]..end[v]`: the unused edges leaving vertex `v`. + let mut end = vec![0usize; pts.len()]; + for e in &edges { + *end.get_mut(e.0 as usize)? += 1; + } + let mut next = vec![0usize; pts.len()]; + let mut at = 0usize; + for (n, e) in next.iter_mut().zip(end.iter_mut()) { + *n = at; + at += *e; + *e = at; + } + let mut out = Vec::new(); + for start in 0..pts.len() { + while next.get(start)? < end.get(start)? { + // Follow unused edges from `start` until one leads back to it. Each step uses an + // edge, so this ends; balance means only `start` can be left with no edge out. + let mut ring = vec![*pts.get(start)?]; + let mut cur = start; + loop { + let i = *next.get(cur)?; + if i >= *end.get(cur)? { + return None; + } + *next.get_mut(cur)? += 1; + let to = edges.get(i)?.1 as usize; + if to == start { + break; + } + ring.push(*pts.get(to)?); + cur = to; + } + out.push(ring); + } + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Fill paths of one subpath per closed ring with the nonzero rule, as a PDF viewer would. + /// Aliased, so a pixel is filled exactly when the winding at its sample point is nonzero; + /// with anti-aliasing, coverage sums along the triangles' inner edges round differently by + /// a level in a few pixels. + fn raster(rings: &[Vec]) -> Vec { + let mut pb = tiny_skia::PathBuilder::new(); + for r in rings { + for (j, (x, y)) in r.iter().enumerate() { + if j == 0 { + pb.move_to(*x, *y); + } else { + pb.line_to(*x, *y); + } + } + pb.close(); + } + let mut pm = tiny_skia::Pixmap::new(64, 64).unwrap(); + if let Some(path) = pb.finish() { + let mut paint = tiny_skia::Paint::default(); + paint.set_color_rgba8(0, 0, 0, 255); + paint.anti_alias = false; + pm.fill_path(&path, &paint, tiny_skia::FillRule::Winding, tiny_skia::Transform::identity(), None); + } + pm.data().to_vec() + } + + fn soup(tris: &[[Pt; 3]]) -> Vec> { + tris.iter().map(|t| t.to_vec()).collect() + } + + fn vertices(rings: &[Vec]) -> usize { + rings.iter().map(Vec::len).sum() + } + + /// A fan of a regular polygon around its centre, `n` triangles. + fn fan(c: Pt, r: f32, n: usize, ccw: bool) -> Vec<[Pt; 3]> { + let p = |i: usize| { + let a = std::f32::consts::TAU * (i % n) as f32 / n as f32; + (c.0 + r * a.cos(), c.1 + r * a.sin()) + }; + (0..n).map(|i| if ccw { [c, p(i), p(i + 1)] } else { [c, p(i + 1), p(i)] }).collect() + } + + /// The outline fills the same pixels as the triangles, and is no larger. + fn same_fill(tris: &[[Pt; 3]]) -> Vec> { + let rings = loops(tris).expect("traced"); + let (a, b) = (raster(&rings), raster(&soup(tris))); + let differ = a.iter().zip(&b).filter(|(x, y)| x != y).count(); + assert_eq!(differ, 0, "{rings:?}"); + assert!(vertices(&rings) <= 3 * tris.len()); + rings + } + + #[test] + fn a_fan_becomes_its_rim() { + let tris = fan((32.0, 32.0), 25.0, 40, true); + let rings = same_fill(&tris); + assert_eq!(rings.len(), 1); + assert!(vertices(&rings) < tris.len() + 1, "{} vertices for {} triangles", vertices(&rings), tris.len()); + } + + #[test] + fn a_ring_with_a_hole_keeps_the_hole() { + // A square annulus: outer 8..56, hole 24..40, as eight triangles. + let (o0, o1, i0, i1) = (8.0, 56.0, 24.0, 40.0); + let q = |a: Pt, b: Pt, c: Pt, d: Pt| [[a, b, c], [a, c, d]]; + let mut tris = Vec::new(); + tris.extend(q((o0, o0), (o1, o0), (i1, i0), (i0, i0))); + tris.extend(q((o1, o0), (o1, o1), (i1, i1), (i1, i0))); + tris.extend(q((o1, o1), (o0, o1), (i0, i1), (i1, i1))); + tris.extend(q((o0, o1), (o0, o0), (i0, i0), (i0, i1))); + let rings = same_fill(&tris); + assert_eq!(rings.len(), 2, "{rings:?}"); + let centre = raster(&rings)[(32 * 64 + 32) * 4 + 3]; + assert_eq!(centre, 0, "the hole stays empty"); + } + + #[test] + fn mixed_orientations_overlaps_degenerates_and_t_junctions_fill_the_same() { + let mut tris = fan((20.0, 20.0), 15.0, 12, true); + // Overlapping, the other way round: where they overlap the windings cancel. + tris.extend(fan((34.0, 30.0), 15.0, 9, false)); + // The same triangle twice. + tris.push([(40.0, 40.0), (60.0, 42.0), (50.0, 60.0)]); + tris.push([(40.0, 40.0), (60.0, 42.0), (50.0, 60.0)]); + // A T-junction: one big triangle beside two that split its edge. + tris.push([(2.0, 50.0), (2.0, 62.0), (14.0, 56.0)]); + tris.push([(2.0, 50.0), (-4.0, 53.0), (2.0, 56.0)]); + tris.push([(2.0, 56.0), (-4.0, 59.0), (2.0, 62.0)]); + // Zero-area triangles: collinear, and with a repeated vertex. + tris.push([(5.0, 5.0), (10.0, 10.0), (15.0, 15.0)]); + tris.push([(30.0, 5.0), (30.0, 5.0), (40.0, 8.0)]); + // Vertices a rounding step apart are not merged. + tris.push([(50.0, 10.0), (60.0, 10.0), (55.0, 20.0)]); + tris.push([(60.0, 10.0), (50.0, 10.000_001), (55.0, 2.0)]); + same_fill(&tris); + } + + #[test] + fn nothing_in_nothing_out() { + assert_eq!(loops(&[]), Some(Vec::new())); + assert_eq!(loops(&[[(1.0, 1.0); 3]]), Some(Vec::new())); + } +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 5d6bacd8d..ba9165f73 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -77,6 +77,7 @@ mod ole2frame_roundtrip; mod ole_frame; mod paperview_marker; mod passthrough_image_roundtrip; +mod pdf_fill_outline; mod pdf_followups; mod pdf_import; mod pdf_layers; diff --git a/crates/io/tests/it/pdf_fill_outline.rs b/crates/io/tests/it/pdf_fill_outline.rs new file mode 100644 index 000000000..ebd15e3bf --- /dev/null +++ b/crates/io/tests/it/pdf_fill_outline.rs @@ -0,0 +1,89 @@ +//! A solid fill is plotted to PDF as the outline of its triangles (#3459): far less path data, +//! the same filled area, islands still empty. + +use cadcraft_doc::{Common, Drawing, EntityKind, Hatch, HatchLoop, Space}; +use cadcraft_geom::{PolyVertex, Vec2}; +use cadcraft_io::plotter; +use serde_json::json; + +/// Vertices of the outer boundary. +const RIM: usize = 400; +/// Radius of the outer boundary. +const R: f64 = 100.0; +/// Half the width of the square island. +const HALF: f64 = 20.0; + +fn ring(points: impl Iterator, outer: bool) -> HatchLoop { + HatchLoop { vertices: points.map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(), outer, boundary_flags: None, sources: Vec::new() } +} + +/// A solid hatch: a many-sided outer loop around a square island. +fn drawing() -> Drawing { + let rim = (0..RIM).map(|i| { + let a = std::f64::consts::TAU * i as f64 / RIM as f64; + (R * a.cos(), R * a.sin()) + }); + let island = [(-HALF, -HALF), (HALF, -HALF), (HALF, HALF), (-HALF, HALF)].into_iter(); + let hatch = Hatch { + pattern: "SOLID".into(), + solid: true, + loops: vec![ring(rim, true), ring(island, false)], + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + }; + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch)).unwrap(); + d +} + +#[test] +fn a_solid_hatch_plots_as_its_outline_with_the_island_empty() { + let bytes = plotter::plot(&drawing(), &Space::Model, &json!({"paper": "A4", "compress": false})).unwrap(); + let doc = crate::pdf_read::read(&bytes); + let drawn = crate::pdf_read::drawn(doc.content()); + let fills = drawn.iter().filter(|o| o.op == "f").count(); + assert_eq!(fills, 1, "one fill for the hatch"); + let path: Vec<&crate::pdf_read::Op> = drawn.iter().filter(|o| matches!(o.op.as_str(), "m" | "l")).collect(); + // The triangles of a fill around an island number at least its boundary vertices; one + // subpath per triangle would give that many `m` and twice as many `l`. + let subpaths = path.iter().filter(|o| o.op == "m").count(); + assert!(subpaths < RIM / 10, "{subpaths} subpaths for {RIM} boundary vertices"); + assert!(path.len() < 2 * RIM, "{} path vertices for {RIM} boundary vertices", path.len()); + + // Fill the path as a viewer does and compare with the shape. + let mut pb = tiny_skia::PathBuilder::new(); + let (mut lo, mut hi) = ((f32::MAX, f32::MAX), (f32::MIN, f32::MIN)); + for o in &path { + let (x, y) = (o.nums[0] as f32, o.nums[1] as f32); + (lo, hi) = ((lo.0.min(x), lo.1.min(y)), (hi.0.max(x), hi.1.max(y))); + if o.op == "m" { + pb.close(); + pb.move_to(x, y); + } else { + pb.line_to(x, y); + } + } + pb.close(); + let size = 400u32; + let k = size as f32 / (hi.0 - lo.0).max(hi.1 - lo.1); + let mut pm = tiny_skia::Pixmap::new(size, size).unwrap(); + let mut paint = tiny_skia::Paint::default(); + paint.set_color_rgba8(0, 0, 0, 255); + let to_px = tiny_skia::Transform::from_row(k, 0.0, 0.0, k, -lo.0 * k, -lo.1 * k); + pm.fill_path(&pb.finish().unwrap(), &paint, tiny_skia::FillRule::Winding, to_px, None); + let alpha = |fx: f64, fy: f64| pm.pixel((fx * f64::from(size)) as u32, (fy * f64::from(size)) as u32).unwrap().alpha(); + assert_eq!(alpha(0.5, 0.5), 0, "the island is empty"); + assert_eq!(alpha(0.5 + 0.3, 0.5), 255, "the ring between island and rim is filled"); + assert_eq!(alpha(0.03, 0.03), 0, "outside the rim is empty"); + // The filled share of the bounding square matches the ring's. + let covered: f64 = pm.pixels().iter().map(|p| f64::from(p.alpha()) / 255.0).sum::() / f64::from(size * size); + let want = (std::f64::consts::PI * R * R - 4.0 * HALF * HALF) / (4.0 * R * R); + assert!((covered - want).abs() < 0.01, "covered {covered}, the ring covers {want}"); +} From 0590499adc41bf329eefdc60bcb5837a3b5715f9 Mon Sep 17 00:00:00 2001 From: vantruong-dang Date: Tue, 1 Dec 2026 16:52:55 +0700 Subject: [PATCH 37/43] fix(io): apply SPATIAL_FILTER boundary transform to preserve pasted XCLIPs (#2922) * test(io): cover non-identity XCLIP filter transform * fix(io): apply SPATIAL_FILTER boundary transform to clip vertices * test(io): add DXF and DWG round-trip coverage for transformed XCLIP boundaries * docs(io): document SPATIAL_FILTER matrix semantics and cover rotation/scale * fix(io): invert boundary transform matrix per Autodesk DXF spec * docs(io): annotate SPATIAL_FILTER group 40 translation indices in integration test * fix(io): reject sheared boundary transforms to preserve foreign data * fix(io): use scale-independent orthogonality check for boundary transforms * fix(io): expand rotated 2-corner boundary_xf clips and add docstrings * test(io): verify rotated 2-corner boundary expansion across 30/45/60/90 degrees * fix(io): expand 2-corner clips on any rotated net transform and align rotated writer * test(io): cover rotated+inverted 2-point XCLIP round-trip * fix(io): use pure rotation boundary_xf for rotated 2-point clips to support non-uniform scale * fix(io): canonicalize 2-point SPATIAL_FILTER corners in boundary space * fix(io): read DWG through the shared DXF bridge in the XCLIP test --------- Co-authored-by: vantruong-dang --- crates/io/src/dxf_clip.rs | 316 ++++++++++++++++++++++++-- crates/io/tests/it/xclip_roundtrip.rs | 274 ++++++++++++++++++++++ 2 files changed, 569 insertions(+), 21 deletions(-) diff --git a/crates/io/src/dxf_clip.rs b/crates/io/src/dxf_clip.rs index 5e239e85c..a50f4d602 100644 --- a/crates/io/src/dxf_clip.rs +++ b/crates/io/src/dxf_clip.rs @@ -3,7 +3,8 @@ //! The filter holds the boundary vertices in the reference's coordinates (group 70 the count, //! 10/20 the vertices), whether clipping is on (71), the front and back clip (72/73, 40/41) and //! two 3×4 matrices (group 40, row by row): the inverse of the reference's transform, which takes -//! the boundary into the block's coordinates, and the boundary's own transform (identity here). +//! the boundary into the block's coordinates, and the boundary's own transform (composed with +//! the inverse transform when non-identity, e.g. on clipboard-pasted block references). //! //! An inverted clip ("Invert clip") is marked as the reference app writes it in a file: the //! filter has an extension dictionary whose `ACAD_XREC_ROUNDTRIP` entry is an XRECORD holding @@ -15,7 +16,7 @@ //! written. The record goes through DWG as it is. //! //! Reading takes the planar filters the model can hold out of the kept foreign data and puts them -//! on the references ([`read`]); others (front/back clipping, a skewed boundary transform) stay +//! on the references ([`read`]); others (front/back clipping, non-planar extrusion, sheared boundary transform) stay //! foreign and are written back untouched. Writing adds the dictionaries and the filter of every //! clipped reference to a copy of the drawing's foreign data ([`prepare`]), which the raw-data //! writer (#528) then places on the reference. @@ -164,9 +165,22 @@ fn roundtrip(f: &Foreign, idx: &Index, filter: &ForeignObject) -> Option= 2).then_some(boundary) } -/// The boundary a planar SPATIAL_FILTER holds, in the block's coordinates; with `boundary`, the -/// clip is inverted and that is its outline (in the filter's coordinates). `None` for anything -/// the model can't hold as it is (it then stays foreign). +/// The boundary a planar SPATIAL_FILTER holds, in the block's coordinates. +/// +/// Per the Autodesk DXF Reference for `SPATIAL_FILTER`: +/// - Group 40 (first 12 values): 3×4 matrix representing the inverse of the block reference +/// transformation (maps coordinates from WCS to block local space). +/// - Group 40 (second 12 values): 3×4 matrix representing the transformation into the coordinate +/// system of the clip boundary ($WCS \to \text{Boundary}$). +/// +/// Since boundary vertices (group 10/20) are stored in the clip boundary's coordinate system, +/// transforming them into the block's local coordinates requires inverting the boundary transform +/// ($\text{Boundary} \to WCS$) and then applying the inverse block transform ($WCS \to \text{Block}$): +/// $P_{\text{block}} = M_{\text{inverse}} \times (M_{\text{boundary\_xf}})^{-1} \times P_{\text{boundary}}$. +/// In code: `boundary_xf.inverse()?.then(inverse)`. +/// +/// With `boundary`, the clip is inverted and that is its outline (in the filter's coordinates). +/// Returns `None` for unsupported configurations (e.g. non-planar extrusion, front/back clipping depth). fn parse_filter(o: &ForeignObject, boundary: Option<&[Vec2]>) -> Option { let count = usize::try_from(number(&o.tags, 70)? as i64).ok()?; if !(2..=MAX_CLIP_VERTICES).contains(&count) { @@ -180,30 +194,47 @@ fn parse_filter(o: &ForeignObject, boundary: Option<&[Vec2]>) -> Option = o.tags.iter().filter(|t| t.code == 40).map(|t| t.value.trim().parse::().unwrap_or(f64::NAN)).collect(); - let (inverse, own) = match m.len() { + let (inverse, boundary_xf) = match m.len() { 24 => (matrix_2d(m.get(..12)?)?, matrix_2d(m.get(12..)?)?), // Without matrices the vertices are taken as the block's own. 0 => (Mat3::IDENTITY, Mat3::IDENTITY), _ => return None, }; - if (own.a - 1.0).abs() > 1e-9 - || own.b.abs() > 1e-9 - || own.c.abs() > 1e-9 - || (own.d - 1.0).abs() > 1e-9 - || own.e.abs() > 1e-9 - || own.f.abs() > 1e-9 - { + // Reject sheared/skewed boundary transforms that cannot be losslessly represented. + // Scale-independent orthogonality check: |u . v| > 1e-4 * |u| * |v| + let u_len = (boundary_xf.a * boundary_xf.a + boundary_xf.b * boundary_xf.b).sqrt(); + let v_len = (boundary_xf.c * boundary_xf.c + boundary_xf.d * boundary_xf.d).sqrt(); + if u_len <= 1e-9 || v_len <= 1e-9 { return None; } - let own = vertices(&o.tags, count)?; - let outline = boundary.unwrap_or(&own); - if !(2..=MAX_CLIP_VERTICES).contains(&outline.len()) { + let dot = boundary_xf.a * boundary_xf.c + boundary_xf.b * boundary_xf.d; + if dot.abs() > 1e-4 * u_len * v_len { return None; } - let points: Vec = outline.iter().map(|p| inverse.apply(*p)).collect(); + let verts = vertices(&o.tags, count)?; + let raw_outline = boundary.unwrap_or(&verts); + if !(2..=MAX_CLIP_VERTICES).contains(&raw_outline.len()) { + return None; + } + let net = boundary_xf.inverse()?.then(inverse); + // Expand a 2-corner rectangle to 4 corners whenever the net transform from boundary space + // to block space introduces rotation, preserving its rotated orientation in block space. + let rotated_rect; + let net_rotated = net.b.abs() > 1e-9 || net.c.abs() > 1e-9; + let outline = match raw_outline { + [a, b] if net_rotated => { + rotated_rect = vec![*a, Vec2::new(b.x, a.y), *b, Vec2::new(a.x, b.y)]; + &rotated_rect[..] + } + other => other, + }; + let mut points: Vec = outline.iter().map(|p| net.apply(*p)).collect(); if !points.iter().all(|p| p.is_finite()) { return None; } + if let [a, b] = points.as_slice() { + points = vec![Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y))]; + } let inverted = boundary.is_some() || number(&o.tags, 290).is_some_and(|v| v != 0.0); let clip = ClipBoundary { points, enabled: number(&o.tags, 71).unwrap_or(1.0) != 0.0, inverted }; cadcraft_render::clip::PolyClip::new(&clip.polygon()).is_some().then_some(clip) @@ -318,6 +349,25 @@ fn dictionary(h: Handle, owner: Handle) -> ForeignObject { } } +/// The boundary transform (`boundary_xf`) and boundary-space vertices for `clip`. +/// +/// A 2-vertex `SPATIAL_FILTER` defines an axis-aligned rectangle in `boundary_xf` space, with +/// vertices ordered lower-left then upper-right per the DXF specification. When the reference is +/// rotated, a 2-point block-space rectangle is axis-aligned in a frame rotated by +/// `-to_world.rotation()` (orthogonal even under non-uniform or mirrored scale), and the two +/// transformed corners are canonicalized to `(min_x, min_y)` then `(max_x, max_y)` in that +/// boundary frame. Polyline boundaries (`len > 2`) keep their transformed vertex order. +fn filter_geometry(clip: &ClipBoundary, to_world: &Mat3) -> (Mat3, Vec) { + let block_space_rect = clip.points.len() == 2 && (to_world.b.abs() > 1e-9 || to_world.c.abs() > 1e-9); + let boundary_xf = if block_space_rect { Mat3::rotate(-to_world.rotation()) } else { Mat3::IDENTITY }; + let pts_xf = to_world.then(boundary_xf); + let mut points: Vec = clip.points.iter().map(|p| pts_xf.apply(*p)).collect(); + if let [a, b] = points.as_slice() { + points = vec![Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y))]; + } + (boundary_xf, points) +} + /// The SPATIAL_FILTER of `clip`; `xdict` is its extension dictionary (an inverted clip's). /// No group 290: the reference app discards a file whose filter has one. fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3, inverse: &Mat3, xdict: Option) -> ForeignObject { @@ -326,14 +376,14 @@ fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3 tags.extend([raw(102, "{ACAD_XDICTIONARY"), raw(360, x.hex()), raw(102, "}")]); } tags.extend([raw(330, owner.hex()), raw(100, "AcDbFilter"), raw(100, "AcDbSpatialFilter"), raw(70, clip.points.len())]); - for p in &clip.points { - let q = to_world.apply(*p); + let (boundary_xf, points) = filter_geometry(clip, to_world); + for q in points { tags.push(raw(10, q.x)); tags.push(raw(20, q.y)); } tags.extend([raw(210, 0.0), raw(220, 0.0), raw(230, 1.0), raw(11, 0.0), raw(21, 0.0), raw(31, 0.0)]); tags.extend([raw(71, i32::from(clip.enabled)), raw(72, 0), raw(73, 0)]); - for v in matrix_values(inverse).into_iter().chain(matrix_values(&Mat3::IDENTITY)) { + for v in matrix_values(inverse).into_iter().chain(matrix_values(&boundary_xf)) { tags.push(raw(40, v)); } ForeignObject { handle: h, kind: "SPATIAL_FILTER".into(), tags } @@ -417,7 +467,7 @@ pub(crate) fn prepare(d: &Drawing) -> Option { let mut own = dictionary(x, sf); own.tags.extend([raw(3, ROUNDTRIP_KEY), raw(360, r.hex())]); add(own); - let world: Vec = clip.points.iter().map(|p| to_world.apply(*p)).collect(); + let (_, world) = filter_geometry(&clip, &to_world); add(roundtrip_record(r, x, &world)); } } @@ -548,4 +598,228 @@ mod tests { assert!(parse_filter(&filter, None).is_none(), "{count}"); } } + + /// Builds a mock SPATIAL_FILTER [`ForeignObject`] with a 10×10 rectangle boundary: + /// (0,0), (10,0), (10,10), (0,10). + fn make_test_filter(inverse: &Mat3, own: &Mat3) -> ForeignObject { + let mut tags = vec![ + raw(100, "AcDbFilter"), + raw(100, "AcDbSpatialFilter"), + raw(70, 4), + raw(10, 0.0), + raw(20, 0.0), + raw(10, 10.0), + raw(20, 0.0), + raw(10, 10.0), + raw(20, 10.0), + raw(10, 0.0), + raw(20, 10.0), + raw(210, 0.0), + raw(220, 0.0), + raw(230, 1.0), + raw(71, 1), + raw(72, 0), + raw(73, 0), + ]; + for v in matrix_values(inverse).into_iter().chain(matrix_values(own)) { + tags.push(raw(40, v)); + } + ForeignObject { handle: Handle(0x100), kind: "SPATIAL_FILTER".into(), tags } + } + + /// Baseline check: verifies `parse_filter` accepts filters where the boundary matrix is identity. + #[test] + fn parse_filter_accepts_identity_boundary_transform() { + // Baseline: parse_filter accepts filters where the second matrix is Identity. + let filter = make_test_filter(&Mat3::IDENTITY, &Mat3::IDENTITY); + let parsed = parse_filter(&filter, None); + assert!(parsed.is_some(), "Baseline filter with identity own matrix must be accepted"); + } + + /// Regression test: verifies `parse_filter` preserves filters with a non-identity translation matrix. + #[test] + fn parse_filter_preserves_non_identity_boundary_transform() { + // WHY: + // SPATIAL_FILTER can contain two transformation matrices. + // parse_filter previously rejected every non-identity `own` matrix, + // causing an otherwise valid clipping definition to be discarded. + // + // Matrix 2 transforms WCS into boundary coordinates; its inverse transforms + // boundary coordinates into WCS, mapping (0..10, 0..10) shifted by (-100, -50). + + let inverse = Mat3::IDENTITY; + let own = Mat3::translate(Vec2::new(100.0, 50.0)); + + let filter = make_test_filter(&inverse, &own); + let parsed = parse_filter(&filter, None); + + assert!(parsed.is_some(), "A valid non-identity boundary transform must not cause the filter to be discarded"); + let clip = parsed.unwrap(); + assert_eq!(clip.points.len(), 4); + assert!(clip.points[0].near(Vec2::new(-100.0, -50.0), 1e-9)); + assert!(clip.points[1].near(Vec2::new(-90.0, -50.0), 1e-9)); + assert!(clip.points[2].near(Vec2::new(-90.0, -40.0), 1e-9)); + assert!(clip.points[3].near(Vec2::new(-100.0, -40.0), 1e-9)); + } + + /// Verifies `boundary_xf.inverse()?.then(inverse)` correctly composes rotation, scaling, and translation. + #[test] + fn parse_filter_applies_rotation_and_scale_boundary_transform() { + let boundary_xf = Mat3::scale(2.0, 2.0).then(Mat3::rotate(std::f64::consts::FRAC_PI_2)).then(Mat3::translate(Vec2::new(50.0, 20.0))); + let inverse = Mat3::translate(Vec2::new(-10.0, -5.0)); + + let filter = make_test_filter(&inverse, &boundary_xf); + let parsed = parse_filter(&filter, None); + + assert!(parsed.is_some(), "Combined scale, rotation, and translation boundary transform must be parsed"); + let clip = parsed.unwrap(); + assert_eq!(clip.points.len(), 4); + assert!(clip.points[0].near(Vec2::new(-20.0, 20.0), 1e-9)); + assert!(clip.points[1].near(Vec2::new(-20.0, 15.0), 1e-9)); + assert!(clip.points[2].near(Vec2::new(-15.0, 15.0), 1e-9)); + assert!(clip.points[3].near(Vec2::new(-15.0, 20.0), 1e-9)); + } + /// Verifies `parse_filter` rejects sheared boundary matrices to preserve foreign data. + #[test] + fn parse_filter_rejects_sheared_boundary_transform() { + let inverse = Mat3::IDENTITY; + // Non-orthogonal shear matrix: (x' = x + 0.5y, y' = y) + let shear = Mat3 { a: 1.0, b: 0.0, c: 0.5, d: 1.0, e: 0.0, f: 0.0 }; + let filter = make_test_filter(&inverse, &shear); + assert!(parse_filter(&filter, None).is_none(), "Sheared transforms must be rejected to stay foreign"); + } + + /// Verifies that an explicit boundary slice (e.g. inverted clip) is transformed correctly. + #[test] + fn parse_filter_applies_transform_to_inverted_boundary() { + let inverse = Mat3::translate(Vec2::new(-10.0, 0.0)); + let boundary_xf = Mat3::translate(Vec2::new(50.0, 0.0)); + let filter = make_test_filter(&inverse, &boundary_xf); + + let explicit_boundary = vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0)]; + let parsed = parse_filter(&filter, Some(&explicit_boundary)); + assert!(parsed.is_some()); + let clip = parsed.unwrap(); + assert!(clip.inverted); + // Explicit boundary points transformed by net: (x - 50 - 10) = x - 60 + assert_eq!(clip.points.len(), 3); + assert!(clip.points[0].near(Vec2::new(-60.0, 0.0), 1e-9)); + assert!(clip.points[1].near(Vec2::new(-50.0, 0.0), 1e-9)); + assert!(clip.points[2].near(Vec2::new(-50.0, 10.0), 1e-9)); + } + /// Verifies that small-scale sheared transforms are rejected by the scale-independent guard. + #[test] + fn parse_filter_rejects_small_scale_sheared_boundary_transform() { + // WHY: + // A sheared transform with tiny scale factors (e.g. u = (0.001, 0), v = (0.0005, 0.001)) + // yields a small absolute dot product (5e-7), which would bypass a naive absolute tolerance. + // The orthogonality guard is scale-independent (|u . v| > 1e-4 * |u| * |v|) so that + // non-orthogonal shears are consistently rejected across all coordinate scales. + let inverse = Mat3::IDENTITY; + let small_shear = Mat3 { a: 0.001, b: 0.0, c: 0.0005, d: 0.001, e: 0.0, f: 0.0 }; + let filter = make_test_filter(&inverse, &small_shear); + assert!(parse_filter(&filter, None).is_none(), "Small-scale sheared transform must be rejected"); + } + + /// Verifies that a 2-corner rectangle rotated by 30°, 45°, 60°, or 90° (whether via + /// `boundary_xf` or via `inverse` with an unrotated/translated `boundary_xf`) expands + /// to an exact 4-corner orthogonal rectangle in block coordinates without collapsing or skewing. + #[test] + fn parse_filter_expands_rotated_two_corner_boundary() { + for deg in [30.0_f64, 45.0, 60.0, 90.0] { + let rot = Mat3::rotate(deg.to_radians()); + let trans = Mat3::translate(Vec2::new(15.0, -10.0)); + for (inverse, boundary_xf) in [(Mat3::IDENTITY, rot), (rot, Mat3::IDENTITY), (rot, trans)] { + let mut tags = vec![ + raw(100, "AcDbFilter"), + raw(100, "AcDbSpatialFilter"), + raw(70, 2), + raw(10, 0.0), + raw(20, 0.0), + raw(10, 10.0), + raw(20, 20.0), + raw(210, 0.0), + raw(220, 0.0), + raw(230, 1.0), + raw(71, 1), + raw(72, 0), + raw(73, 0), + ]; + for v in matrix_values(&inverse).into_iter().chain(matrix_values(&boundary_xf)) { + tags.push(raw(40, v)); + } + let filter = ForeignObject { handle: Handle(0x102), kind: "SPATIAL_FILTER".into(), tags }; + let clip = parse_filter(&filter, None).expect("rotated 2-corner clip must not collapse"); + assert_eq!(clip.points.len(), 4, "angle {deg}°"); + let e01 = clip.points[1] - clip.points[0]; + let e12 = clip.points[2] - clip.points[1]; + assert!((e01.len() - 10.0).abs() < 1e-9, "width preserved at {deg}°"); + assert!((e12.len() - 20.0).abs() < 1e-9, "height preserved at {deg}°"); + assert!(e01.dot(e12).abs() < 1e-9, "right angle preserved at {deg}°"); + } + } + } + + #[test] + fn spatial_filter_canonicalizes_mirrored_two_point_corners_in_boundary_space() { + let clip = ClipBoundary::new(vec![Vec2::new(-1.0, 0.5), Vec2::new(3.0, 2.5)]); + for (sx, sy, rot) in [(-2.0, 3.0, 0.0), (2.0, -3.0, 0.0), (-2.0, -3.0, 0.0), (-2.0, 3.0, 0.3)] { + let to_world = Mat3::translate(Vec2::new(10.0, 20.0)).then_before(Mat3::rotate(rot)).then_before(Mat3::scale(sx, sy)); + let inverse = to_world.inverse().unwrap(); + let sf = spatial_filter(Handle(0x10), Handle(0x1), &clip, &to_world, &inverse, None); + let verts = vertices(&sf.tags, 2).unwrap(); + assert_eq!(verts.len(), 2); + assert!(verts[0].x < verts[1].x && verts[0].y < verts[1].y, "expected lower-left < upper-right for ({sx},{sy},{rot}): {verts:?}"); + } + + // Polyline boundaries (> 2 vertices) must preserve their transformed vertex order. + let poly = ClipBoundary::new(vec![Vec2::new(3.0, 2.5), Vec2::new(-1.0, 2.5), Vec2::new(1.0, -1.0)]); + let to_world = Mat3::scale(-2.0, 3.0); + let (_, pts) = filter_geometry(&poly, &to_world); + assert_eq!(pts, vec![Vec2::new(-6.0, 7.5), Vec2::new(2.0, 7.5), Vec2::new(-2.0, -3.0)]); + } + + #[test] + fn prepare_canonicalizes_inverted_mirrored_companion_record() { + let mut d = Drawing::new_metric(); + d.blocks.insert("B".into(), Arc::new(cadcraft_doc::Block::new("B"))); + let clip = ClipBoundary { inverted: true, ..ClipBoundary::new(vec![Vec2::new(-1.0, 0.5), Vec2::new(3.0, 2.5)]) }; + let ins = cadcraft_doc::Insert { + block: "B".into(), + insert: cadcraft_geom::Vec3::new(10.0, 20.0, 0.0), + scale: cadcraft_geom::Vec3::new(-2.0, 3.0, 1.0), + rotation: 0.3, + clip: Some(clip), + ..Default::default() + }; + d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + + let out = prepare(&d).unwrap(); + let sf = out.foreign.objects.iter().find(|o| o.kind == "SPATIAL_FILTER").unwrap(); + let sf_verts = vertices(&sf.tags, 2).unwrap(); + assert!(sf_verts[0].x < sf_verts[1].x && sf_verts[0].y < sf_verts[1].y); + + let xr = out.foreign.objects.iter().find(|o| o.kind == "XRECORD").unwrap(); + let xrec_list = |marker: &str| -> Vec { + let start = xr.tags.iter().position(|t| t.code == 102 && t.value == marker).unwrap() + 1; + let end = xr.tags[start..].iter().position(|t| t.code == 102).map_or(xr.tags.len(), |n| start + n); + let mut pts = Vec::new(); + let mut x = None; + for t in &xr.tags[start..end] { + if t.code == 10 { + x = t.value.parse::().ok(); + } else if t.code == 20 + && let (Some(px), Ok(py)) = (x.take(), t.value.parse::()) + { + pts.push(Vec2::new(px, py)); + } + } + pts + }; + let rt = xrec_list(ROUNDTRIP); + let cmp = xrec_list(COMPARE); + assert_eq!((rt.len(), cmp.len()), (2, 2)); + assert!(rt[0].near(sf_verts[0], 1e-9) && rt[1].near(sf_verts[1], 1e-9)); + assert!(cmp[0].near(sf_verts[0], 1e-9) && cmp[1].near(sf_verts[1], 1e-9)); + } } diff --git a/crates/io/tests/it/xclip_roundtrip.rs b/crates/io/tests/it/xclip_roundtrip.rs index 407b02cda..abdcd25f7 100644 --- a/crates/io/tests/it/xclip_roundtrip.rs +++ b/crates/io/tests/it/xclip_roundtrip.rs @@ -172,3 +172,277 @@ fn hostile_spatial_filters_do_not_panic() { let _ = read(bad.as_bytes(), "a.dxf"); } } + +/// Verifies that a `SPATIAL_FILTER` with a non-identity boundary transform matrix is preserved +/// across DXF and DWG round-trips (R2004, R2010, R2018), while a sheared filter stays foreign. +#[test] +fn spatial_filter_with_non_identity_boundary_transform_round_trips() { + let mut d = Drawing::new_metric(); + let mut block = Block::new("P"); + block.entities.push(Entity::new(d.new_handle(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(100.0, 100.0, 0.0) }))); + d.blocks.insert("P".into(), Arc::new(block)); + let clip = ClipBoundary::new(vec![Vec2::new(20.0, 20.0), Vec2::new(80.0, 80.0)]); + d.add( + &Space::Model, + Common::default(), + EntityKind::Insert(Insert { block: "P".into(), insert: Vec3::new(150.0, 0.0, 0.0), clip: Some(clip), ..Insert::default() }), + ) + .unwrap(); + let text = String::from_utf8(save(&d, "a.dxf", Version::R2018)).unwrap(); + + let mut lines: Vec = text.lines().map(|l| l.trim().to_string()).collect(); + let at = lines.windows(2).position(|w| w[0] == "0" && w[1] == "SPATIAL_FILTER").unwrap(); + let end = (at + 2..lines.len()).step_by(2).find(|i| lines[*i] == "0").unwrap(); + + let mut g40_indices = Vec::new(); + for i in (at..end).step_by(2) { + if lines[i] == "40" { + g40_indices.push(i + 1); + } + } + assert_eq!(g40_indices.len(), 24); + // Group 40 stores two 3x4 matrices row by row: + // Matrix 1 (elements 0..11): inverse insert transform + // Matrix 2 (elements 12..23): boundary transform + // Index 15 = Matrix 2 row 0, col 3 (Tx translation) + // Index 19 = Matrix 2 row 1, col 3 (Ty translation) + lines[g40_indices[15]] = "10.0".to_string(); + lines[g40_indices[19]] = "5.0".to_string(); + + let mutated = lines.join("\r\n") + "\r\n"; + let loaded = read(mutated.as_bytes(), "a.dxf").unwrap(); + let loaded_clips = clips(&loaded); + let ins_clip = loaded_clips[0].as_ref().expect("clip must be preserved"); + assert!(ins_clip.points[0].near(Vec2::new(10.0, 15.0), 1e-9)); + assert!(ins_clip.points[1].near(Vec2::new(70.0, 75.0), 1e-9)); + + for v in [Version::R2004, Version::R2010, Version::R2018] { + let dxf_back = read(&save(&loaded, "resaved.dxf", v), "resaved.dxf").unwrap(); + same(&clips(&dxf_back), &clips(&loaded)); + + let dwg_back = read(&save(&loaded, "resaved.dwg", v), "resaved.dwg").unwrap(); + same(&clips(&dwg_back), &clips(&loaded)); + } + + // Index 13 = Matrix 2 row 0, col 1 (shear term c). A sheared filter cannot be represented + // losslessly as a planar 2D clip and must remain in `foreign.objects` untouched. + lines[g40_indices[13]] = "0.5".to_string(); + let sheared_dxf = lines.join("\r\n") + "\r\n"; + let sheared_loaded = read(sheared_dxf.as_bytes(), "a.dxf").unwrap(); + assert!(clips(&sheared_loaded)[0].is_none(), "sheared filter must not be converted into a lossy clip"); + assert!( + sheared_loaded.foreign.objects.iter().any(|o| o.kind.eq_ignore_ascii_case("SPATIAL_FILTER")), + "sheared SPATIAL_FILTER must be preserved in foreign objects" + ); +} + +/// Verifies that rotated `INSERT` references with uniform, non-uniform, and mirrored scales +/// and normal or inverted 2-point block-space `ClipBoundary` rectangles round-trip losslessly +/// across DXF and DWG (`R2004`, `R2010`, `R2018`) without producing sheared `boundary_xf` matrices. +#[test] +fn inverted_rotated_2point_clip_round_trips() { + let mut d = Drawing::new_metric(); + let mut block = Block::new("Plan"); + block.entities.push(Entity::new(d.new_handle(), EntityKind::Line(Line { a: Vec3::new(-10.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) }))); + d.blocks.insert(block.name.clone(), Arc::new(block)); + + for scale in [Vec3::new(2.0, 2.0, 1.0), Vec3::new(2.0, 3.0, 1.0), Vec3::new(-2.0, 3.0, 1.0)] { + for inverted in [false, true] { + let clip = ClipBoundary { inverted, ..ClipBoundary::new(vec![Vec2::new(-2.0, -1.0), Vec2::new(2.0, 1.0)]) }; + let ins = + Insert { block: "Plan".into(), insert: Vec3::new(10.0, 20.0, 0.0), scale, rotation: 0.3, clip: Some(clip), ..Insert::default() }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + } + } + + for v in [Version::R2004, Version::R2010, Version::R2018] { + let dxf_back = read(&save(&d, "inv_rot.dxf", v), "inv_rot.dxf").unwrap(); + same(&clips(&dxf_back), &clips(&d)); + + let dwg_back = read(&save(&d, "inv_rot.dwg", v), "inv_rot.dwg").unwrap(); + same(&clips(&dwg_back), &clips(&d)); + } +} + +/// Extracts `(group_70_count, vertices)` from every `SPATIAL_FILTER` in raw DXF text. +fn raw_spatial_filters(dxf_text: &str) -> Vec<(i32, Vec)> { + let lines: Vec<&str> = dxf_text.lines().map(str::trim).collect(); + let mut out = Vec::new(); + let mut i = 0; + while i + 1 < lines.len() { + if lines[i] == "0" && lines[i + 1] == "SPATIAL_FILTER" { + let mut count = None; + let mut verts = Vec::new(); + let mut pending_x: Option = None; + i += 2; + while i + 1 < lines.len() && lines[i] != "0" { + match lines[i] { + "70" => count = lines[i + 1].parse::().ok(), + "10" => pending_x = lines[i + 1].parse::().ok(), + "20" => { + if let (Some(x), Ok(y)) = (pending_x.take(), lines[i + 1].parse::()) { + verts.push(Vec2::new(x, y)); + } + } + _ => {} + } + i += 2; + } + out.push((count.unwrap_or(-1), verts)); + } else { + i += 2; + } + } + out +} + +/// Extracts `(ACAD_INVERTEDCLIP_ROUNDTRIP, ACAD_INVERTEDCLIP_ROUNDTRIP_COMPARE)` vertex pairs +/// from every `XRECORD` carrying inverted-clip data in raw DXF text. +fn raw_inverted_xrecords(dxf_text: &str) -> Vec<(Vec, Vec)> { + let lines: Vec<&str> = dxf_text.lines().map(str::trim).collect(); + let mut out = Vec::new(); + let mut i = 0; + while i + 1 < lines.len() { + if lines[i] == "0" && lines[i + 1] == "XRECORD" { + let mut section = ""; + let mut rt = Vec::new(); + let mut cmp = Vec::new(); + let mut pending_x: Option = None; + i += 2; + while i + 1 < lines.len() && lines[i] != "0" { + match lines[i] { + "102" => section = lines[i + 1], + "10" => pending_x = lines[i + 1].parse::().ok(), + "20" => { + if let (Some(x), Ok(y)) = (pending_x.take(), lines[i + 1].parse::()) { + match section { + "ACAD_INVERTEDCLIP_ROUNDTRIP" => rt.push(Vec2::new(x, y)), + "ACAD_INVERTEDCLIP_ROUNDTRIP_COMPARE" => cmp.push(Vec2::new(x, y)), + _ => {} + } + } + } + _ => {} + } + i += 2; + } + if !rt.is_empty() || !cmp.is_empty() { + out.push((rt, cmp)); + } + } else { + i += 2; + } + } + out +} + +fn assert_canonical_raw_two_point_clips(dxf_text: &str, expected_filters: usize, expected_inverted: usize) { + let filters = raw_spatial_filters(dxf_text); + assert_eq!(filters.len(), expected_filters); + for (count, verts) in &filters { + assert_eq!(*count, 2, "expected 2-point rectangular SPATIAL_FILTER"); + assert_eq!(verts.len(), 2); + assert!(verts[0].x < verts[1].x && verts[0].y < verts[1].y, "SPATIAL_FILTER corners must be ordered lower-left then upper-right: {verts:?}"); + } + + let xrecords = raw_inverted_xrecords(dxf_text); + assert_eq!(xrecords.len(), expected_inverted); + for (rt, cmp) in &xrecords { + assert_eq!((rt.len(), cmp.len()), (2, 2)); + assert!(rt[0].x < rt[1].x && rt[0].y < rt[1].y, "ROUNDTRIP corners must be lower-left..upper-right: {rt:?}"); + assert!(cmp[0].x < cmp[1].x && cmp[0].y < cmp[1].y, "COMPARE corners must be lower-left..upper-right: {cmp:?}"); + assert!(filters.iter().any(|(_, fv)| fv[0].near(rt[0], 1e-6) && fv[1].near(rt[1], 1e-6))); + assert!(rt[0].near(cmp[0], 1e-6) && rt[1].near(cmp[1], 1e-6)); + } +} + +/// Verifies that mirrored rectangular clips (both ordinary and inverted, unrotated and rotated) +/// write canonical `(lower-left, upper-right)` vertices in raw DXF/DWG `SPATIAL_FILTER` and +/// `ACAD_XREC_ROUNDTRIP` records, and preserve the exact clipped visible region after round-trip. +#[test] +fn mirrored_rectangular_clip_writes_canonical_corners_and_preserves_visible_region() { + let mut base = Drawing::new_metric(); + let mut block = Block::new("Plan"); + // Crossing lines inside the asymmetric clip [-1, 3] x [0.5, 2.5], plus an outside-only line. + block.entities.push(Entity::new(base.new_handle(), EntityKind::Line(Line { a: Vec3::new(-10.0, 1.5, 0.0), b: Vec3::new(10.0, 1.5, 0.0) }))); + block.entities.push(Entity::new(base.new_handle(), EntityKind::Line(Line { a: Vec3::new(1.0, -10.0, 0.0), b: Vec3::new(1.0, 10.0, 0.0) }))); + block.entities.push(Entity::new(base.new_handle(), EntityKind::Line(Line { a: Vec3::new(-8.0, -8.0, 0.0), b: Vec3::new(-5.0, -5.0, 0.0) }))); + base.blocks.insert(block.name.clone(), Arc::new(block)); + + // Ordinary unrotated mirrored insert: verify exact clipped visible bounds after DXF & DWG round-trip. + let mut ordinary = base.clone(); + let asym_clip = ClipBoundary::new(vec![Vec2::new(-1.0, 0.5), Vec2::new(3.0, 2.5)]); + ordinary + .add( + &Space::Model, + Common::default(), + EntityKind::Insert(Insert { + block: "Plan".into(), + insert: Vec3::new(10.0, 20.0, 0.0), + scale: Vec3::new(-2.0, 3.0, 1.0), + rotation: 0.0, + clip: Some(asym_clip.clone()), + ..Insert::default() + }), + ) + .unwrap(); + + let expected_bounds = cadcraft_render::build(&ordinary, &Space::Model, &cadcraft_render::Options::default()).bounds; + assert!((expected_bounds.min.x - 4.0).abs() < 1e-6 && (expected_bounds.max.x - 12.0).abs() < 1e-6); + assert!((expected_bounds.min.y - 21.5).abs() < 1e-6 && (expected_bounds.max.y - 27.5).abs() < 1e-6); + + // Combined ordinary + inverted mirrored inserts across scales and rotations. + let mut combined = base; + let mut filter_count = 0; + let mut inverted_count = 0; + for (idx, (scale, rotation)) in + [(Vec3::new(-2.0, 3.0, 1.0), 0.0), (Vec3::new(2.0, -3.0, 1.0), 0.0), (Vec3::new(-2.0, -3.0, 1.0), 0.0), (Vec3::new(-2.0, 3.0, 1.0), 0.3)] + .into_iter() + .enumerate() + { + for inverted in [false, true] { + let clip = ClipBoundary { inverted, ..asym_clip.clone() }; + let ins = Insert { + block: "Plan".into(), + insert: Vec3::new(10.0 + (idx as f64) * 50.0, 20.0, 0.0), + scale, + rotation, + clip: Some(clip), + ..Insert::default() + }; + combined.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + filter_count += 1; + if inverted { + inverted_count += 1; + } + } + } + + for v in [Version::R2004, Version::R2010, Version::R2018] { + // 1. Ordinary mirrored clip: raw DXF/DWG order + visible rendered region. + let ord_dxf = save(&ordinary, "ord_mirror.dxf", v); + assert_canonical_raw_two_point_clips(&String::from_utf8(ord_dxf.clone()).unwrap(), 1, 0); + let ord_dxf_back = read(&ord_dxf, "ord_mirror.dxf").unwrap(); + let dxf_bounds = cadcraft_render::build(&ord_dxf_back, &Space::Model, &cadcraft_render::Options::default()).bounds; + assert!(dxf_bounds.min.near(expected_bounds.min, 1e-4) && dxf_bounds.max.near(expected_bounds.max, 1e-4)); + + let ord_dwg = save(&ordinary, "ord_mirror.dwg", v); + let ord_dwg_dxf = craft_dwg::dwg_to_dxf(&ord_dwg).unwrap(); + assert_canonical_raw_two_point_clips(&String::from_utf8(ord_dwg_dxf).unwrap(), 1, 0); + let ord_dwg_back = read(&ord_dwg, "ord_mirror.dwg").unwrap(); + let dwg_bounds = cadcraft_render::build(&ord_dwg_back, &Space::Model, &cadcraft_render::Options::default()).bounds; + assert!(dwg_bounds.min.near(expected_bounds.min, 1e-4) && dwg_bounds.max.near(expected_bounds.max, 1e-4)); + + // 2. Combined ordinary + inverted mirrored clips across scales and rotations. + let comb_dxf = save(&combined, "comb_mirror.dxf", v); + assert_canonical_raw_two_point_clips(&String::from_utf8(comb_dxf.clone()).unwrap(), filter_count, inverted_count); + let comb_dxf_back = read(&comb_dxf, "comb_mirror.dxf").unwrap(); + same(&clips(&comb_dxf_back), &clips(&combined)); + + let comb_dwg = save(&combined, "comb_mirror.dwg", v); + let comb_dwg_dxf = craft_dwg::dwg_to_dxf(&comb_dwg).unwrap(); + assert_canonical_raw_two_point_clips(&String::from_utf8(comb_dwg_dxf).unwrap(), filter_count, inverted_count); + let comb_dwg_back = read(&comb_dwg, "comb_mirror.dwg").unwrap(); + same(&clips(&comb_dwg_back), &clips(&combined)); + } +} From 20524853c1e7169bfb815a9116195121b7908f1e Mon Sep 17 00:00:00 2001 From: Coast Date: Tue, 1 Dec 2026 02:55:01 -0700 Subject: [PATCH 38/43] Options: preview and selection effects in Visual Effect Settings (#964) * Options: preview and selection effects in Visual Effect Settings Selection Preview Effect (Dash / Thicken / Both, PREVIEWEFFECT) as AutoCAD offers it, and Selected Objects Effect (Dashed / Selection color, SELECTIONEFFECT), so neither has to be typed. They stay off the Selection tab itself. Co-Authored-By: Claude Opus 5.5 * Options test: each Visual Effect Settings choice sets its variable Co-Authored-By: Claude Opus 5.5 * Tests: the visual effect test sets up the app's headless runtime, as main's UI tests now do Co-Authored-By: Claude Opus 5.5 * Translations to craft-i18n (AGENTS.md rule 16) The Greek and Ukrainian rows this PR added to the app catalogs are removed; the English keys stay, and show until craft-i18n has them. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/options/dialog.rs | 24 +++++++++++- crates/ui-egui/tests/it/options_dialog.rs | 45 +++++++++++++++++++++-- 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/options/dialog.rs b/crates/ui-egui/src/options/dialog.rs index 239d64d19..caa717db5 100644 --- a/crates/ui-egui/src/options/dialog.rs +++ b/crates/ui-egui/src/options/dialog.rs @@ -459,8 +459,11 @@ fn heading(ui: &mut egui::Ui, text: &str) -> egui::Response { ui.label(RichText::new(text).strong()) } -/// Visual Effect Settings: the selection area (window and crossing fills) and the objects the -/// cursor never highlights (PREVIEWFILTER). Changes apply at once, as on the Options tabs. +/// Visual Effect Settings: how the object under the cursor is highlighted (PREVIEWEFFECT: Dash, +/// Thicken or Both, as AutoCAD offers it) and how selected objects are (SELECTIONEFFECT: dashed +/// or redrawn in the selection colour), the selection area (window and crossing fills) and the +/// objects the cursor never highlights (PREVIEWFILTER). Changes apply at once, as on the Options +/// tabs. fn visual_effects(ctx: &egui::Context, st: &cadcraft_engine::Settings, open: &mut bool, changes: &mut Map) { let mut close = false; egui::Window::new(crate::tl!("Visual Effect Settings")) @@ -473,6 +476,23 @@ fn visual_effects(ctx: &egui::Context, st: &cadcraft_engine::Settings, open: &mu .show(ctx, |ui| { ui.columns(2, |cols| { let [left, right] = cols else { return }; + heading(left, crate::tl!("Selection Preview Effect")); + left.horizontal(|ui| { + for (v, label) in [(0u8, crate::tl!("Dash")), (1, crate::tl!("Thicken")), (2, crate::tl!("Both"))] { + if ui.radio(st.previeweffect == v, label).clicked() { + changes.insert("PREVIEWEFFECT".into(), json!(v)); + } + } + }); + heading(left, crate::tl!("Selected Objects Effect")); + left.horizontal(|ui| { + for (v, label) in [(0u8, crate::tl!("Dashed")), (1, crate::tl!("Selection color"))] { + if ui.radio(st.selectioneffect == v, label).clicked() { + changes.insert("SELECTIONEFFECT".into(), json!(v)); + } + } + }); + left.add_space(6.0); heading(left, crate::tl!("Selection Area Effect")); let mut area = st.selectionarea; if left.checkbox(&mut area, crate::tl!("Indicate selection area")).changed() { diff --git a/crates/ui-egui/tests/it/options_dialog.rs b/crates/ui-egui/tests/it/options_dialog.rs index 540ef1808..41d91adfe 100644 --- a/crates/ui-egui/tests/it/options_dialog.rs +++ b/crates/ui-egui/tests/it/options_dialog.rs @@ -235,15 +235,23 @@ fn selection_highlight_settings_set_save_and_show_in_the_selection_tab() { ] { assert!(text.contains(label), "{label} missing from:\n{text}"); } - // HIGHLIGHT, SELECTIONEFFECT and PREVIEWEFFECT are typed, not offered (as in AutoCAD), so - // the highlight can't be switched off or changed by accident. + // HIGHLIGHT is typed, not offered (as in AutoCAD), so the highlight can't be switched off by + // accident; the effects are in Visual Effect Settings, not on the tab. for label in ["Highlight selected objects", "Preview effect", "Dashed"] { assert!(!text.contains(label), "{label} offered"); } - // Visual Effect Settings: the selection area and the preview filter. + // Visual Effect Settings: the preview and selection effects, the selection area and the + // preview filter. ctx.data_mut(|d| d.insert_temp(egui::Id::unique("cc_options_visual_effects"), true)); let text = render(&mut a, &ctx); for label in [ + "Selection Preview Effect", + "Dash", + "Thicken", + "Both", + "Selected Objects Effect", + "Dashed", + "Selection color", "Selection Area Effect", "Indicate selection area", "Window selection color:", @@ -256,6 +264,37 @@ fn selection_highlight_settings_set_save_and_show_in_the_selection_tab() { } } +/// Visual Effect Settings: each preview and selection effect choice sets its variable. +#[test] +fn the_visual_effect_choices_set_their_variables() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + + let mut a = app(); + a.cmdline("options"); + a.ui.dialog = Some("options:selection".into()); + let mut h = + Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(egui::vec2(1600.0, 1000.0)).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + a, + ); + h.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("cc_options_visual_effects"), true)); + h.run_steps(2); + for (label, v) in [("Thicken", 1), ("Both", 2), ("Dash", 0)] { + h.get_by_label(label).click(); + h.run_steps(2); + assert_eq!(h.state().session.settings.previeweffect, v, "{label}"); + } + for (label, v) in [("Dashed", 0), ("Selection color", 1), ("Dashed", 0)] { + h.get_by_label(label).click(); + h.run_steps(2); + assert_eq!(h.state().session.settings.selectioneffect, v, "{label}"); + } +} + #[test] fn reset_brings_back_hidden_menu_bar_toolbar_and_status_bar() { // #1240: with the in-window menu bar, the toolbar and the status bar hidden, OPTIONS ▸ Reset From e6bbf59c3156355e1fa3676b6aa44a4790838322 Mon Sep 17 00:00:00 2001 From: CA Date: Tue, 1 Dec 2026 14:38:34 +0400 Subject: [PATCH 39/43] Expose xdata through entities, properties.set and AutoLISP's -3 group (#2469) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Expose xdata through entities, properties.set and AutoLISP's -3 group An entity's extended data was read, kept and written back (#528) but invisible to the API: `entities` left it out, `properties.set` had no field for it, `entget` never returned the -3 group and `entmod` dropped it. Now `entities {xdata: true | "APP"}` and `properties` list it per application with values typed by group code, `properties.set {xdata}` replaces or removes one application's data after checking codes, values, braces and sizes, and AutoLISP's entget/entmod/entmake carry the -3 group, with `regapp` and the APPID table. The applications CADCraft writes from its own model are reserved (one list, now in cadcraft_doc, shared with the DXF reader). Co-Authored-By: Claude Fable 5.1 * Check xdata before any change in properties.set; cap entmake's xdata across applications Review follow-ups on #2469: - properties.set validated xdata after ensure_layer, so a request naming a new layer and carrying bad or oversized xdata left the layer behind on failure. The xdata checks now run first. - entmake capped each application's groups but not their sum; an entity could exceed MAX_XDATA_GROUPS across applications. The total is checked as entmod already does, with a test. - docs: the control-protocol xdata section is an h2 like its neighbours; the file-format-parity revision row no longer has a pipe inside a code span. Co-Authored-By: Claude Fable 5.1 * properties.set checks every handle first; a dotted -3 group is a bad list Review follow-ups on #2469: - properties.set edited the objects before a handle that names nothing and then failed, keeping those edits (and a new layer). Every handle is checked before anything changes; a missing one is refused with its hex. - xdata_from_list read `(-3 . 7)` as "no applications" and let entmake/entmod succeed with nothing set. A -3 whose cdr is not a list is refused (listp), so both return nil as for any bad list. Co-Authored-By: Claude Fable 5.1 * An xdata application's groups must be a proper list Review follow-up on #2469: `("ACME" . 7)` in a -3 group read as "no groups", which `entmod` takes as "remove ACME's data", and a dotted tail after real groups was dropped. The application's tail is checked as a list (listp) like the -3 group itself, so entmake/entmod answer nil and change nothing; test covers both shapes. Co-Authored-By: Claude Fable 5.1 * Runs of one xdata application in any case are one application in the API Review follow-up on #2469: a file can carry `ACME` and `acme` runs on one entity. `entities` showed them as two JSON keys and `entget` as two lists, and writing either back through properties.set or entmod replaced the application twice, keeping only the last run's groups. Both projections now merge runs case-insensitively (first spelling, all the groups), as set_xdata_app already treats them; tests round-trip such an entity through both APIs. Co-Authored-By: Claude Fable 5.1 * Refuse raw ACAD xdata on a dimension, whose ACAD run is written from its overrides Review follow-up on #2469 (austin62jake): properties.set accepted `xdata: {"ACAD": …}` on a dimension and `entities` showed it, but the DXF writer emits the dimension's ACAD run (DSTYLE) from its overrides and the reader models it back, so the raw groups vanished on save. ACAD can't join RESERVED_XDATA_APPS (files carry ACAD data on other entities that CADCraft keeps raw), so the rule is per entity: `is_model_xdata_app(name, kind)` is the reserved list on any entity plus ACAD on a dimension. properties.set refuses it before anything changes, entmake/entmod answer nil. Tests cover both paths, including that ACAD on a line survives a DXF round trip and the dimension's own override does too. control-protocol.md says so. Co-Authored-By: Claude Fable 5.1 * fix(lisp): return and accept REAL for xdata group 1071 --------- Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 Co-authored-by: FredApps Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/doc/src/entity.rs | 6 + crates/doc/src/entity/xdata.rs | 293 +++++++++++++++++++++++++++ crates/engine/src/cmd/inquiry.rs | 17 +- crates/engine/src/cmd/props.rs | 7 +- crates/engine/src/cmd/props/set.rs | 31 +++ crates/engine/src/cmd/props/xdata.rs | 293 +++++++++++++++++++++++++++ crates/engine/src/lisp.rs | 5 + crates/engine/src/lisp/builtins.rs | 1 + crates/engine/src/lisp/drawing.rs | 220 +++++++++++++++++++- crates/engine/src/lisp/tests.rs | 148 ++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/xdata_api.rs | 246 ++++++++++++++++++++++ crates/io/src/dxf_raw.rs | 9 +- crates/mcp/src/tools.rs | 5 +- docs/autolisp.md | 15 +- docs/control-protocol.md | 28 +++ docs/file-format-parity.md | 5 +- docs/gaps.md | 7 +- docs/mcp.md | 4 +- 19 files changed, 1313 insertions(+), 28 deletions(-) create mode 100644 crates/doc/src/entity/xdata.rs create mode 100644 crates/engine/src/cmd/props/xdata.rs create mode 100644 crates/engine/tests/it/xdata_api.rs diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index ebd3ccfa0..d4bcb2de8 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -46,6 +46,12 @@ mod layout; mod proxy; mod text; mod wipeout; +mod xdata; + +pub use xdata::{ + MAX_XDATA_APP_NAME, MAX_XDATA_CHUNK, MAX_XDATA_GROUPS, MAX_XDATA_STRING, RESERVED_XDATA_APPS, XdataError, check_xdata_app_name, + check_xdata_groups, is_model_xdata_app, is_reserved_xdata_app, is_xdata_group, set_xdata_app, xdata_apps, xdata_of, +}; pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal}; pub use common::{Common, Handle, Lineweight, RawTag, Transparency}; diff --git a/crates/doc/src/entity/xdata.rs b/crates/doc/src/entity/xdata.rs new file mode 100644 index 000000000..9f830801f --- /dev/null +++ b/crates/doc/src/entity/xdata.rs @@ -0,0 +1,293 @@ +//! Extended entity data (xdata): the groups 1000–1071 other applications attach to an entity, +//! kept raw in [`Common::xdata`](super::Common::xdata) as whole applications, each from its +//! `1001` group on. This module reads them per application, replaces or removes one +//! application's data, and checks data that comes from outside (a command's parameters, a LISP +//! list) before it goes onto an entity: input is hostile, so codes, values, brace nesting and +//! sizes are all checked and nothing here panics. + +use super::RawTag; + +/// Most xdata groups one object may carry (AutoCAD allows 16 KB of xdata per object). +pub const MAX_XDATA_GROUPS: usize = 16_384; +/// Longest application name, in bytes. +pub const MAX_XDATA_APP_NAME: usize = 255; +/// Longest string value (groups 1000 and 1003), in bytes: what one DXF group holds. +pub const MAX_XDATA_STRING: usize = 255; +/// Longest binary chunk (group 1004), in bytes. +pub const MAX_XDATA_CHUNK: usize = 127; + +/// Applications whose xdata CADCraft writes itself, from its own model, when a drawing is saved. +/// It is never kept as an entity's raw xdata (the reader models it) and can't be set as such: +/// a copy written beside the generated data would contradict it. +pub const RESERVED_XDATA_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"]; + +/// Whether `name` (any case) is one of [`RESERVED_XDATA_APPS`]. +pub fn is_reserved_xdata_app(name: &str) -> bool { + let up = name.trim().to_ascii_uppercase(); + RESERVED_XDATA_APPS.contains(&up.as_str()) +} + +/// Whether application `name`'s xdata on an entity of `kind` is written from the model rather +/// than kept raw: the [`RESERVED_XDATA_APPS`] on any entity, and `ACAD` on a dimension, whose +/// `ACAD` run (`DSTYLE`) holds its dimension-style overrides. The reader models those too, so +/// raw groups set under such a name would be dropped on save; they are refused instead. +pub fn is_model_xdata_app(name: &str, kind: &super::EntityKind) -> bool { + is_reserved_xdata_app(name) || (name.trim().eq_ignore_ascii_case("ACAD") && matches!(kind, super::EntityKind::Dimension(_))) +} + +/// Why an application name or a run of xdata groups was refused. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct XdataError(pub String); + +impl std::fmt::Display for XdataError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for XdataError {} + +fn err(msg: impl Into) -> Result { + Err(XdataError(msg.into())) +} + +/// Check an application name: not empty, at most [`MAX_XDATA_APP_NAME`] bytes, no control +/// characters and none of the characters a symbol table name can't hold. +pub fn check_xdata_app_name(name: &str) -> Result<(), XdataError> { + let name = name.trim(); + if name.is_empty() { + return err("an xdata application name must not be empty"); + } + if name.len() > MAX_XDATA_APP_NAME { + return err(format!("an xdata application name may have at most {MAX_XDATA_APP_NAME} bytes")); + } + if name.chars().any(|c| c.is_control() || "<>/\\\":;?*|,=`".contains(c)) { + return err(format!("`{name}` is not a valid xdata application name (no control characters or <>/\\\":;?*|,=`)")); + } + Ok(()) +} + +/// Whether `code` is an xdata group code an application's data may hold (`1001`, the +/// application name, is not one of them: it starts an application). +pub fn is_xdata_group(code: i32) -> bool { + matches!(code, 1000 | 1002..=1005 | 1010..=1013 | 1020..=1023 | 1030..=1033 | 1040..=1042 | 1070 | 1071) +} + +/// Check the groups of one application (after its `1001`): every code an xdata code with a +/// value of its kind, control strings `{` and `}` balanced, points complete (a `101x` group +/// followed by its `102x` and `103x`), at most [`MAX_XDATA_GROUPS`] groups. +pub fn check_xdata_groups(groups: &[RawTag]) -> Result<(), XdataError> { + if groups.len() > MAX_XDATA_GROUPS { + return err(format!("at most {MAX_XDATA_GROUPS} xdata groups per application")); + } + let mut depth: u32 = 0; + let mut i = 0; + while let Some(t) = groups.get(i) { + let v = t.value.trim(); + match t.code { + 1000 | 1003 => { + if t.value.len() > MAX_XDATA_STRING { + return err(format!("group {}: a string may have at most {MAX_XDATA_STRING} bytes", t.code)); + } + if t.value.chars().any(|c| c == '\n' || c == '\r') { + return err(format!("group {}: a string may not hold a line break", t.code)); + } + } + 1002 => match v { + "{" => depth = depth.saturating_add(1), + "}" => match depth.checked_sub(1) { + Some(d) => depth = d, + None => return err("group 1002: a `}` without its `{`"), + }, + _ => return err("group 1002 must be `{` or `}`"), + }, + 1004 => { + if v.len() > MAX_XDATA_CHUNK * 2 || v.len() % 2 != 0 || !v.bytes().all(|b| b.is_ascii_hexdigit()) { + return err(format!("group 1004 must be hex text of an even length, at most {MAX_XDATA_CHUNK} bytes")); + } + } + 1005 => { + if v.is_empty() || v.len() > 16 || !v.bytes().all(|b| b.is_ascii_hexdigit()) { + return err("group 1005 must be a hex handle"); + } + } + 1010..=1013 => { + let (y, z) = (groups.get(i + 1), groups.get(i + 2)); + let complete = y.is_some_and(|y| y.code == t.code + 10) && z.is_some_and(|z| z.code == t.code + 20); + if !complete { + return err(format!("group {}: a point needs its {} and {} groups", t.code, t.code + 10, t.code + 20)); + } + for p in [Some(t), y, z].into_iter().flatten() { + real(p)?; + } + i += 3; + continue; + } + 1020..=1023 | 1030..=1033 => return err(format!("group {} may only follow its {} group", t.code, t.code - (t.code - 1010) / 10 * 10)), + 1040..=1042 => { + real(t)?; + } + 1070 => { + let ok = v.parse::().is_ok_and(|n| i16::try_from(n).is_ok()); + if !ok { + return err("group 1070 must be a 16-bit integer"); + } + } + 1071 => { + let ok = v.parse::().is_ok_and(|n| i32::try_from(n).is_ok()); + if !ok { + return err("group 1071 must be a 32-bit integer"); + } + } + 1001 => return err("group 1001 (an application name) can't be inside an application's data"), + c => return err(format!("group {c} is not an xdata group code (1000–1071)")), + } + i += 1; + } + if depth != 0 { + return err("group 1002: a `{` without its `}`"); + } + Ok(()) +} + +fn real(t: &RawTag) -> Result { + match t.value.trim().parse::() { + Ok(v) if v.is_finite() => Ok(v), + _ => err(format!("group {} must be a finite number", t.code)), + } +} + +/// The applications of an xdata run, in order: each name as written and its groups after the +/// `1001`. Groups before the first `1001` belong to nobody and are left out. +pub fn xdata_apps(xdata: &[RawTag]) -> Vec<(&str, &[RawTag])> { + let mut out = Vec::new(); + let mut start: Option<(usize, &str)> = None; + for (i, t) in xdata.iter().enumerate() { + if t.code != 1001 { + continue; + } + if let Some((s, name)) = start.take() { + out.push((name, xdata.get(s + 1..i).unwrap_or(&[]))); + } + start = Some((i, t.value.trim())); + } + if let Some((s, name)) = start { + out.push((name, xdata.get(s + 1..).unwrap_or(&[]))); + } + out +} + +/// The groups of application `app` (any case): those of its first run. +pub fn xdata_of<'a>(xdata: &'a [RawTag], app: &str) -> Option<&'a [RawTag]> { + xdata_apps(xdata).into_iter().find(|(name, _)| name.eq_ignore_ascii_case(app.trim())).map(|(_, g)| g) +} + +/// Replace the xdata of application `app` (any case) with `groups`, or remove it (`None`, or no +/// groups). Every run of that application goes; new data is appended after the other +/// applications' data, with its `1001` group. The groups are taken as given: check them with +/// [`check_xdata_groups`] first when they come from outside. +pub fn set_xdata_app(xdata: &mut Vec, app: &str, groups: Option<&[RawTag]>) { + let app = app.trim(); + let mut kept: Vec = Vec::with_capacity(xdata.len()); + let mut skipping = false; + for t in xdata.drain(..) { + if t.code == 1001 { + skipping = t.value.trim().eq_ignore_ascii_case(app); + } + if !skipping { + kept.push(t); + } + } + if let Some(groups) = groups.filter(|g| !g.is_empty()) { + kept.push(RawTag { code: 1001, value: app.to_string() }); + kept.extend(groups.iter().cloned()); + } + *xdata = kept; +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + fn t(code: i32, value: &str) -> RawTag { + RawTag { code, value: value.into() } + } + + #[test] + fn apps_are_split_at_their_names() { + let x = vec![t(1001, "A"), t(1000, "one"), t(1070, "1"), t(1001, "b"), t(1000, "two")]; + let apps = xdata_apps(&x); + assert_eq!(apps.len(), 2); + assert_eq!(apps[0].0, "A"); + assert_eq!(apps[0].1.len(), 2); + assert_eq!(apps[1], ("b", &x[4..])); + assert_eq!(xdata_of(&x, "B"), Some(&x[4..])); + assert_eq!(xdata_of(&x, "c"), None); + assert!(xdata_apps(&[t(1000, "stray")]).is_empty()); + } + + #[test] + fn set_replaces_removes_and_appends() { + let mut x = vec![t(1001, "A"), t(1000, "one"), t(1001, "B"), t(1000, "two"), t(1001, "a"), t(1000, "dup")]; + set_xdata_app(&mut x, "a", Some(&[t(1070, "7")])); + assert_eq!(x, vec![t(1001, "B"), t(1000, "two"), t(1001, "a"), t(1070, "7")]); + set_xdata_app(&mut x, "B", None); + assert_eq!(x, vec![t(1001, "a"), t(1070, "7")]); + set_xdata_app(&mut x, "C", Some(&[])); + assert_eq!(x.len(), 2); + set_xdata_app(&mut x, "A", None); + assert!(x.is_empty()); + } + + #[test] + fn checks_accept_every_kind_and_refuse_bad_data() { + let good = vec![ + t(1000, "text"), + t(1002, "{"), + t(1003, "Layer"), + t(1004, "DEADBEEF"), + t(1005, "1A2"), + t(1010, "1.5"), + t(1020, "2"), + t(1030, "0"), + t(1040, "2.5"), + t(1041, "1e3"), + t(1042, "-1"), + t(1070, "32767"), + t(1071, "2147483647"), + t(1002, "}"), + ]; + assert_eq!(check_xdata_groups(&good), Ok(())); + for bad in [ + vec![t(1002, "}")], + vec![t(1002, "{")], + vec![t(1002, "x")], + vec![t(1001, "APP")], + vec![t(999, "comment")], + vec![t(8, "layer")], + vec![t(1010, "1"), t(1020, "2")], + vec![t(1020, "2")], + vec![t(1010, "nan"), t(1020, "2"), t(1030, "3")], + vec![t(1040, "inf")], + vec![t(1040, "x")], + vec![t(1070, "40000")], + vec![t(1071, "3000000000")], + vec![t(1004, "ABC")], + vec![t(1004, "XY")], + vec![t(1005, "")], + vec![t(1005, "zz")], + vec![t(1000, &"x".repeat(256))], + vec![t(1000, "a\nb")], + vec![t(1000, "x"); MAX_XDATA_GROUPS + 1], + ] { + assert!(check_xdata_groups(&bad).is_err(), "{:?}", bad.first()); + } + assert_eq!(check_xdata_app_name("PE_URL"), Ok(())); + assert_eq!(check_xdata_app_name("My App-1.0$"), Ok(())); + for bad in ["", " ", "a*b", "a\tb", "x/y", &"n".repeat(256)] { + assert!(check_xdata_app_name(bad).is_err(), "{bad:?}"); + } + assert!(is_reserved_xdata_app("cadcraft") && !is_reserved_xdata_app("ACAD")); + } +} diff --git a/crates/engine/src/cmd/inquiry.rs b/crates/engine/src/cmd/inquiry.rs index 65e141865..964dd1331 100644 --- a/crates/engine/src/cmd/inquiry.rs +++ b/crates/engine/src/cmd/inquiry.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { CommandSpec::new("status", "Status", run_status).menu(&["Tools", "Inquiry", "Status"]).noundo(), CommandSpec::new("drawing.inspect", "Inspect Drawing", run_inspect).params("{entities?: bool, limit?: n}").noundo(), CommandSpec::new("entities", "Query Entities", run_entities) - .params("{type?, layer?, selected?: bool (default false; true = current selection in active space), window?: [[x,y],[x,y]], crossing?: bool (default true; false = entirely inside), limit?, offset?} → {count (all matches), returned, offset, entities}") + .params("{type?, layer?, selected?: bool (default false; true = current selection in active space), window?: [[x,y],[x,y]], crossing?: bool (default true; false = entirely inside), xdata?: true | \"APP\" | [\"APP\", …] (add each entity's extended data {\"APP\": [[code, value], …]}; a name also keeps only entities carrying that application's data), limit?, offset?} → {count (all matches), returned, offset, entities}") .noundo(), CommandSpec::new("shapes", "Analyze Shapes", shapes::run).params(shapes::PARAMS).noundo(), CommandSpec::new("usage", "Analyze Usage", usage::run).params(usage::PARAMS).noundo(), @@ -658,6 +658,7 @@ fn run_entities(s: &mut Session, p: &Value) -> Result { .transpose()?; let crossing = given("crossing").map_or(Ok(true), |v| v.as_bool().ok_or_else(|| bad(CMD, "`crossing` must be true or false")))?; let selected = given("selected").map_or(Ok(false), |v| v.as_bool().ok_or_else(|| bad(CMD, "`selected` must be true or false")))?; + let xdata = super::props::xdata::XdataSelect::parse(given("xdata")).map_err(|m| bad(CMD, m))?; let limit = count("limit", 500)?; let offset = count("offset", 0)?; let st = s.state()?; @@ -671,8 +672,20 @@ fn run_entities(s: &mut Session, p: &Value) -> Result { .filter(|e| ty.as_ref().is_none_or(|t| e.kind.type_name().to_ascii_lowercase() == *t || e.kind.dxf_name().to_ascii_lowercase() == *t)) .filter(|e| layer.as_ref().is_none_or(|l| e.common.layer.to_ascii_lowercase() == *l)) .filter(|e| window.as_ref().is_none_or(|w| crate::select::in_window(d, e, None, w, crossing, tol))) + .filter(|e| !xdata.filters() || xdata.matches(&e.common.xdata)) + .collect(); + let page: Vec = matches + .iter() + .skip(offset) + .take(limit) + .map(|e| { + let mut v = entity_summary(e); + if let (Some(x), Some(o)) = (xdata.json(&e.common.xdata), v.as_object_mut()) { + o.insert("xdata".into(), x); + } + v + }) .collect(); - let page: Vec = matches.iter().skip(offset).take(limit).map(|e| entity_summary(e)).collect(); // `count` is every match; `returned` is this page of them (`offset`, `limit`). Ok(json!({ "count": matches.len(), "returned": page.len(), "offset": offset, "entities": page })) } diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index b87a9431a..cd14477c3 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -7,6 +7,7 @@ mod dash_units; mod matchprop; mod rename; mod set; +pub(crate) mod xdata; pub use matchprop::MatchProps; use set::run_set; @@ -27,7 +28,8 @@ pub fn specs() -> Vec { , text: style?, justify?, oblique?, backwards?, upsideDown?, positionX/Y/Z?, alignmentX/Y?, \ mtext: style?, justify?, lineSpacing?, lineSpacingDistance?, lineSpacingStyle?: atLeast | exactly, positionX/Y/Z?, \ dimension: dimStyle?, textOverride?, textRotation?, textPositionX/Y?, prefix?, suffix?, altPrefix?, altSuffix?, dimScale?, precision?, \ - , clearOverrides?, clear?: [variable]} \ + , clearOverrides?, clear?: [variable], \ + xdata?: {\"APP\": [[code, value], …] | null} (replaces or removes that application's extended data; codes 1000–1071, points as [1010, [x, y, z]])} \ → {changed, locked, message?, ignored: keys no selected object took} (the keys are those of `properties.describe` rows): objects on locked layers \ (and, during REFEDIT, outside the working set) are left out, and `message` says how many", ), @@ -125,6 +127,9 @@ pub(super) fn entity_props(d: &cadcraft_doc::Drawing, e: &cadcraft_doc::Entity) o.insert("annotative".into(), json!(cadcraft_doc::is_annotative(e))); o.insert("annotativeScales".into(), json!(e.common.anno_scales.iter().map(|s| s.name.clone()).collect::>())); } + if let (Some(x), Some(o)) = (xdata::xdata_json(&e.common.xdata), v.as_object_mut()) { + o.insert("xdata".into(), x); + } let geo = serde_json::to_value(&e.kind).unwrap_or(Value::Null); if let (Some(o), Some(g)) = (v.as_object_mut(), geo.as_object()) { o.insert("geometry".into(), Value::Object(g.clone())); diff --git a/crates/engine/src/cmd/props/set.rs b/crates/engine/src/cmd/props/set.rs index 3f7c1543e..fa5401896 100644 --- a/crates/engine/src/cmd/props/set.rs +++ b/crates/engine/src/cmd/props/set.rs @@ -48,6 +48,7 @@ const SET_KEYS: &[&str] = &[ "suffix", "altPrefix", "altSuffix", + "xdata", // An insert's or hatch's scale; a dimension's overall scale is `dimScale` (or DIMSCALE). "scale", ]; @@ -324,6 +325,32 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { .map(|n| d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found")))) .transpose()?; let dim_vars = DimVars::new(d, p)?; + // xdata is checked before anything changes (`ensure_layer` below adds a layer the drawing + // keeps even when the command then fails): no object may end up with more xdata than a + // file holds for one. + let xd = p.get("xdata").filter(|v| !v.is_null()).map(super::xdata::xdata_from_json).transpose().map_err(|m| bad("properties.set", m))?; + if let Some(changes) = &xd { + for h in &hs { + let Some(e) = d.entity(*h) else { continue }; + // A dimension's `ACAD` run is written from its overrides (textHeight, arrowSize…) and + // read back into them: raw groups under that name would be lost on save. + if let Some((app, _)) = changes.iter().find(|(app, _)| cadcraft_doc::is_model_xdata_app(app, &e.kind)) { + return Err(bad( + "properties.set", + format!( + "{}: xdata application {app} of a {} is written from its own properties and can't be set as raw data", + h.hex(), + e.kind.dxf_name() + ), + )); + } + let mut after = e.common.xdata.clone(); + super::xdata::apply(&mut after, changes); + if after.len() > cadcraft_doc::MAX_XDATA_GROUPS { + return Err(bad("properties.set", format!("{}: xdata would exceed {} groups", h.hex(), cadcraft_doc::MAX_XDATA_GROUPS))); + } + } + } // A pattern must be one each hatch can take, as HATCHEDIT refuses others. if let Some(v) = str_param(p, "pattern").filter(|v| !v.trim().is_empty()) && hs.iter().any(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if !crate::cmd::hatch::takes_pattern(x, v))) @@ -373,6 +400,10 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { EntityKind::Hatch(ha) => hatch(ha, &c, &mut used), _ => {} } + if let Some(changes) = &xd { + super::xdata::apply(&mut e.common.xdata, changes); + used.insert("xdata"); + } })?; } let ignored: Vec<&str> = p diff --git a/crates/engine/src/cmd/props/xdata.rs b/crates/engine/src/cmd/props/xdata.rs new file mode 100644 index 000000000..48c5b0827 --- /dev/null +++ b/crates/engine/src/cmd/props/xdata.rs @@ -0,0 +1,293 @@ +//! Xdata as JSON, for `entities`, `properties` and `properties.set`: an object by application, +//! `{"APP": [[code, value], …]}`, with each group's value typed by its code: strings for 1000, +//! 1002 (`{` / `}`), 1003 (a layer name), 1004 (hex) and 1005 (a handle), a point `[x, y, z]` +//! for 1010–1013 (its 1020 and 1030 groups folded in), numbers for 1040–1042, integers for +//! 1070 and 1071. Setting takes the same form; `null` for an application removes its data. + +use cadcraft_doc::{MAX_XDATA_GROUPS, RawTag, check_xdata_app_name, check_xdata_groups, is_reserved_xdata_app, set_xdata_app, xdata_apps}; +use serde_json::{Map, Value, json}; + +/// Most applications one `properties.set` call may set. +const MAX_APPS_PER_CALL: usize = 256; + +/// Which applications' xdata a query returns. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) enum XdataSelect { + /// None (the default). + #[default] + None, + /// Every application's. + All, + /// These applications' (any case); an entity without any of them doesn't match the query. + Apps(Vec), +} + +impl XdataSelect { + /// The `xdata` parameter of a query: `true`, `false`, an application name or a list of names. + pub(crate) fn parse(v: Option<&Value>) -> Result { + const MSG: &str = "`xdata` must be true, false, an application name or a list of names"; + match v { + None | Some(Value::Null) => Ok(Self::None), + Some(Value::Bool(b)) => Ok(if *b { Self::All } else { Self::None }), + Some(Value::String(s)) => Ok(Self::Apps(vec![s.clone()])), + Some(Value::Array(a)) if !a.is_empty() && a.len() <= MAX_APPS_PER_CALL => { + a.iter().map(|x| x.as_str().map(str::to_string).ok_or_else(|| MSG.to_string())).collect::, _>>().map(Self::Apps) + } + Some(_) => Err(MSG.into()), + } + } + + /// Whether the selection narrows a query to entities carrying the named applications' data. + pub(crate) fn filters(&self) -> bool { + matches!(self, Self::Apps(_)) + } + + /// Whether an entity with this xdata passes the filter. + pub(crate) fn matches(&self, xdata: &[RawTag]) -> bool { + match self { + Self::None | Self::All => true, + Self::Apps(apps) => xdata_apps(xdata).iter().any(|(name, _)| apps.iter().any(|a| a.trim().eq_ignore_ascii_case(name))), + } + } + + /// The selected applications' data of an entity as JSON; `None` when there is none to show. + pub(crate) fn json(&self, xdata: &[RawTag]) -> Option { + let apps = match self { + Self::None => return None, + Self::All => None, + Self::Apps(apps) => Some(apps), + }; + let mut out = Map::new(); + for (name, groups) in xdata_apps(xdata) { + if apps.is_some_and(|apps| !apps.iter().any(|a| a.trim().eq_ignore_ascii_case(name))) { + continue; + } + // A second run of the same application (not something AutoCAD writes; `ACME` and + // `acme` are one application, as `set_xdata_app` treats them) joins the first. + let key = out.keys().find(|k| k.eq_ignore_ascii_case(name)).cloned(); + match key.and_then(|k| out.get_mut(&k)) { + Some(Value::Array(v)) => v.extend(groups_json(groups)), + _ => { + out.insert(name.to_string(), Value::Array(groups_json(groups))); + } + } + } + (!out.is_empty()).then_some(Value::Object(out)) + } +} + +/// Every application's data of an entity as JSON; `None` when it has none. +pub(crate) fn xdata_json(xdata: &[RawTag]) -> Option { + XdataSelect::All.json(xdata) +} + +fn number(t: &RawTag) -> Value { + t.value.trim().parse::().ok().filter(|v| v.is_finite()).map_or_else(|| json!(t.value), |v| json!(v)) +} + +fn integer(t: &RawTag) -> Value { + t.value.trim().parse::().map_or_else(|_| json!(t.value), |v| json!(v)) +} + +/// One application's groups as `[code, value]` pairs, points folded. +fn groups_json(groups: &[RawTag]) -> Vec { + let mut out = Vec::with_capacity(groups.len()); + let mut i = 0; + while let Some(t) = groups.get(i) { + let v = match t.code { + 1010..=1013 => { + let y = groups.get(i + 1).filter(|y| y.code == t.code + 10); + let z = groups.get(i + 2).filter(|z| z.code == t.code + 20); + if let (Some(y), Some(z)) = (y, z) { + i += 3; + out.push(json!([t.code, [number(t), number(y), number(z)]])); + continue; + } + number(t) + } + 1020..=1033 | 1040..=1042 => number(t), + 1070 | 1071 => integer(t), + _ => json!(t.value), + }; + out.push(json!([t.code, v])); + i += 1; + } + out +} + +/// What `properties.set`'s `xdata` parameter asks for: per application, its new groups (with +/// their `1001` left out) or `None` to remove it. Everything is checked here: names, codes, value +/// types and ranges, braces, sizes; reserved applications are refused. +pub(crate) fn xdata_from_json(v: &Value) -> Result>)>, String> { + let Some(obj) = v.as_object() else { return Err("`xdata` must be an object {\"APP\": [[code, value], …] | null}".into()) }; + if obj.len() > MAX_APPS_PER_CALL { + return Err(format!("`xdata` may name at most {MAX_APPS_PER_CALL} applications")); + } + let mut out = Vec::with_capacity(obj.len()); + for (app, groups) in obj { + check_xdata_app_name(app).map_err(|e| e.to_string())?; + if is_reserved_xdata_app(app) { + return Err(format!("xdata application `{app}` is reserved: CADCraft writes its data itself")); + } + let groups = match groups { + Value::Null => None, + Value::Array(a) => Some(groups_from_json(app, a)?), + _ => return Err(format!("xdata of `{app}` must be a list of [code, value] pairs, or null to remove it")), + }; + out.push((app.trim().to_string(), groups)); + } + Ok(out) +} + +/// `[[code, value], …]` of one application as groups, each value checked for its code. +fn groups_from_json(app: &str, pairs: &[Value]) -> Result, String> { + if pairs.len() > MAX_XDATA_GROUPS { + return Err(format!("xdata of `{app}`: at most {MAX_XDATA_GROUPS} groups")); + } + let mut out = Vec::with_capacity(pairs.len()); + for (n, pair) in pairs.iter().enumerate() { + let at = || format!("xdata of `{app}`, group {}", n + 1); + let (code, value) = match pair.as_array().map(Vec::as_slice) { + Some([c, v]) => (c.as_i64().and_then(|c| i32::try_from(c).ok()).ok_or_else(|| format!("{}: the code must be an integer", at()))?, v), + _ => return Err(format!("{}: each group is a [code, value] pair", at())), + }; + let real = |x: &Value| x.as_f64().filter(|x| x.is_finite()).map(craft_dxf::format_real); + match code { + 1000 | 1003 => { + let s = value.as_str().ok_or_else(|| format!("{}: group {code} takes a string", at()))?; + out.push(RawTag { code, value: s.to_string() }); + } + 1002 => match value.as_str() { + Some(b @ ("{" | "}")) => out.push(RawTag { code, value: b.to_string() }), + _ => return Err(format!("{}: group 1002 takes \"{{\" or \"}}\"", at())), + }, + 1004 => { + let s = value.as_str().ok_or_else(|| format!("{}: group 1004 takes hex text", at()))?; + out.push(RawTag { code, value: s.trim().to_ascii_uppercase() }); + } + 1005 => { + let s = value.as_str().ok_or_else(|| format!("{}: group 1005 takes a hex handle", at()))?; + out.push(RawTag { code, value: s.trim().to_ascii_uppercase() }); + } + 1010..=1013 => { + let p = value.as_array().filter(|a| a.len() == 2 || a.len() == 3).and_then(|a| a.iter().map(real).collect::>>()); + let Some(p) = p else { return Err(format!("{}: group {code} takes a point [x, y, z] of finite numbers", at())) }; + out.push(RawTag { code, value: p.first().cloned().unwrap_or_default() }); + out.push(RawTag { code: code + 10, value: p.get(1).cloned().unwrap_or_default() }); + out.push(RawTag { code: code + 20, value: p.get(2).cloned().unwrap_or_else(|| "0.0".into()) }); + } + 1020..=1023 | 1030..=1033 => return Err(format!("{}: give the point as [{}, [x, y, z]]", at(), 1010 + (code % 10))), + 1040..=1042 => { + let x = real(value).ok_or_else(|| format!("{}: group {code} takes a finite number", at()))?; + out.push(RawTag { code, value: x }); + } + 1070 | 1071 => { + let i = value.as_i64().ok_or_else(|| format!("{}: group {code} takes an integer", at()))?; + out.push(RawTag { code, value: i.to_string() }); + } + _ => return Err(format!("{}: {code} is not an xdata group code (1000–1071)", at())), + } + } + check_xdata_groups(&out).map_err(|e| format!("xdata of `{app}`: {e}"))?; + Ok(out) +} + +/// Apply a parsed `xdata` parameter to an entity's xdata. +pub(crate) fn apply(xdata: &mut Vec, changes: &[(String, Option>)]) { + for (app, groups) in changes { + set_xdata_app(xdata, app, groups.as_deref()); + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + fn t(code: i32, value: &str) -> RawTag { + RawTag { code, value: value.into() } + } + + #[test] + fn json_round_trip_types_every_kind() { + let x = vec![ + t(1001, "ACME"), + t(1000, "D-07"), + t(1002, "{"), + t(1003, "Walls"), + t(1004, "0AFF"), + t(1005, "2A"), + t(1010, "1.5"), + t(1020, "2.0"), + t(1030, "0.0"), + t(1040, "2.5"), + t(1070, "3"), + t(1071, "70000"), + t(1002, "}"), + t(1001, "PE_URL"), + t(1000, "https://example.com"), + ]; + let j = xdata_json(&x).unwrap(); + assert_eq!( + j["ACME"], + json!([ + [1000, "D-07"], + [1002, "{"], + [1003, "Walls"], + [1004, "0AFF"], + [1005, "2A"], + [1010, [1.5, 2.0, 0.0]], + [1040, 2.5], + [1070, 3], + [1071, 70000], + [1002, "}"] + ]) + ); + assert_eq!(j["PE_URL"], json!([[1000, "https://example.com"]])); + let back = xdata_from_json(&j).unwrap(); + let mut y = Vec::new(); + apply(&mut y, &back); + assert_eq!(y, x); + assert_eq!(xdata_json(&[]), None); + assert_eq!(XdataSelect::Apps(vec!["pe_url".into()]).json(&x).unwrap().as_object().unwrap().len(), 1); + assert!(XdataSelect::Apps(vec!["nope".into()]).json(&x).is_none()); + assert!(!XdataSelect::Apps(vec!["nope".into()]).matches(&x) && XdataSelect::Apps(vec!["acme".into()]).matches(&x)); + } + + #[test] + fn bad_input_is_refused() { + for bad in [ + json!([]), + json!({"": [[1000, "x"]]}), + json!({"CADCRAFT": [[1000, "x"]]}), + json!({"A": [[1000, 5]]}), + json!({"A": [[1001, "B"]]}), + json!({"A": [[8, "layer"]]}), + json!({"A": [[1002, "("]]}), + json!({"A": [[1002, "{"]]}), + json!({"A": [[1010, [1, 2, 3, 4]]]}), + json!({"A": [[1010, [1, "x"]]]}), + json!({"A": [[1010, 1]]}), + json!({"A": [[1020, 1]]}), + json!({"A": [[1040, "1"]]}), + json!({"A": [[1070, 1.5]]}), + json!({"A": [[1070, 70000]]}), + json!({"A": [[1071, 1e12]]}), + json!({"A": [[1004, "ABC"]]}), + json!({"A": [[1005, "xyz"]]}), + json!({"A": [1000, "x"]}), + json!({"A": "x"}), + json!({"A": [[1000, "x".repeat(300)]]}), + ] { + assert!(xdata_from_json(&bad).is_err(), "{bad}"); + } + assert_eq!(xdata_from_json(&json!({"A": null})).unwrap(), vec![("A".to_string(), None)]); + assert_eq!(xdata_from_json(&json!({"A": []})).unwrap(), vec![("A".to_string(), Some(Vec::new()))]); + assert!(XdataSelect::parse(Some(&json!(1))).is_err()); + assert!(XdataSelect::parse(Some(&json!([]))).is_err()); + assert!(XdataSelect::parse(Some(&json!([1]))).is_err()); + assert_eq!(XdataSelect::parse(Some(&json!(true))).unwrap(), XdataSelect::All); + assert_eq!(XdataSelect::parse(Some(&json!("A"))).unwrap(), XdataSelect::Apps(vec!["A".into()])); + assert_eq!(XdataSelect::parse(None).unwrap(), XdataSelect::None); + } +} diff --git a/crates/engine/src/lisp.rs b/crates/engine/src/lisp.rs index 14ce5e94a..7ad3b6a96 100644 --- a/crates/engine/src/lisp.rs +++ b/crates/engine/src/lisp.rs @@ -75,6 +75,10 @@ pub struct Env { /// The command history's length after LISP last printed a line: when something else wrote since /// (a prompt, a command's echo), a leading newline only ends that line. pub printed_at: Option, + /// Application names `regapp` registered (upper case). A drawing's APPID table is written + /// from the xdata its objects carry, so this only makes `regapp` answer like AutoCAD's and + /// shows the names in the APPID table `tblsearch` lists. + pub regapps: std::collections::BTreeSet, } impl Default for Env { @@ -93,6 +97,7 @@ impl Default for Env { pending_block: None, objects: objects::Names::default(), printed_at: None, + regapps: std::collections::BTreeSet::new(), }; builtins::install(&mut e); e diff --git a/crates/engine/src/lisp/builtins.rs b/crates/engine/src/lisp/builtins.rs index 01f103bfc..3f080e2fe 100644 --- a/crates/engine/src/lisp/builtins.rs +++ b/crates/engine/src/lisp/builtins.rs @@ -252,6 +252,7 @@ static BUILTINS: &[Builtin] = &[ ctx!("ENTNEXT", drawing::entnext), ctx!("ENTUPD", drawing::entupd), ctx!("HANDENT", drawing::handent), + ctx!("REGAPP", drawing::regapp), ctx!("SSGET", drawing::ssget), ctx!("SSADD", drawing::ssadd), ctx!("SSDEL", drawing::ssdel), diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 69ee83466..d6caf844a 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -6,13 +6,16 @@ //! //! Entity lists use the DXF groups the file reader and writer use (through //! [`crate::cmd::file::entity_codec`]), so what `entget` shows is what a DXF file holds, except -//! for angles, which are radians in a list and degrees in a file. +//! for angles, which are radians in a list and degrees in a file. Extended data (xdata) is the +//! `-3` group, as in AutoCAD: `(entget ename '("APP" …))` adds `(-3 ("APP" (1000 . "…") …))` for +//! the applications named (wildcards allowed), `entmake` and `entmod` take it, and `regapp` +//! registers an application name. use std::collections::HashMap; use std::sync::{Arc, Mutex}; -use cadcraft_doc::{Entity, Handle, Space}; +use cadcraft_doc::{Entity, Handle, RawTag, Space}; use cadcraft_geom::Vec2; use craft_dxf::Tag; @@ -340,7 +343,7 @@ fn list_to_groups(list: &Value) -> Result<(String, Vec), LispError> { other => return Err(LispError::bad_arg("stringp", other)), }) } - -1 | 5 | 330 | 360 | 410 | 102 => {} + -1 | -3 | 5 | 330 | 360 | 410 | 102 => {} _ if point_group(code) && matches!(v, Value::Cons(_)) => { let p = v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &v))?; tags.push(Tag::f(code, p[0])); @@ -374,6 +377,12 @@ fn space_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option { pub fn entget(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 2)?; let h = ename(&a[0])?; + // The applications whose xdata to list: names or wildcard patterns ("*": every application). + let apps: Option> = match a.get(1) { + None | Some(Value::Nil) => None, + Some(v) if v.is_list() => Some(v.iter().map(|x| string(&x)).collect::>()?), + Some(other) => return Err(LispError::bad_arg("listp", other)), + }; let drawn = ctx.s.doc().is_ok_and(|d| d.entity(h).is_some()); let from_block = if drawn { None } else { block_entity(ctx, h) }; let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) }; @@ -385,6 +394,7 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec) -> Result { (None, None) => return Ok(Flow::Value(super::objects::entget(ctx, h))), }; let (kind, mut tags) = (codec()?.groups)(d, e); + let xdata = apps.map(|apps| xdata_to_list(&e.common.xdata, &apps)).filter(|v| !v.is_nil()); convert_angles(&kind, &mut tags, f64::to_radians); let layout = match space_of(d, h) { Some(Space::Paper(name)) => name, @@ -401,12 +411,157 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec) -> Result { placed_layout = true; } } + if let Some(x) = xdata { + items.push(Value::cons(Value::Int(-3), x)); + } Ok(Flow::Value(Value::list(items))) } -/// The entity a list describes, as the reader makes it; a missing layer (8) is the current one. -fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<(String, cadcraft_doc::Common, cadcraft_doc::EntityKind), LispError> { +/// A group kept raw, typed by its code (so a 1070 lists as an integer, a 1040 as a real, and a +/// 1071 as a real per AutoLISP's `entget`, though the file holds a 32-bit integer). +fn typed_tag(r: &RawTag) -> Tag { + use craft_dxf::{Kind, Value as V, kind_of}; + let v = r.value.trim(); + let value = if r.code == 1071 { + v.parse::().ok().map(|n| V::Real(n as f64)) + } else { + match kind_of(r.code) { + Kind::Real => v.parse::().ok().filter(|x| x.is_finite()).map(V::Real), + Kind::Int16 | Kind::Int32 | Kind::Int64 => v.parse::().ok().map(V::Int), + Kind::Bool => v.parse::().ok().map(|x| V::Bool(x != 0)), + Kind::Hex => Some(V::Hex(v.to_string())), + Kind::Str => None, + } + }; + Tag::new(r.code, value.unwrap_or_else(|| V::Str(r.value.clone()))) +} + +/// The `-3` group's value: `(("APP" (1000 . "…") (1070 . 3) (1010 x y z) …) …)` for the +/// applications of `xdata` matching one of `patterns` (any case; `wcmatch` wildcards). +fn xdata_to_list(xdata: &[RawTag], patterns: &[String]) -> Value { + let patterns: Vec = patterns.iter().map(|p| p.trim().to_ascii_uppercase()).collect(); + // A file may hold several runs of one application, `ACME` and `acme` among them; they are + // one application to `set_xdata_app`, so they are one list here (first spelling, all the + // groups), or `(entmod (entget e '("*")))` would keep only the last run. + let mut apps: Vec<(&str, Vec)> = Vec::new(); + for (name, groups) in cadcraft_doc::xdata_apps(xdata) { + let up = name.to_ascii_uppercase(); + if !patterns.iter().any(|p| super::builtins::wild_match(&up, p)) { + continue; + } + match apps.iter_mut().find(|(app, _)| app.eq_ignore_ascii_case(name)) { + Some((_, all)) => all.extend_from_slice(groups), + None => apps.push((name, groups.to_vec())), + } + } + let lists: Vec = apps + .into_iter() + .map(|(name, groups)| { + let tags: Vec = groups.iter().map(typed_tag).collect(); + Value::list_with_tail(vec![Value::str(name)], Value::list(groups_to_list(&tags))) + }) + .collect(); + Value::list(lists) +} + +/// The applications of a list's `-3` group, each with its groups (checked as xdata): `None` +/// when the list has no `-3`. An application with no groups removes its data in `entmod`. +fn xdata_from_list(list: &Value) -> Result)>>, LispError> { + let Some(x) = list.iter().find(|v| v.car().as_number() == Some(-3.0)).map(|v| v.cdr()) else { return Ok(None) }; + // `(-3 . 7)` is not a list of applications: refused, not read as "no applications". + if !x.is_list() { + return Err(LispError::bad_arg("listp", &x)); + } + let bad = |what: &str| LispError::new(format!("bad DXF group: {what}")); + let mut out = Vec::new(); + for app in x.iter() { + let name = match app.car() { + Value::Str(s) => s.to_string(), + other => return Err(LispError::bad_arg("stringp", &other)), + }; + cadcraft_doc::check_xdata_app_name(&name).map_err(|e| bad(&e.to_string()))?; + if cadcraft_doc::is_reserved_xdata_app(&name) { + return Err(bad(&format!("xdata application {name} is reserved"))); + } + // The application's groups must be a proper list too: `("ACME" . 7)` would otherwise + // read as "no groups" and remove the data in `entmod`, and a dotted tail after real + // groups would be dropped. + let tail = app.cdr(); + if !tail.is_list() { + return Err(LispError::bad_arg("listp", &tail)); + } + let mut groups: Vec = Vec::new(); + for g in tail.iter() { + if groups.len() >= cadcraft_doc::MAX_XDATA_GROUPS { + return Err(bad("too many xdata groups")); + } + let Value::Cons(c) = &g else { return Err(LispError::bad_arg("consp", &g)) }; + let Value::Int(code) = c.car else { return Err(LispError::bad_arg("fixnump", &c.car)) }; + match &c.cdr { + Value::Cons(_) if (1010..=1013).contains(&code) => { + let p = c.cdr.as_point().ok_or_else(|| LispError::bad_arg("3D point", &c.cdr))?; + if p.iter().any(|v| !v.is_finite()) { + return Err(bad("xdata point must be finite")); + } + groups.push(RawTag { code, value: craft_dxf::format_real(p[0]) }); + groups.push(RawTag { code: code + 10, value: craft_dxf::format_real(p[1]) }); + groups.push(RawTag { code: code + 20, value: craft_dxf::format_real(p[2]) }); + } + Value::Int(i) => groups.push(RawTag { code, value: i.to_string() }), + Value::Real(r) if code == 1071 => { + if r.is_finite() && r.fract() == 0.0 && *r >= f64::from(i32::MIN) && *r <= f64::from(i32::MAX) { + groups.push(RawTag { code, value: (*r as i32).to_string() }); + } else { + return Err(bad("group 1071 must be a 32-bit integer")); + } + } + Value::Real(r) => groups.push(RawTag { code, value: craft_dxf::format_real(*r) }), + Value::Str(s) => groups.push(RawTag { code, value: s.to_string() }), + Value::Ename(h) => groups.push(RawTag { code, value: h.hex() }), + other => return Err(LispError::bad_arg("DXF group value", other)), + } + } + cadcraft_doc::check_xdata_groups(&groups).map_err(|e| bad(&e.to_string()))?; + out.push((name, groups)); + } + Ok(Some(out)) +} + +/// `(regapp "name")`: register an application for xdata. The name when it is new, nil when it +/// is already registered (by `regapp` or by xdata an object carries) or invalid. Saving writes +/// an APPID record for every application with xdata, so nothing else is needed. +pub fn regapp(ctx: &mut Ctx<'_>, a: Vec) -> Result { + arity(&a, 1, 1)?; + let name = string(&a[0])?; + if cadcraft_doc::check_xdata_app_name(&name).is_err() { + return Ok(Flow::Value(Value::Nil)); + } + let up = name.trim().to_ascii_uppercase(); + let known = ctx.env.regapps.contains(&up) || ctx.s.doc().is_ok_and(|d| xdata_app_names(d).contains(&up)); + if known { + return Ok(Flow::Value(Value::Nil)); + } + ctx.env.regapps.insert(up); + Ok(Flow::Value(Value::str(name.trim()))) +} + +/// The upper-case names of every application registered in the drawing or carrying xdata on an object. +fn xdata_app_names(d: &cadcraft_doc::Drawing) -> std::collections::BTreeSet { + std::iter::once(&d.model) + .chain(d.layouts.iter().map(|l| &l.entities)) + .chain(d.blocks.values().map(|b| &b.entities)) + .flat_map(|s| s.iter()) + .flat_map(|e| cadcraft_doc::xdata_apps(&e.common.xdata).into_iter().map(|(n, _)| n.to_ascii_uppercase()).collect::>()) + .chain(d.foreign.appids.iter().map(|n| n.to_ascii_uppercase())) + .collect() +} + +/// The entity a list describes, as the reader makes it, with the applications of its `-3` +/// group (their xdata is on the entity); a missing layer (8) is the current one. +type ListedEntity = (String, cadcraft_doc::Common, cadcraft_doc::EntityKind, Option)>>); +fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result { let (kind, mut tags) = list_to_groups(list)?; + let xdata = xdata_from_list(list)?; convert_angles(&kind, &mut tags, f64::to_degrees); if !tags.iter().any(|t| t.code == 8) { let layer = crate::sysvars::get(ctx.s, "CLAYER").and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "0".into()); @@ -415,7 +570,23 @@ fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<(String, cadcraft_doc match (codec()?.entity)(&kind, &tags) { // A type the reader only carries through (an unknown or invalid name) isn't made. Some((_, cadcraft_doc::EntityKind::Unknown(_))) | None => Err(LispError::new(format!("bad DXF group: {kind} can't be made from this list"))), - Some((common, k)) => Ok((kind, common, k)), + Some((mut common, k)) => { + if let Some(apps) = &xdata { + for (app, groups) in apps { + // `ACAD` on a dimension holds its overrides (DSTYLE), written from the model. + if cadcraft_doc::is_model_xdata_app(app, &k) { + return Err(LispError::new(format!("bad DXF group: xdata application {app} of a {kind} is written from its own properties"))); + } + cadcraft_doc::set_xdata_app(&mut common.xdata, app, Some(groups)); + } + // Each application's groups are checked one by one above; together they must + // still fit what a file holds for one object. + if common.xdata.len() > cadcraft_doc::MAX_XDATA_GROUPS { + return Err(LispError::new("bad DXF group: too many xdata groups")); + } + } + Ok((kind, common, k, xdata)) + } } } @@ -428,7 +599,7 @@ pub fn entmake(ctx: &mut Ctx<'_>, a: Vec) -> Result { Ok((k, _)) if k == "ENDBLK" => return Ok(Flow::Value(end_block(ctx))), _ => {} } - let (_, common, kind) = match entity_from_list(ctx, list) { + let (_, common, kind, _) = match entity_from_list(ctx, list) { Ok(x) => x, Err(_) => return Ok(Flow::Value(Value::Nil)), }; @@ -531,7 +702,7 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec) -> Result { return Err(LispError::bad_arg("lentityp", &Value::Nil)); }; let Some(old) = ctx.s.doc().ok().and_then(|d| d.entity(h)).cloned() else { return Ok(Flow::Value(Value::Nil)) }; - let (kind_name, common, mut kind) = match entity_from_list(ctx, list) { + let (kind_name, mut common, mut kind, xdata) = match entity_from_list(ctx, list) { Ok(x) => x, Err(_) => return Ok(Flow::Value(Value::Nil)), }; @@ -539,6 +710,17 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec) -> Result { if !kind_name.eq_ignore_ascii_case(old.kind.dxf_name()) { return Ok(Flow::Value(Value::Nil)); } + // Xdata stays unless the list has a -3 group, which replaces the data of the applications it + // names (one with no groups removes it) and leaves the others alone, as in AutoCAD. + common.xdata = old.common.xdata.clone(); + if let Some(apps) = &xdata { + for (app, groups) in apps { + cadcraft_doc::set_xdata_app(&mut common.xdata, app, Some(groups)); + } + if common.xdata.len() > cadcraft_doc::MAX_XDATA_GROUPS { + return Ok(Flow::Value(Value::Nil)); + } + } // A block reference's attributes are entities of their own in AutoCAD, which entmod of the // INSERT leaves alone; its list doesn't hold them, so they are kept from the reference. if let (cadcraft_doc::EntityKind::Insert(new), cadcraft_doc::EntityKind::Insert(was)) = (&mut kind, &old.kind) @@ -1116,11 +1298,27 @@ fn table_records(d: &cadcraft_doc::Drawing, table: &str) -> Vec { .iter() .map(|s| Value::list(vec![pair(0, Value::str("DIMSTYLE")), pair(2, Value::str(&s.name)), pair(70, Value::Int(0))])) .collect(), - "APPID" => vec![Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str("ACAD")), pair(70, Value::Int(0))])], + "APPID" => std::iter::once("ACAD".to_string()) + .chain(xdata_app_names(d).into_iter().filter(|n| n != "ACAD")) + .map(|n| Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str(&n)), pair(70, Value::Int(0))])) + .collect(), _ => Vec::new(), } } +/// [`table_records`] plus, for APPID, the applications `regapp` registered in this session. +fn table_records_with(ctx: &Ctx<'_>, d: &cadcraft_doc::Drawing, table: &str) -> Vec { + let mut records = table_records(d, table); + if table == "APPID" { + let have: Vec = records.iter().map(record_name).map(|n| n.to_ascii_uppercase()).collect(); + for app in ctx.env.regapps.iter().filter(|a| !have.contains(a)) { + let pair = |c: i32, v: Value| Value::cons(Value::Int(c), v); + records.push(Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str(app)), pair(70, Value::Int(0))])); + } + } + records +} + fn record_name(r: &Value) -> String { r.iter().find(|p| p.car().as_number() == Some(2.0)).map(|p| to_text(&p.cdr(), false)).unwrap_or_default() } @@ -1130,7 +1328,7 @@ pub fn tblsearch(ctx: &mut Ctx<'_>, a: Vec) -> Result { let table = string(&a[0])?.to_ascii_uppercase(); let name = string(&a[1])?; let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) }; - let records = table_records(d, &table); + let records = table_records_with(ctx, d, &table); let found = records.iter().position(|r| record_name(r).eq_ignore_ascii_case(&name)); if let Some(i) = found && a.get(2).is_some_and(|v| !v.is_nil()) @@ -1145,7 +1343,7 @@ pub fn tblnext(ctx: &mut Ctx<'_>, a: Vec) -> Result { let table = string(&a[0])?.to_ascii_uppercase(); let rewind = a.get(1).is_some_and(|v| !v.is_nil()); let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) }; - let records = table_records(d, &table); + let records = table_records_with(ctx, d, &table); let i = if rewind { 0 } else { ctx.env.tblnext.get(&table).copied().unwrap_or(0) }; ctx.env.tblnext.insert(table, i + 1); Ok(Flow::Value(records.get(i).cloned().unwrap_or_default())) diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index 59438b591..5bb4225bd 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -666,6 +666,154 @@ fn handseed_follows_new_objects() { assert_eq!(ok(&mut s, "(cdr (assoc 5 (entget (entlast))))"), format!("\"{:X}\"", held + 1)); } +#[test] +fn entity_lists_carry_xdata_in_group_minus_3() { + let mut s = session(); + // entmake with a -3 group puts the xdata on the new entity; entget shows it only when asked. + let made = ok( + &mut s, + "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACME\" (1000 . \"D-07\") (1070 . 3) (1040 . 2.5) (1010 1.0 2.0 0.0) (1005 . \"2A\") (1071 . 100000)) (\"PE_URL\" (1000 . \"https://example.com\")))))", + ); + assert!(made.contains("LINE")); + assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast)))"), "nil"); + assert_eq!( + ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"acme\"))))"), + "((\"ACME\" (1000 . \"D-07\") (1070 . 3) (1040 . 2.5) (1010 1.0 2.0 0.0) (1005 . \"2A\") (1071 . 100000.0)))" + ); + // Group 1070 is INT, whereas group 1071 is REAL in AutoLISP's entget while remaining a 32-bit + // integer in the drawing/API and when written back with entmod. + assert_eq!( + ok( + &mut s, + "(setq g (cdr (car (cdr (assoc -3 (entget (entlast) '(\"ACME\"))))))) (list (type (cdr (assoc 1070 g))) (type (cdr (assoc 1071 g))))" + ), + "(INT REAL)" + ); + assert!(ok(&mut s, "(entmod (entget (entlast) '(\"ACME\")))").contains("LINE")); + assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2"); + assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"PE_*\" \"nope\")))))"), "1"); + assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast) '(\"nope\")))"), "nil"); + // The xdata is what the drawing holds (the API sees 1070 and 1071 as integers too). + let x = s.execute("entities", &serde_json::json!({"xdata": "ACME"})).unwrap(); + assert_eq!(x["entities"][0]["xdata"]["ACME"][1], serde_json::json!([1070, 3])); + assert_eq!(x["entities"][0]["xdata"]["ACME"][5], serde_json::json!([1071, 100000])); + // entmod without -3 keeps the xdata; with -3 it replaces the named applications' data and + // removes one listed without groups; the others stay. + ok(&mut s, "(setq d (entget (entlast))) (entmod (subst (cons 8 \"WALLS\") (assoc 8 d) d))"); + assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2"); + ok(&mut s, "(entmod (append (entget (entlast)) (list (list -3 (list \"ACME\" (cons 1070 9))))))"); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACME\"))))"), "((\"ACME\" (1070 . 9)))"); + assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2"); + ok(&mut s, "(entmod (append (entget (entlast)) '((-3 (\"PE_URL\")))))"); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))"); + // Bad xdata is refused as a bad list (nil), and nothing changes. + for bad in [ + "(-3 (\"ACME\" (1002 . \"{\")))", + "(-3 (\"ACME\" (8 . \"0\")))", + "(-3 (\"ACME\" (1070 . 70000)))", + "(-3 (\"ACME\" (1071 . 1.5)))", + "(-3 (\"ACME\" (1071 . 2147483648.0)))", + "(-3 (\"ACME\" (1071 . -2147483649.0)))", + "(-3 (\"ACME\" (1010 1.0)))", + "(-3 (\"CADCRAFT\" (1000 . \"x\")))", + "(-3 (\"\" (1000 . \"x\")))", + "(-3 (7 (1000 . \"x\")))", + "(-3 (\"ACME\" 5))", + ] { + assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '({bad})))")), "nil", "{bad}"); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))", "{bad}"); + } + assert!(eval(&mut s, "(entget (entlast) \"ACME\")").is_err(), "the second argument is a list"); + // regapp: the name when new, nil once registered (by regapp or by xdata an object carries); + // the APPID table lists both. + assert_eq!(ok(&mut s, "(regapp \"ACME\")"), "nil"); + assert_eq!(ok(&mut s, "(regapp \"MYAPP\")"), "\"MYAPP\""); + assert_eq!(ok(&mut s, "(regapp \"myapp\")"), "nil"); + assert_eq!(ok(&mut s, "(regapp \"bad*name\")"), "nil"); + assert_eq!(ok(&mut s, "(cdr (assoc 2 (tblsearch \"APPID\" \"acme\")))"), "\"ACME\""); + assert_eq!(ok(&mut s, "(cdr (assoc 2 (tblsearch \"APPID\" \"MYAPP\")))"), "\"MYAPP\""); + assert_eq!(ok(&mut s, "(tblsearch \"APPID\" \"PE_URL\")"), "nil"); +} + +#[test] +fn group_1071_boundary_reals_round_trip_as_32bit_integers() { + let mut s = session(); + let made = + ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"LIMITS\" (1071 . 2147483647.0) (1071 . -2147483648.0) (1071 . -0.0)))))"); + assert!(made.contains("LINE")); + assert_eq!(ok(&mut s, "(type (cdr (assoc 1071 (cdr (car (cdr (assoc -3 (entget (entlast) '(\"LIMITS\")))))))))"), "REAL"); + assert!(ok(&mut s, "(entmod (entget (entlast) '(\"LIMITS\")))").contains("LINE")); + let lim = s.execute("entities", &serde_json::json!({"xdata": "LIMITS"})).unwrap(); + assert_eq!(lim["entities"][0]["xdata"]["LIMITS"], serde_json::json!([[1071, 2147483647], [1071, -2147483648], [1071, 0]])); +} + +#[test] +fn entmake_refuses_xdata_over_the_object_limit_across_applications() { + // Each application's groups fit the per-application cap; together they exceed what an object + // may hold, so the list is refused (nil) and nothing is made. + let mut s = session(); + ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0)))"); + let last = ok(&mut s, "(entlast)"); + let groups = "(1000 . \"x\") ".repeat(cadcraft_doc::MAX_XDATA_GROUPS / 2 + 8); + let code = format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 (\"A1\" {groups}) (\"A2\" {groups}))))"); + assert_eq!(ok(&mut s, &code), "nil"); + assert_eq!(ok(&mut s, "(entlast)"), last, "nothing was made"); + // Half of that on one application is within the limit and is made. + let code = format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 (\"A1\" {groups}))))"); + assert!(ok(&mut s, &code).contains("LINE")); + assert_ne!(ok(&mut s, "(entlast)"), last); +} + +#[test] +fn a_dotted_minus_3_group_is_refused() { + // `(-3 . 7)` names no applications; it is a bad list (nil), not an empty one. + let mut s = session(); + ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACME\" (1070 . 9)))))"); + let last = ok(&mut s, "(entlast)"); + assert_eq!(ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 . 7)))"), "nil"); + assert_eq!(ok(&mut s, "(entlast)"), last, "nothing was made"); + assert_eq!(ok(&mut s, "(entmod (append (entget (entlast)) '((-3 . 7))))"), "nil"); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))"); + // The same one level down: an application whose groups are not a proper list is refused, + // not read as "no groups" (which would remove its data), and a dotted tail after real + // groups is not dropped. + for bad in ["(\"ACME\" . 7)", "(\"ACME\" (1070 . 1) . 5)", "(\"NEW\" . \"x\")"] { + assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '((-3 {bad}))))")), "nil", "{bad}"); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))", "{bad}"); + assert_eq!(ok(&mut s, &format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 {bad})))")), "nil", "{bad}"); + assert_eq!(ok(&mut s, "(entlast)"), last, "{bad}"); + } +} + +#[test] +fn runs_of_one_application_in_any_case_are_one_list() { + // A file with `ACME` and `acme` runs on one entity: entget shows one application with every + // group, and writing that list back with entmod keeps them all. + let dxf = "0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n2A\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\ + 1001\nACME\n1070\n1\n1001\nacme\n1070\n2\n1001\nOTHER\n1000\nx\n0\nENDSEC\n0\nEOF\n"; + let mut s = session(); + s.open_drawing(cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(), "runs", None); + let want = "((\"ACME\" (1070 . 1) (1070 . 2)) (\"OTHER\" (1000 . \"x\")))"; + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), want); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"acme\"))))"), "((\"ACME\" (1070 . 1) (1070 . 2)))"); + assert!(ok(&mut s, "(entmod (entget (entlast) '(\"*\")))").contains("LINE")); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), want); +} + +#[test] +fn acad_xdata_of_a_dimension_is_refused_but_kept_on_other_entities() { + // A dimension's ACAD run is its DSTYLE overrides, written from the model: raw ACAD groups + // on it are refused (nil, nothing changes). On a line, ACAD is foreign data and stays. + let mut s = session(); + s.script("dimlinear 0,0 10,0 5,-3\n").unwrap(); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entlast))))"), "\"DIMENSION\""); + assert_eq!(ok(&mut s, "(entmod (append (entget (entlast)) '((-3 (\"ACAD\" (1070 . 1))))))"), "nil"); + assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast) '(\"*\")))"), "nil"); + let made = ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACAD\" (1000 . \"MINE\") (1070 . 42)))))"); + assert!(made.contains("LINE")); + assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACAD\"))))"), "((\"ACAD\" (1000 . \"MINE\") (1070 . 42)))"); +} + #[test] fn entity_lists_hold_angles_in_radians() { let mut s = session(); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 2825794a8..7bef32dce 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -212,6 +212,7 @@ mod vplayer_prompts; mod vports; mod wipeout_grips; mod xclip; +mod xdata_api; mod xdata_follows_entity; mod zoom_keywords; mod zoom_viewport; diff --git a/crates/engine/tests/it/xdata_api.rs b/crates/engine/tests/it/xdata_api.rs new file mode 100644 index 000000000..0945acfe5 --- /dev/null +++ b/crates/engine/tests/it/xdata_api.rs @@ -0,0 +1,246 @@ +//! Extended data (xdata) through the API: `entities` shows it when asked (`xdata: true`, or an +//! application name that also filters), `properties` lists it, and `properties.set` replaces or +//! removes one application's data, checked as hostile input; what is set is written to DXF with +//! its APPID record and read back the same. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use serde_json::{Value, json}; + +/// A LINE with a hyperlink and another application's data, a circle without any, and an +/// LWPOLYLINE with the second application's data. +const DXF: &str = "0\nSECTION\n2\nENTITIES\n\ +0\nLINE\n5\n2A\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\ +1001\nPE_URL\n1000\nhttps://example.com/door-7\n1002\n{\n1000\nDoor 7\n1002\n}\n\ +1001\nACME_TAGS\n1000\nD-07\n1070\n3\n1040\n2.5\n1071\n70000\n1010\n1.5\n1020\n2.5\n1030\n0\n1005\n2B\n1004\n0AFF\n\ +0\nCIRCLE\n5\n2C\n8\n0\n10\n50\n20\n50\n30\n0\n40\n5\n\ +0\nLWPOLYLINE\n5\n2B\n8\n0\n90\n3\n70\n0\n10\n0\n20\n5\n10\n5\n20\n5\n10\n5\n20\n10\n\ +1001\nACME_TAGS\n1000\nP-01\n\ +0\nENDSEC\n0\nEOF\n"; + +fn session_from(dxf: &str) -> Session { + let d = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "xdata", None); + s +} + +fn entities(s: &mut Session, p: Value) -> Vec { + s.execute("entities", &p).unwrap()["entities"].as_array().unwrap().clone() +} + +fn handle_of(s: &Session, line: bool) -> String { + s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Line(_)) == line).map(|e| e.handle.hex()).unwrap() +} + +#[test] +fn entities_show_xdata_only_when_asked() { + let mut s = session_from(DXF); + let plain = entities(&mut s, json!({})); + assert_eq!(plain.len(), 3); + assert!(plain.iter().all(|e| e.get("xdata").is_none()), "{plain:?}"); + + let all = entities(&mut s, json!({"xdata": true})); + let line = all.iter().find(|e| e["type"] == "Line").unwrap(); + assert_eq!(line["xdata"]["PE_URL"], json!([[1000, "https://example.com/door-7"], [1002, "{"], [1000, "Door 7"], [1002, "}"]])); + assert_eq!( + line["xdata"]["ACME_TAGS"], + json!([[1000, "D-07"], [1070, 3], [1040, 2.5], [1071, 70000], [1010, [1.5, 2.5, 0.0]], [1005, "2B"], [1004, "0AFF"]]) + ); + assert!(all.iter().find(|e| e["type"] == "Circle").unwrap().get("xdata").is_none(), "no xdata, no key"); + assert_eq!(s.execute("entities", &json!({"xdata": false})).unwrap()["entities"], json!(plain)); + + // An application name keeps only the entities carrying its data and shows just that. + let acme = entities(&mut s, json!({"xdata": "acme_tags"})); + assert_eq!(acme.len(), 2); + assert!(acme.iter().all(|e| e["xdata"].as_object().unwrap().keys().eq(["ACME_TAGS"])), "{acme:?}"); + let r = s.execute("entities", &json!({"xdata": ["PE_URL"], "type": "Line"})).unwrap(); + assert_eq!((r["count"].as_u64(), r["returned"].as_u64()), (Some(1), Some(1))); + assert_eq!(s.execute("entities", &json!({"xdata": ["NOPE"]})).unwrap()["count"], 0); + for bad in [json!({"xdata": 1}), json!({"xdata": []}), json!({"xdata": [1]}), json!({"xdata": {"app": true}})] { + assert!(s.execute("entities", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn properties_set_replaces_removes_and_round_trips_through_dxf() { + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let h = handle_of(&s, true); + // A 1005 handle refers to an object of the drawing (here the line itself): saving remaps it + // with the other references, so one that refers to nothing would come back as 0. + let acme = json!([ + [1000, "D-07"], + [1002, "{"], + [1003, "0"], + [1004, "0aff"], + [1005, h.to_ascii_lowercase()], + [1010, [1.5, 2.5]], + [1011, [1, 2, 3]], + [1040, 2.5], + [1041, -1.0], + [1042, 1e3], + [1070, -3], + [1071, 70000], + [1002, "}"] + ]); + let want = json!([ + [1000, "D-07"], + [1002, "{"], + [1003, "0"], + [1004, "0AFF"], + [1005, h], + [1010, [1.5, 2.5, 0.0]], + [1011, [1.0, 2.0, 3.0]], + [1040, 2.5], + [1041, -1.0], + [1042, 1000.0], + [1070, -3], + [1071, 70000], + [1002, "}"] + ]); + let r = s.execute("properties.set", &json!({"handles": [h], "xdata": {"ACME": acme, "PE_URL": [[1000, "https://example.com"]]}})).unwrap(); + assert_eq!(r["changed"], 1); + let got = &entities(&mut s, json!({"xdata": true}))[0]["xdata"]; + assert_eq!(got["ACME"], want); + assert_eq!(got["PE_URL"], json!([[1000, "https://example.com"]])); + // `properties` lists it too. + let props = s.execute("properties", &json!({"handles": [h]})).unwrap(); + assert_eq!(props["objects"][0]["xdata"]["ACME"], want); + + // Saved and read back the same, with an APPID record for each application. + let text = cadcraft_io::write_dxf(s.doc().unwrap()); + let tags = craft_dxf::parse_ascii(&text).unwrap(); + let appids: Vec = + craft_dxf::records(&tags).iter().filter(|(k, _)| k == "APPID").filter_map(|(_, t)| t.iter().find(|t| t.code == 2).map(|t| t.str())).collect(); + assert!(appids.contains(&"ACME".to_string()) && appids.contains(&"PE_URL".to_string()), "{appids:?}"); + let mut back = session_from(&text); + assert_eq!(handle_of(&back, true), h, "the line keeps its handle"); + let again = &entities(&mut back, json!({"xdata": true}))[0]["xdata"]; + assert_eq!(again, got, "{text}"); + + // Replacing one application leaves the other; null removes; undo brings it back. + s.execute("properties.set", &json!({"handles": [h], "xdata": {"ACME": [[1070, 9]]}})).unwrap(); + let got = &entities(&mut s, json!({"xdata": true}))[0]["xdata"]; + assert_eq!(got, &json!({"ACME": [[1070, 9]], "PE_URL": [[1000, "https://example.com"]]})); + s.execute("properties.set", &json!({"handles": [h], "xdata": {"PE_URL": null, "ACME": []}})).unwrap(); + assert!(entities(&mut s, json!({"xdata": true}))[0].get("xdata").is_none()); + s.undo().unwrap(); + assert_eq!(entities(&mut s, json!({"xdata": true}))[0]["xdata"]["ACME"], json!([[1070, 9]])); + // The xdata of a drawing's own file comes with it and can be edited too. + let mut s = session_from(DXF); + let h = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_))).map(|e| e.handle.hex()).unwrap(); + s.execute("properties.set", &json!({"handles": [h], "xdata": {"acme_tags": [[1000, "P-02"]]}})).unwrap(); + assert_eq!(entities(&mut s, json!({"xdata": "ACME_TAGS", "type": "LwPolyline"}))[0]["xdata"], json!({"acme_tags": [[1000, "P-02"]]})); +} + +#[test] +fn bad_xdata_is_refused_and_changes_nothing() { + let mut s = session_from(DXF); + let h = handle_of(&s, true); + let before = entities(&mut s, json!({"xdata": true})); + let huge: Vec = std::iter::repeat_n(json!([1000, "x"]), cadcraft_engine::doc::MAX_XDATA_GROUPS + 1).collect(); + for bad in [ + json!([]), + json!("ACME"), + json!({"": [[1000, "x"]]}), + json!({"CADCRAFT": [[1000, "x"]]}), + json!({"bad*name": [[1000, "x"]]}), + json!({"ACME": "x"}), + json!({"ACME": [1000, "x"]}), + json!({"ACME": [[1000]]}), + json!({"ACME": [[1000, 5]]}), + json!({"ACME": [[1001, "B"]]}), + json!({"ACME": [[8, "0"]]}), + json!({"ACME": [[999, "x"]]}), + json!({"ACME": [[1072, 1]]}), + json!({"ACME": [["1000", "x"]]}), + json!({"ACME": [[1e300, "x"]]}), + json!({"ACME": [[1002, "("]]}), + json!({"ACME": [[1002, "}"]]}), + json!({"ACME": [[1002, "{"], [1000, "x"]]}), + json!({"ACME": [[1010, 1]]}), + json!({"ACME": [[1010, [1]]]}), + json!({"ACME": [[1010, [1, 2, 3, 4]]]}), + json!({"ACME": [[1010, [1, "y"]]]}), + json!({"ACME": [[1020, 1]]}), + json!({"ACME": [[1040, "1"]]}), + json!({"ACME": [[1040, null]]}), + json!({"ACME": [[1070, 1.5]]}), + json!({"ACME": [[1070, 40000]]}), + json!({"ACME": [[1071, 3000000000i64]]}), + json!({"ACME": [[1004, "ABC"]]}), + json!({"ACME": [[1004, "zz"]]}), + json!({"ACME": [[1005, ""]]}), + json!({"ACME": [[1005, "nothex"]]}), + json!({"ACME": [[1000, "x".repeat(256)]]}), + json!({"ACME": [[1000, "a\nb"]]}), + json!({"ACME": huge}), + ] { + let err = s.execute("properties.set", &json!({"handles": [h], "xdata": bad})).expect_err(&format!("{bad} must be refused")); + assert!(!err.to_string().is_empty()); + assert_eq!(entities(&mut s, json!({"xdata": true})), before, "{bad} changed something"); + } + // Together, two applications may not exceed what one object holds. + let full: Vec = std::iter::repeat_n(json!([1070, 1]), cadcraft_engine::doc::MAX_XDATA_GROUPS - 1).collect(); + s.execute("properties.set", &json!({"handles": [h], "xdata": {"PE_URL": null, "ACME_TAGS": null, "FULL": full}})).unwrap(); + let err = s.execute("properties.set", &json!({"handles": [h], "xdata": {"MORE": [[1070, 1]]}})).unwrap_err(); + assert!(err.to_string().contains("exceed"), "{err}"); + assert!(entities(&mut s, json!({"xdata": true}))[0]["xdata"].get("MORE").is_none()); +} + +#[test] +fn a_missing_handle_changes_nothing() { + // One handle that names no object fails the whole call before any object or the layer + // table changes: the other object keeps its data and the new layer is not created. + let mut s = session_from(DXF); + let h = handle_of(&s, true); + let before = entities(&mut s, json!({"xdata": true})); + let r = s.execute("properties.set", &json!({"handles": [h, "FFFF"], "layer": "NEWLAYER", "xdata": {"ACME": [[1000, "x"]]}})); + assert!(r.is_err(), "a missing handle is refused"); + assert_eq!(entities(&mut s, json!({"xdata": true})), before); + assert!(s.doc().unwrap().layer("NEWLAYER").is_none(), "no layer is left behind"); +} + +#[test] +fn runs_of_one_application_in_any_case_are_one_entry() { + // `ACME` and `acme` runs on one entity are one application (as `set_xdata_app` treats + // them): one JSON key with every group, and `properties.set` with that entry keeps them all. + let dxf = "0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n2A\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\ + 1001\nACME\n1070\n1\n1001\nacme\n1070\n2\n1001\nOTHER\n1000\nx\n0\nENDSEC\n0\nEOF\n"; + let mut s = session_from(dxf); + let h = handle_of(&s, true); + let shown = entities(&mut s, json!({"xdata": true})); + assert_eq!(shown[0]["xdata"], json!({"ACME": [[1070, 1], [1070, 2]], "OTHER": [[1000, "x"]]})); + assert_eq!(entities(&mut s, json!({"xdata": "acme"}))[0]["xdata"], json!({"ACME": [[1070, 1], [1070, 2]]})); + s.execute("properties.set", &json!({"handles": [h], "xdata": shown[0]["xdata"]})).unwrap(); + assert_eq!(entities(&mut s, json!({"xdata": true}))[0]["xdata"], shown[0]["xdata"]); +} + +#[test] +fn acad_xdata_of_a_dimension_is_refused_and_kept_elsewhere() { + // A dimension's `ACAD` run is its DSTYLE overrides, written from the model and read back + // into them: raw `ACAD` groups on a dimension would be lost on save, so they are refused + // (nothing changes). On any other object `ACAD` is foreign data and survives a save. + let mut s = Session::new(); + s.script("dimlinear 0,0 10,0 5,-3\n").unwrap(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let dim = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).map(|e| e.handle.hex()).unwrap(); + let line = handle_of(&s, true); + s.execute("properties.set", &json!({"handles": [&dim], "textHeight": 5})).unwrap(); + let before = entities(&mut s, json!({"xdata": true})); + let r = s.execute("properties.set", &json!({"handles": [&dim], "xdata": {"ACAD": [[1000, "MINE"], [1070, 42]]}})); + assert!(r.is_err(), "ACAD on a dimension is refused"); + assert_eq!(entities(&mut s, json!({"xdata": true})), before); + s.execute("properties.set", &json!({"handles": [&line], "xdata": {"ACAD": [[1000, "MINE"], [1070, 42]]}})).unwrap(); + let bytes = cadcraft_io::write(s.doc().unwrap(), "acad.dxf").unwrap(); + let mut back = Session::empty(); + back.open_drawing(cadcraft_io::read_dxf(&bytes).unwrap(), "acad", None); + let kept = entities(&mut back, json!({"xdata": "ACAD"})); + assert_eq!(kept.len(), 1, "only the line carries raw ACAD data"); + assert_eq!(kept[0]["type"], "Line"); + assert_eq!(kept[0]["xdata"], json!({"ACAD": [[1000, "MINE"], [1070, 42]]})); + // The dimension's own override is still there after the round trip. + let dm = back.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap(); + assert!(matches!(&dm.kind, EntityKind::Dimension(d) if !d.overrides.is_empty()), "the DSTYLE overrides survive"); +} diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index d2dbee7f2..64735a9f4 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -66,14 +66,15 @@ fn modelled_xdict_key(key: &str, of_insert: bool) -> bool { 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"]; +/// Applications whose xdata CADCraft reads and writes itself +/// ([`cadcraft_doc::RESERVED_XDATA_APPS`]). `ACAD` holds dimension overrides (DSTYLE) on +/// dimensions and dimension styles; elsewhere it is kept. +const OWN_APPS: &[&str] = cadcraft_doc::RESERVED_XDATA_APPS; /// Most objects kept from one file. const MAX_OBJECTS: usize = 1_000_000; /// Most xdata groups kept per record (AutoCAD allows 16 KB of xdata per object). -const MAX_XDATA_GROUPS: usize = 16_384; +const MAX_XDATA_GROUPS: usize = cadcraft_doc::MAX_XDATA_GROUPS; /// Longest ownership chain followed. const MAX_DEPTH: usize = 64; diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index b71c79d4f..de6def4f2 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -18,10 +18,11 @@ pub fn tool_definitions(has_ui: bool) -> Value { "inputSchema": {"type": "object", "properties": {"filter": {"type": "string"}}}}), json!({"name": "inspect_drawing", "description": "Summary of the active drawing: entity counts, extents, layers, styles, blocks, layouts, selection, undo history and (optionally) entities with handles and geometry.", "inputSchema": {"type": "object", "properties": {"entities": {"type": "boolean"}, "limit": {"type": "integer"}}}}), - json!({"name": "query_entities", "description": "Entities filtered by type (Line, Circle, Polyline…), layer, current selection (selected:true; active space only) and/or a window [[x0,y0],[x1,y1]] (objects whose geometry is inside or crosses it; crossing:false = entirely inside). Returns count (all matches), returned (this page) and entities; page with offset and limit (default 500).", + json!({"name": "query_entities", "description": "Entities filtered by type (Line, Circle, Polyline…), layer, current selection (selected:true; active space only) and/or a window [[x0,y0],[x1,y1]] (objects whose geometry is inside or crosses it; crossing:false = entirely inside). xdata:true adds each entity's extended data {APP: [[code, value], …]}; an application name (or a list of names) keeps only the entities carrying that application's data and shows it. Returns count (all matches), returned (this page) and entities; page with offset and limit (default 500).", "inputSchema": {"type": "object", "properties": {"type": {"type": "string"}, "layer": {"type": "string"}, "selected": {"type": "boolean"}, "window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2}, - "crossing": {"type": "boolean"}, "limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}), + "crossing": {"type": "boolean"}, "xdata": {"type": ["boolean", "string", "array"], "items": {"type": "string"}}, + "limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}), json!({"name": "render", "description": "Render the active drawing to a PNG and return it as an image content block (content[0].type is \"image\", not text): fitted to the extents by default, or just the area `window` [[x0,y0],[x1,y1]] (drawing units), e.g. one sheet or one room of a large drawing. With a window and no size the image is 1600 px wide with the window's shape. `background`: \"dark\" (the canvas; the default without a plot style), \"white\" (the default with one, as a plot prints on paper), \"paper\" or \"#rrggbb\"; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. \"monochrome.ctb\" (every colour black, as most plots) or \"grayscale.ctb\", which make light colours readable on white; \"none\" (or \"\") draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown background or plot style is refused.", "inputSchema": {"type": "object", "properties": {"width": {"type": "integer", "minimum": 16}, "height": {"type": "integer", "minimum": 16}, "fit": {"type": "boolean"}, "window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2}, diff --git a/docs/autolisp.md b/docs/autolisp.md index 4ca363570..3ce9703f4 100644 --- a/docs/autolisp.md +++ b/docs/autolisp.md @@ -89,7 +89,7 @@ reached", malformed source is a reader error, and every built-in checks its argu - **Drawing:** `command` (also `command-s`, `vl-cmdf`) with `pause`, entity names and `entsel` lists at prompts picking one object (a bare name picks at its DXF group 10 point, as in AutoCAD), a command left open for the next call, and `(command)` to cancel; `getvar setvar`; `entget entmake entmod entdel entlast - entnext entupd handent`; `ssget` (modes X, L, P, I, W, C, F, WP, CP, a point, or the user + entnext entupd handent regapp`; `ssget` (modes X, L, P, I, W, C, F, WP, CP, a point, or the user selecting; filters with wildcards and `-4` operators) `ssadd ssdel sslength ssname ssmemb sssetfirst ssgetfirst`; `tblsearch tblnext` (LAYER, LTYPE, STYLE, BLOCK, DIMSTYLE, APPID); `namedobjdict dictsearch dictnext tblobjname`, with `entget` and `handent` of the non-graphic @@ -109,10 +109,23 @@ it keeps them and their values. `entlast` and `entnext` see every change a routi own `entmake`, `entmod` and `entdel` included. `(getvar "HANDSEED")` is the next handle the drawing gives out, in hex. +Extended data (xdata) is the `-3` group, as in AutoCAD. `(entget ename '("APP" "PE_*"))` adds +`(-3 ("APP" (1000 . "text") (1070 . 3) (1040 . 2.5) (1010 x y z) (1005 . "2A") …) …)` for the +applications whose names match (any case, `wcmatch` wildcards; `'("*")` lists every +application); without the second argument the list holds no xdata. `entmake` puts a list's `-3` +group on the new entity. `entmod` keeps an entity's xdata unless the list has a `-3` group, +which replaces the data of the applications it names and removes one listed with no groups +(`(-3 ("APP"))`); other applications stay. Group codes, values and brace nesting are checked as +in a file (`entmod` and `entmake` answer nil to a bad `-3`). `(regapp "APP")` returns the name +when it is new and nil when the drawing already has that application's xdata (or `regapp` +registered it); saving writes an APPID record for every application with xdata anyway, and +`tblsearch "APPID"` lists them. + Block definitions can be read: `(tblsearch "BLOCK" name)` gives the block's first entity in group -2, `entnext` goes from one entity of a definition to the next (nil after the last) and `entget` lists them (without a layout, group 410). So a routine can read what a block stores, such as the text of a dimension's `*D` block. `entmod` and `entdel` don't change a definition's entities. + `entmake` defines blocks: a BLOCK list (2 name, 70 flags, 10 base point, 4 description) begins a definition, the entities made after it go into the block instead of the drawing, and an ENDBLK list adds the block (redefining one of the same name) and returns its name. Flag 1 with a `*U` diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bf344c7c3..19e218ab0 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -114,6 +114,34 @@ The existing response is unchanged: `count` is all matches, `returned` is the pa `entities` contains handles, layers and geometry. This query does not change selection, drawing contents or undo history. `entities` is a command, not a top-level protocol method. +## Extended data (xdata) + +Other applications' extended data travels with an entity (it is read from the file, kept on +copies and written back with an APPID record for each application). `entities` leaves it out +unless asked: `xdata: true` adds an `xdata` object to each entity that has any, by application, +each group as a `[code, value]` pair typed by its code — strings for 1000, 1002 (`{` / `}`), +1003 (a layer name), 1004 (hex) and 1005 (a handle), a point `[x, y, z]` for 1010–1013 (its +1020 and 1030 groups folded in), numbers for 1040–1042, integers for 1070 and 1071. An +application name (or a list of names) instead of `true` keeps only the entities carrying that +application's data and shows just it. `properties` lists every application's data of the +objects it reports. + +```json +{"id":8,"method":"engine.execute","params":{"command":"entities","params":{"xdata":"PE_URL","limit":100}}} +{"id":9,"method":"engine.execute","params":{"command":"properties.set","params":{"handles":["2A"],"xdata":{"ACME":[[1000,"D-07"],[1070,3],[1010,[1.5,2.5,0]]],"PE_URL":null}}}} +``` + +`properties.set` takes the same form: each application named is replaced by the groups given +(their `1001` left out) or removed by `null` (or an empty list); applications not named stay. +Names, codes, value types and ranges, brace nesting and sizes (16,384 groups per object, 255 +bytes per string) are checked and a bad `xdata` changes nothing. The applications CADCraft +writes from its own model (`CADCRAFT`, `AcadAnnotative`, the layer transparency and +description applications) can't be set this way, nor can `ACAD` on a dimension, whose `ACAD` +run holds its dimension-style overrides (set those through `textHeight`, `arrowSize` and the +other dimension properties); `ACAD` data on any other object is kept as it is. The change is +one undo step, like any other property edit. In AutoLISP the same data is the `-3` group of `entget`, `entmod` and `entmake` +(see [autolisp.md](autolisp.md)). + The MCP server (`cadcraft-cli mcp --connect 127.0.0.1:PORT`) wraps this protocol; headless (`cadcraft-cli mcp`) it serves the same methods from an in-process session. MCP tool names are another interface: `execute` maps to `engine.execute`, `list_commands` to diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 3f0210996..d67e33b52 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-31 · **Change:** minor (re-audit against main 7cee28580: justification, ATTDEF and CLASS rows; file-test count; previously: R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them; previously: attribute value edits refresh exported baselines; previously: LAYOUT SAveas writes a layout as a DWT template; previously: re-audit against main 41d9b5e95: acadrust 0.6.5, ACIS data, dynamic block, SCRIPT and SHX rows, io test count; previously: DIMASSOC objects for angular, diametric and radial dimensions) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (re-audit against main 7cee28580: justification, ATTDEF and CLASS rows; file-test count; previously: an entity's xdata is readable and editable through `entities`, `properties.set` and AutoLISP's `-3` group; previously: R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them; previously: attribute value edits refresh exported baselines; previously: LAYOUT SAveas writes a layout as a DWT template; previously: re-audit against main 41d9b5e95: acadrust 0.6.5, ACIS data, dynamic block, SCRIPT and SHX rows, io test count; previously: DIMASSOC objects for angular, diametric and radial dimensions) · **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 @@ -115,7 +115,7 @@ R2000 structure with the selected `$ACADVER`, version-specific groups and UTF-8 | Objects: LAYOUT, DICTIONARY, XRECORD, TABLESTYLE, DIMASSOC | yes | yes | | | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read; a proxy object (ACAD_PROXY_OBJECT) keeps its class: its group 91 is renumbered to the written CLASSES, which keep the class it names, and one whose number names no class is dropped (#1812) | not editable | -| Foreign xdata, extension dictionaries, reactors, unmodelled objects, colour books | kept raw (#528); an entity's xdata is part of the entity, so COPY, MIRROR, ARRAY and paste keep it on the copies (EXPLODE pieces don't); a renamed layer, block, linetype, text style or dimension style keeps its own | written back, handles remapped, references to deleted objects dropped | through DWG: xdata on table records and blocks, entity colour books and reactors, custom-class objects lost (acadrust) | +| Foreign xdata, extension dictionaries, reactors, unmodelled objects, colour books | kept raw (#528); an entity's xdata is part of the entity, so COPY, MIRROR, ARRAY and paste keep it on the copies (EXPLODE pieces don't); a renamed layer, block, linetype, text style or dimension style keeps its own; readable per application through `entities {xdata}`, `properties` and AutoLISP `entget` (`-3`) | written back, handles remapped, references to deleted objects dropped; an entity's xdata is editable (`properties.set {xdata}`, `entmod`, `entmake`), with an APPID record written for each application | through DWG: xdata on table records and blocks, entity colour books and reactors, custom-class objects lost (acadrust) | | Objects: dynamic block data (ACAD_EVALUATION_GRAPH, BLOCK…PARAMETER, BLOCK…ACTION, grips) | read into a model (`dynblock`, `blocks.dynamic`): parameters, visibility states, value sets, stretch and lookup actions; references: their dynamic block, values and custom properties (`blocks.reference`, Properties ▸ Custom); kept raw (#528) | written back as read; a changed reference is written as AutoCAD writes it (a new anonymous block with its `AcDbBlockRepBTag`, the objects' `AcDbBlockRepETag`, the reference's representation data) | visibility states, lookups (both ways), distances and positions can be changed (`blocks.reference.set`, Properties ▸ Custom, #860, #878), running the stretch and move actions that follow, and their grips show and drag (#883); polar, XY, rotation, alignment and flip parameters and the scale, rotate, flip, array and polar stretch actions are read but not applied (`dynblock/apply.rs`); no authoring; DWG open and save keep it too (checked with an AutoCAD dynamic block; open PR #1000 keeps the C++ class names the file gives) | | Handles and owners | entity handles kept; others regenerated | consistent | stable across CADCraft re-saves (#495); other programs' table and object handles renumbered once | @@ -159,6 +159,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| | 2026-10-30 | minor | Raster images: the picture is loaded from its file when a drawing opens and drawn on screen and in PNG output (#1756, viewport part; based on #1029) | +| 2026-10-30 | minor | An entity's xdata is exposed: `entities {xdata: true or "APP"}` and `properties` list it typed by group code, `properties.set {xdata}` replaces or removes one application's data (checked as hostile input), AutoLISP `entget` takes the application list and returns the `-3` group, `entmod`/`entmake` take it, `regapp` registers names; the APPID table is written as before | | 2026-10-29 | minor | R2000 DXF: CLASS records written without group 91 (instance count), which came with the 2004 format; AutoCAD LT 2026 stopped responding on every R2000 DXF CADCraft saved (checked black-box in AutoCAD LT 2026) | | 2026-10-26 | minor | CC-046: ATTEDIT and -ATTEDIT value changes invalidate derived justified baselines before DXF/DWG export; preserve alignment anchors, unchanged values and Aligned/Fit endpoints. Review follow-up: baseline recomputation preserves insertion elevation independently of alignment elevation. The shared writer correction also applies to justified TEXT. Independent of attribute editor UI; reverting the follow-up restores elevation loss on recomputation, while reverting the value setter restores stale XY baselines. | | 2026-10-25 | minor | LAYOUT SAveas (`layout.saveas`) writes a layout as a drawing template: its page setup and paper space objects, no model space objects or other layouts, and only the named objects they use | diff --git a/docs/gaps.md b/docs/gaps.md index f5896e6d3..abea859ac 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-12-01 · **Change:** minor (rows updated for what merged from 2026-11-25 to 2026-12-01: REFEDIT on xrefs, the automatic fallback renderer, EXTRIM, QLEADER, OFFSETGAPTYPE, pasted and wrapped table text, what saves keep, group display and draw order, JIS paper sizes, the Tamil catalog; previously: rows updated for what merged from 2026-11-21 to 2026-11-25: PDFIMPORT, dynamic block reference actions, proxy graphics and kept dimensions, what saves keep, Generate Boundary, the Array window, ATTDIA and constant attributes, Tab through every snap, macOS opening from Finder, the update-check option; U4 removed (done); previously: alpha-blocker marks follow the six-row gate of 2026-11-19; rows updated for what merged on 2026-11-19 and 2026-11-20: the Dimension Style Manager, the UCS command, in-place TEXT editing, -ATTEDIT, -RENAME and -LAYER options, ARRAY Key point, right-click settings and the interface reset; new row P4 for startup on older graphics hardware; previously: re-audit against main 7cee28580: file-test and catalog counts, REFEDIT, dynamic-block and QSAVE rows; previously: QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated; previously: BEDIT in the Block Editor switches blocks: F3 updated; previously: Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected; previously: DIMTFILL limits in the `*D` block, EXPLODE and DXF: F7 updated; re-audit against main 41d9b5e95: CI gate (#6, S1), MVIEW Restore (F15, U11), open-PR and catalog counts, file-test count; previously: Command Aliases dialog for ALIASEDIT: U12 and E5 narrowed) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-01 · **Change:** minor (rows updated for what merged from 2026-11-25 to 2026-12-01: REFEDIT on xrefs, the automatic fallback renderer, EXTRIM, QLEADER, OFFSETGAPTYPE, pasted and wrapped table text, what saves keep, group display and draw order, JIS paper sizes, the Tamil catalog; previously: rows updated for what merged from 2026-11-21 to 2026-11-25: PDFIMPORT, dynamic block reference actions, proxy graphics and kept dimensions, what saves keep, Generate Boundary, the Array window, ATTDIA and constant attributes, Tab through every snap, macOS opening from Finder, the update-check option; U4 removed (done); previously: alpha-blocker marks follow the six-row gate of 2026-11-19; rows updated for what merged on 2026-11-19 and 2026-11-20: the Dimension Style Manager, the UCS command, in-place TEXT editing, -ATTEDIT, -RENAME and -LAYER options, ARRAY Key point, right-click settings and the interface reset; new row P4 for startup on older graphics hardware; previously: re-audit against main 7cee28580: file-test and catalog counts, REFEDIT, dynamic-block and QSAVE rows; previously: xdata through `entities`, `properties.set` and LISP `-3`: FF1 and E1 narrowed; previously: QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated; previously: BEDIT in the Block Editor switches blocks: F3 updated; previously: Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected; previously: DIMTFILL limits in the `*D` block, EXPLODE and DXF: F7 updated; re-audit against main 41d9b5e95: CI gate (#6, S1), MVIEW Restore (F15, U11), open-PR and catalog counts, file-test count; previously: Command Aliases dialog for ALIASEDIT: U12 and E5 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 @@ -72,7 +72,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 (RENAME keeps the foreign data of layers, blocks and styles since #1020). A user's QSAVE now asks before such a loss and keeps the previous file as `.bak`; the loss itself remains. Proxy entities read from DXF are drawn from the proxy graphics their file carries and stay on their layers when the layer table changes (#2697, #3435, #3437); a dimension kept as read draws from its `*D` block, which a save keeps (#3439); saves keep registered applications (#2918), hatch boundary path flags (#3389), fit text (#3391), every layout's plot settings (#3233, #3386, #3390) and table cell text in DXF 2007 and later (#3392). Since then (#3689, #3692): covered table cell text (#3520), WIPEOUTFRAME (#3611), each layout's own LAYOUT flags (#3668), the `*Active` VPORT records' group 72 (#3670), an attribute set on layer 0 (#3613), dimension measurements with DIMLFAC (#3540), and the proxy-graphics follow-ups (#3483); a DWG save keeps the first 255 dash elements of a linetype and says so (#3536). | High | 6–10 | +| FF1 | **[alpha blocker]** Round-trip what we don't model. DXF done (#528): unknown entities and objects (with their CLASS records), foreign xdata (hyperlinks included), extension dictionaries, persistent reactors, DICTIONARYVAR and XRECORDs, layer states, colour book colours, references remapped on save; IMAGE, VIEW/UCS, groups, block descriptions, true colours, transparency (#201, #204, #208, #209, #213, #223); WIPEOUT and gradients (#147, #162). Left: through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour book names and reactors; UCS elevation; MTEXT background colours; unknown entities follow only layer edits (RENAME keeps the foreign data of layers, blocks and styles since #1020). A user's QSAVE now asks before such a loss and keeps the previous file as `.bak`; the loss itself remains. An entity's xdata is readable and editable through `entities`/`properties.set` and LISP's `-3` group, that of table records and blocks is not. Proxy entities read from DXF are drawn from the proxy graphics their file carries and stay on their layers when the layer table changes (#2697, #3435, #3437); a dimension kept as read draws from its `*D` block, which a save keeps (#3439); saves keep registered applications (#2918), hatch boundary path flags (#3389), fit text (#3391), every layout's plot settings (#3233, #3386, #3390) and table cell text in DXF 2007 and later (#3392). Since then (#3689, #3692): covered table cell text (#3520), WIPEOUTFRAME (#3611), each layout's own LAYOUT flags (#3668), the `*Active` VPORT records' group 72 (#3670), an attribute set on layer 0 (#3613), dimension measurements with DIMLFAC (#3540), and the proxy-graphics follow-ups (#3483); a DWG save keeps the first 255 dash elements of a linetype and says so (#3536). | High | 6–10 | | FF2 | Multileader leftovers (native MULTILEADER read/write landed, #459): several landings per multileader (extra leader roots are folded into the lines), per-object overrides (leader colour and linetype, arrowhead symbol, text frame), annotative scale contexts; check the text placement of our MULTILEADER output in AutoCAD | Medium | 3–5 | | FF3 | Save-version leftovers (DXF/DWG 2000–2018, binary DXF, SAVEAS `version`/`binary` and the default save version landed, #421): no R14 DWG or R12 DXF output; the Save dialog can't pick the version per file (the file picker doesn't report the chosen type; File > Default Save Format sets it); no command-line SAVEAS format prompt | Low | 2–4 | | FF4 | Code-page leftovers (pre-2007 DXF read in their `$DWGCODEPAGE` landed, #505): Johab (ANSI_1361) and DOS 855/857/860–865/869 read as ANSI_1252; saving declares `ANSI_1252` instead of the file's code page (the text is pure ASCII, so still correct); acadrust approximates DOS code pages in pre-2007 DWG (DOS437 as 866, DOS850 as 1252) | Low | 1–2 | @@ -133,7 +133,7 @@ Detail: [localization-parity.md](localization-parity.md). | # | Gap | Est. | |---|---|---| -| E1 | AutoLISP beyond the core (#758 landed the language, `command`, entity lists, selection sets, `get…` input, APPLOAD, `(load)`, `c:` commands and `acad.lsp`/`acaddoc.lsp` at startup; #1820 gave APPLOAD its `.lsp` file picker): Visual LISP ActiveX (`vlax-`, `vla-`), DCL dialogs, reactors, an APPLOAD Startup Suite, UCS-aware `trans` | 26–46 | +| E1 | AutoLISP beyond the core (#758 landed the language, `command`, entity lists, selection sets, `get…` input, APPLOAD, `(load)`, `c:` commands and `acad.lsp`/`acaddoc.lsp` at startup; #1820 gave APPLOAD its `.lsp` file picker; xdata: `entget` with an application list, the `-3` group in `entmod`/`entmake`, `regapp`): Visual LISP ActiveX (`vlax-`, `vla-`), DCL dialogs, reactors, an APPLOAD Startup Suite, UCS-aware `trans` | 26–46 | | E3 | Express Tools equivalents (SUPERHATCH; NCOPY, BREAKLINE, TXT2MTXT, BURST, MOCORO and EXTRIM exist: EXTRIM takes one cutting edge per run and skips block references, hatches, text and objects on locked layers (#3471, which lands #2808; follow-ups #3526 in #3690); BREAKLINE's Block option takes a block of the drawing, not a `.dwg` file, and TXT2MTXT's Settings are command-line prompts rather than a dialog, without the uniform line spacing option) | 24–40 | | E4 | Plug-in API (owner decision: Rust/WASM plug-ins rather than ObjectARX/.NET) | 30–50 | | E5 | CUI customisation (the alias editor, ALIASEDIT's Command Aliases dialog, landed, #1381; edits stay for the session) | 13–23 | @@ -155,6 +155,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-11-20 | minor | Batch for what merged on 2026-11-19 and 2026-11-20, and the six-row alpha gate: alpha-blocker marks removed from row 4, F1 and F3 (not gate rows any more) and added to H3 and the new P4 (startup on older graphics hardware, #3336); F1 narrowed (-ATTEDIT, -RENAME and -LAYER options, #3311); F5 (ARRAY Key point, #2368); F7 (Dimension Style Manager, #1460; dimension values kept on save, #3335); F9 (double-click edits TEXT, attribute definitions and dimension text in place, #3345); F20 (right-click settings, interface reset, #3308); F24 (UCS in the drawing plane, #3310); FF6 (size limits, typed OPEN in the background, #3343); U13 and P3 (#3344 waits for a Mac); S3 count. Hours not re-estimated | | 2026-11-03 | minor | XCLIP (rectangular, polygonal and polyline boundaries, Invert clip, ON/OFF, Delete, generate Polyline) and XCLIPFRAME: a boundary per block or xref reference (`Insert::clip`, block coordinates), drawn, plotted and framed clipped, the extents cut to it, and read and written as the reference's ACAD_FILTER/SPATIAL SPATIAL_FILTER in DXF and DWG: F2 and top-10 row 4 narrowed | | 2026-11-03 | minor | SHX fonts: shape fonts, big fonts and unifonts read (`cadcraft_fonts::shx`, every count and offset bounded) and drawn for TEXT, MTEXT, attributes, dimensions and tables, with the style's big font and vertical flag; found by file name beside the drawing, in `CADCRAFT_SHXPATH`, through a font map or from `.shx` files opened in the web app, never in another CAD program's folder; FONTALT may name a font and a big font; linetype shape elements drawn when their file is found: FF8 and FF9 narrowed | +| 2026-10-30 | minor | Xdata through the API: `entities {xdata}` and `properties` list an entity's extended data by application, `properties.set {xdata}` replaces or removes one application's data, AutoLISP `entget`/`entmod`/`entmake` carry the `-3` group and `regapp` registers names: FF1 and E1 narrowed | | 2026-10-30 | minor | QSAVE asks before replacing a file with content the DWG writer can't keep, and ISAVEBAK keeps the previous file as `.bak`: row 1 narrowed, FF1 and F20 updated | | 2026-10-25 | minor | Named Viewports (View ▸ Viewports ▸ Named Viewports..., `vports.named`) lists the saved viewport configurations with a preview and the current one's name, and restores or deletes one; in a layout Restore places it as MVIEW Restore does: U11 narrowed. F15 and U11 no longer list MVIEW Restore (#633), and F21 no longer says PURGE skips multiline styles | | 2026-10-25 | minor | DIMTFILL limits: with DIMTFILL 1 (the drawing's background color) the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI: F7 updated | diff --git a/docs/mcp.md b/docs/mcp.md index 534f4f1c8..ed61d5419 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -112,12 +112,12 @@ sandbox as well if other programs can change these folders. | `execute {command, params}` | Any command with JSON parameters, never a dialog. `list_commands` shows ids and parameter docs. | | `list_commands {filter?}` | The command catalog; `filter` matches part of a command's id, label or an alias. | | `inspect_drawing {entities?, limit?}` | Counts, extents, layers, styles, blocks, layouts, selection, undo history and entities. | -| `query_entities {type?, layer?, window?, crossing?, limit?, offset?}` | Filtered entities with handles and geometry. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `count` is every match, `returned` the page (`offset`, `limit`, default 500). | +| `query_entities {type?, layer?, window?, crossing?, xdata?, limit?, offset?}` | Filtered entities with handles and geometry. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `xdata: true` adds each entity's extended data as `{"APP": [[code, value], …]}`; an application name (or a list of names) keeps only the entities carrying that application's data and shows just it. `count` is every match, `returned` the page (`offset`, `limit`, default 500). | | `execute {"command": "shapes", "params": {type?, layer?, window?, crossing?, limit?, offset?, tolerance?}}` | Facts about the closed shapes — closed polylines, circles, full ellipses, closed splines: perimeter, area, centroid, winding, the first self-intersection and coincident vertices, exact with arcs and bulges. Other matches are counted under `skipped` with the reason. `selfCheck` says what was found, analysed and skipped, the caps hit with their values (`limit`, `crossingSegments`) and implausible values (perimeter past 10× the bounding-box diagonal, area larger than the drawing extents, each past a 1e-9 relative tolerance for rounding; with no visible objects there are no extents, so no area bound applies). | | `execute {"command": "shapes", "params": {type?, layer?, window?, crossing?, limit?, offset?, tolerance?}}` | Facts about the closed shapes — closed polylines, circles, full ellipses, closed splines: perimeter, area, centroid, winding, the first self-intersection and coincident vertices, exact with arcs and bulges. Other matches are counted under `skipped` with the reason. | | `execute {"command": "usage", "params": {type?, limit?, offset?}}` | Read-only cross-reference of the layers, blocks, text styles and linetypes: for each, the objects in model space and layouts that use it, the objects in block definitions that use it, whether it is used only inside block definitions, and whether it is empty or unused. `summary` counts each kind and `unused` lists what PURGE would offer, in table order. One scan reads at most 5,000,000 objects; a larger drawing sets `incomplete: true` with an `incompleteReason`, because counts, statuses and summaries then omit the objects past the limit. | | `execute {"command": "loops", "params": {tolerance?, maxPairs?, limit?, offset?}}` | Implied closed loops from loose LINE and ARC chains: each closed loop with its member handles, perimeter, area and winding, exact with arcs; each open chain with the endpoint gap, its location (`at`, `ends`) and length; and branch junctions (three or more ends meeting), reported but not resolved. `tolerance` defaults to 1e-9 × the extents diagonal; the quadratic endpoint pairing stops at `maxPairs` (default 1,000,000) and reports `capped` with `pairTestsNeeded` instead of guessing from a partial pairing. | -| `query_entities {type?, layer?, selected?, window?, crossing?, limit?, offset?}` | Filtered entities with handles and geometry. `selected: true` restricts results to the current selection in the active space; an empty selection returns no entities. Omitted/false queries all entities in that space. Filters combine before paging. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `count` is every match, `returned` the page (`offset`, `limit`, default 500). | +| `query_entities {type?, layer?, selected?, window?, crossing?, xdata?, limit?, offset?}` | Filtered entities with handles and geometry. `selected: true` restricts results to the current selection in the active space; an empty selection returns no entities. Omitted/false queries all entities in that space. Filters combine before paging. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `xdata: true` adds each entity's extended data (see [control-protocol.md](control-protocol.md#extended-data-xdata)); an application name keeps only the entities carrying its data. `count` is every match, `returned` the page (`offset`, `limit`, default 500). | | `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`; `"none"` (or `""`) draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. | | `find_text {contains?, query?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (`contains`, or `query` as an alias; any case), layer and a window around the insertion points. Read-only (the `texts` command). | | `new_drawing {metric?}`, `open {path}`, `save {path?}`, `cancel` | Files and Escape. `save` to a `.svg`, `.png` or `.pdf` path exports: the drawing keeps its name and unsaved changes. | From b778851b4847d0152dd14e7d7e15d1213204276c Mon Sep 17 00:00:00 2001 From: Books Date: Tue, 1 Dec 2026 06:16:30 -0500 Subject: [PATCH 40/43] Viewports keep their own UCS and their other settings through save and copy (part of #1316) (#1484) * Viewports keep their own UCS and their other settings through save and copy (part of #1316) A layout viewport's own UCS and every setting CADCraft doesn't model were dropped on read, so saving a sheet set lost them for good. - Viewport::ucs (origin, X/Y axes, elevation, orthographic type, named and base UCS by name) and ucs_per_viewport (UCSVP), read from and written as VIEWPORT groups 110-112, 146, 79, 345/346 and 71. - Viewport::extra: the viewport's other groups as read (snap, grid, lens and clipping, render mode, plot style sheet, shade plot, visual style, background, lighting). They belong to the entity, so COPY and MIRROR carry them; dxf_raw::finish writes them before the xdata and points their references at what they named (ForeignExtra::tail). - Not carried raw: the view twist, direction and target (51, 16, 17), which say where the view centre is measured from; writing them back while the centre is in drawing coordinates would move the view. - DWG: the bridge drops 345/346, the plot style sheet, shade plot and lighting groups, so CADCraft xdata keeps a copy (VPUCS, VPEXTRA) that the reader falls back on. The visual style, background and shade plot references are still lost through DWG (file-format-parity.md). - A UCS with unreadable or zero-length axes is no UCS; a named UCS that's no longer in the table isn't pointed at. Tests: another program's viewport read; DXF save and reread; two DWG round trips; a copied viewport; a deleted named UCS; a viewport without a UCS written as before; hostile groups (5000 extras, NaN axes, bad handles); COPY and MIRROR through the engine. * Viewports: VPEXTRA keeps only a viewport's own groups; a base UCS handle alone is kept - CADCraft's VPEXTRA xdata copy of a viewport's unmodelled groups is merged only for groups that can stand inside the AcDbViewport subclass: a record start (0), handles (5, 105), a subclass (100), a group brace (102) or xdata (1000 on) from a crafted file are dropped, so a save can't write records or handles the user didn't draw. - A VIEWPORT whose only UCS group is its base UCS handle (346) now reads a UCS, so the base UCS is resolved and written back. * Viewports: drop structural groups from a record's own extras; index UCS names for the xdata fallback - A VIEWPORT's own AcDbViewport groups are kept raw only when they can stand in the subclass, as CADCraft's VPEXTRA copy already was: a second handle (5, 105) or a group brace (102) written back would give the record two handles. The record's own pointer groups stay, to be remapped with it. - The named and base UCS that CADCraft's xdata names are looked up in a case-insensitive index built once with the UCS table, not by scanning every UCS for each viewport. * Parity checklist: regenerated after merging main * Parity checklist: regenerated after merging main * Parity checklist: regenerated after merging main * xtask: take main's stats.rs (the merge kept a test import Linux clippy rejects) * Viewport tests built on main set the UCS fields * WIP row 74: Codex's test edits kept; production normalisation (identity UCS -> None, default-valued extras dropped in dxf_read viewport_ucs/viewport_extra) still to do * Viewports: a default viewport reads back with no UCS or extra groups (#1484) A DWG save writes an identity UCS and the default snap, grid, lens, clip, render and shade groups for every viewport, so a viewport nobody gave a UCS came back with one and a dozen extras. The DXF reader now reads an unnamed identity UCS (UCSVP 0) as none, and keeps a group in extra only when it differs from the defaults, listed in one table. Tests: a_default_viewport_reads_back_without_ucs_or_extras, a_viewport_with_non_default_snap_keeps_it; layouts_and_paperspace passes. * Viewports: clippy range patterns; raster_image test builds with the viewport's UCS fields * Tests: move the viewport UCS suites into the it entry points (#1316) viewport_ucs_roundtrip.rs and viewport_ucs_copy.rs were separate test binaries; AGENTS section 30 wants the existing entry points. All 12 DXF/DWG persistence tests and the COPY/MIRROR tests are kept. * Tests: move the viewport UCS suites into the it entry points (#1316) viewport_ucs_roundtrip.rs and viewport_ucs_copy.rs were separate test binaries; AGENTS section 30 wants the existing entry points. All 12 DXF/DWG persistence tests and the COPY/MIRROR tests are kept. --------- Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Claude Co-authored-by: SBaksa <18648812+SBaksa@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/doc/src/entity.rs | 2 +- crates/doc/src/entity/layout.rs | 39 +- crates/doc/src/foreign.rs | 10 +- crates/engine/src/cmd/modify2/tests.rs | 3 + crates/engine/tests/it/main.rs | 1 + .../tests/it/measure_distance_snapping.rs | 3 + crates/engine/tests/it/viewport_ucs_copy.rs | 86 ++++ crates/io/src/dxf_ext.rs | 35 ++ crates/io/src/dxf_raw.rs | 43 +- crates/io/src/dxf_read.rs | 7 +- crates/io/src/dxf_read/entities.rs | 149 +++++- crates/io/src/dxf_read/tables.rs | 1 + crates/io/src/dxf_write.rs | 2 +- crates/io/src/dxf_write/entity.rs | 38 +- crates/io/src/tests.rs | 12 + crates/io/tests/it/block_expansion.rs | 3 + crates/io/tests/it/dwg_roundtrip_losses.rs | 3 + crates/io/tests/it/main.rs | 1 + crates/io/tests/it/paperview_marker.rs | 3 + crates/io/tests/it/pdf_layers.rs | 3 + crates/io/tests/it/viewport_ucs_roundtrip.rs | 432 ++++++++++++++++++ crates/io/tests/pdf_text.rs | 3 + crates/render/src/tests.rs | 3 + crates/render/tests/it/plot_line_styles.rs | 3 + crates/render/tests/it/psltscale.rs | 3 + crates/render/tests/it/render_props.rs | 3 + .../render/tests/it/viewport_frozen_layer.rs | 3 + crates/render/tests/raster_image.rs | 3 + .../ui-egui/tests/it/gpu_origin_stability.rs | 3 + .../tests/it/measure_distance_snapping.rs | 3 + .../ui-egui/tests/it/mspace_viewport_view.rs | 3 + 31 files changed, 890 insertions(+), 16 deletions(-) create mode 100644 crates/engine/tests/it/viewport_ucs_copy.rs create mode 100644 crates/io/tests/it/viewport_ucs_roundtrip.rs diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index d4bcb2de8..bfcc6664e 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -58,7 +58,7 @@ pub use common::{Common, Handle, Lineweight, RawTag, Transparency}; pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid}; pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader}; pub use fill::{Gradient, Hatch, HatchLoop}; -pub use layout::{Image, Table, TableCell, Viewport}; +pub use layout::{Image, Table, TableCell, Viewport, ViewportUcs}; pub use proxy::{ProxyTables, TableOrder, proxy_entities}; pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign}; pub use wipeout::Wipeout; diff --git a/crates/doc/src/entity/layout.rs b/crates/doc/src/entity/layout.rs index 9155add9e..327fb5a61 100644 --- a/crates/doc/src/entity/layout.rs +++ b/crates/doc/src/entity/layout.rs @@ -1,6 +1,6 @@ use cadcraft_geom::Mat3; -use super::common::Handle; +use super::common::{Handle, RawTag}; use super::{Color, Deserialize, Serialize, Vec2, Vec3, standard, yes}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -27,6 +27,19 @@ pub struct Viewport { /// Display on (MVIEW ON/OFF). An off viewport shows its border but no model space. #[serde(default = "yes")] pub on: bool, + /// The viewport's own UCS (DXF groups 110–112, 79, 146, 345, 346), the one it keeps while + /// `ucs_per_viewport` is set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ucs: Option, + /// UCS per viewport (UCSVP, DXF group 71): the viewport keeps its own UCS instead of + /// following the current one. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub ucs_per_viewport: bool, + /// The viewport's groups CADCraft doesn't model (snap, grid, lens and clipping, render mode, + /// plot style sheet, shade plot, visual style, background, lighting…), as read: written back + /// on save and carried by copies, their references pointed at what they named. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub extra: Vec, /// The view twist (DVIEW TWist inside the viewport; DXF group 51): radians counterclockwise, /// the model view seen through the viewport is turned on the sheet by it. 0 is untwisted. #[serde(default, skip_serializing_if = "is_zero_twist")] @@ -62,6 +75,27 @@ impl Viewport { } } +/// A layout viewport's own UCS. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ViewportUcs { + pub origin: Vec3, + pub x_axis: Vec3, + pub y_axis: Vec3, + /// Elevation (DXF group 146). + #[serde(default)] + pub elevation: f64, + /// Orthographic type (DXF group 79): 0 none, 1 top, 2 bottom, 3 front, 4 back, 5 left, 6 right. + #[serde(default)] + pub ortho: u8, + /// The named UCS it is, by UCS table name (DXF group 345). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub named: Option, + /// The UCS an orthographic one is based on, by UCS table name (DXF group 346); none: the WCS. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base: Option, +} + impl Default for Viewport { fn default() -> Self { Viewport { @@ -76,6 +110,9 @@ impl Default for Viewport { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, } } diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 8b12dec5f..d5095a189 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -42,11 +42,19 @@ pub struct ForeignExtra { pub color_book: Option<(String, String)>, /// Other unmodelled property groups (material 347, shadow mode 284). pub props: Vec, + /// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled + /// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them. + pub tail: Vec, } impl ForeignExtra { pub fn is_empty(&self) -> bool { - self.xdict.is_none() && self.reactors.is_empty() && self.xdata.is_empty() && self.color_book.is_none() && self.props.is_empty() + self.xdict.is_none() + && self.reactors.is_empty() + && self.xdata.is_empty() + && self.color_book.is_none() + && self.props.is_empty() + && self.tail.is_empty() } } diff --git a/crates/engine/src/cmd/modify2/tests.rs b/crates/engine/src/cmd/modify2/tests.rs index bca62e613..3eaa9b36f 100644 --- a/crates/engine/src/cmd/modify2/tests.rs +++ b/crates/engine/src/cmd/modify2/tests.rs @@ -411,6 +411,9 @@ fn chspace_json_and_command_line() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; s.doc_mut().unwrap().add(&Space::Paper("Layout1".into()), Default::default(), EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 7bef32dce..37eee060d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -208,6 +208,7 @@ mod undo_layout_tab; mod viewport_clip; mod viewport_frozen_block_parts; mod viewport_frozen_selection; +mod viewport_ucs_copy; mod vplayer_prompts; mod vports; mod wipeout_grips; diff --git a/crates/engine/tests/it/measure_distance_snapping.rs b/crates/engine/tests/it/measure_distance_snapping.rs index e392f4c40..6e7c1369c 100644 --- a/crates/engine/tests/it/measure_distance_snapping.rs +++ b/crates/engine/tests/it/measure_distance_snapping.rs @@ -27,6 +27,9 @@ fn drawing() -> (Drawing, Space) { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }), ) diff --git a/crates/engine/tests/it/viewport_ucs_copy.rs b/crates/engine/tests/it/viewport_ucs_copy.rs new file mode 100644 index 000000000..14fe9fb41 --- /dev/null +++ b/crates/engine/tests/it/viewport_ucs_copy.rs @@ -0,0 +1,86 @@ +//! COPY and MIRROR of a layout viewport keep its own UCS and its unmodelled settings (#1316): they +//! belong to the viewport, like its view. + +use cadcraft_doc::{EntityKind, Handle, RawTag, Space, Viewport, ViewportUcs}; +use cadcraft_engine::Session; +use cadcraft_geom::Vec3; +use serde_json::json; + +fn viewports(s: &Session) -> Vec<(Handle, Viewport)> { + let d = s.doc().unwrap(); + d.layout("Layout1") + .unwrap() + .entities + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Viewport(v) if v.id != 1 => Some((e.handle, v.clone())), + _ => None, + }) + .collect() +} + +fn ucs() -> ViewportUcs { + ViewportUcs { + origin: Vec3::new(100.0, 50.0, 0.0), + x_axis: Vec3::new(0.0, 1.0, 0.0), + y_axis: Vec3::new(-1.0, 0.0, 0.0), + elevation: 2.5, + ortho: 0, + named: Some("SITE".into()), + base: None, + } +} + +fn extra() -> Vec { + vec![RawTag { code: 1, value: "monochrome.ctb".into() }, RawTag { code: 15, value: "10.0".into() }, RawTag { code: 170, value: "2".into() }] +} + +/// Layout1 with one viewport that has its own UCS and settings. +fn session() -> (Session, Handle) { + let mut s = Session::new(); + s.new_drawing(true); + s.execute("line", &json!({"points": [[0, 0], [100, 100]]})).unwrap(); + s.execute("layout.set", &json!({"name": "Layout1"})).unwrap(); + let old: Vec = viewports(&s).iter().map(|(h, _)| h.hex()).collect(); + if !old.is_empty() { + s.execute("erase", &json!({"handles": old})).unwrap(); + } + s.execute("mview", &json!({"p1": [10, 10], "p2": [110, 80]})).unwrap(); + let (h, _) = viewports(&s).into_iter().next().unwrap(); + let d = s.doc_mut().unwrap(); + let store = d.space_mut(&Space::Paper("Layout1".into())).unwrap(); + let mut e = (**store.get(h).unwrap()).clone(); + if let EntityKind::Viewport(v) = &mut e.kind { + v.ucs = Some(ucs()); + v.ucs_per_viewport = true; + v.extra = extra(); + } + assert!(store.replace(e)); + (s, h) +} + +fn assert_kept(v: &Viewport) { + assert_eq!(v.ucs, Some(ucs())); + assert!(v.ucs_per_viewport); + assert_eq!(v.extra, extra()); +} + +#[test] +fn copy_keeps_a_viewport_s_ucs_and_settings() { + let (mut s, h) = session(); + s.execute("copy", &json!({"handles": [h.hex()], "delta": [150, 0]})).unwrap(); + let vps = viewports(&s); + assert_eq!(vps.len(), 2); + for (_, v) in &vps { + assert_kept(v); + } +} + +#[test] +fn mirror_keeps_a_viewport_s_ucs_and_settings() { + let (mut s, h) = session(); + s.execute("mirror", &json!({"handles": [h.hex()], "p1": [0, 100], "p2": [10, 100]})).unwrap(); + for (_, v) in &viewports(&s) { + assert_kept(v); + } +} diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 40d4b6140..d441dfd30 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -701,6 +701,41 @@ pub(crate) fn read_layer_colors(tags: &[Tag]) -> Vec<(String, Color)> { names.as_chunks::<2>().0.iter().filter_map(|[name, color]| Some((name.clone(), Color::parse(color)?))).collect() } +/// A viewport's named and base UCS as CADCraft xdata: `1000 VPUCS`, `1002 {`, `1000 named`, +/// `1000 base` (empty for none), `1002 }`. Groups 345 and 346 say the same, but the DWG bridge +/// drops them. +pub(crate) fn ucs_xdata(named: Option<&str>, base: Option<&str>) -> Vec { + vec![Tag::s(1000, "VPUCS"), Tag::s(1002, "{"), Tag::s(1000, named.unwrap_or_default()), Tag::s(1000, base.unwrap_or_default()), Tag::s(1002, "}")] +} + +/// The named and base UCS written by [`ucs_xdata`]; `(None, None)` for files from other writers. +pub(crate) fn read_ucs_names(tags: &[Tag]) -> (Option, Option) { + let list = xdata_list(xdata(tags, APP), "VPUCS"); + let mut names = list.iter().filter(|t| t.code == 1000).map(Tag::str).map(|s| Some(s).filter(|s| !s.trim().is_empty())); + (names.next().flatten(), names.next().flatten()) +} + +/// A copy of a viewport's unmodelled groups ([`cadcraft_doc::Viewport::extra`]) that aren't +/// references, as CADCraft xdata: `1000 VPEXTRA`, `1002 {`, then per group `1000 code` and +/// `1000 value`, `1002 }`. The groups themselves are in the record; the DWG bridge drops some +/// of them (the plot style sheet, shade plot and lighting), and this copy brings them back. +pub(crate) fn extra_xdata(extra: &[cadcraft_doc::RawTag]) -> Vec { + let mut v = vec![Tag::s(1000, "VPEXTRA"), Tag::s(1002, "{")]; + for t in extra.iter().filter(|t| !crate::dxf_raw::is_pointer(t.code)) { + v.push(Tag::s(1000, t.code.to_string())); + v.push(Tag::s(1000, t.value.clone())); + } + v.push(Tag::s(1002, "}")); + v +} + +/// The groups written by [`extra_xdata`]; empty for files from other writers, bad pairs skipped. +pub(crate) fn read_extra(tags: &[Tag]) -> Vec<(i32, String)> { + let list = xdata_list(xdata(tags, APP), "VPEXTRA"); + let items: Vec = list.iter().take(MAX_XDATA_ITEMS * 2).filter(|t| t.code == 1000).map(Tag::str).collect(); + items.as_chunks::<2>().0.iter().filter_map(|[code, value]| Some((code.trim().parse::().ok()?, value.clone()))).collect() +} + const POINT_NAMES: [&str; 5] = ["defpt", "p13", "p14", "p15", "p16"]; /// Associativity links from CADCraft xdata; malformed links are skipped. diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 64735a9f4..5a7c14a55 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -116,7 +116,7 @@ fn handle(s: &str) -> Option { } /// Group codes whose values are handles of other objects (DXF Reference, group code ranges). -fn is_pointer(code: i32) -> bool { +pub(crate) fn is_pointer(code: i32) -> bool { matches!(code, 320..=369 | 390..=399 | 480..=481 | 1005) } @@ -486,6 +486,9 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) { } for e in all_entities(d) { note(&e.common.xdata); + if let EntityKind::Viewport(v) = &e.kind { + note(&v.extra); + } } for e in all_entities(d) { if let EntityKind::Unknown(u) = &e.kind { @@ -1748,17 +1751,41 @@ fn extra_for<'a>( } } -/// Entities' own xdata ([`cadcraft_doc::Common::xdata`]), by handle. -type XdataOf<'a> = HashMap; +/// What an entity carries itself (so its copies carry it too), by handle: its xdata +/// ([`cadcraft_doc::Common::xdata`]) and a viewport's unmodelled groups +/// ([`cadcraft_doc::Viewport::extra`]). +type XdataOf<'a> = HashMap>; -/// The extras of entity `h`: what the drawing keeps for it, with the entity's own xdata. +#[derive(Clone, Copy)] +struct Own<'a> { + xdata: &'a [RawTag], + tail: &'a [RawTag], +} + +/// The [`Own`] data of every entity that carries any. +fn own_data(d: &Drawing) -> XdataOf<'_> { + all_entities(d) + .filter_map(|e| { + let tail: &[RawTag] = match &e.kind { + EntityKind::Viewport(v) => &v.extra, + _ => &[], + }; + (!e.common.xdata.is_empty() || !tail.is_empty()).then_some((e.handle, Own { xdata: &e.common.xdata, tail })) + }) + .collect() +} + +/// The extras of entity `h`: what the drawing keeps for it, with what the entity carries itself. fn entity_extra<'a>(f: &'a Foreign, xd: &XdataOf, h: Handle) -> Option> { let kept = f.entities.get(&h); match xd.get(&h) { None => kept.map(Cow::Borrowed), - Some(xdata) => { + Some(own) => { let mut x = kept.cloned().unwrap_or_default(); - x.xdata = xdata.to_vec(); + if !own.xdata.is_empty() { + x.xdata = own.xdata.to_vec(); + } + x.tail = own.tail.to_vec(); Some(Cow::Owned(x)) } } @@ -1822,7 +1849,7 @@ pub(crate) fn finish( ) -> HashSet { let f = d.foreign.as_ref(); let unknown = unknown_handles(d); - let xd: XdataOf = all_entities(d).filter(|e| !e.common.xdata.is_empty()).map(|e| (e.handle, e.common.xdata.as_slice())).collect(); + let xd = own_data(d); if f.is_empty() && unknown.is_empty() && xd.is_empty() { return HashSet::new(); } @@ -2296,6 +2323,7 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti if i == xdata_at && let Some(x) = x { + out.extend(x.tail.iter().map(|p| map.group(p))); xdata(map, x, &own_apps, out); } if t.code == 102 { @@ -2341,6 +2369,7 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti out.extend(x.props.iter().map(|p| map.group(p))); } if xdata_at == b.len() { + out.extend(x.tail.iter().map(|p| map.group(p))); xdata(map, x, &own_apps, out); } } diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 02f026d62..6d653ba0a 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -7,7 +7,8 @@ use cadcraft_doc::{ Arc, AssocSnap, Attrib, AttribModes, AttribProps, Block, Circle, Common, DashElement, DimAssoc, DimKind, DimStyle, Dimension, Drawing, Ellipse, Entity, EntityKind, Face3d, Gradient, Group, HAlign, HVal, Handle, Hatch, HatchLoop, Helix, HelixConstrain, Insert, Layer, Layout, Leader, Line, Linetype, Lineweight, LwPolyline, MAX_FRAME_CHARS, MLeaderStyle, MText, MultilineAttrib, NamedView, PageSetup, Point, Polyline3d, RawTag, - RayLine, Solid, Table, TableCell, Text, TextStyle, Tolerance, Transparency, Ucs, Unknown, VAlign, Viewport, VportConfig, VportTile, Wipeout, + RayLine, Solid, Table, TableCell, Text, TextStyle, Tolerance, Transparency, Ucs, Unknown, VAlign, Viewport, ViewportUcs, VportConfig, VportTile, + Wipeout, }; use cadcraft_geom::{PolyVertex, Spline, Vec2, Vec3}; use craft_dxf::{Tag, record_slices, section_slices}; @@ -75,8 +76,10 @@ struct Rx { /// Layer, linetype and text style names in the order of the file's tables, which proxy /// graphics refer to by index (the drawing's own tables are ordered differently). proxy_tables: cadcraft_doc::ProxyTables, - /// UCS record handle (upper case) → UCS name (a layout's named UCS, group 345). + /// UCS record handle (upper case) → UCS name (VIEWPORT groups 345 and 346). ucss: HashMap, + /// Upper-case UCS name → UCS name, for a viewport that names its UCS in CADCraft's xdata. + ucs_names: HashMap, /// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport /// (PAPERVIEW) the reader dropped. paper_views_dropped: Vec<(Option, bool, Option)>, diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index ca587d581..c43507007 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -5,10 +5,144 @@ use super::text::{attdef, attrib_modes, attrib_props, flatten_tilted, mtext_from use super::{ Arc, Attrib, Circle, Common, DimKind, Dimension, Ellipse, EntityKind, Face3d, Handle, HashMap, Helix, HelixConstrain, Insert, Leader, Line, LwPolyline, MAX_FRAME_CHARS, Point, PolyVertex, Polyline3d, RawTag, RayLine, Rx, Solid, Spline, Table, TableCell, Tag, Tolerance, Unknown, Vec2, - Vec3, Viewport, Wipeout, record_slices, + Vec3, Viewport, ViewportUcs, Wipeout, record_slices, }; use cadcraft_doc::PolyfaceMesh; +/// VIEWPORT groups that are not kept raw in [`Viewport::extra`]: those read into the model, and +/// the view twist, direction and target (51, 16, 17), which say where the view centre is measured +/// from: carried along while the centre is written in drawing coordinates, they would move the +/// view on the next read. +const VIEWPORT_NOT_EXTRA: &[i32] = &[ + 10, 20, 30, 40, 41, 68, 69, 12, 22, 45, 90, 340, 341, 331, 71, 110, 120, 130, 111, 121, 131, 112, 122, 132, 79, 146, 345, 346, 51, 16, 26, 36, + 17, 27, 37, +]; + +/// The values a viewport nobody set anything on has for the groups below: what the DWG writer +/// (the bridge's) puts in every viewport, and the DXF Reference's defaults. A group at its default +/// is not "extra" data: a default viewport reads back with no extras, a changed one keeps its +/// group. Each entry is a group code with its default; `(x, y)` pairs (13/23 snap base, +/// 14/24 snap spacing, 15/25 grid spacing) are default only together. +const VIEWPORT_DEFAULTS: &[(i32, f64)] = &[ + (13, 0.0), + (23, 0.0), + (14, 10.0), + (24, 10.0), + (15, 10.0), + (25, 10.0), + // Lens length, front and back clip planes, snap angle, circle sides, render mode, major grid. + (42, 50.0), + (43, 0.0), + (44, 0.0), + (50, 0.0), + (72, 1000.0), + (281, 0.0), + (61, 5.0), + // Shade plot mode. + (170, 0.0), +]; + +/// The group that goes with `code` in a coordinate pair (13/23, 14/24, 15/25). +fn pair_of(code: i32) -> Option { + match code { + 13..=15 => Some(code + 10), + 23..=25 => Some(code - 10), + _ => None, + } +} + +/// Is the group `code` of `groups` at its default (see [`VIEWPORT_DEFAULTS`])? A value that +/// doesn't read as a number is not. +fn at_default(groups: &[RawTag], code: i32, value: &str) -> bool { + let is = |c: i32, v: &str| { + VIEWPORT_DEFAULTS.iter().find(|(k, _)| *k == c).is_some_and(|(_, d)| v.trim().parse::().is_ok_and(|x| (x - d).abs() < 1e-9)) + }; + is(code, value) + && match pair_of(code) { + Some(other) => groups.iter().find(|t| t.code == other).is_some_and(|t| is(other, &t.value)), + None => true, + } +} + +/// Most groups kept raw on one viewport (a VIEWPORT record has about forty). +const MAX_VIEWPORT_EXTRA: usize = 512; + +/// The groups of a VIEWPORT's own subclass (after `100 AcDbViewport`, before any xdata). +fn viewport_groups(tags: &[Tag]) -> &[Tag] { + let Some(start) = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbViewport") else { return &[] }; + let rest = tags.get(start + 1..).unwrap_or(&[]); + rest.get(..rest.iter().position(|t| t.code == 100 || t.code >= 1000).unwrap_or(rest.len())).unwrap_or(&[]) +} + +/// A VIEWPORT's own UCS (groups 110–112, 79, 146), if it has one. The named and base UCS (345, +/// 346) are table handles, resolved once the UCS table is known ([`entity_extras`]). +fn viewport_ucs(tags: &[Tag]) -> Option { + let g = viewport_groups(tags); + // Any UCS group, the base UCS handle (346) alone too: a viewport that only names its base + // UCS keeps it. + if !g.iter().any(|t| matches!(t.code, 110 | 111 | 112 | 345 | 346)) { + return None; + } + let t = T(g); + let has = |c: i32| g.iter().any(|t| t.code == c); + let (origin, x_axis, y_axis) = + (t.p(110), if has(111) { t.p(111) } else { Vec3::new(1.0, 0.0, 0.0) }, if has(112) { t.p(112) } else { Vec3::new(0.0, 1.0, 0.0) }); + // Unreadable numbers come through as 0, so a broken axis is one with no length. + let finite = [origin, x_axis, y_axis].iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite()); + if !finite || x_axis.len() <= 1e-12 || y_axis.len() <= 1e-12 { + return None; + } + // The World UCS of a viewport that names no UCS and keeps none of its own (UCSVP 0) is what a + // viewport nobody gave a UCS reads as (a DWG writes one for every viewport): no UCS. + let ortho = t.i(79).unwrap_or(0); + let nothing_named = !g.iter().any(|t| matches!(t.code, 345 | 346)) && crate::dxf_ext::read_ucs_names(tags) == (None, None); + let identity = origin.len() <= 1e-12 + && (x_axis - Vec3::new(1.0, 0.0, 0.0)).len() <= 1e-12 + && (y_axis - Vec3::new(0.0, 1.0, 0.0)).len() <= 1e-12 + && t.f(146).unwrap_or(0.0) == 0.0 + && ortho == 0; + if identity && nothing_named && t.i(71) != Some(1) { + return None; + } + Some(ViewportUcs { + origin, + x_axis, + y_axis, + elevation: t.f(146).filter(|e| e.is_finite()).unwrap_or(0.0), + ortho: t.i(79).and_then(|o| u8::try_from(o).ok()).filter(|o| *o <= 6).unwrap_or(0), + named: None, + base: None, + }) +} + +/// A VIEWPORT's groups CADCraft doesn't model, as read ([`VIEWPORT_NOT_EXTRA`]), plus those of +/// CADCraft's xdata copy that the record lacks (a DWG drops some). +fn viewport_extra(tags: &[Tag]) -> Vec { + // Only groups that can stand inside the AcDbViewport subclass: no record start (0), handle (5, + // 105), subclass (100), group brace (102) or xdata (1000 on), which written back would break + // the record or give it a second handle. + let own_group = |code: i32| (1..1000).contains(&code) && !matches!(code, 5 | 100 | 102 | 105); + // The record's own pointer groups stay: they are remapped with the record. + let mut out: Vec = viewport_groups(tags) + .iter() + .filter(|t| own_group(t.code) && !VIEWPORT_NOT_EXTRA.contains(&t.code)) + .take(MAX_VIEWPORT_EXTRA) + .map(|t| RawTag { code: t.code, value: t.str() }) + .collect(); + for (code, value) in crate::dxf_ext::read_extra(tags) { + if out.len() >= MAX_VIEWPORT_EXTRA { + break; + } + if own_group(code) && !VIEWPORT_NOT_EXTRA.contains(&code) && !crate::dxf_raw::is_pointer(code) && !out.iter().any(|t| t.code == code) { + out.push(RawTag { code, value }); + } + } + let keep: Vec = out.iter().map(|t| !at_default(&out, t.code, &t.value)).collect(); + let mut keep = keep.into_iter(); + out.retain(|_| keep.next().unwrap_or(true)); + out +} + /// Parse one entity record. POLYLINE/INSERT followers are handled by the caller. pub(super) fn entity(kind: &str, tags: &[Tag]) -> Option<(Common, EntityKind)> { entity_with_table_budget(kind, tags, &mut 4_000_000, &mut CurvePoints::default()) @@ -330,6 +464,9 @@ pub(super) fn entity_with_table_budget( clip: t.s(340).and_then(|h| Handle::parse_hex(&h)).filter(|h| h.0 != 0 && t.i(90).unwrap_or(0) & 65536 != 0), on: t.i(90).unwrap_or(0) & 131072 == 0, twist, + ucs: viewport_ucs(tags), + ucs_per_viewport: t.i(71) == Some(1), + extra: viewport_extra(tags), } }), "WIPEOUT" => { @@ -584,6 +721,16 @@ pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityK let named = handles.filter_map(|t| rx.layers.get(&t.str().trim().to_ascii_uppercase())); let mut seen = std::collections::HashSet::new(); v.frozen_layers = named.chain(&v.frozen_layers).filter(|n| seen.insert(n.to_ascii_uppercase())).cloned().collect(); + // The named and base UCS, by name: groups 345 and 346, else CADCraft's xdata (which a + // DWG keeps when they are dropped). A name that isn't in the UCS table: none. + if let Some(u) = &mut v.ucs { + let t = T(viewport_groups(tags)); + let by_handle = |code: i32| t.s(code).and_then(|h| rx.ucss.get(&h.trim().to_ascii_uppercase()).cloned()); + let (xn, xb) = crate::dxf_ext::read_ucs_names(tags); + let known = |n: Option| n.and_then(|n| rx.ucs_names.get(&n.to_ascii_uppercase()).cloned()); + u.named = by_handle(345).or_else(|| known(xn)); + u.base = by_handle(346).or_else(|| known(xb)); + } } _ => {} } diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 481b3b01a..8c521df66 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -340,6 +340,7 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) { rx.layers.insert(handle.trim().to_ascii_uppercase(), name); } "UCS" => { + rx.ucs_names.entry(name.to_ascii_uppercase()).or_insert_with(|| name.clone()); rx.ucss.insert(handle.trim().to_ascii_uppercase(), name); } _ => {} diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 241dc1749..83c534ba0 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -48,7 +48,7 @@ struct W { pstyles: HashMap, /// Upper-case layer name → its LAYER table record handle (group 331/341 of viewports). layers: HashMap, - /// Upper-case UCS name → its UCS table record handle (group 345 of layouts and viewports). + /// Upper-case UCS name → its UCS table record handle (groups 345 and 346 of viewports). ucss: HashMap, /// Active VPORT group-345 tags (their index in `t`) waiting for the handle of the named UCS /// (upper case) they refer to, filled in after the UCS table is written. diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index d59bceb32..7f410d702 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -807,8 +807,30 @@ fn write_viewport_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: if let Some(h) = clip { w.s(340, h.hex()); } - // One CADCraft xdata group holds both lists: readers stop at the first group of an app. - if !unrecorded.is_empty() || !v.layer_colors.is_empty() { + // The viewport's own UCS. Its other unmodelled groups (`extra`) go in after this, just + // before the xdata (dxf_raw::finish). + if v.ucs.is_some() || v.ucs_per_viewport { + w.i(71, i64::from(v.ucs_per_viewport)); + } + // The named and base UCS that are still in the UCS table. + let mut ucs_names = (None, None); + if let Some(u) = &v.ucs { + w.p(110, u.origin); + w.p(111, u.x_axis); + w.p(112, u.y_axis); + w.i(79, i64::from(u.ortho)); + w.f(146, u.elevation); + ucs_names = (live_ucs(&w.ucss, &u.named), live_ucs(&w.ucss, &u.base)); + for (code, name) in [(345, &ucs_names.0), (346, &ucs_names.1)] { + if let Some((_, h)) = name { + w.s(code, h.clone()); + } + } + } + let has_ucs_names = ucs_names.0.is_some() || ucs_names.1.is_some(); + let has_extra = v.extra.iter().any(|t| !crate::dxf_raw::is_pointer(t.code)); + // One CADCraft xdata group holds all the lists: readers stop at the first group of an app. + if !unrecorded.is_empty() || !v.layer_colors.is_empty() || has_ucs_names || has_extra { w.s(1001, dxf_ext::APP); if !unrecorded.is_empty() { w.xdata(dxf_ext::frozen_xdata(&unrecorded)); @@ -816,6 +838,12 @@ fn write_viewport_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: if !v.layer_colors.is_empty() { w.xdata(dxf_ext::layer_colors_xdata(&v.layer_colors)); } + if has_ucs_names { + w.xdata(dxf_ext::ucs_xdata(ucs_names.0.map(|(n, _)| n), ucs_names.1.map(|(n, _)| n))); + } + if has_extra { + w.xdata(dxf_ext::extra_xdata(&v.extra)); + } } } } @@ -968,3 +996,9 @@ fn hatch_xdata(w: &mut W, h: &Hatch) { w.p(1011, h.origin.to3(0.0)); w.s(1000, h.background.map(Color::name).unwrap_or_default()); } + +/// A viewport's named or base UCS with its record handle, if the UCS table still has it. +fn live_ucs<'a>(ucss: &HashMap, name: &'a Option) -> Option<(&'a str, String)> { + let n = name.as_deref()?; + Some((n, ucss.get(&n.to_ascii_uppercase())?.clone())) +} diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 6b5af49f5..30060b142 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -1089,6 +1089,9 @@ fn pdf_layout_one_to_one_with_viewport() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }), ) @@ -1464,6 +1467,9 @@ fn viewport_frozen_layers_roundtrip() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }) }; @@ -1652,6 +1658,9 @@ fn frozen_vp_dxf() -> (Drawing, Vec<(String, String)>) { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }); d.add(&paper, Common::default(), vp).unwrap(); @@ -1796,6 +1805,9 @@ fn viewport_layer_colors_roundtrip() { layer_colors: colors, clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }) }; diff --git a/crates/io/tests/it/block_expansion.rs b/crates/io/tests/it/block_expansion.rs index 7aac5d7db..7fd0a337c 100644 --- a/crates/io/tests/it/block_expansion.rs +++ b/crates/io/tests/it/block_expansion.rs @@ -395,6 +395,9 @@ fn an_empty_followup_viewport_does_not_mark_an_exact_budget_truncated() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; let paper = Space::Paper("Layout1".into()); diff --git a/crates/io/tests/it/dwg_roundtrip_losses.rs b/crates/io/tests/it/dwg_roundtrip_losses.rs index 8e9cb3bb0..3337f1e5b 100644 --- a/crates/io/tests/it/dwg_roundtrip_losses.rs +++ b/crates/io/tests/it/dwg_roundtrip_losses.rs @@ -28,6 +28,9 @@ fn viewport(id: u32) -> EntityKind { layer_colors: vec![], clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }) } diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index ba9165f73..e80d30a37 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -113,6 +113,7 @@ mod user_lin_pat_roundtrip; mod view_tables_roundtrip; mod view_target; mod viewport_clip_roundtrip; +mod viewport_ucs_roundtrip; #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] mod visualstyle_dwg; mod vport_circle_sides; diff --git a/crates/io/tests/it/paperview_marker.rs b/crates/io/tests/it/paperview_marker.rs index 283cfc8ac..74231d8c8 100644 --- a/crates/io/tests/it/paperview_marker.rs +++ b/crates/io/tests/it/paperview_marker.rs @@ -18,6 +18,9 @@ fn viewport(id: u32, frozen_layers: Vec, layer_colors: Vec<(String, Colo layer_colors, clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }) } diff --git a/crates/io/tests/it/pdf_layers.rs b/crates/io/tests/it/pdf_layers.rs index b32682f46..3711ccf6b 100644 --- a/crates/io/tests/it/pdf_layers.rs +++ b/crates/io/tests/it/pdf_layers.rs @@ -150,6 +150,9 @@ fn viewport_contents_keep_their_layers() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&paper, Common { layer: "Viewports".into(), ..Default::default() }, EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/io/tests/it/viewport_ucs_roundtrip.rs b/crates/io/tests/it/viewport_ucs_roundtrip.rs new file mode 100644 index 000000000..d2d8db754 --- /dev/null +++ b/crates/io/tests/it/viewport_ucs_roundtrip.rs @@ -0,0 +1,432 @@ +//! A layout viewport's own UCS (UCSVP and groups 110–112, 79, 146, 345, 346) and the groups +//! CADCraft doesn't model (snap, grid, lens, plot style, visual style, lighting…) survive reading, +//! saving as DXF or DWG and copying (#1316). + +use cadcraft_doc::*; +use cadcraft_geom::{Vec2, Vec3}; + +fn viewport() -> EntityKind { + EntityKind::Viewport(Viewport { + center: Vec3::new(50.0, 40.0, 0.0), + width: 80.0, + height: 60.0, + view_center: Vec2::new(10.0, 10.0), + view_height: 50.0, + id: 2, + ..Viewport::default() + }) +} + +/// A drawing with two named UCSs and one layout viewport, saved by CADCraft. +fn base() -> (Drawing, Handle) { + let mut d = Drawing::default(); + d.ucss.push(Ucs { name: "SITE".into(), origin: Vec3::new(100.0, 50.0, 0.0), x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 1.0, 0.0) }); + d.ucss.push(Ucs { name: "BASE".into(), origin: Vec3::ZERO, x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 1.0, 0.0) }); + let paper = Space::Paper(d.layouts[0].name.clone()); + let h = d.add(&paper, Common::default(), viewport()).unwrap(); + (d, h) +} + +/// The (code, value) pairs of every `kind` record in DXF text. +fn records(text: &str, kind: &str) -> Vec> { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out: Vec> = Vec::new(); + let mut inside = false; + for pair in lines.chunks(2) { + let [code, value] = pair else { break }; + if *code == "0" { + inside = *value == kind; + if inside { + out.push(Vec::new()); + } + } else if inside && let Some(rec) = out.last_mut() { + rec.push((code.to_string(), value.to_string())); + } + } + out +} + +fn group<'a>(rec: &'a [(String, String)], code: &str) -> Option<&'a str> { + rec.iter().find(|(c, _)| c == code).map(|(_, v)| v.as_str()) +} + +/// The handle of the `kind` table record named `name`. +fn record_handle(text: &str, kind: &str, name: &str) -> String { + records(text, kind).into_iter().find(|r| group(r, "2") == Some(name)).and_then(|r| group(&r, "5").map(str::to_string)).unwrap() +} + +/// The viewport record with handle `h`. +fn viewport_record(text: &str, h: Handle) -> Vec<(String, String)> { + records(text, "VIEWPORT").into_iter().find(|r| group(r, "5") == Some(h.hex().as_str())).unwrap() +} + +/// `text` with `groups` put into viewport `h`'s record after its status flags (group 90). +fn inject(text: &str, h: Handle, groups: &[(i32, String)]) -> String { + let lines: Vec<&str> = text.lines().collect(); + let mut out: Vec = Vec::new(); + let (mut in_vp, mut done) = (false, false); + let mut i = 0; + while i + 1 < lines.len() { + let (code, value) = (lines[i].trim(), lines[i + 1].trim()); + if code == "0" { + in_vp = value == "VIEWPORT"; + } + let ours = in_vp && !done; + out.push(lines[i].to_string()); + out.push(lines[i + 1].to_string()); + if ours && code == "5" && value != h.hex() { + in_vp = false; + } + if ours && code == "90" { + for (c, v) in groups { + out.push(c.to_string()); + out.push(v.clone()); + } + done = true; + } + i += 2; + } + assert!(done, "viewport {h:?} not found"); + out.join("\n") + "\n" +} + +const C6: f64 = 0.994_521_895_368_273_3; +const S6: f64 = 0.104_528_463_267_653_47; + +/// The groups another program writes on a viewport with a 6° UCS, after its status flags: +/// UCS, then the ones CADCraft doesn't model, with a visual style handle (`style`), plus the view +/// twist, direction and target that must not be carried raw. +fn foreign_groups(site: &str, base_ucs: &str, style: &str) -> Vec<(i32, String)> { + let mut g: Vec<(i32, String)> = vec![ + (13, "1.0".into()), + (23, "2.0".into()), + (14, "0.5".into()), + (24, "0.5".into()), + (15, "10.0".into()), + (25, "10.0".into()), + (16, "0.0".into()), + (26, "0.0".into()), + (36, "1.0".into()), + (17, "0.0".into()), + (27, "0.0".into()), + (37, "0.0".into()), + (42, "50.0".into()), + (43, "0.0".into()), + (44, "0.0".into()), + (50, "0.0".into()), + (51, "6.0".into()), + (72, "1000".into()), + (1, "monochrome.ctb".into()), + (281, "0".into()), + (71, "1".into()), + (74, "0".into()), + ]; + for (c, v) in [(110, [100.0, 50.0, 0.0]), (111, [C6, S6, 0.0]), (112, [-S6, C6, 0.0])] { + for (k, x) in v.iter().enumerate() { + g.push((c + 10 * k as i32, format!("{x:?}"))); + } + } + g.extend([ + (79, "0".into()), + (146, "2.5".into()), + (345, site.into()), + (346, base_ucs.into()), + (170, "0".into()), + (61, "5".into()), + (348, style.into()), + (292, "1".into()), + (282, "1".into()), + (141, "0.0".into()), + (142, "0.0".into()), + (63, "250".into()), + ]); + g +} + +/// The non-default unmodelled groups, in file order; default-valued settings are canonical absence. +const EXTRA: &[i32] = &[13, 23, 14, 24, 1, 74, 348, 292, 282, 141, 142, 63]; + +fn the_viewport(d: &Drawing) -> (Handle, Viewport) { + d.layouts + .iter() + .flat_map(|l| l.entities.iter()) + .find_map(|e| if let EntityKind::Viewport(v) = &e.kind { (v.id != 1).then(|| (e.handle, v.clone())) } else { None }) + .unwrap() +} + +/// A drawing whose viewport carries another program's UCS and unmodelled groups, its visual +/// style handle pointing at layer 0's record (a record CADCraft writes itself, under a new +/// handle on save). +fn foreign() -> Drawing { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + let (site, base_ucs, layer0) = (record_handle(&text, "UCS", "SITE"), record_handle(&text, "UCS", "BASE"), record_handle(&text, "LAYER", "0")); + cadcraft_io::read_dxf(inject(&text, h, &foreign_groups(&site, &base_ucs, &layer0)).as_bytes()).unwrap() +} + +fn expected_ucs() -> ViewportUcs { + ViewportUcs { + origin: Vec3::new(100.0, 50.0, 0.0), + x_axis: Vec3::new(C6, S6, 0.0), + y_axis: Vec3::new(-S6, C6, 0.0), + elevation: 2.5, + ortho: 0, + named: Some("SITE".into()), + base: Some("BASE".into()), + } +} + +fn num(v: &str) -> Option { + v.trim().parse::().ok() +} + +/// The unmodelled groups agree: same codes in the same order, same values (numbers compared as +/// numbers), the visual style pointing at layer 0 in each file. +fn assert_extra(text: &str, rec: &[(String, String)]) { + let codes: Vec = rec.iter().filter_map(|(c, _)| c.parse::().ok()).filter(|c| EXTRA.contains(c)).collect(); + assert_eq!(codes, EXTRA, "{rec:?}"); + for (code, want) in foreign_groups("", "", "").into_iter().filter(|(c, _)| EXTRA.contains(c) && *c != 348) { + let got = group(rec, &code.to_string()).unwrap(); + match (num(got), num(&want)) { + (Some(a), Some(b)) => assert!((a - b).abs() < 1e-12, "{code}: {got} vs {want}"), + _ => assert_eq!(got, want, "{code}"), + } + } + assert_eq!(group(rec, "348"), Some(record_handle(text, "LAYER", "0").as_str()), "visual style pointer"); +} + +#[test] +fn another_program_s_viewport_ucs_and_settings_are_read() { + let d = foreign(); + let (_, v) = the_viewport(&d); + assert!(v.ucs_per_viewport); + assert_eq!(v.ucs, Some(expected_ucs())); + let codes: Vec = v.extra.iter().map(|t| t.code).collect(); + assert_eq!(codes, EXTRA); +} + +#[test] +fn viewport_ucs_and_settings_survive_a_dxf_save() { + let d = foreign(); + let (h, v) = the_viewport(&d); + let text = cadcraft_io::write_dxf(&d); + let rec = viewport_record(&text, h); + assert_eq!(group(&rec, "71"), Some("1")); + assert_eq!(group(&rec, "345"), Some(record_handle(&text, "UCS", "SITE").as_str())); + assert_eq!(group(&rec, "346"), Some(record_handle(&text, "UCS", "BASE").as_str())); + assert_eq!(num(group(&rec, "146").unwrap()), Some(2.5)); + assert_extra(&text, &rec); + // Written once each, and the view twist, direction and target are not carried raw. + for code in EXTRA.iter().chain(&[71, 110, 345, 346]) { + assert_eq!(rec.iter().filter(|(c, _)| *c == code.to_string()).count(), 1, "group {code} in {rec:?}"); + } + assert!((num(group(&rec, "51").unwrap()).unwrap() - 6.0).abs() < 1e-12); + for code in ["16", "17"] { + assert!(group(&rec, code).is_none(), "{code} in {rec:?}"); + } + // And it reads back the same. + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let (_, w) = the_viewport(&back); + assert_eq!((w.ucs, w.ucs_per_viewport), (v.ucs, v.ucs_per_viewport)); + let again = cadcraft_io::write_dxf(&back); + assert_extra(&again, &viewport_record(&again, h)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn viewport_ucs_and_settings_survive_a_dwg_save() { + cadcraft_io::dwg_worker::allow_in_process(); + let d = foreign(); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + let (h, v) = the_viewport(&back); + assert!(v.ucs_per_viewport); + let u = v.ucs.clone().unwrap(); + let want = expected_ucs(); + for (a, b) in [(u.origin, want.origin), (u.x_axis, want.x_axis), (u.y_axis, want.y_axis)] { + assert!((a - b).len() < 1e-12, "{a:?} vs {b:?}"); + } + assert_eq!((u.elevation, u.ortho, u.named.as_deref(), u.base.as_deref()), (2.5, 0, Some("SITE"), Some("BASE"))); + // Every group that isn't a reference comes back with its value, also those the DWG bridge + // drops from the record (plot style sheet, shade plot, lighting: from CADCraft's xdata copy). + // The visual style reference (348) is lost through DWG (docs/file-format-parity.md). + let text = cadcraft_io::write_dxf(&back); + let rec = viewport_record(&text, h); + for (code, want) in foreign_groups("", "", "").into_iter().filter(|(c, _)| EXTRA.contains(c) && *c != 348) { + let got = group(&rec, &code.to_string()).unwrap_or_else(|| panic!("group {code} lost through DWG: {rec:?}")); + match (num(got), num(&want)) { + (Some(a), Some(b)) => assert!((a - b).abs() < 1e-12, "{code}: {got} vs {want}"), + _ => assert_eq!(got, want, "{code}"), + } + } + // And a second trip through DWG changes nothing more. + let twice = cadcraft_io::read(&cadcraft_io::write(&back, "x.dwg").unwrap(), "x.dwg").unwrap(); + let (_, w) = the_viewport(&twice); + assert_eq!((w.ucs, w.ucs_per_viewport), (v.ucs, v.ucs_per_viewport)); + let mut a: Vec = v.extra.iter().map(|t| t.code).collect(); + let mut b: Vec = w.extra.iter().map(|t| t.code).collect(); + a.sort_unstable(); + b.sort_unstable(); + assert_eq!(a, b); +} + +#[test] +fn a_copied_viewport_keeps_its_ucs_and_settings() { + let mut d = foreign(); + let (h, v) = the_viewport(&d); + let paper = Space::Paper(d.layouts[0].name.clone()); + let copy = d.add(&paper, Common::default(), EntityKind::Viewport(Viewport { id: 3, center: Vec3::new(150.0, 40.0, 0.0), ..v.clone() })).unwrap(); + let text = cadcraft_io::write_dxf(&d); + for vh in [h, copy] { + let rec = viewport_record(&text, vh); + assert_eq!(group(&rec, "345"), Some(record_handle(&text, "UCS", "SITE").as_str()), "{vh:?}"); + assert_extra(&text, &rec); + } +} + +#[test] +fn a_viewport_without_a_ucs_is_written_as_before() { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + let rec = viewport_record(&text, h); + for code in ["71", "110", "111", "112", "79", "146", "345", "346"] { + assert!(group(&rec, code).is_none(), "{code} in {rec:?}"); + } + let (_, v) = the_viewport(&cadcraft_io::read_dxf(text.as_bytes()).unwrap()); + assert_eq!((v.ucs, v.ucs_per_viewport, v.extra.len()), (None, false, 0)); +} + +#[test] +fn a_deleted_named_ucs_is_not_pointed_at() { + let mut d = foreign(); + d.ucss.retain(|u| u.name != "SITE"); + let (h, _) = the_viewport(&d); + let text = cadcraft_io::write_dxf(&d); + let rec = viewport_record(&text, h); + assert!(group(&rec, "345").is_none(), "{rec:?}"); + assert_eq!(group(&rec, "346"), Some(record_handle(&text, "UCS", "BASE").as_str())); +} + +/// CADCraft's `VPEXTRA` copy of a viewport's unmodelled groups can't smuggle structure into the +/// record: a record start, handles, a subclass, a group brace, an owner or xdata are dropped on +/// read, so a save writes nothing the user didn't draw. +#[test] +fn vpextra_cannot_inject_records_or_handles() { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + let lines_before = d.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(); + let mut g: Vec<(i32, String)> = vec![(1001, "CADCRAFT".into()), (1000, "VPEXTRA".into()), (1002, "{".into())]; + for (code, value) in + [("0", "LINE"), ("5", "1F"), ("100", "AcDbLine"), ("102", "{ACAD_REACTORS"), ("105", "2A"), ("330", "1"), ("1001", "X"), ("13", "4.5")] + { + g.push((1000, code.into())); + g.push((1000, value.into())); + } + g.push((1002, "}".into())); + let back = cadcraft_io::read_dxf(inject(&text, h, &g).as_bytes()).unwrap(); + let (_, v) = the_viewport(&back); + let codes: Vec = v.extra.iter().map(|t| t.code).collect(); + assert!(codes.iter().all(|c| (1..1000).contains(c) && !matches!(c, 5 | 100 | 102 | 105 | 330)), "{codes:?}"); + assert!(v.extra.iter().any(|t| t.code == 13 && t.value.trim() == "4.5"), "a viewport's own group is still kept: {:?}", v.extra); + // Saved and opened again: still one viewport, no LINE it never had, no stray subclass. + let saved = cadcraft_io::write_dxf(&back); + assert!(!saved.lines().any(|l| l.trim() == "AcDbLine"), "no injected subclass"); + let again = cadcraft_io::read_dxf(saved.as_bytes()).unwrap(); + assert_eq!(again.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), lines_before, "no injected LINE"); + assert!(the_viewport(&again).1.extra.iter().all(|t| (1..1000).contains(&t.code))); +} + +/// Structural groups inside the record's own AcDbViewport subclass (a second handle, a group +/// brace) aren't kept either: written back, the record would have two handles. +#[test] +fn a_viewport_records_own_structural_groups_are_not_kept() { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + let g: Vec<(i32, String)> = vec![(5, "FFFFF1".into()), (105, "FFFFF2".into()), (102, "{ACAD_REACTORS".into()), (13, "4.5".into())]; + let back = cadcraft_io::read_dxf(inject(&text, h, &g).as_bytes()).unwrap(); + let (_, v) = the_viewport(&back); + let codes: Vec = v.extra.iter().map(|t| t.code).collect(); + assert!(codes.iter().all(|c| !matches!(c, 5 | 102 | 105)), "{codes:?}"); + assert!(v.extra.iter().any(|t| t.code == 13 && t.value.trim() == "4.5"), "a viewport's own group is still kept: {:?}", v.extra); + let saved = cadcraft_io::write_dxf(&back); + assert!(!saved.lines().any(|l| l.trim() == "FFFFF1" || l.trim() == "FFFFF2"), "no second handle"); +} + +/// A viewport whose only UCS group is its base UCS handle (346) keeps that base UCS. +#[test] +fn a_base_ucs_handle_alone_is_kept() { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + assert!(the_viewport(&d).1.ucs.is_none() && group(&viewport_record(&text, h), "110").is_none(), "no UCS groups of its own"); + let handle = record_handle(&text, "UCS", "BASE"); + let back = cadcraft_io::read_dxf(inject(&text, h, &[(346, handle)]).as_bytes()).unwrap(); + let u = the_viewport(&back).1.ucs.expect("a UCS from 346 alone"); + assert_eq!(u.base.as_deref(), Some("BASE")); + let again = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&back).as_bytes()).unwrap(); + assert_eq!(the_viewport(&again).1.ucs.and_then(|u| u.base).as_deref(), Some("BASE"), "kept through a save"); +} + +#[test] +fn hostile_viewport_ucs_groups_do_not_panic() { + let (d, h) = base(); + let text = cadcraft_io::write_dxf(&d); + let mut g: Vec<(i32, String)> = vec![ + (71, "7".into()), + (110, "nan".into()), + (120, "inf".into()), + (111, "1e400".into()), + (79, "99".into()), + (146, "-inf".into()), + (345, "ZZZZ".into()), + ]; + // Far more unmodelled groups than any viewport has. + g.extend((0..5000).map(|i| (13, i.to_string()))); + let back = cadcraft_io::read_dxf(inject(&text, h, &g).as_bytes()).unwrap(); + let (_, v) = the_viewport(&back); + assert_eq!(v.ucs, None, "unreadable axes give no UCS"); + assert!(!v.ucs_per_viewport, "71 is 1 or 0"); + assert!(v.extra.len() <= 512, "{}", v.extra.len()); + let _ = cadcraft_io::write_dxf(&back); + // A finite UCS with a nonsense orthographic type, elevation and named UCS. + let g: Vec<(i32, String)> = vec![(110, "1.0".into()), (79, "99".into()), (146, "nan".into()), (345, "ZZZZ".into()), (346, "".into())]; + let back = cadcraft_io::read_dxf(inject(&text, h, &g).as_bytes()).unwrap(); + let u = the_viewport(&back).1.ucs.unwrap(); + assert_eq!((u.ortho, u.elevation, u.named, u.base), (0, 0.0, None, None)); + assert_eq!((u.x_axis, u.y_axis), (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0))); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_default_viewport_reads_back_without_ucs_or_extras() { + cadcraft_io::dwg_worker::allow_in_process(); + for version in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] { + let (d, _) = base(); + let bytes = cadcraft_io::write_with(&d, "viewport.dwg", &cadcraft_io::SaveOptions { version: Some(version), binary: false }).unwrap(); + let back = cadcraft_io::read(&bytes, "viewport.dwg").unwrap(); + let (_, viewport) = the_viewport(&back); + assert!(viewport.ucs.is_none(), "{version}: {:?}", viewport.ucs); + assert!(!viewport.ucs_per_viewport, "{version}"); + assert!(viewport.extra.is_empty(), "{version}: {:?}", viewport.extra); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_viewport_with_non_default_snap_keeps_it() { + cadcraft_io::dwg_worker::allow_in_process(); + for version in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] { + let (mut d, h) = base(); + d.modify_entity(h, |e| { + let EntityKind::Viewport(v) = &mut e.kind else { return }; + v.extra = vec![RawTag { code: 14, value: "2.0".into() }, RawTag { code: 24, value: "2.0".into() }]; + }) + .unwrap(); + let bytes = cadcraft_io::write_with(&d, "viewport.dwg", &cadcraft_io::SaveOptions { version: Some(version), binary: false }).unwrap(); + let back = cadcraft_io::read(&bytes, "viewport.dwg").unwrap(); + let (_, viewport) = the_viewport(&back); + for code in [14, 24] { + assert_eq!(viewport.extra.iter().find(|t| t.code == code).and_then(|t| num(&t.value)), Some(2.0), "{version}"); + } + assert_eq!(viewport.extra.len(), 2, "only the non-default snap spacing remains: {version}: {:?}", viewport.extra); + } +} diff --git a/crates/io/tests/pdf_text.rs b/crates/io/tests/pdf_text.rs index 9ad2bebd2..33b51b5c6 100644 --- a/crates/io/tests/pdf_text.rs +++ b/crates/io/tests/pdf_text.rs @@ -233,6 +233,9 @@ fn text_seen_through_a_viewport_and_on_layers() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 497a972fb..5a45d9108 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -449,6 +449,9 @@ fn vp(center: Vec2, w: f64, h: f64, view_center: Vec2, view_height: f64, id: u32 layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, } } diff --git a/crates/render/tests/it/plot_line_styles.rs b/crates/render/tests/it/plot_line_styles.rs index b0abc6702..5a803cfdd 100644 --- a/crates/render/tests/it/plot_line_styles.rs +++ b/crates/render/tests/it/plot_line_styles.rs @@ -167,6 +167,9 @@ fn viewport_contents_get_their_pens() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; let space = Space::Paper("Layout1".into()); diff --git a/crates/render/tests/it/psltscale.rs b/crates/render/tests/it/psltscale.rs index ed0f17ea5..baaf89cf7 100644 --- a/crates/render/tests/it/psltscale.rs +++ b/crates/render/tests/it/psltscale.rs @@ -25,6 +25,9 @@ fn drawing(psltscale: i64) -> Drawing { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/render/tests/it/render_props.rs b/crates/render/tests/it/render_props.rs index cbc6741c1..29660b10e 100644 --- a/crates/render/tests/it/render_props.rs +++ b/crates/render/tests/it/render_props.rs @@ -63,6 +63,9 @@ fn dimensions_take_the_viewport_layer_colour() { layer_colors: vec![("a".into(), Color::Index(3))], clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/render/tests/it/viewport_frozen_layer.rs b/crates/render/tests/it/viewport_frozen_layer.rs index 876b33574..30879e4f4 100644 --- a/crates/render/tests/it/viewport_frozen_layer.rs +++ b/crates/render/tests/it/viewport_frozen_layer.rs @@ -21,6 +21,9 @@ fn drawing() -> Drawing { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common { layer: "VPORTS".into(), ..Default::default() }, EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/render/tests/raster_image.rs b/crates/render/tests/raster_image.rs index 2572fcf72..a76fccb27 100644 --- a/crates/render/tests/raster_image.rs +++ b/crates/render/tests/raster_image.rs @@ -258,6 +258,9 @@ fn a_layout_viewport_cuts_the_image_to_its_outline() { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/ui-egui/tests/it/gpu_origin_stability.rs b/crates/ui-egui/tests/it/gpu_origin_stability.rs index 96e654a2d..db1c61b16 100644 --- a/crates/ui-egui/tests/it/gpu_origin_stability.rs +++ b/crates/ui-egui/tests/it/gpu_origin_stability.rs @@ -319,6 +319,9 @@ fn layout_viewport_far_from_origin_reuses_mesh_recenters_and_keeps_highlight_ali layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }), ) diff --git a/crates/ui-egui/tests/it/measure_distance_snapping.rs b/crates/ui-egui/tests/it/measure_distance_snapping.rs index 8471c3f77..ac1f85201 100644 --- a/crates/ui-egui/tests/it/measure_distance_snapping.rs +++ b/crates/ui-egui/tests/it/measure_distance_snapping.rs @@ -30,6 +30,9 @@ fn harness(paper: bool, render: bool) -> Harness<'static, CadApp> { layer_colors: Vec::new(), clip: None, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }), ) diff --git a/crates/ui-egui/tests/it/mspace_viewport_view.rs b/crates/ui-egui/tests/it/mspace_viewport_view.rs index 0992c29c6..0f3e26e16 100644 --- a/crates/ui-egui/tests/it/mspace_viewport_view.rs +++ b/crates/ui-egui/tests/it/mspace_viewport_view.rs @@ -37,6 +37,9 @@ fn harness(clipped: bool) -> Harness<'static, CadApp> { layer_colors: Vec::new(), clip, on: true, + ucs: None, + ucs_per_viewport: false, + extra: Vec::new(), twist: 0.0, }), ) From a79b9feca966878abc9295e9342e9d4f63948e02 Mon Sep 17 00:00:00 2001 From: vantruong-dang Date: Tue, 1 Dec 2026 18:50:47 +0700 Subject: [PATCH 41/43] feat(doc,io,render): support MTEXT background mask (DXF 90/63/421/45) (#3240) * feat(mtext): support MTEXT background mask (DXF 90/63/421/45) in doc, io, and render * fix(mtext): write background mask before column tags and use Autodesk border offset factor * fix(render): resolve ByLayer/ByBlock for MTEXT background mask and guard non-finite rotation * fix(render/mtext): cover overflowing glyphs, MLeader text opt, and attrib ByBlock bg * fix(io/dxf): omit inactive MTEXT background mask conditional tags * Fix MTEXT background test for current Text fields Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --------- Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: vantruong-dang Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/doc/src/entity.rs | 2 +- crates/doc/src/entity/text.rs | 21 ++ crates/doc/src/extents.rs | 2 + crates/doc/src/tests.rs | 1 + crates/engine/src/cmd/annotate/leader.rs | 3 + crates/engine/src/cmd/annotate/mleader.rs | 1 + crates/engine/src/cmd/draw/text.rs | 1 + crates/engine/src/cmd/modify/explode.rs | 1 + crates/engine/src/cmd/modify2/textedit.rs | 2 + crates/engine/src/cmd/mtext_opts.rs | 1 + crates/engine/src/cmd/txt2mtxt.rs | 2 + crates/engine/src/sample.rs | 2 +- crates/engine/src/select.rs | 1 + crates/engine/src/snap.rs | 3 + crates/engine/tests/it/attedit_prompts.rs | 2 + crates/engine/tests/it/attrib_modes.rs | 1 + crates/engine/tests/it/mtext_columns.rs | 1 + .../engine/tests/it/multiline_attributes.rs | 1 + .../tests/it/viewport_frozen_block_parts.rs | 1 + crates/io/src/dxf_mleader.rs | 1 + crates/io/src/dxf_read/text.rs | 11 + crates/io/src/dxf_write/blocks.rs | 2 + crates/io/src/dxf_write/entity.rs | 24 ++ crates/io/src/tests.rs | 3 + .../io/tests/it/annotative_text_contexts.rs | 1 + crates/io/tests/it/followups_626.rs | 1 + crates/io/tests/it/main.rs | 1 + crates/io/tests/it/mleader_roundtrip.rs | 1 + crates/io/tests/it/mtext_background_mask.rs | 128 +++++++++ crates/io/tests/it/mtext_caret_spaces.rs | 1 + crates/io/tests/it/mtext_columns_roundtrip.rs | 1 + crates/io/tests/it/mtext_embedded_object.rs | 1 + crates/io/tests/it/mtext_line_spacing.rs | 71 +++++ .../io/tests/it/roundtrip/cases/geometry.rs | 1 + crates/io/tests/it/roundtrip/compare.rs | 3 +- .../tests/it/roundtrip/dxf/geometry_groups.rs | 1 + crates/render/src/blocks.rs | 8 +- crates/render/src/draw.rs | 8 +- crates/render/src/tests.rs | 265 ++++++++++++++++++ crates/render/src/text_entity.rs | 46 ++- crates/render/tests/it/dim_text_fill.rs | 3 + 41 files changed, 620 insertions(+), 11 deletions(-) create mode 100644 crates/io/tests/it/mtext_background_mask.rs diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index bfcc6664e..75978e0e2 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -60,7 +60,7 @@ pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspe pub use fill::{Gradient, Hatch, HatchLoop}; pub use layout::{Image, Table, TableCell, Viewport, ViewportUcs}; pub use proxy::{ProxyTables, TableOrder, proxy_entities}; -pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign}; +pub use text::{HAlign, MText, MTextBackground, MTextColumnType, MTextColumns, Text, VAlign}; pub use wipeout::Wipeout; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Unknown { diff --git a/crates/doc/src/entity/text.rs b/crates/doc/src/entity/text.rs index 8fc5ae5d2..bf2ac77d3 100644 --- a/crates/doc/src/entity/text.rs +++ b/crates/doc/src/entity/text.rs @@ -90,6 +90,27 @@ pub struct MText { /// one column. #[serde(default, skip_serializing_if = "Option::is_none")] pub columns: Option, + /// Background mask (DXF 90/63/421/45); `None` when off. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub background: Option, +} + +/// MTEXT background mask (DXF 90, 63/421, 45). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MTextBackground { + /// DXF group 90 bitmask: bit 1 = fill colour set, bit 2 = use drawing background colour. + pub mask: u8, + /// DXF group 63 (ACI) or 421 (true colour); `None` when using drawing background. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + /// DXF group 45 border offset factor (default 1.5, valid 1.0..=5.0). + #[serde(default = "default_bg_scale")] + pub scale: f64, +} + +fn default_bg_scale() -> f64 { + 1.5 } fn attach_tl() -> u8 { diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 39e23da84..67ca89028 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -913,6 +913,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, } } @@ -988,6 +989,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; let ml = crate::MLeader { leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0)]], diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index f822d5d87..f04c86b00 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -686,6 +686,7 @@ fn mtext_kind(contents: &str) -> EntityKind { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }) } diff --git a/crates/engine/src/cmd/annotate/leader.rs b/crates/engine/src/cmd/annotate/leader.rs index 45a4bf76b..d7a955484 100644 --- a/crates/engine/src/cmd/annotate/leader.rs +++ b/crates/engine/src/cmd/annotate/leader.rs @@ -151,6 +151,7 @@ impl Interactive for LeaderM { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), EntityKind::MText(m) => Some(m.clone()), _ => None, @@ -324,6 +325,7 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }))?) } Annotation::Quick { lines, width } => { @@ -341,6 +343,7 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }))?) } Annotation::Copy(m) => { diff --git a/crates/engine/src/cmd/annotate/mleader.rs b/crates/engine/src/cmd/annotate/mleader.rs index 9b4e74128..129762739 100644 --- a/crates/engine/src/cmd/annotate/mleader.rs +++ b/crates/engine/src/cmd/annotate/mleader.rs @@ -31,6 +31,7 @@ fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option< line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), style: st.name.clone(), arrow_size: st.arrow_size, diff --git a/crates/engine/src/cmd/draw/text.rs b/crates/engine/src/cmd/draw/text.rs index 4d0d3c506..7f7259011 100644 --- a/crates/engine/src/cmd/draw/text.rs +++ b/crates/engine/src/cmd/draw/text.rs @@ -97,6 +97,7 @@ pub(super) fn run_mtext(s: &mut Session, p: &Value) -> Result { line_spacing: f64_or(p, "lineSpacing", 1.0), line_spacing_exact: bool_or(p, "lineSpacingExact", false), columns: crate::cmd::mtext_opts::json_columns(p, height, width)?, + background: None, }); added(s.add_entity(k)?) } diff --git a/crates/engine/src/cmd/modify/explode.rs b/crates/engine/src/cmd/modify/explode.rs index 400b5ceba..52858c5eb 100644 --- a/crates/engine/src/cmd/modify/explode.rs +++ b/crates/engine/src/cmd/modify/explode.rs @@ -179,6 +179,7 @@ fn explode_dimension(d: &cadcraft_doc::Drawing, e: &Entity, dm: &cadcraft_doc::D line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), }); } diff --git a/crates/engine/src/cmd/modify2/textedit.rs b/crates/engine/src/cmd/modify2/textedit.rs index 9f3226c31..328e27221 100644 --- a/crates/engine/src/cmd/modify2/textedit.rs +++ b/crates/engine/src/cmd/modify2/textedit.rs @@ -48,6 +48,7 @@ pub(crate) fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, } } @@ -95,6 +96,7 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; Some(TextEditor { mtext, kind: EditorKind::Dimension { measured }, key, extents: None }) } diff --git a/crates/engine/src/cmd/mtext_opts.rs b/crates/engine/src/cmd/mtext_opts.rs index c234271bf..301b2ea80 100644 --- a/crates/engine/src/cmd/mtext_opts.rs +++ b/crates/engine/src/cmd/mtext_opts.rs @@ -89,6 +89,7 @@ impl MTextOpts { line_spacing: self.spacing, line_spacing_exact: self.exact, columns: self.columns.clone().filter(|_| width > 0.0), + background: None, } } } diff --git a/crates/engine/src/cmd/txt2mtxt.rs b/crates/engine/src/cmd/txt2mtxt.rs index fb024f08e..dcacf34ca 100644 --- a/crates/engine/src/cmd/txt2mtxt.rs +++ b/crates/engine/src/cmd/txt2mtxt.rs @@ -107,6 +107,7 @@ fn convert(s: &mut Session, hs: &[Handle], o: &Txt2MtxtOptions) -> Result<(Vec = items.iter().skip(1).map(|(h, ..)| *h).collect(); @@ -196,6 +197,7 @@ fn single(t: &Text) -> MText { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, } } diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index 702770e3f..5673b84b3 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -216,7 +216,7 @@ pub fn bracket() -> Drawing { add(on("Notes"), text(Vec2::new(4.1, -0.3), 0.16, "FRONT VIEW")); add( on("Notes"), - EntityKind::MText(MText { insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None }), + EntityKind::MText(MText { insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None, background: None }), ); let tb0 = Vec2::new(14.0, -0.5); add(on("Title"), lwpoly(rect_vertices(tb0, tb0 + Vec2::new(4.0, 2.0)), true)); diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index fa23c8f1f..07f277079 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -962,6 +962,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }) } diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index f35b8577b..d70ee03c6 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -1374,6 +1374,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); } @@ -1405,6 +1406,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); } @@ -1488,6 +1490,7 @@ mod tests { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); } diff --git a/crates/engine/tests/it/attedit_prompts.rs b/crates/engine/tests/it/attedit_prompts.rs index a0d33d19a..7d3122dcc 100644 --- a/crates/engine/tests/it/attedit_prompts.rs +++ b/crates/engine/tests/it/attedit_prompts.rs @@ -304,6 +304,7 @@ fn dash_attedit_edits_a_multiline_attributes_text() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; set_t(&mut s, h, |a| a.multiline = Some(MultilineAttrib { mtext: mtext.clone(), read_as: "abc".into() })); let before = attrib_t(&s, h).text.insert; @@ -337,6 +338,7 @@ fn dash_attedit_defaults_of_a_multiline_attribute_come_from_its_multiline_text() line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; set_t(&mut s, h, |a| { a.text.height = 1.25; diff --git a/crates/engine/tests/it/attrib_modes.rs b/crates/engine/tests/it/attrib_modes.rs index 12e744851..7401a221d 100644 --- a/crates/engine/tests/it/attrib_modes.rs +++ b/crates/engine/tests/it/attrib_modes.rs @@ -76,6 +76,7 @@ fn definition(tag: &str, x: f64, modes: AttribModes, invisible: bool, multiline: line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; MultilineAttrib { mtext, read_as: format!("{tag}\nTWO") } }); diff --git a/crates/engine/tests/it/mtext_columns.rs b/crates/engine/tests/it/mtext_columns.rs index 61420352a..d1fbff904 100644 --- a/crates/engine/tests/it/mtext_columns.rs +++ b/crates/engine/tests/it/mtext_columns.rs @@ -103,6 +103,7 @@ fn scale_scales_multileader_text_width_and_columns() { heights: vec![3.0, 4.0], flow_reversed: false, }), + background: None, }; let mut s = Session::new(); let ml = MLeader { diff --git a/crates/engine/tests/it/multiline_attributes.rs b/crates/engine/tests/it/multiline_attributes.rs index 9e747e215..da2b20362 100644 --- a/crates/engine/tests/it/multiline_attributes.rs +++ b/crates/engine/tests/it/multiline_attributes.rs @@ -36,6 +36,7 @@ fn session() -> Session { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; let def = Attrib { tag: "LABEL".into(), diff --git a/crates/engine/tests/it/viewport_frozen_block_parts.rs b/crates/engine/tests/it/viewport_frozen_block_parts.rs index 089d58c0a..ee1dabfaa 100644 --- a/crates/engine/tests/it/viewport_frozen_block_parts.rs +++ b/crates/engine/tests/it/viewport_frozen_block_parts.rs @@ -1287,6 +1287,7 @@ fn dimension_with_its_text_on_hidden() -> (cadcraft_engine::doc::Drawing, Handle line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; let mut text = Entity::new(Handle(5), EntityKind::MText(words)); text.common.layer = "Hidden".into(); diff --git a/crates/io/src/dxf_mleader.rs b/crates/io/src/dxf_mleader.rs index a73c814bb..52a5be370 100644 --- a/crates/io/src/dxf_mleader.rs +++ b/crates/io/src/dxf_mleader.rs @@ -310,6 +310,7 @@ pub(crate) fn read(tags: &[Tag]) -> MLeader { line_spacing: pos(p.line_spacing).unwrap_or(1.0), line_spacing_exact: p.line_spacing_style == Some(2), columns: None, + background: None, } }); let block = has_block.then(|| { diff --git a/crates/io/src/dxf_read/text.rs b/crates/io/src/dxf_read/text.rs index 7fcff5784..2e5a6d001 100644 --- a/crates/io/src/dxf_read/text.rs +++ b/crates/io/src/dxf_read/text.rs @@ -73,6 +73,16 @@ pub(super) fn mtext_from(tags: &[Tag], c: &Common) -> MText { a => a, }; } + let background = own.i(90).filter(|&m| (m & 0x03) != 0).map(|m| { + let mask = (m & 0x03) as u8; + let color = if let Some(tc) = own.i(421) { + Some(cadcraft_color::Color::True(cadcraft_color::Rgb::from_u32(tc as u32))) + } else { + own.i(63).map(|aci| cadcraft_color::Color::from_aci(aci as i16)) + }; + let scale = own.fd(45, 1.5).clamp(1.0, 5.0); + cadcraft_doc::MTextBackground { mask, color, scale } + }); MText { insert: t.p(10), height: t.fd(40, 0.2).max(1e-9), @@ -89,6 +99,7 @@ pub(super) fn mtext_from(tags: &[Tag], c: &Common) -> MText { line_spacing: t.fd(44, 1.0), line_spacing_exact: t.i(73) == Some(2), columns: columns.map(|(c, _)| c), + background, } } diff --git a/crates/io/src/dxf_write/blocks.rs b/crates/io/src/dxf_write/blocks.rs index 594f8f8c5..40c65ee8d 100644 --- a/crates/io/src/dxf_write/blocks.rs +++ b/crates/io/src/dxf_write/blocks.rs @@ -147,6 +147,7 @@ pub(super) fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Ve line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), }); } @@ -201,6 +202,7 @@ pub(crate) fn table_block_entities(d: &Drawing, t: &Table, layer: &str) -> Vec { + w.i(63, i64::from(cadcraft_color::nearest_aci(rgb))); + w.i(421, i64::from(rgb.to_u32())); + } + c => w.i(63, i64::from(c.to_aci())), + } + } + let scale = if bg.scale.is_finite() { bg.scale.clamp(1.0, 5.0) } else { 1.5 }; + w.f(45, scale); + } + } w.t.extend(crate::dxf_read::mtext_dxf::column_tags(t, cx.target >= Version::R2018 && !cx.legacy_columns)); cx.anno_xdata(w, e); } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 30060b142..305055247 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -59,6 +59,7 @@ fn sample() -> Drawing { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), ) .unwrap(); @@ -3066,6 +3067,7 @@ fn intl_sample() -> Drawing { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), ) .unwrap(); @@ -3310,6 +3312,7 @@ fn mleader_is_written_as_multileader() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; let m = cadcraft_doc::MLeader { leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0)]], diff --git a/crates/io/tests/it/annotative_text_contexts.rs b/crates/io/tests/it/annotative_text_contexts.rs index 4cdf181eb..dd8ca9098 100644 --- a/crates/io/tests/it/annotative_text_contexts.rs +++ b/crates/io/tests/it/annotative_text_contexts.rs @@ -699,6 +699,7 @@ fn with_mleader() -> (Drawing, Handle) { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; let m = cadcraft_doc::MLeader { leaders: vec![vec![Vec3::ZERO]], diff --git a/crates/io/tests/it/followups_626.rs b/crates/io/tests/it/followups_626.rs index 376d309b6..0ba550789 100644 --- a/crates/io/tests/it/followups_626.rs +++ b/crates/io/tests/it/followups_626.rs @@ -46,6 +46,7 @@ fn mleader_drawing() -> (Drawing, MLeader) { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), style: "Standard".into(), arrow_size: 1.0, diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index e80d30a37..e3d58fbe8 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -66,6 +66,7 @@ mod mleader_roundtrip; mod mline_roundtrip; #[cfg(not(target_arch = "wasm32"))] mod model_layout_plot_type; +mod mtext_background_mask; mod mtext_caret_spaces; mod mtext_columns_roundtrip; mod mtext_embedded_object; diff --git a/crates/io/tests/it/mleader_roundtrip.rs b/crates/io/tests/it/mleader_roundtrip.rs index d373c8fbe..5fa1814f8 100644 --- a/crates/io/tests/it/mleader_roundtrip.rs +++ b/crates/io/tests/it/mleader_roundtrip.rs @@ -32,6 +32,7 @@ fn text_mleader() -> MLeader { line_spacing: 1.25, line_spacing_exact: true, columns: None, + background: None, }), style: "Callout".into(), arrow_size: 0.3, diff --git a/crates/io/tests/it/mtext_background_mask.rs b/crates/io/tests/it/mtext_background_mask.rs new file mode 100644 index 000000000..383ebee74 --- /dev/null +++ b/crates/io/tests/it/mtext_background_mask.rs @@ -0,0 +1,128 @@ +//! MTEXT background mask (DXF groups 90, 63/421, 45) conditional emission and round-trip. + +use cadcraft_color::{Color, Rgb}; +use cadcraft_doc::{Common, Drawing, EntityKind, MText, MTextBackground, MTextColumnType, MTextColumns, Space}; +use cadcraft_geom::Vec3; +use cadcraft_io::{read_dxf, write_dxf}; + +fn make_mtext(background: Option, columns: Option) -> MText { + MText { + insert: Vec3::new(10.0, 20.0, 0.0), + height: 2.5, + width: 50.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "Hello MTEXT".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns, + background, + } +} + +fn round_trip(t: MText) -> (MText, String) { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); + let dxf = write_dxf(&d); + let back = read_dxf(dxf.as_bytes()).unwrap(); + let entity = back + .model + .iter() + .find_map(|e| match &e.kind { + EntityKind::MText(m) => Some(m.clone()), + _ => None, + }) + .expect("MText after round trip"); + (entity, dxf) +} + +/// Extract `(group_code, value)` pairs of the first `MTEXT` entity in `ENTITIES`. +fn mtext_entity_tags(dxf: &str) -> Vec<(i32, String)> { + let mut lines = dxf.lines(); + let mut pairs = Vec::new(); + let mut in_entities = false; + let mut in_mtext = false; + while let (Some(c), Some(v)) = (lines.next(), lines.next()) { + let code: i32 = c.trim().parse().expect("group code"); + let val = v.trim().to_string(); + if code == 0 && val == "SECTION" { + if let (Some(_), Some(sec)) = (lines.next(), lines.next()) { + in_entities = sec.trim() == "ENTITIES"; + } + continue; + } + if !in_entities { + continue; + } + if code == 0 { + if in_mtext { + break; + } + if val == "MTEXT" { + in_mtext = true; + } + continue; + } + if in_mtext { + pairs.push((code, val)); + } + } + pairs +} + +#[test] +fn mtext_background_mask_zero_omits_conditional_tags() { + let bg = MTextBackground { mask: 0, color: Some(Color::True(Rgb(10, 20, 30))), scale: 2.0 }; + let (back, dxf) = round_trip(make_mtext(Some(bg), None)); + assert_eq!(back.background, None); + + let tags = mtext_entity_tags(&dxf); + for forbidden in [90, 63, 421, 45, 441] { + assert!(!tags.iter().any(|(c, _)| *c == forbidden), "mask 0 must not emit group {forbidden}: {tags:?}"); + } +} + +#[test] +fn mtext_background_window_fill_omits_color_tags_and_roundtrips() { + for mask in [2u8, 3u8] { + let bg = MTextBackground { mask, color: Some(Color::Index(1)), scale: 2.25 }; + let (back, dxf) = round_trip(make_mtext(Some(bg), None)); + assert_eq!(back.background, Some(MTextBackground { mask, color: None, scale: 2.25 })); + + let tags = mtext_entity_tags(&dxf); + assert!(tags.iter().any(|(c, v)| *c == 90 && v == &mask.to_string()), "expected group 90={mask}: {tags:?}"); + assert!(tags.iter().any(|(c, v)| *c == 45 && v.parse::().ok() == Some(2.25)), "expected group 45=2.25: {tags:?}"); + for color_code in [63, 421, 441] { + assert!(!tags.iter().any(|(c, _)| *c == color_code), "window background (mask={mask}) must not emit group {color_code}: {tags:?}"); + } + } +} + +#[test] +fn mtext_background_custom_aci_and_truecolor_before_columns_roundtrips() { + let cols = MTextColumns { kind: MTextColumnType::Static, count: 2, gutter: 5.0, height: 20.0, ..Default::default() }; + + let bg_aci = MTextBackground { mask: 1, color: Some(Color::Index(3)), scale: 1.75 }; + let (back_aci, dxf_aci) = round_trip(make_mtext(Some(bg_aci.clone()), Some(cols.clone()))); + assert_eq!(back_aci.background, Some(bg_aci)); + let tags_aci = mtext_entity_tags(&dxf_aci); + let col_pos_aci = tags_aci.iter().position(|(c, _)| *c == 75 || *c == 101).expect("column tags"); + let p90 = tags_aci.iter().position(|(c, v)| *c == 90 && v == "1").expect("group 90=1"); + let p63 = tags_aci.iter().position(|(c, v)| *c == 63 && v == "3").expect("group 63=3"); + let p45 = tags_aci.iter().position(|(c, v)| *c == 45 && v.parse::().ok() == Some(1.75)).expect("group 45=1.75"); + assert!(!tags_aci.iter().any(|(c, _)| *c == 421), "ACI color must not emit 421: {tags_aci:?}"); + assert!(p90 < col_pos_aci && p63 < col_pos_aci && p45 < col_pos_aci, "background tags must precede columns"); + + let rgb = Rgb(0x12, 0x34, 0x56); + let bg_rgb = MTextBackground { mask: 1, color: Some(Color::True(rgb)), scale: 2.0 }; + let (back_rgb, dxf_rgb) = round_trip(make_mtext(Some(bg_rgb.clone()), Some(cols))); + assert_eq!(back_rgb.background, Some(bg_rgb)); + let tags_rgb = mtext_entity_tags(&dxf_rgb); + let col_pos_rgb = tags_rgb.iter().position(|(c, _)| *c == 75 || *c == 101).expect("column tags"); + let r90 = tags_rgb.iter().position(|(c, v)| *c == 90 && v == "1").expect("group 90=1"); + let r63 = tags_rgb.iter().position(|(c, _)| *c == 63).expect("group 63"); + let r421 = tags_rgb.iter().position(|(c, v)| *c == 421 && v == &rgb.to_u32().to_string()).expect("group 421"); + let r45 = tags_rgb.iter().position(|(c, v)| *c == 45 && v.parse::().ok() == Some(2.0)).expect("group 45=2.0"); + assert!(r90 < col_pos_rgb && r63 < col_pos_rgb && r421 < col_pos_rgb && r45 < col_pos_rgb, "truecolor background tags must precede columns"); +} diff --git a/crates/io/tests/it/mtext_caret_spaces.rs b/crates/io/tests/it/mtext_caret_spaces.rs index 31ccf4c30..93e4019e6 100644 --- a/crates/io/tests/it/mtext_caret_spaces.rs +++ b/crates/io/tests/it/mtext_caret_spaces.rs @@ -41,6 +41,7 @@ fn drawing() -> Result<(Drawing, Vec<(Handle, String)>), Box) -> MText line_spacing: 1.0, line_spacing_exact: false, columns, + background: None, } } diff --git a/crates/io/tests/it/mtext_embedded_object.rs b/crates/io/tests/it/mtext_embedded_object.rs index 4bd95cb77..b4e870cbd 100644 --- a/crates/io/tests/it/mtext_embedded_object.rs +++ b/crates/io/tests/it/mtext_embedded_object.rs @@ -22,6 +22,7 @@ fn with_embedded_object(rotation: f64, dir: (f64, f64)) -> String { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); let dxf = write_dxf(&d); diff --git a/crates/io/tests/it/mtext_line_spacing.rs b/crates/io/tests/it/mtext_line_spacing.rs index 8a030cbc7..a3afcb75f 100644 --- a/crates/io/tests/it/mtext_line_spacing.rs +++ b/crates/io/tests/it/mtext_line_spacing.rs @@ -18,6 +18,7 @@ fn line_spacing_style_roundtrips() { line_spacing: 1.5, line_spacing_exact: exact, columns: None, + background: None, }; d.add(&Space::Model, Common::default(), EntityKind::MText(t.clone())).unwrap(); let bytes = cadcraft_io::write(&d, "a.dxf").unwrap(); @@ -27,3 +28,73 @@ fn line_spacing_style_roundtrips() { assert_eq!(r.line_spacing, 1.5); } } + +#[test] +fn background_mask_roundtrips() { + use cadcraft_color::{Color, Rgb}; + use cadcraft_doc::MTextBackground; + for bg in [ + MTextBackground { mask: 2, color: None, scale: 1.5 }, + MTextBackground { mask: 1, color: Some(Color::Index(3)), scale: 2.0 }, + MTextBackground { mask: 1, color: Some(Color::True(Rgb(12, 34, 56))), scale: 1.25 }, + ] { + let mut d = Drawing::new_metric(); + let t = MText { + insert: Vec3::new(1.0, 2.0, 0.0), + height: 2.5, + width: 40.0, + attach: 5, + rotation: 0.0, + style: "Standard".into(), + contents: "MASKED".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(bg.clone()), + }; + d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); + let bytes = cadcraft_io::write(&d, "a.dxf").unwrap(); + let back = cadcraft_io::read(&bytes, "a.dxf").unwrap(); + let Some(EntityKind::MText(r)) = back.model.iter().map(|e| e.kind.clone()).next() else { panic!("no mtext") }; + assert_eq!(r.background, Some(bg)); + } +} + +#[test] +fn background_mask_roundtrips_with_legacy_and_embedded_columns() { + use cadcraft_color::Color; + use cadcraft_doc::{MTextBackground, MTextColumnType, MTextColumns}; + use cadcraft_io::{SaveOptions, Version, write_with}; + let bg = MTextBackground { mask: 1, color: Some(Color::Index(3)), scale: 1.5 }; + let cols = MTextColumns { + kind: MTextColumnType::Static, + count: 2, + gutter: 2.0, + height: 20.0, + auto_height: false, + heights: Vec::new(), + flow_reversed: false, + }; + for version in [Version::R2013, Version::R2018] { + let mut d = Drawing::new_metric(); + let t = MText { + insert: Vec3::new(1.0, 2.0, 0.0), + height: 2.5, + width: 22.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "COL1\\NCOL2".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: Some(cols.clone()), + background: Some(bg.clone()), + }; + d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); + let bytes = write_with(&d, "a.dxf", &SaveOptions { version: Some(version), ..Default::default() }).unwrap(); + let back = cadcraft_io::read(&bytes, "a.dxf").unwrap(); + let Some(EntityKind::MText(r)) = back.model.iter().map(|e| e.kind.clone()).next() else { panic!("no mtext") }; + assert_eq!(r.background, Some(bg.clone()), "version={version:?}"); + assert!(r.columns.is_some(), "columns lost for version={version:?}"); + } +} diff --git a/crates/io/tests/it/roundtrip/cases/geometry.rs b/crates/io/tests/it/roundtrip/cases/geometry.rs index e8168c183..0e36bfcaf 100644 --- a/crates/io/tests/it/roundtrip/cases/geometry.rs +++ b/crates/io/tests/it/roundtrip/cases/geometry.rs @@ -133,6 +133,7 @@ pub(crate) fn mtext() -> MText { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, } } diff --git a/crates/io/tests/it/roundtrip/compare.rs b/crates/io/tests/it/roundtrip/compare.rs index 31ff260eb..12b1137cf 100644 --- a/crates/io/tests/it/roundtrip/compare.rs +++ b/crates/io/tests/it/roundtrip/compare.rs @@ -237,7 +237,7 @@ fn text(expected: &Text, actual: &Text, context: &str) { } fn mtext(expected: &MText, actual: &MText, context: &str) { - let MText { insert, height, width, attach, rotation, style, contents, line_spacing, line_spacing_exact, columns } = expected; + let MText { insert, height, width, attach, rotation, style, contents, line_spacing, line_spacing_exact, columns, background } = expected; equal(insert, &actual.insert, context, "mtext.insert"); equal(height, &actual.height, context, "mtext.height"); equal(width, &actual.width, context, "mtext.width"); @@ -248,6 +248,7 @@ fn mtext(expected: &MText, actual: &MText, context: &str) { equal(line_spacing, &actual.line_spacing, context, "mtext.line_spacing"); equal(line_spacing_exact, &actual.line_spacing_exact, context, "mtext.line_spacing_exact"); equal(columns, &actual.columns, context, "mtext.columns"); + equal(background, &actual.background, context, "mtext.background"); } fn attrib(expected: &Attrib, actual: &Attrib, context: &str) { diff --git a/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs b/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs index 19e15beaa..0e42f6386 100644 --- a/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs +++ b/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs @@ -74,6 +74,7 @@ fn fixtures() -> Vec { line_spacing: 1.75, line_spacing_exact: true, columns: None, + background: None, }), groups: "10\n1.25\n20\n-2.5\n30\n3.75\n40\n2.25\n41\n12.5\n71\n5\n50\n90\n7\nStandard\n1\nfirst\\Psecond\n73\n2\n44\n1.75\n", output: vec![ diff --git a/crates/render/src/blocks.rs b/crates/render/src/blocks.rs index 432824a1c..731a32598 100644 --- a/crates/render/src/blocks.rs +++ b/crates/render/src/blocks.rs @@ -219,8 +219,8 @@ fn attributes(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert // on insertion), except those set on the attribute itself: ByBlock = the reference's, // layer 0 from the definition = the reference's layer. let def = defs.get(&a.tag.to_ascii_lowercase()).copied(); - let (ink, lw, shown, t) = match (def, a.props.is_empty()) { - (None, true) => (rgb, resolve(ctx, e, b.plotting).1, true, reference), + let (ink, lw, shown, t, attr_ctx, attr_layer) = match (def, a.props.is_empty()) { + (None, true) => (rgb, resolve(ctx, e, b.plotting).1, true, reference, sub_ctx(ctx, e, Mat3::IDENTITY), e.common.layer.clone()), (def, _) => { let c = a.props.over(&def.map(|d| d.common.clone()).unwrap_or_else(by_block)); let mut sub = sub_ctx(ctx, e, Mat3::IDENTITY); @@ -233,14 +233,14 @@ fn attributes(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert // ByBlock takes the reference's own transparency, not its locked-layer fade. let t = if b.opts.transparency { transparency(c.transparency, layer_t, own) } else { 0 }; let t = if b.opts.on_screen { t.max(fade) } else { t }; - (ink, lw, shown, t) + (ink, lw, shown, t, sub, c.layer) } }; if shown { b.transparency = t; let lw = if b.opts.lineweights { lw } else { 0.0 }; match (&multiline, &sh) { - (Some(m), _) => mtext(b, ctx, m, ink, lw), + (Some(m), _) => mtext(b, &attr_ctx, &attr_layer, m, ink, lw), (None, Some(sh)) => b.shaped(ctx, ink, lw, sh), (None, None) => {} } diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 1385f1483..1575f66aa 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -168,9 +168,9 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { return; } if e.common.matches_layout_orientation() && t.rotation != 0.0 { - mtext(b, ctx, &cadcraft_doc::MText { rotation: 0.0, ..t.clone() }, rgb, lw); + mtext(b, ctx, &e.common.layer, &cadcraft_doc::MText { rotation: 0.0, ..t.clone() }, rgb, lw); } else { - mtext(b, ctx, t, rgb, lw); + mtext(b, ctx, &e.common.layer, t, rgb, lw); } } EntityKind::Insert(ins) => insert(b, ctx, e, ins, rgb, own), @@ -308,7 +308,9 @@ fn draw_mleader(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &cadcraft_doc::MLeade let land = m.landing.xy(); let dir = if t.insert.x >= land.x { 1.0 } else { -1.0 }; b.polyline(ctx, rgb, lw, &[land, land + Vec2::new(m.dogleg * dir, 0.0)]); - mtext(b, ctx, t, rgb, lw); + if b.opts.text { + mtext(b, ctx, &e.common.layer, t, rgb, lw); + } } if let Some(ins) = &m.block { if m.dogleg > 0.0 && !m.leaders.is_empty() { diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 5a45d9108..423268990 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -749,6 +749,7 @@ fn truetype_mtext_and_dimension_text() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }), ) .unwrap(); @@ -1416,6 +1417,7 @@ fn mtext_exact_spacing_ignores_taller_lines() { line_spacing, line_spacing_exact, columns: None, + background: None, }; let d = Drawing::new_imperial(); let height = |contents: &str, ls: f64, exact: bool| layout_mtext_entity(&d, &mtext(contents, ls, exact)).bounds.height(); @@ -1905,6 +1907,269 @@ fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() { assert_eq!(loops_of(&h).len(), 2); } +#[test] +fn mtext_background_mask_emits_mask_before_text() { + let mut d = Drawing::new_metric(); + d.add( + &Space::Model, + Common::default(), + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.25, + style: "Standard".into(), + contents: "ANCHOR".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 2, color: None, scale: 1.5 }), + }), + ) + .unwrap(); + let list = build(&d, &Space::Model, &Options::default()); + let mask_idx = list.prims.iter().position(|p| p.kind == Kind::Mask).expect("background mask"); + assert_eq!(mask_idx, 0, "mask must precede text primitives"); + + let mut d2 = Drawing::new_metric(); + d2.add( + &Space::Model, + Common::default(), + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "COLORED".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 1, color: Some(Color::Index(3)), scale: 1.5 }), + }), + ) + .unwrap(); + let list2 = build(&d2, &Space::Model, &Options::default()); + assert!(list2.prims.iter().any(|p| p.kind == Kind::Tris && p.color == Rgb(0, 255, 0)), "green background fill"); + assert!(!list2.prims.iter().any(|p| p.kind == Kind::Mask)); + // Border offset factor 1.5 with height 2.0 expands each side by (1.5 - 1.0) * 2.0 = 1.0. + let mut d2_plain = Drawing::new_metric(); + d2_plain + .add( + &Space::Model, + Common::default(), + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "COLORED".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: None, + }), + ) + .unwrap(); + let plain_list = build(&d2_plain, &Space::Model, &Options::default()); + assert!((list2.bounds.width() - plain_list.bounds.width() - 2.0).abs() < 1e-6, "expected +2.0 width margin"); + assert!((list2.bounds.height() - plain_list.bounds.height() - 2.0).abs() < 1e-6, "expected +2.0 height margin"); +} + +#[test] +fn mtext_background_mask_stays_paper_mask_under_monochrome_ctb() { + let mut d = Drawing::new_metric(); + d.add( + &Space::Model, + Common::default(), + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::new(5.0, 5.0, 0.0), + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.5, + style: "Standard".into(), + contents: "MASKED".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 3, color: None, scale: 1.5 }), + }), + ) + .unwrap(); + let opts = Options { + plot_style_table: Some(std::sync::Arc::new(cadcraft_doc::PlotStyleTable::builtin("monochrome.ctb").unwrap())), + ..Default::default() + }; + let list = build_plot(&d, &Space::Model, &opts); + let mask_idx = list.prims.iter().position(|p| p.kind == Kind::Mask).expect("Kind::Mask must remain"); + let text_idx = list.prims.iter().position(|p| p.kind != Kind::Mask).expect("text prims"); + assert!(mask_idx < text_idx, "Kind::Mask must precede text under monochrome.ctb"); +} + +#[test] +fn mtext_background_mask_resolves_bylayer_byblock_and_nonfinite_rotation() { + let mut d = Drawing::new_metric(); + d.layers.push(cadcraft_doc::Layer { name: "RED_LAYER".into(), color: Color::Index(1), ..Default::default() }); + d.add( + &Space::Model, + Common { layer: "RED_LAYER".into(), ..Default::default() }, + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 0.0, + attach: 1, + rotation: f64::NAN, + style: "Standard".into(), + contents: "BYLAYER".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 1, color: Some(Color::ByLayer), scale: 1.5 }), + }), + ) + .unwrap(); + let mut blk = cadcraft_doc::Block::new("BG_BLK"); + blk.entities.push(block_entity( + 8001, + Common { layer: "0".into(), ..Default::default() }, + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::new(0.0, 20.0, 0.0), + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "BYBLOCK".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 1, color: Some(Color::ByBlock), scale: 1.5 }), + }), + )); + d.blocks.insert("BG_BLK".into(), std::sync::Arc::new(blk)); + let mut ins = insert_of("BG_BLK"); + if let EntityKind::Insert(ref mut i) = ins { + i.insert = Vec3::new(0.0, 20.0, 0.0); + } + d.add(&Space::Model, Common { color: Color::Index(5), ..Default::default() }, ins).unwrap(); + + let list = build(&d, &Space::Model, &Options::default()); + assert!(list.prims.iter().any(|p| p.kind == Kind::Tris && p.color == Rgb(255, 0, 0)), "ByLayer red background fill"); + assert!(list.prims.iter().any(|p| p.kind == Kind::Tris && p.color == Rgb(0, 0, 255)), "ByBlock blue background fill"); + assert!(list.tris.iter().all(|v| v.x.is_finite() && v.y.is_finite()), "non-finite rotation must yield finite background tris"); + + // Multiline ATTRIB without ATTDEF and with empty props inherits INSERT block_color for ByBlock background mask. + let mut d_attr = Drawing::new_metric(); + d_attr.blocks.insert("EMPTY_BLK".into(), std::sync::Arc::new(cadcraft_doc::Block::new("EMPTY_BLK"))); + let mut ins_attr = insert_of("EMPTY_BLK"); + if let EntityKind::Insert(ref mut i) = ins_attr { + i.attribs.push(cadcraft_doc::Attrib { + tag: "TAG".into(), + text: cadcraft_doc::Text { + insert: Vec3::ZERO, + align_pt: None, + height: 2.0, + value: "ATTR".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: Default::default(), + valign: Default::default(), + backwards: false, + upside_down: false, + }, + multiline: Some(cadcraft_doc::MultilineAttrib { + mtext: cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "ATTR".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 1, color: Some(Color::ByBlock), scale: 1.5 }), + }, + read_as: "ATTR".into(), + }), + invisible: false, + constant: false, + prompt: String::new(), + props: cadcraft_doc::AttribProps::default(), + modes: cadcraft_doc::AttribModes::default(), + }); + } + d_attr.add(&Space::Model, Common { color: Color::Index(3), ..Default::default() }, ins_attr).unwrap(); + let attr_list = build(&d_attr, &Space::Model, &Options::default()); + assert!(attr_list.prims.iter().any(|p| p.kind == Kind::Tris && p.color == Rgb(0, 255, 0)), "Attrib ByBlock green background fill"); + + // MLeader with opts.text == false must not emit MText background mask triangles. + let mut d_ml = Drawing::new_metric(); + d_ml.add( + &Space::Model, + Common::default(), + EntityKind::MLeader(cadcraft_doc::MLeader { + leaders: Vec::new(), + landing: Vec3::ZERO, + dogleg: 1.0, + style: "Standard".into(), + arrow_size: 1.0, + spline: false, + text: Some(cadcraft_doc::MText { + insert: Vec3::new(2.0, 0.0, 0.0), + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "ML".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 3, color: None, scale: 1.5 }), + }), + block: None, + }), + ) + .unwrap(); + let ml_no_text = build(&d_ml, &Space::Model, &Options { text: false, ..Default::default() }); + assert!(!ml_no_text.prims.iter().any(|p| p.kind == Kind::Mask), "MLeader background mask must not draw when opts.text is false"); + + // Unbreakable word overflowing narrow reference width expands background quad beyond reference width. + let mut d_ovf = Drawing::new_metric(); + d_ovf + .add( + &Space::Model, + Common::default(), + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::ZERO, + height: 2.0, + width: 1.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "WWWWWW".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + background: Some(cadcraft_doc::MTextBackground { mask: 3, color: None, scale: 1.5 }), + }), + ) + .unwrap(); + let ovf_list = build(&d_ovf, &Space::Model, &Options::default()); + let min_x = ovf_list.tris.iter().map(|v| v.x).fold(f64::INFINITY, f64::min); + let max_x = ovf_list.tris.iter().map(|v| v.x).fold(f64::NEG_INFINITY, f64::max); + assert!(max_x - min_x > 8.0, "overflowing word background quad width ({}) must cover actual glyph strokes", max_x - min_x); +} + // ---------- point and primitive budgets (#1922, #1603) ---------- fn circle() -> EntityKind { diff --git a/crates/render/src/text_entity.rs b/crates/render/src/text_entity.rs index ec426576b..3178737fd 100644 --- a/crates/render/src/text_entity.rs +++ b/crates/render/src/text_entity.rs @@ -81,13 +81,57 @@ fn mtext_color(c: Option, rgb: Ink) -> Ink { } } -pub(crate) fn mtext(b: &mut Builder, ctx: &Ctx, t: &cadcraft_doc::MText, rgb: Ink, lw: f32) { +pub(crate) fn mtext(b: &mut Builder, ctx: &Ctx, layer: &str, t: &cadcraft_doc::MText, rgb: Ink, lw: f32) { let l = layout_mtext_entity(ctx.d, t); + let layer_name = if layer == "0" { ctx.block_layer.as_deref().unwrap_or("0") } else { layer }; + let layer_color = ctx.layer_color(layer_name).unwrap_or(Color::Index(7)); + if b.opts.fill + && let Some(bg) = &t.background + && (bg.mask & 0x03) != 0 + && let Some([p0, p1, p2, p3]) = mtext_bg_quad(ctx.d, t, &l, bg.scale) + { + let n = b.list.prims.len(); + let use_mask = (bg.mask & 2) != 0 || bg.color.is_none(); + let fill_ink = match bg.color { + Some(c) if !use_mask => ink(c, layer_color, ctx.block_color), + _ => Ink { rgb: Rgb(255, 255, 255), aci7: false, aci: 0 }, + }; + b.tris(ctx, fill_ink, &[p0, p1, p2, p0, p2, p3]); + if use_mask && let Some(p) = b.list.prims.get_mut(n) { + p.kind = super::Kind::Mask; + } + } for p in &l.pieces { b.shaped(ctx, mtext_color(p.color, rgb), lw, &p.shaped); } } +fn mtext_bg_quad(d: &Drawing, t: &cadcraft_doc::MText, l: &cadcraft_fonts::MTextLayout, scale: f64) -> Option<[cadcraft_geom::Vec2; 4]> { + let rot = if t.rotation.is_finite() { t.rotation } else { 0.0 }; + let u_owned; + let u = if rot == 0.0 { + l + } else { + u_owned = layout_mtext_entity(d, &cadcraft_doc::MText { rotation: 0.0, background: None, ..t.clone() }); + &u_owned + }; + let mut bounds = u.bounds; + for q in u.strokes.iter().flatten() { + if q.is_finite() { + bounds.add(*q); + } + } + if !(bounds.width().is_finite() && bounds.height().is_finite()) || bounds.width() <= 0.0 || bounds.height() <= 0.0 { + return None; + } + let gap = (scale - 1.0).clamp(0.0, 4.0) * t.height.max(0.0); + let (lo, hi) = (bounds.min - cadcraft_geom::Vec2::new(gap, gap), bounds.max + cadcraft_geom::Vec2::new(gap, gap)); + let at = t.insert.xy(); + let (x, y) = (cadcraft_geom::Vec2::from_angle(rot), cadcraft_geom::Vec2::from_angle(rot).perp()); + let turn = |p: cadcraft_geom::Vec2| at + x * (p.x - at.x) + y * (p.y - at.y); + Some([turn(lo), turn(cadcraft_geom::Vec2::new(hi.x, lo.y)), turn(hi), turn(cadcraft_geom::Vec2::new(lo.x, hi.y))]) +} + /// A TEXT's justification as the fonts' alignment (used where text is placed outside a build). pub fn text_align(h: cadcraft_doc::HAlign, v: cadcraft_doc::VAlign) -> (cadcraft_fonts::Align, cadcraft_fonts::VAlign) { align(h, v) diff --git a/crates/render/tests/it/dim_text_fill.rs b/crates/render/tests/it/dim_text_fill.rs index 66292d6e4..e13b44e2a 100644 --- a/crates/render/tests/it/dim_text_fill.rs +++ b/crates/render/tests/it/dim_text_fill.rs @@ -149,6 +149,7 @@ fn a_dimension_read_with_its_block_keeps_the_block_and_gets_the_background() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; blk.entities.push(Entity::new(Handle(2), EntityKind::MText(text))); d.blocks.insert("*D1".into(), std::sync::Arc::new(blk)); @@ -181,6 +182,7 @@ fn every_text_of_a_block_gets_a_background() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; blk.entities.push(Entity::new(Handle(i as u64 + 1), EntityKind::MText(text))); } @@ -211,6 +213,7 @@ fn a_block_that_holds_its_background_gets_no_second_one() { line_spacing: 1.0, line_spacing_exact: false, columns: None, + background: None, }; blk.entities.push(Entity::new(Handle(2), EntityKind::MText(text))); d.blocks.insert("*D1".into(), std::sync::Arc::new(blk)); From 0f7940a9865148cd4ee314ff0117cf2a78e1ffed Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:37:27 +0100 Subject: [PATCH 42/43] test: count attribute tag matching work instead of timing it (#3723) --- crates/doc/src/entity/block.rs | 40 ++++++++++ crates/doc/src/tests.rs | 10 ++- crates/engine/src/cmd/blocks/attribs.rs | 75 ++++++++++++++++++- .../engine/tests/it/attribute_tag_matching.rs | 4 +- 4 files changed, 123 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/entity/block.rs b/crates/doc/src/entity/block.rs index 9d41548ea..652e2fb2e 100644 --- a/crates/doc/src/entity/block.rs +++ b/crates/doc/src/entity/block.rs @@ -154,7 +154,43 @@ impl AttribProps { #[derive(Clone, Copy, Debug)] pub struct TagKey<'a>(pub &'a str); +#[cfg(test)] +std::thread_local! { + static TAG_CROSS_PROBE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +fn record_tag_cross_probe(left: &str, right: &str) { + TAG_CROSS_PROBE.with(|probe| { + let Some((position, mut counts)) = probe.get() else { return }; + match (left.as_bytes().get(position), right.as_bytes().get(position)) { + (Some(b'A'), Some(b'D')) => counts[0] += 1, + (Some(b'D'), Some(b'A')) => counts[1] += 1, + _ => return, + } + probe.set(Some((position, counts))); + }); +} + impl TagKey<'_> { + /// Count comparisons in both directions between the A and D fixture tag sets. + #[cfg(test)] + pub(crate) fn with_cross_probes(position: usize, f: impl FnOnce() -> T) -> (T, [usize; 2]) { + struct Restore(Option<(usize, [usize; 2])>); + + impl Drop for Restore { + fn drop(&mut self) { + TAG_CROSS_PROBE.with(|probe| probe.set(self.0)); + } + } + + TAG_CROSS_PROBE.with(|probe| { + let _restore = Restore(probe.replace(Some((position, [0; 2])))); + let value = f(); + (value, probe.get().map_or([0; 2], |(_, counts)| counts)) + }) + } + /// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case` /// finds equal. fn folded(&self) -> impl Iterator + '_ { @@ -164,6 +200,8 @@ impl TagKey<'_> { impl PartialEq for TagKey<'_> { fn eq(&self, other: &Self) -> bool { + #[cfg(test)] + record_tag_cross_probe(self.0, other.0); self.0.eq_ignore_ascii_case(other.0) } } @@ -172,6 +210,8 @@ impl Eq for TagKey<'_> {} impl Ord for TagKey<'_> { fn cmp(&self, other: &Self) -> Ordering { + #[cfg(test)] + record_tag_cross_probe(self.0, other.0); self.folded().cmp(other.folded()) } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index f04c86b00..550059aa2 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -1076,9 +1076,13 @@ fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() { let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") }; ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect(); d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); - let t = std::time::Instant::now(); - assert!(!d.extents(&Space::Model).is_empty()); - assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + let (bounds, cross_probes) = crate::TagKey::with_cross_probes(1000, || d.extents(&Space::Model)); + assert!(!bounds.is_empty()); + // Layer inheritance and the constant-value filter each query the opposite set. + // With no matches, an unindexed scan bypasses the probe (zero) or compares every pair. + for probes in cross_probes { + assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {cross_probes:?}"); + } } /// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N diff --git a/crates/engine/src/cmd/blocks/attribs.rs b/crates/engine/src/cmd/blocks/attribs.rs index b6d6b2d24..ac7cf7868 100644 --- a/crates/engine/src/cmd/blocks/attribs.rs +++ b/crates/engine/src/cmd/blocks/attribs.rs @@ -104,12 +104,17 @@ pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec let m = ins.transform(blk.base.xy()); // The reference's attributes by tag, gathered once for all the definitions (#1923). let carried = ins.attribs_by_tag(); + #[cfg(test)] + let carried = carried.into_iter().map(|(tag, attrib)| (tests::MeasuredTag(tag), attrib)).collect::>(); defs.iter() .map(|ad| { let mut k = EntityKind::Text(ad.text.clone()); k.transform(&m); let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() }; - t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone()); + let key = TagKey(&ad.tag); + #[cfg(test)] + let key = tests::MeasuredTag(key); + t.value = carried.get(&key).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone()); Attrib { tag: ad.tag.clone(), text: t, @@ -359,6 +364,74 @@ impl Interactive for AttsyncM { mod tests { use super::*; + std::thread_local! { + static SYNC_CROSS_PROBES: std::cell::Cell> = const { std::cell::Cell::new(None) }; + } + + /// Use the actual tag ordering and count only probes between different fixture sets. + pub(super) struct MeasuredTag<'a>(pub(super) TagKey<'a>); + + impl MeasuredTag<'_> { + fn record(&self, other: &Self) { + let TagKey(left) = self.0; + let TagKey(right) = other.0; + let sides = (left.as_bytes().first(), right.as_bytes().first()); + if matches!(sides, (Some(b'A'), Some(b'D')) | (Some(b'D'), Some(b'A'))) { + SYNC_CROSS_PROBES.with(|count| count.set(count.get().map(|n| n + 1))); + } + } + } + + impl PartialEq for MeasuredTag<'_> { + fn eq(&self, other: &Self) -> bool { + self.record(other); + self.0 == other.0 + } + } + + impl Eq for MeasuredTag<'_> {} + + impl PartialOrd for MeasuredTag<'_> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } + } + + impl Ord for MeasuredTag<'_> { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.record(other); + self.0.cmp(&other.0) + } + } + + #[test] + fn sync_uses_indexed_cross_set_tag_matching() { + const N: usize = 512; + let mut s = Session::new(); + s.execute("attdef", &json!({"tag":"T", "default":"d", "at":[0, 1], "height":1.0})).unwrap(); + s.execute("line", &json!({"points":[[0, 0], [10, 0]]})).unwrap(); + let ids: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({"name":"B", "base":[0, 0], "keep":"delete", "handles":ids})).unwrap(); + let added = s.execute("insert", &json!({"name":"B", "at":[0, 0], "attribs":{"T":"v"}})).unwrap(); + let handle = Handle::parse_hex(added["handle"].as_str().unwrap()).unwrap(); + let doc = s.doc().unwrap(); + let blk = doc.block("B").unwrap(); + let base = (*attdefs(blk)[0]).clone(); + let EntityKind::Insert(mut ins) = doc.entity(handle).unwrap().kind.clone() else { panic!("insert expected") }; + let value = ins.attribs[0].clone(); + let defs: Vec<_> = (0..N).map(|i| Attrib { tag: format!("D{i:05}"), ..base.clone() }).collect(); + let defs: Vec<_> = defs.iter().collect(); + ins.attribs = (0..N).map(|i| Attrib { tag: format!("A{i:05}"), ..value.clone() }).collect(); + + SYNC_CROSS_PROBES.with(|count| count.set(Some(0))); + let result = synced(blk, &defs, &ins); + let probes = SYNC_CROSS_PROBES.with(|count| count.replace(None).unwrap()); + assert_eq!(result.len(), N); + assert!(result.iter().all(|a| a.text.value == "d")); + // No cross-set comparisons means this lookup was bypassed, whereas a scan does N*N. + assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {probes}"); + } + #[test] fn attdisp_keywords_map_to_attmode() { assert_eq!([attmode("Normal"), attmode("on"), attmode("OFF"), attmode("x")], [Some(1), Some(2), Some(0), None]); diff --git a/crates/engine/tests/it/attribute_tag_matching.rs b/crates/engine/tests/it/attribute_tag_matching.rs index f06cfd2b4..5e69c4a99 100644 --- a/crates/engine/tests/it/attribute_tag_matching.rs +++ b/crates/engine/tests/it/attribute_tag_matching.rs @@ -65,9 +65,9 @@ fn burst_matches_many_attributes_without_comparing_every_pair() { #[test] fn attsync_matches_many_definitions_without_comparing_every_pair() { let (mut s, h) = reference(N); - let t = std::time::Instant::now(); + // The adjacent engine unit test checks exact indexed lookup work; this keeps + // the same end-to-end ATTSYNC fixture and its result checks. s.execute("attsync", &json!({"name": "B"})).unwrap(); - assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); // An attribute for each definition (T and the N others), with its default value: the // reference carried none of their tags. let a = attribs(&s, h); From 5f751ee30d04b1b4857b08344b7bc11372c9fd3b Mon Sep 17 00:00:00 2001 From: code-compliant <8724460+code-compliant@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:34:42 +0800 Subject: [PATCH 43/43] AutoLISP: entnext reaches an INSERT's ATTRIBs and SEQEND (#1660) (#3396) * AutoLISP: entnext reaches an INSERT's ATTRIBs and SEQEND (#1660) - lisp: name an INSERT's ATTRIB and SEQEND records; entnext walks them, then the next main entity, and entget lists a record with its owner in group -2 (#1660) - lisp: entmod of an ATTRIB takes its value (group 1) only, as one undo step; another property, a SEQEND, entdel and entmake of one return nil and change nothing (#1660) - doc: the handles LISP named, shared with the drawing's snapshots and never given out by new_handle; 65,536 names, 1,024 probes past taken handles (#1660) - io: entity_sub_record, one record of an INSERT at a time, never its other records (#1660) - engine: an optional host hook for that record, so EntityCodec is unchanged (#1660) - cli, web, app: install the hook; CLI tests for the walk, the value edit, the name bounds and the refusals (#1660) - docs: autolisp.md on the records, their names, when a name ends, and the value-only edit (#1660) - reused from #1753 (closed), with thanks: the entity_list extraction with the -2 owner, the writer's record splitting, and the entnext_walks_an_inserts_attribs test skeleton * Keep AutoLISP's attribute names within their drawing - Hold an INSERT's attribute names in the session's LISP state, not in cadcraft_doc::Drawing: comparing drawings is plain data again and takes no lock. The session reserves the handles in the drawing before any change, so new_handle still never gives one out, also after a drawing swap. - End the names when the Block Editor closes: its drawing starts from the host's handles, so a name given there must never resolve to a host record. - End only the erased reference's names on ERASE. Erasing another object leaves an attribute name holding, and OOPS still revives none. - Go on to the next entity when an INSERT has no record provider installed. - Refuse an ATTRIB edit whose outer list ends in an atom. * Keep issued attribute names out of the drawing. A copied drawing could reuse a name, and storing the names in the drawing marked a saved drawing changed. * Name an INSERT's ATTRIBs and SEQEND apart from drawing handles An ATTRIB or SEQEND has no handle of its own in the drawing, so the name AutoLISP gives it is now a value of its own (an entity name for `type`), numbered from one count for the whole process that never gives a number twice. No handle of any drawing, of a copy of one, of another session or of another thread can be such a name, so nothing is reserved in the handle space any more: cadcraft-doc, `new_handle` and the copy-then-install paths are as on main, and naming or reading a record changes neither the drawing nor its saved state. What a name stands for (reference, place, tag) stays in the engine's LISP state, by document. Names end on Undo, Redo, ATTSYNC, -BLOCKREPLACE, on opening and closing the Block Editor, and when a change is taken back; erasing a reference ends only its names, and OOPS or `entdel` bringing it back revives none. `entupd` of a record answers its name; selection sets and `command` take no record. Tests cover other sessions, documents and threads giving out handles in a drawing copy, the copy paths (INSERT from a file, XATTACH, AUDIT, REFCLOSE), and the AutoLISP behaviour of the names. * Keep one ATTDEF index per state of a block's entities EntityStore gets a content token: a clone has its store's, and every edit gives the store one that no store has had. The DXF writer keys its ATTDEF index on that token and keeps the indexes of several blocks, up to a fixed number of tags in all. Two copies edited apart, or a different edit after Undo, never read each other's definition properties, in AutoLISP reads or in a saved file, and reads that alternate between references of different blocks examine each definition once. * End record names when a command puts an earlier drawing back. MOCORO Undo restored its history drawing, handle seed included, so the next Copy could reuse the removed reference's handle. That restore now advances the name epoch. An ATTDEF index that would pass the tag budget is not stored. * Match an oversized ATTDEF definition in full and remember it is too large to index * Count record names with try_update, not the deprecated fetch_update Rust 1.100 deprecates fetch_update and names try_update in its place, so clippy with -D warnings stopped the gate at RecordName::fresh. It is the same operation: the checked increment and the None once the count runs out are unchanged. try_update compiles on Rust 1.95, the workspace's minimum. Co-Authored-By: Claude Fable 5.2 * Record tests check the objects they rely on Five tests could pass without the state they are about. The two ATTDEF index tests changed only a layer, so both states of the block gave T the same handle, and an index kept for the wrong state still read the right layer. One state now keeps T on the first ATTDEF and the other passes T to the second, on another layer. With one index shared by every store, the old tests passed and these fail. The MOCORO and grip Copy tests did not check that a copy was made, or that the copy after the Undo took the removed copy's handle. They now check both, and that the name read the first copy before the Undo. The walk at the top of the handle range compared two values that are both nil when the line at FFFFFFFFFFFFFFFF is not in the drawing. It now reads that line first. Co-Authored-By: Claude Fable 5.2 * Test that entdel preserves unrelated ATTRIB names * Fix AutoLISP record lifetime and REFEDIT edits * Run attribute name cases in engine integration suite * Fix text fixtures after main merge --------- Co-authored-by: Claude Fable 5.2 --- apps/cadcraft-cli/src/lib.rs | 2 + apps/cadcraft-cli/tests/it/block_resources.rs | 406 ++++++++++ apps/cadcraft-cli/tests/it/main.rs | 1 + apps/cadcraft-web/src/main.rs | 2 + apps/cadcraft/src/main.rs | 2 + crates/doc/src/store.rs | 75 +- crates/engine/src/blockedit.rs | 6 + crates/engine/src/cmd/audit.rs | 6 +- crates/engine/src/cmd/blocks/attribs.rs | 2 + crates/engine/src/cmd/blocks/blockreplace.rs | 2 + crates/engine/src/cmd/blocks/refedit.rs | 2 +- crates/engine/src/cmd/file.rs | 41 + crates/engine/src/cmd/griphot.rs | 5 +- crates/engine/src/cmd/hatch.rs | 5 +- crates/engine/src/cmd/modify/explode.rs | 5 +- crates/engine/src/cmd/modify/fillet.rs | 5 +- crates/engine/src/cmd/modify/offset.rs | 5 +- crates/engine/src/cmd/modify/oops.rs | 7 + crates/engine/src/cmd/modify2/mocoro.rs | 5 +- crates/engine/src/cmd/modify2/pedit_multi.rs | 3 +- crates/engine/src/cmd/trimextend.rs | 5 +- crates/engine/src/cmd/view.rs | 2 +- crates/engine/src/cmd/view/dview.rs | 2 +- crates/engine/src/doc_state.rs | 26 + crates/engine/src/finite.rs | 2 +- crates/engine/src/lisp.rs | 14 +- crates/engine/src/lisp/drawing.rs | 412 +++++++++- crates/engine/src/lisp/tests.rs | 708 +++++++++++++++++- crates/engine/src/lisp/value.rs | 29 +- crates/engine/src/session/execute.rs | 4 +- crates/engine/src/session/interactive.rs | 4 +- crates/engine/tests/it/attrib_names.rs | 203 +++++ crates/engine/tests/it/lisp_findfile.rs | 5 +- crates/engine/tests/it/main.rs | 4 + crates/io/src/dxf_write.rs | 41 + crates/io/src/dxf_write/common.rs | 144 +++- crates/io/src/dxf_write/entity.rs | 59 +- crates/io/src/lib.rs | 2 +- crates/io/src/tests.rs | 321 ++++++++ docs/autolisp.md | 26 + 40 files changed, 2500 insertions(+), 100 deletions(-) create mode 100644 apps/cadcraft-cli/tests/it/block_resources.rs create mode 100644 crates/engine/tests/it/attrib_names.rs diff --git a/apps/cadcraft-cli/src/lib.rs b/apps/cadcraft-cli/src/lib.rs index fbb4462f6..5993b1e4a 100644 --- a/apps/cadcraft-cli/src/lib.rs +++ b/apps/cadcraft-cli/src/lib.rs @@ -61,6 +61,8 @@ fn install_io() { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups, }); + // ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`. + cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record); // ... and non-graphic objects (tables, dictionaries, layouts) as DXF records. cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records); // What a DXF before 2007 leaves out for its proxies' string streams (#3229). diff --git a/apps/cadcraft-cli/tests/it/block_resources.rs b/apps/cadcraft-cli/tests/it/block_resources.rs new file mode 100644 index 000000000..ac76bba00 --- /dev/null +++ b/apps/cadcraft-cli/tests/it/block_resources.rs @@ -0,0 +1,406 @@ +//! An INSERT's ATTRIBs and SEQEND reached from AutoLISP through the CLI (`entnext`, `entget`, +//! `entmod`, `entdel`): the walk, a value edit (one Undo step), names that stop holding (erase, +//! ATTSYNC, Undo, a reinsert that reuses the parent handle), edits that are refused, and the +//! name bounds. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +use serde_json::{Value, json}; + +/// A scratch directory, removed on drop also when an assertion fails. +struct Dir(PathBuf); + +impl Dir { + fn new(tag: &str) -> Dir { + let p = std::env::temp_dir().join(format!("cc-cli-attribs-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&p); + std::fs::create_dir_all(&p).expect("create scratch dir"); + Dir(p) + } + + fn path(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// One `cadcraft-cli run`: a fresh profile, an optional drawing to open, and the steps to run. +struct Run { + args: Vec, +} + +impl Run { + fn new(dir: &Dir, file: Option<&Path>) -> Run { + let mut args: Vec = vec!["run".into(), "--config-dir".into(), dir.path("profile").to_string_lossy().into_owned()]; + match file { + Some(f) => args.push(f.to_string_lossy().into_owned()), + None => args.push("--metric".into()), + } + Run { args } + } + + fn cmd(&mut self, id: &str, params: Value) -> &mut Run { + self.args.push("--cmd".into()); + self.args.push(format!("{id} {params}")); + self + } + + fn lisp(&mut self, code: &str) -> &mut Run { + self.cmd("lisp", json!({ "code": code })) + } + + fn save(&mut self, path: &Path) -> &mut Run { + self.args.push("--save".into()); + self.args.push(path.to_string_lossy().into_owned()); + self + } + + fn output(&self) -> Output { + Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&self.args).output().expect("run cadcraft-cli") + } + + /// Run it: the value each `lisp` step returned, in order (commands' own results are left out). + fn out(&self) -> Vec { + let out = self.output(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{}: {}", self.args.join(" "), err); + let text = String::from_utf8_lossy(&out.stdout); + text.lines() + .map(|l| serde_json::from_str::(l).unwrap_or_else(|e| panic!("not a result: {l}: {e}"))) + .filter(|v| v.get("value").is_some()) + .collect() + } +} + +/// The value a `lisp` step returned, as AutoLISP's `prin1` shows it. +fn value(results: &[Value], i: usize) -> String { + match results.get(i).and_then(|r| r.get("value")) { + Some(Value::String(s)) => s.clone(), + other => panic!("step {i}: no value: {other:?} in {results:?}"), + } +} + +/// `value` without the quotes `prin1` puts round a string. +fn text(results: &[Value], i: usize) -> String { + value(results, i).trim_matches('"').to_string() +} + +/// TAGBLK.dxf: block TAGBLK with a circle and four attribute definitions (TAG1 D1, TAG2 D2 +/// verify, TAG3 P3 preset, TAG4 C4 constant). Opening the file again gives the drawing fresh +/// names. +const FIXTURE: &str = r#"(progn + (entmake '((0 . "BLOCK") (2 . "TAGBLK") (70 . 2) (10 0.0 0.0 0.0))) + (entmake '((0 . "CIRCLE") (10 -5.0 0.0 0.0) (40 . 2.0))) + (entmake '((0 . "ATTDEF") (10 0.0 0.0 0.0) (40 . 2.5) (1 . "D1") (3 . "P1") (2 . "TAG1") (70 . 0))) + (entmake '((0 . "ATTDEF") (10 0.0 5.0 0.0) (40 . 2.5) (1 . "D2") (3 . "P2") (2 . "TAG2") (70 . 4))) + (entmake '((0 . "ATTDEF") (10 0.0 10.0 0.0) (40 . 2.5) (1 . "P3") (3 . "P3") (2 . "TAG3") (70 . 8))) + (entmake '((0 . "ATTDEF") (10 0.0 15.0 0.0) (40 . 2.5) (1 . "C4") (3 . "P4") (2 . "TAG4") (70 . 2))) + (entmake '((0 . "ENDBLK"))))"#; + +/// The first reference: INSERT TAGBLK at (10,10) with TAG1 "A1", TAG2 verified as "B1" and +/// TAG3 preset ("P3"); TAG4 is constant, so it is not asked. +const INSERT: &str = r#"(command "_.-INSERT" "TAGBLK" '(10 10) 1 1 0 "A1" "B1" "")"#; + +fn fixture(dir: &Dir) -> PathBuf { + let file = dir.path("TAGBLK.dxf"); + let mut run = Run::new(dir, None); + let out = run.lisp(FIXTURE).save(&file).out(); + assert_eq!(text(&out, 0), "TAGBLK"); + file +} + +/// The walk from the entity named `i`: its records' tags and values, then the type of the record +/// that ends the run. +const WALK: &str = r#"(progn + (setq e (entnext i) n 0 ts nil ed nil) + (while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e)))))) + (setq ts (append ts (list (cdr (assoc 2 ed)) (cdr (assoc 1 ed)))) n (1+ n) e (entnext e))) + (list n ts (cdr (assoc 0 ed))))"#; + +#[test] +fn the_walk_reaches_each_attrib_and_ends_at_the_seqend() { + let dir = Dir::new("walk"); + let file = fixture(&dir); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!( + r#"(progn + {INSERT} + (setq i (entlast)) + (setvar "ATTREQ" 0) + (command "_.-INSERT" "TAGBLK" '(60 10) 1 1 0) + (setvar "ATTREQ" 1) + (setq second (entlast)) + "inserted")"# + )) + // Three attributes, then the SEQEND owned by the reference, then the next main entity. + .lisp(&format!( + r#"(progn {WALK} + (list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (equal (entnext e) second) (cdr (assoc 0 (entget (entnext e))))))"# + )) + // The second reference (no attribute answers, ATTREQ 0) took the definitions' values; its + // own run ends at its SEQEND, with nothing drawn after it. + .lisp(&format!( + r#"(progn (setq i second) {WALK} + (list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (entnext e)))"# + )) + .out(); + assert_eq!(text(&out, 0), "inserted"); + assert_eq!(value(&out, 1), "(3 (\"TAG1\" \"A1\" \"TAG2\" \"B1\" \"TAG3\" \"P3\") \"SEQEND\" T T \"INSERT\")"); + // Its record ends with its own SEQEND, and nothing is drawn after the reference. + assert_eq!(value(&out, 2), "(3 (\"TAG1\" \"D1\" \"TAG2\" \"D2\" \"TAG3\" \"P3\") \"SEQEND\" T nil)"); +} + +#[test] +fn a_value_edit_changes_group_one_only_and_is_one_undo_step() { + let dir = Dir::new("value"); + let file = fixture(&dir); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 2 (entget a))) (cdr (assoc 1 (entget a)))))"#)) + .lisp( + r#"(progn + (setq d (entget a) r (entmod (subst (cons 1 "A2") (assoc 1 d) d))) + (list (cdr (assoc 0 r)) (cdr (assoc 1 r)) (cdr (assoc 1 (entget a))) (cdr (assoc 2 (entget a))) + (cdr (assoc 40 (entget a))) (cdr (assoc 8 (entget a))) (equal (cdr (assoc -2 (entget a))) i)))"#, + ) + .cmd("undo", json!({ "count": 1 })) + // The edit is one Undo step: the value is back, and the name given before it holds no + // longer (the drawing it was given in was restored from another state). + .lisp( + r#"(list (entget a) (progn (setq e (entnext (entlast))) + (list (cdr (assoc 2 (entget e))) (cdr (assoc 1 (entget e))))))"#, + ) + .out(); + assert_eq!(value(&out, 0), "(\"TAG1\" \"A1\")"); + assert_eq!(value(&out, 1), "(\"ATTRIB\" \"A2\" \"A2\" \"TAG1\" 2.5 \"0\" T)"); + assert_eq!(value(&out, 2), "(nil (\"TAG1\" \"A1\"))"); + // Redo brings the edit back; the name given before the Undo still names nothing. + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i) d (entget a)) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#)) + .cmd("undo", json!({ "count": 1 })) + .cmd("redo", json!({ "count": 1 })) + .lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))") + .out(); + assert_eq!(value(&out, 1), "(nil \"A2\")"); +} + +#[test] +fn a_name_stops_holding_after_erase_attsync_and_undo() { + let dir = Dir::new("stale"); + let file = fixture(&dir); + let mut run = Run::new(&dir, Some(&file)); + let out = run.lisp(&format!(r#"(progn {INSERT} (setq i (entlast)) (cdr (assoc 5 (entget i))))"#)).out(); + let handle = text(&out, 0); + + // Erased: the reference's records are gone with it, and the name names nothing. + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (cdr (assoc 2 (entget a))))"#)) + .cmd("erase", json!({ "handles": [handle] })) + .lisp("(list (entget a) (entnext a))") + // Undone: the reference is back, but a name given before the Undo does not come back with + // it: a walk gives its records new ones. + .cmd("undo", json!({ "count": 1 })) + .lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))") + // ATTSYNC rebuilds the reference's attributes: the name given before names nothing, and + // the rebuilt attribute keeps the value. + .lisp("(progn (setq b (entnext (entlast))) (cdr (assoc 2 (entget b))))") + .cmd("attsync", json!({ "name": "TAGBLK" })) + .lisp("(list (entget b) (cdr (assoc 1 (entget (entnext (entlast))))))") + .out(); + assert_eq!(value(&out, 0), "\"TAG1\""); + assert_eq!(value(&out, 1), "(nil nil)"); + assert_eq!(value(&out, 2), "(nil \"A1\")"); + assert_eq!(value(&out, 3), "\"TAG1\""); + assert_eq!(value(&out, 4), "(nil \"A1\")"); + + // A reinsert after an Undo takes the parent handle back: the old name must not name its + // attribute. + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 5 (entget i))) (cdr (assoc 2 (entget a)))))"#)) + .cmd("undo", json!({ "count": 1 })) + .lisp(&format!(r#"(progn {INSERT} (list (cdr (assoc 5 (entget (entlast)))) (entget a)))"#)) + .lisp("(list (cdr (assoc 2 (entget (entnext (entlast))))) (cdr (assoc 1 (entget (entnext (entlast))))))") + .out(); + assert_eq!(text(&out, 0), format!("(\"{handle}\" \"TAG1\")")); + // The same handle, and the old name names nothing in the new reference. + assert_eq!(value(&out, 1), format!("(\"{handle}\" nil)")); + assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\")"); +} + +#[test] +fn an_edit_of_anything_but_the_value_is_refused() { + let dir = Dir::new("refused"); + let file = fixture(&dir); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!( + r#"(progn {INSERT} (setq i (entlast) a (entnext i) s (entnext (entnext (entnext a))) p0 (cdr (assoc 10 (entget a)))) "named")"# + )) + .lisp( + r#"(progn + (setq d (entget a)) + (list + (entmod (subst (cons 2 "TAGX") (assoc 2 d) d)) + (entmod (subst (cons 40 9.0) (assoc 40 d) d)) + (entmod (subst (cons 0 "SEQEND") (assoc 0 d) d)) + (entmod (entget s)) + (entmod (subst (cons 410 "Layout2") (assoc 410 d) d)) + (entmod (subst (cons 1 "A2") (assoc 1 d) (subst (cons 410 "Layout2") (assoc 410 d) d))) + (entdel a) (entdel s)))"#, + ) + // Nothing changed: the same tag, value, height and place, and the name still holds. + .lisp( + r#"(progn (setq e (entnext (entlast)) d (entget e)) + (list (cdr (assoc 2 d)) (cdr (assoc 1 d)) (cdr (assoc 40 d)) (equal p0 (cdr (assoc 10 d))) (equal (entget a) d)))"#, + ) + .out(); + assert_eq!(text(&out, 0), "named"); + assert_eq!(value(&out, 1), "(nil nil nil nil nil nil nil nil)"); + assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\" 2.5 T T)"); +} + +/// A minimal drawing: `before` (records written as they are), then an INSERT with `attribs` +/// ATTRIBs (each tag T, value V) and its SEQEND, last in the file. A header `$HANDSEED` is +/// written when `handseed` is given (a hostile file can name any next handle). +fn insert_dxf_seed(attribs: usize, before: &str, handseed: Option<&str>) -> String { + let mut s = String::with_capacity(before.len().saturating_add(attribs.saturating_mul(96))); + if let Some(seed) = handseed { + s.push_str("0\nSECTION\n2\nHEADER\n9\n$HANDSEED\n5\n"); + s.push_str(seed); + s.push('\n'); + s.push_str("0\nENDSEC\n"); + } + s.push_str("0\nSECTION\n2\nENTITIES\n"); + s.push_str(before); + s.push_str("0\nINSERT\n5\n20\n8\n0\n66\n1\n2\nTAGBLK\n10\n0\n20\n0\n30\n0\n"); + for _ in 0..attribs { + s.push_str("0\nATTRIB\n5\n21\n8\n0\n10\n0\n20\n0\n30\n0\n40\n1\n1\nV\n2\nT\n70\n0\n"); + } + s.push_str("0\nSEQEND\n5\n22\n0\nENDSEC\n0\nEOF\n"); + s +} + +fn insert_dxf(attribs: usize, before: &str) -> String { + insert_dxf_seed(attribs, before, None) +} + +/// The number of records a walk from `i` reaches, counting each `entnext`. +const COUNT: &str = r#"(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)"#; + +#[test] +fn a_walk_is_stable_and_its_names_are_no_handles() { + let dir = Dir::new("stable"); + // A file's line one below the top of the handle range: it keeps its handle, and the + // records' names, which are no handles, never name it. + let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n"; + let file = dir.path("hostile.dxf"); + std::fs::write(&file, insert_dxf(2, before)).expect("write the DXF"); + + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp( + r#"(progn + (setq i (handent "20") line (handent "FFFFFFFFFFFFFFFE") a (entnext i) b (entnext i)) + (list (cdr (assoc 5 (entget line))) (equal (handent "FFFFFFFFFFFFFFFE") line) + (not (equal a line)) (cdr (assoc 0 (entget a))) (equal a b) (equal (entnext a) (entnext b))))"#, + ) + .lisp(&format!(r#"(progn (setq i (handent "20")) {COUNT})"#)) + .out(); + assert_eq!(value(&out, 0), "(\"FFFFFFFFFFFFFFFE\" T T \"ATTRIB\" T T)"); + // Two ATTRIBs and the SEQEND, then the line (it sorts last by its handle), then the end. + assert_eq!(value(&out, 1), "4"); +} + +#[test] +fn a_restored_reference_does_not_revive_an_old_name() { + let dir = Dir::new("restored"); + let file = fixture(&dir); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!( + r#"(progn {INSERT} (setq i (entlast) a (entnext i)) + (entdel i) + (setq gone (entget a)) + (entdel i) + (list gone (entget a) (cdr (assoc 1 (entget (entnext i))))))"# + )) + .out(); + assert_eq!(value(&out, 0), "(nil nil \"A1\")", "the reference comes back, the old name does not"); + + // ERASE, then OOPS: the same. The old name never comes back with the reference. + let mut run = Run::new(&dir, Some(&file)); + let handle = text(&run.lisp(&format!(r#"(progn {INSERT} (cdr (assoc 5 (entget (entlast)))))"#)).out(), 0); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(&format!(r#"(progn {INSERT} (setq a (entnext (entlast))) "named")"#)) + .cmd("erase", json!({ "handles": [handle] })) + .cmd("oops", json!({})) + .lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))") + .out(); + assert_eq!(value(&out, 1), "(nil \"A1\")", "OOPS restores the reference, not the old name"); +} + +#[test] +fn a_new_line_is_never_a_record() { + let dir = Dir::new("handseed"); + let file = dir.path("hostile.dxf"); + // A file's $HANDSEED in the reserved band is the file's own handle and is not followed (#913), + // so the line made after the walk gets the drawing's seed. The record's name is no handle: + // the line is the line, and the name still names the attribute. The engine's + // `a_new_object_at_any_handle_is_never_a_record` puts the seed at the top of the range. + std::fs::write(&file, insert_dxf_seed(1, "", Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF"); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(r#"(progn (setq i (handent "20") a (entnext i)) (list (cdr (assoc 0 (entget a))) (cdr (assoc 5 (entget (entlast))))))"#) + .lisp(r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#) + .lisp(r#"(list (cdr (assoc 0 (entget a))) (entdel a))"#) + .out(); + assert_eq!(value(&out, 0), "(\"ATTRIB\" \"20\")"); + assert_eq!(value(&out, 1), "\"100\""); + assert_eq!(value(&out, 2), "(\"ATTRIB\" nil)"); +} + +#[test] +fn lines_at_the_top_of_the_handle_range_walk_as_lines() { + let dir = Dir::new("walkrange"); + let file = dir.path("hostile.dxf"); + let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n\ + 0\nLINE\n5\nFFFFFFFFFFFFFFFF\n8\n0\n10\n0\n20\n0\n30\n0\n11\n6\n21\n6\n31\n0\n"; + std::fs::write(&file, insert_dxf_seed(1, before, Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF"); + let mut run = Run::new(&dir, Some(&file)); + let out = run + .lisp(r#"(progn (setq i (handent "20")) (entnext i))"#) + // The line at the top of the range is in the drawing. Without it, the walk from the line + // below would end in nil, and nil equals the nil `handent` gives for a handle not there. + .lisp(r#"(progn (setq top (handent "FFFFFFFFFFFFFFFF")) (list (cdr (assoc 0 (entget top))) (cdr (assoc 5 (entget top)))))"#) + .lisp(r#"(equal (entnext (handent "FFFFFFFFFFFFFFFE")) top)"#) + .lisp("(entnext top)") + .out(); + assert_eq!(value(&out, 1), "(\"LINE\" \"FFFFFFFFFFFFFFFF\")"); + assert_eq!(value(&out, 2), "T"); + assert_eq!(value(&out, 3), "nil"); +} + +#[test] +fn the_session_names_at_most_65536_records() { + let dir = Dir::new("names"); + let file = dir.path("many.dxf"); + // One more attribute than the limit of names: the walk stops at the limit, and nothing in the + // drawing changed. + std::fs::write(&file, insert_dxf(65_537, "")).expect("write the DXF"); + let mut run = Run::new(&dir, Some(&file)); + let out = run.lisp(&format!("(progn (setq i (entlast)) {COUNT})")).lisp(&format!("(progn (setq i (entlast)) {COUNT})")).out(); + assert_eq!(value(&out, 0), "65536"); + // The names given by the first walk hold: the second walk is the same. + assert_eq!(value(&out, 1), "65536"); +} diff --git a/apps/cadcraft-cli/tests/it/main.rs b/apps/cadcraft-cli/tests/it/main.rs index 0f8a0997a..7b74f031a 100644 --- a/apps/cadcraft-cli/tests/it/main.rs +++ b/apps/cadcraft-cli/tests/it/main.rs @@ -1,3 +1,4 @@ +mod block_resources; mod cli; mod dash_limit_note; mod drafting_spacing; diff --git a/apps/cadcraft-web/src/main.rs b/apps/cadcraft-web/src/main.rs index 14e53285d..9da9817ec 100644 --- a/apps/cadcraft-web/src/main.rs +++ b/apps/cadcraft-web/src/main.rs @@ -136,6 +136,8 @@ mod web { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups, }); + // ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`. + cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record); // ... and non-graphic objects (tables, dictionaries, layouts) as DXF records. cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records); // What a DXF before 2007 leaves out for its proxies' string streams (#3229). diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index be49388a6..61e94954a 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -199,6 +199,8 @@ pub fn install_io() { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups, }); + // ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`. + cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record); // ... and non-graphic objects (tables, dictionaries, layouts) as DXF records. cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records); // What a DXF before 2007 leaves out for its proxies' string streams (#3229). diff --git a/crates/doc/src/store.rs b/crates/doc/src/store.rs index 1b26a0514..558eb06fb 100644 --- a/crates/doc/src/store.rs +++ b/crates/doc/src/store.rs @@ -6,12 +6,19 @@ use std::collections::HashMap; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use crate::{Entity, Handle}; const CHUNK_MAX: usize = 1024; const SHARDS: usize = 64; +/// A content token no store has had: one count for the process (a `u64` does not run out). +fn next_token() -> u64 { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + #[derive(Clone, Debug, Default)] struct Chunk { id: u32, @@ -24,11 +31,19 @@ pub struct EntityStore { shards: Vec>>, len: usize, next_chunk: u32, + /// This state of the entities ([`EntityStore::content_token`]). Not part of [`PartialEq`]. + token: u64, } impl Default for EntityStore { fn default() -> Self { - EntityStore { chunks: Vec::new(), shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(), len: 0, next_chunk: 0 } + EntityStore { + chunks: Vec::new(), + shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(), + len: 0, + next_chunk: 0, + token: next_token(), + } } } @@ -47,6 +62,17 @@ impl EntityStore { pub fn new() -> Self { Self::default() } + /// A number for this state of the entities: a clone has it too, and every edit gives the + /// store a number no store has had, so two stores with one token hold the same entities in + /// the same order. What is derived from the entities (a block's ATTDEFs by tag) can be kept + /// under it. Not part of [`PartialEq`]: equal stores can have different tokens. + pub fn content_token(&self) -> u64 { + self.token + } + /// The entities are about to change: a new token. + fn edited(&mut self) { + self.token = next_token(); + } pub fn len(&self) -> usize { self.len } @@ -101,6 +127,7 @@ impl EntityStore { self.replace(e); return; } + self.edited(); let needs_new = self.chunks.last().is_none_or(|c| c.items.len() >= CHUNK_MAX); if needs_new { let c = self.new_chunk(); @@ -120,6 +147,7 @@ impl EntityStore { self.replace(e); return; } + self.edited(); let needs_new = self.chunks.first().is_none_or(|c| c.items.len() >= CHUNK_MAX); if needs_new { let c = self.new_chunk(); @@ -137,6 +165,7 @@ impl EntityStore { pub fn replace(&mut self, e: Entity) -> bool { let Some(id) = self.chunk_id(e.handle) else { return false }; let Some(pos) = self.chunk_pos(id) else { return false }; + self.edited(); let Some(c) = self.chunks.get_mut(pos) else { return false }; let chunk = Arc::make_mut(c); if let Some(slot) = chunk.items.iter_mut().find(|x| x.handle == e.handle) { @@ -149,6 +178,7 @@ impl EntityStore { pub fn remove(&mut self, h: Handle) -> Option> { let id = self.chunk_id(h)?; let pos = self.chunk_pos(id)?; + self.edited(); let c = self.chunks.get_mut(pos)?; let chunk = Arc::make_mut(c); let i = chunk.items.iter().position(|x| x.handle == h)?; @@ -165,6 +195,7 @@ impl EntityStore { pub fn modify(&mut self, h: Handle, f: F) -> bool { let Some(id) = self.chunk_id(h) else { return false }; let Some(pos) = self.chunk_pos(id) else { return false }; + self.edited(); let Some(c) = self.chunks.get_mut(pos) else { return false }; let chunk = Arc::make_mut(c); match chunk.items.iter_mut().find(|x| x.handle == h) { @@ -219,6 +250,7 @@ impl EntityStore { self.push(Arc::unwrap_or_clone(e)); return false; }; + self.edited(); let Some(c) = self.chunks.get_mut(pos) else { // Unreachable in practice too; never lose the object. self.push(Arc::unwrap_or_clone(e)); @@ -297,6 +329,47 @@ mod tests { Entity::new(Handle(h), EntityKind::Point(Point { p: Vec2::new(h as f64, 0.0).to3(0.0), angle: 0.0 })) } + /// One token per state of the entities: shared by clones, new after every kind of edit, and + /// different for copies edited apart (#1660's ATTDEF index is kept by it). + #[test] + fn a_content_token_names_one_state_of_the_entities() { + let mut a = EntityStore::new(); + for h in 1..=3 { + a.push(ent(h)); + } + assert_eq!(a.clone().content_token(), a.content_token(), "a clone holds the same entities"); + let (mut b, mut c) = (a.clone(), a.clone()); + assert!(b.modify(Handle(1), |e| e.common.layer = "B".into())); + assert!(c.modify(Handle(1), |e| e.common.layer = "C".into())); + assert_ne!(b.content_token(), c.content_token(), "copies edited apart"); + assert_ne!(b.content_token(), a.content_token()); + let edits: [fn(&mut EntityStore); 8] = [ + |s| s.push(ent(9)), + |s| s.push_front(ent(8)), + |s| { + s.replace(ent(2)); + }, + |s| { + s.remove(Handle(3)); + }, + |s| { + s.bring_to_front(Handle(1)); + }, + |s| { + s.send_to_back(Handle(2)); + }, + |s| { + s.move_next_to(Handle(1), Handle(2), true); + }, + |s| s.sort_by_key(|e| std::cmp::Reverse(e.handle.0)), + ]; + for (i, edit) in edits.iter().enumerate() { + let mut s = a.clone(); + edit(&mut s); + assert_ne!(s.content_token(), a.content_token(), "edit {i}"); + } + } + #[test] fn push_get_remove() { let mut s = EntityStore::new(); diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index 8edfee34a..0ce4ca393 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -280,6 +280,9 @@ impl DocState { self.view_history.clear(); self.block_edit = Some(be); self.revision += 1; + // The editor's drawing is another drawing with the host's handles: a name given in the + // host must not resolve in it (BCLOSE ends the editor's names the same way, #1660). + self.expire_names(); } /// Save the Block Editor's objects into the block (BSAVE), or into a new block `as_name` @@ -346,6 +349,9 @@ impl DocState { self.views = host.views; self.view_history = host.view_history; self.revision += 1; + // The editor's drawing shares the host's handles: a name given in it must never resolve + // to a host record (or the other way round) after the drawing comes back. + self.expire_names(); Ok(()) } } diff --git a/crates/engine/src/cmd/audit.rs b/crates/engine/src/cmd/audit.rs index cc3750567..fa959162d 100644 --- a/crates/engine/src/cmd/audit.rs +++ b/crates/engine/src/cmd/audit.rs @@ -117,8 +117,10 @@ fn run_recover(s: &mut Session, p: &Value) -> Result { let st = s.state_mut()?; let report = crate::audit::fix(Arc::make_mut(&mut st.doc)); if report.issues.is_empty() { - // Nothing to fix: the drawing opens unchanged, like OPEN. - st.doc = st.saved.clone(); + // Nothing to fix: the drawing opens unchanged, like OPEN. `fix` may already + // have copied it, so put the saved one back; no record name exists yet. + let saved = st.saved.clone(); + st.restore_drawing(saved); } if copy && !st.is_dirty() { // An unsaved copy (Drawing Recovery): closing it asks to save it under a name. diff --git a/crates/engine/src/cmd/blocks/attribs.rs b/crates/engine/src/cmd/blocks/attribs.rs index ac7cf7868..df9624335 100644 --- a/crates/engine/src/cmd/blocks/attribs.rs +++ b/crates/engine/src/cmd/blocks/attribs.rs @@ -209,6 +209,8 @@ pub(super) fn sync(s: &mut Session, name: &str) -> Result<(String, usize)> { let defs = attdefs(&blk); let d = s.doc_mut()?; let n = update_references(d, &blk.name, |ins| ins.attribs = synced(&blk, &defs, ins)); + // The references have new ATTRIBs: names given to the old ones hold no longer (#1660). + s.state_mut()?.expire_names(); Ok((blk.name.clone(), n)) } diff --git a/crates/engine/src/cmd/blocks/blockreplace.rs b/crates/engine/src/cmd/blocks/blockreplace.rs index f4614cbfb..2b0df7d89 100644 --- a/crates/engine/src/cmd/blocks/blockreplace.rs +++ b/crates/engine/src/cmd/blocks/blockreplace.rs @@ -81,6 +81,8 @@ fn replace(s: &mut Session, old: &str, new: &str, purge: bool) -> Result<(usize, }); let key = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(&old)).cloned(); let purged = purge && !referenced(d, &old) && key.is_some_and(|k| d.blocks.remove(&k).is_some()); + // Replaced references have new ATTRIBs: names given to the old ones hold no longer (#1660). + s.state_mut()?.expire_names(); Ok((n, purged)) } diff --git a/crates/engine/src/cmd/blocks/refedit.rs b/crates/engine/src/cmd/blocks/refedit.rs index 0733270ef..a29340a5e 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -1073,7 +1073,7 @@ pub(crate) fn after_command(s: &mut Session, before: &Arc, id: &str) -> .iter() .any(|store| store.iter().any(|e| !owned.contains(&e.handle) && !st.doc.entity(e.handle).is_some_and(|a| Arc::ptr_eq(a, e)))); if touched { - st.doc = before.clone(); + st.restore_drawing(before.clone()); return Some("Only the working set can be edited during REFEDIT (REFSET adds objects, REFCLOSE ends the edit).".into()); } let seed = before.handseed; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 6dae3281b..212216b97 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -108,6 +108,47 @@ pub fn entity_codec() -> Option<&'static EntityCodec> { CODEC.get() } +/// One record written after an entity's own, at `index` (an INSERT's ATTRIB, then its SEQEND): +/// its type name and the groups of its record, without its `0` group. AutoLISP's `entnext` and +/// `entget` reach an INSERT's attributes through it, one record at a time (the attributes have no +/// handle of their own in the drawing). Installed by the app with the DXF writer, a lower layer; +/// optional, so a host without one simply has no such records ([`EntityCodec`] is unchanged). +pub type EntitySubRecord = fn(&Drawing, &cadcraft_doc::Entity, usize) -> Option<(String, Vec)>; + +static SUB_RECORD: OnceLock = OnceLock::new(); + +// This thread hid the optional provider ([`without_entity_sub_record`], tests only). +#[cfg(test)] +thread_local! { + static SUB_RECORD_HIDDEN: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +pub fn set_entity_sub_record(f: EntitySubRecord) { + let _ = SUB_RECORD.set(f); +} +pub fn entity_sub_record() -> Option { + #[cfg(test)] + if SUB_RECORD_HIDDEN.with(std::cell::Cell::get) { + return None; + } + SUB_RECORD.get().copied() +} + +/// Run `f` as a host that did not install [`EntitySubRecord`]: `entnext` must walk the drawing's +/// entities as it did before the provider existed. Tests only. +#[cfg(test)] +pub(crate) fn without_entity_sub_record(f: impl FnOnce() -> R) -> R { + struct Unhide; + impl Drop for Unhide { + fn drop(&mut self) { + SUB_RECORD_HIDDEN.with(|h| h.set(false)); + } + } + SUB_RECORD_HIDDEN.with(|h| h.set(true)); + let _unhide = Unhide; + f() +} + /// The drawing's non-graphic records as written (tables, BLOCK records, objects): each one's /// type, groups after the type and role (see [`cadcraft_doc::foreign::ForeignKey`]). AutoLISP's /// `namedobjdict`, `tblobjname` and `handent` of non-graphic objects read them (installed by the diff --git a/crates/engine/src/cmd/griphot.rs b/crates/engine/src/cmd/griphot.rs index b56063dbd..852ba1e5a 100644 --- a/crates/engine/src/cmd/griphot.rs +++ b/crates/engine/src/cmd/griphot.rs @@ -276,9 +276,10 @@ impl GripEdit { } "Undo" => match self.undo.pop() { Some(doc) => { - // Settings changed meanwhile stay. + // Settings changed meanwhile stay. The drawing put back is an earlier + // one: names of INSERT records end with it. let header = s.doc()?.header.clone(); - s.state_mut()?.doc = doc; + s.state_mut()?.restore_drawing(doc); s.doc_mut()?.header = header; Ok(Step::Continue) } diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index 9201899e7..43c377d82 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -574,8 +574,9 @@ fn run_boundary(s: &mut Session, p: &Value) -> Result { for q in pts { out.extend(boundary_at(s, q)?.into_iter().map(|h| h.hex())); if out.len() > MAX_BOUNDARY_OUTPUT { - // The refused call leaves no partial result behind. - s.state_mut()?.doc = before; + // The refused call leaves no partial result behind. Handles it gave out can + // be given again, so names of INSERT records end. + s.state_mut()?.restore_drawing(before); return Err(bad("boundary", format!("more than {MAX_BOUNDARY_OUTPUT} boundary polylines in one call; split the work"))); } } diff --git a/crates/engine/src/cmd/modify/explode.rs b/crates/engine/src/cmd/modify/explode.rs index 52858c5eb..9e331af44 100644 --- a/crates/engine/src/cmd/modify/explode.rs +++ b/crates/engine/src/cmd/modify/explode.rs @@ -267,7 +267,7 @@ pub(crate) fn explode_with( // pieces are copies of the block's objects and keep theirs. let own_pieces = !matches!(e.kind, EntityKind::Insert(_)); let d = s.doc_mut()?; - d.remove_entity(*h); + let Some(removed) = d.remove_entity(*h) else { continue }; for mut p in parts { if own_pieces { p.common.xdata.clear(); @@ -278,6 +278,9 @@ pub(crate) fn explode_with( st.push(p); } } + if !own_pieces && let Some(names) = s.record_names() { + names.erased(&removed); + } } s.set_selection(Vec::new()); Ok(out) diff --git a/crates/engine/src/cmd/modify/fillet.rs b/crates/engine/src/cmd/modify/fillet.rs index b0cb32174..ee5fabe77 100644 --- a/crates/engine/src/cmd/modify/fillet.rs +++ b/crates/engine/src/cmd/modify/fillet.rs @@ -328,9 +328,10 @@ impl Interactive for FilletM { Input::Keyword(k) if k == "Undo" => { match self.undo.pop() { Some(doc) => { - // Settings changed meanwhile stay. + // Settings changed meanwhile stay. The drawing put back is an earlier + // one: names of INSERT records end with it. let header = s.doc()?.header.clone(); - s.state_mut()?.doc = doc; + s.state_mut()?.restore_drawing(doc); s.doc_mut()?.header = header; } None => s.echo("Nothing to undo."), diff --git a/crates/engine/src/cmd/modify/offset.rs b/crates/engine/src/cmd/modify/offset.rs index d6bd500a1..492fb0618 100644 --- a/crates/engine/src/cmd/modify/offset.rs +++ b/crates/engine/src/cmd/modify/offset.rs @@ -491,9 +491,10 @@ impl Interactive for OffsetM { (_, Input::Keyword(k)) if k == "Undo" => { match self.undo.pop() { Some((doc, picked)) => { - // Settings changed meanwhile stay. + // Settings changed meanwhile stay. The drawing put back is an earlier + // one: names of INSERT records end with it. let header = s.doc()?.header.clone(); - s.state_mut()?.doc = doc; + s.state_mut()?.restore_drawing(doc); s.doc_mut()?.header = header; self.picked = if self.multiple { picked } else { None }; if self.picked.is_none() { diff --git a/crates/engine/src/cmd/modify/oops.rs b/crates/engine/src/cmd/modify/oops.rs index 6308cc615..0926b099e 100644 --- a/crates/engine/src/cmd/modify/oops.rs +++ b/crates/engine/src/cmd/modify/oops.rs @@ -55,6 +55,13 @@ pub(crate) fn erase_kept(s: &mut Session, hs: &[Handle]) -> Result { // (`refedit::after_command`), so what OOPS had stays. let refused = taken.iter().any(|t| crate::cmd::blocks::refedit::locked(d, t.entity.handle)); if n > 0 && !refused { + // The names of the erased references' records went with them: OOPS bringing them back + // brings none back. Other references' names keep holding (#1660). + if let Some(names) = s.record_names() { + for t in &taken { + names.erased(&t.entity); + } + } s.state_mut()?.erased = Erased(taken); } Ok(n) diff --git a/crates/engine/src/cmd/modify2/mocoro.rs b/crates/engine/src/cmd/modify2/mocoro.rs index 6954919bf..a5e44c458 100644 --- a/crates/engine/src/cmd/modify2/mocoro.rs +++ b/crates/engine/src/cmd/modify2/mocoro.rs @@ -178,9 +178,10 @@ impl MocoroM { fn undo(&mut self, s: &mut Session) -> Result { match self.history.pop() { Some((doc, base)) => { - // Settings changed meanwhile (a transparent command) stay. + // Settings changed meanwhile (a transparent command) stay. The drawing put + // back is an earlier one: names of INSERT records end with it. let header = s.doc()?.header.clone(); - s.state_mut()?.doc = doc; + s.state_mut()?.restore_drawing(doc); if s.doc()?.header != header { s.doc_mut()?.header = header; } diff --git a/crates/engine/src/cmd/modify2/pedit_multi.rs b/crates/engine/src/cmd/modify2/pedit_multi.rs index 7ba2f94d3..773209e86 100644 --- a/crates/engine/src/cmd/modify2/pedit_multi.rs +++ b/crates/engine/src/cmd/modify2/pedit_multi.rs @@ -126,7 +126,8 @@ impl PeditM { "reverse" | "r" => self.apply_all(s, "reverse", &json!({}))?, "undo" | "u" => match self.mundo.pop() { Some((d, multi, morig)) => { - *s.doc_mut()? = d; + // The saved drawing includes its handle seed. + s.state_mut()?.restore_drawing(std::sync::Arc::new(d)); self.multi = multi; self.morig = morig; s.set_selection(self.multi.clone()); diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 24f85503d..30da34b67 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -696,9 +696,10 @@ impl Interactive for TrimM { } "Undo" => match self.undo.pop() { Some(doc) => { - // Settings changed meanwhile stay. + // Settings changed meanwhile stay. The drawing put back is an + // earlier one: names of INSERT records end with it. let header = s.doc()?.header.clone(); - s.state_mut()?.doc = doc; + s.state_mut()?.restore_drawing(doc); s.doc_mut()?.header = header; } None => s.echo("Nothing to undo."), diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 646b1213f..fe6767c1e 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -302,7 +302,7 @@ fn run_view_set(s: &mut Session, p: &Value) -> Result { None => 0.0, }; if !s.state_mut()?.set_view(View { center: c, height: h, twist }) { - s.state_mut()?.doc = before.0; + s.state_mut()?.restore_drawing(before.0); return Err(bad("view.set", "the view is too large to show. Nothing was changed")); } if let Some(dview::Target::Viewport(h)) = target { diff --git a/crates/engine/src/cmd/view/dview.rs b/crates/engine/src/cmd/view/dview.rs index 3133fd6fa..58ddd8a7d 100644 --- a/crates/engine/src/cmd/view/dview.rs +++ b/crates/engine/src/cmd/view/dview.rs @@ -237,7 +237,7 @@ impl DviewM { set_twist(s, t, twist)?; } if !s.state_mut()?.set_view(View { twist, ..v }) { - s.state_mut()?.doc = before; + s.state_mut()?.restore_drawing(before); return Err(EngineError::Other("The view is too large to show.".into())); } Ok(()) diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 5c67ad89b..df68f6b77 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -28,6 +28,13 @@ pub struct DocState { pub title: String, pub saved: Arc, pub revision: u64, + /// How many times the names AutoLISP gave this drawing's INSERTs' ATTRIBs and SEQENDs ended all + /// at once (#1660): another state of the drawing was shown (Undo, Redo, opening or closing the + /// Block Editor, a change taken back, or a command putting an earlier drawing back through + /// [`DocState::restore_drawing`]), or attribute sets were rebuilt in place (ATTSYNC, + /// -BLOCKREPLACE). A name given before names nothing after one of these, never another + /// record. + pub(crate) names_epoch: u64, pub space: Space, /// Tiled model viewports (VPORTS). pub tiles: ModelTiles, @@ -71,6 +78,7 @@ impl DocState { path, title: title.into(), revision: 1, + names_epoch: 0, space: Space::Model, tiles: ModelTiles::default(), mspace: None, @@ -97,8 +105,26 @@ impl DocState { self.follow_layout(&cur.doc); self.reconcile_untiled_twist(); self.revision += 1; + self.expire_names(); cur } + /// Names given to records without handles (an INSERT's ATTRIBs and SEQEND) stop holding: the + /// records of the drawing they were given for may be gone or replaced. They are never given + /// to another record, so a routine's stale name names nothing (`nil`) rather than something + /// else. + pub(crate) fn expire_names(&mut self) { + self.names_epoch = self.names_epoch.wrapping_add(1); + } + /// Show `doc` again. It is a drawing this document already showed, so its handle seed can + /// give the next object a handle a removed one had. Names of INSERT records end, as they do + /// for Undo. The same drawing already on show is left as it is: nothing was given out again. + pub(crate) fn restore_drawing(&mut self, doc: Arc) { + if Arc::ptr_eq(&self.doc, &doc) { + return; + } + self.doc = doc; + self.expire_names(); + } /// After undo/redo replaced the drawing (`before` is the one shown until then): if the current /// layout no longer exists, follow it to its other name when it was renamed (same tab order, /// a name `before` did not have), else go to the Model tab. diff --git a/crates/engine/src/finite.rs b/crates/engine/src/finite.rs index cc81b5e50..a46009dc3 100644 --- a/crates/engine/src/finite.rs +++ b/crates/engine/src/finite.rs @@ -26,7 +26,7 @@ impl Session { }; let Some(st) = st.filter(|st| !Arc::ptr_eq(before, &st.doc)) else { return Ok(()) }; let Some(h) = first_non_finite(before, &st.doc) else { return Ok(()) }; - st.doc = before.clone(); + st.restore_drawing(before.clone()); st.selection = selection.to_vec(); Err(EngineError::BadParams { cmd: cmd.into(), diff --git a/crates/engine/src/lisp.rs b/crates/engine/src/lisp.rs index 7ad3b6a96..c42450ef3 100644 --- a/crates/engine/src/lisp.rs +++ b/crates/engine/src/lisp.rs @@ -126,6 +126,11 @@ impl Env { #[derive(Default)] pub struct LispState { envs: HashMap, + /// The names given to records without a handle of their own (an INSERT's ATTRIBs and SEQEND, + /// #1660), by drawing. They are the session's, not a snapshot's, so the drawing's undo states + /// and the Block Editor's drawing share them; each use checks what a name stands for against + /// the drawing. + pub(crate) records: HashMap, run: Option>, /// A routine runs, from its start to its end (also while its machine is out of `run`). active: bool, @@ -251,6 +256,13 @@ impl Session { pub(crate) fn lisp_forget_closed(&mut self) { let docs = &self.docs; self.lisp.envs.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid)); + self.lisp.records.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid)); + } + + /// The active drawing's names of an INSERT's records (#1660), made on first use. + pub(crate) fn record_names(&mut self) -> Option<&mut drawing::RecordNames> { + let uid = self.state().ok()?.uid; + Some(self.lisp.records.entry(uid).or_default()) } /// A routine is running (possibly waiting for input). @@ -432,7 +444,7 @@ impl Session { if let Some((doc, sel)) = self.lisp.steps.base.as_ref().or(run.before.as_ref()) && let Some(st) = self.docs.iter_mut().find(|d| d.uid == run.uid) { - st.doc = doc.clone(); + st.restore_drawing(doc.clone()); st.selection = sel.clone(); } run.handler = true; diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index d6caf844a..ff56ca9de 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -21,7 +21,7 @@ use craft_dxf::Tag; use super::builtins::args_err; use super::eval::{Ctx, Flow, Need}; -use super::value::{PickSet, Value, to_text}; +use super::value::{PickSet, RecordName, Value, equal, to_text}; use super::{BlockSlots, LispError}; use crate::{Input, Session}; @@ -119,6 +119,8 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec) -> Result { } } Value::Ename(h) => named(ctx.s, *h, None), + // An INSERT's record (#1660) is no object of the drawing: it picks nothing. + Value::Record(_) => feed(ctx.s, Input::Pick(Vec::new())), Value::PickSet(p) => feed(ctx.s, Input::Pick(items(p))), Value::Cons(_) => { if let Some(p) = arg.as_point() { @@ -326,8 +328,8 @@ pub(super) fn groups_to_list(tags: &[Tag]) -> Vec { const MAX_GROUP_TEXT: usize = 32 << 20; /// An association list back to DXF groups (points split into x, y, z groups). The type -/// (`0`), the entity name (`-1`), the handle (`5`), the owner (`330`) and the layout (`410`) are -/// left out: they aren't the entity's to set. +/// (`0`), the entity name (`-1`), the owner of a record (`-2`) and of the entity (`330`), the +/// handle (`5`) and the layout (`410`) are left out: they aren't the entity's to set. fn list_to_groups(list: &Value) -> Result<(String, Vec), LispError> { let mut kind = None; let mut tags = Vec::new(); @@ -343,7 +345,7 @@ fn list_to_groups(list: &Value) -> Result<(String, Vec), LispError> { other => return Err(LispError::bad_arg("stringp", other)), }) } - -1 | -3 | 5 | 330 | 360 | 410 | 102 => {} + -1 | -2 | -3 | 5 | 330 | 360 | 410 | 102 => {} _ if point_group(code) && matches!(v, Value::Cons(_)) => { let p = v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &v))?; tags.push(Tag::f(code, p[0])); @@ -374,8 +376,310 @@ fn space_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option { d.space_of(h) } +// ---------------- an INSERT's ATTRIBs and SEQEND ---------------- + +/// The most names one drawing's LISP holds for an INSERT's records at once: a routine can't fill +/// memory by walking. At the limit `entnext` gives no *new* name (`nil`) until names end (an +/// erased reference, Undo, ATTSYNC) and make room; the names already given still hold. +const MAX_RECORD_NAMES: usize = 65_536; + +/// What a name given to an INSERT's ATTRIB or SEQEND stands for, while it holds. +struct Record { + owner: Handle, + /// The record's place after the INSERT's own: an ATTRIB's index, or `attribs.len()` for the + /// SEQEND. + slot: usize, + /// The ATTRIB's tag, which can be empty. A SEQEND has no tag. + tag: Option, +} + +impl Record { + /// Whether the reference still has the same kind of record in this slot, with the same tag. + fn holds(&self, attribs: &[cadcraft_doc::Attrib]) -> bool { + match (attribs.get(self.slot), self.tag.as_deref()) { + (Some(a), Some(tag)) => a.tag.eq_ignore_ascii_case(tag), + (None, None) => self.slot == attribs.len(), + _ => false, + } + } +} + +/// The names a drawing's LISP gave to INSERTs' ATTRIBs and SEQENDs (#1660). These records have no +/// handle of their own in the drawing, and their names are not handles ([`RecordName`]): nothing +/// a drawing, a copy of it or another session gives out can ever be one. A name holds while its +/// reference keeps the record in that place with that tag, in the drawing's name epoch it was +/// given in (`DocState::expire_names`); otherwise it names nothing (`nil`), never another record. +#[derive(Default)] +pub(crate) struct RecordNames { + /// Names by INSERT and then by slot. Removing an INSERT ends all its names, even after a + /// change to the length of its attribute run. + by_owner: HashMap>, + /// What each name that still holds stands for, by its number. + by_name: HashMap, + /// The drawing's name epoch the names were given in. + epoch: u64, +} + +impl RecordNames { + /// Forget every name once the drawing's name epoch moved on: the records they named may be + /// gone or rebuilt. + fn expire(&mut self, epoch: u64) { + if self.epoch != epoch { + self.by_owner.clear(); + self.by_name.clear(); + self.epoch = epoch; + } + } + + /// Drop the name numbered `id`: it names nothing from now on. + fn retire(&mut self, id: u64) { + if let Some(r) = self.by_name.remove(&id) + && let Some(slots) = self.by_owner.get_mut(&r.owner) + && slots.get(&r.slot).is_some_and(|n| n.id == id) + { + slots.remove(&r.slot); + if slots.is_empty() { + self.by_owner.remove(&r.owner); + } + } + } + + /// End the names of the removed reference. Restoring it does not revive any of its names. + pub(crate) fn erased(&mut self, e: &Entity) { + if let Some(slots) = self.by_owner.remove(&e.handle) { + for n in slots.into_values() { + self.by_name.remove(&n.id); + } + } + } + + /// How many names hold now (tests). + #[cfg(test)] + pub(crate) fn count(&self) -> usize { + self.by_name.len() + } + + /// The INSERT and place `name` stands for in `d` now. A name that no longer holds is dropped: + /// it names nothing from then on, also if its record comes back. + fn lookup(&mut self, epoch: u64, d: &cadcraft_doc::Drawing, name: RecordName) -> Option<(Handle, usize)> { + self.expire(epoch); + let r = self.by_name.get(&name.id)?; + let at = insert_attribs(d, r.owner).filter(|attribs| r.holds(attribs)).map(|_| (r.owner, r.slot)); + if at.is_none() { + self.retire(name.id); + } + at + } + + /// The name of record `slot` after INSERT `owner`'s own (its attributes, then its SEQEND), + /// given now if it has none that holds: the same one while the record holds, so a repeated + /// walk is stable. None past the SEQEND, at the limit of names, or when the numbers run out. + fn name(&mut self, epoch: u64, attribs: &[cadcraft_doc::Attrib], owner: Handle, slot: usize) -> Option { + self.expire(epoch); + if let Some(n) = self.by_owner.get(&owner).and_then(|slots| slots.get(&slot)).copied() { + if self.by_name.get(&n.id).is_some_and(|r| r.holds(attribs)) { + return Some(n); + } + self.retire(n.id); + } + let tag = match attribs.get(slot) { + Some(a) => Some(a.tag.clone()), + None if slot == attribs.len() => None, + None => return None, + }; + if self.by_name.len() >= MAX_RECORD_NAMES { + return None; + } + let name = RecordName::fresh(owner)?; + self.by_owner.entry(owner).or_default().insert(slot, name); + self.by_name.insert(name.id, Record { owner, slot, tag }); + Some(name) + } +} + +/// The attributes of the block reference `h` in `d` (none for anything else, and for a reference +/// with no attributes: an empty run of records is not written). +fn insert_attribs(d: &cadcraft_doc::Drawing, h: Handle) -> Option<&[cadcraft_doc::Attrib]> { + match d.entity(h).map(|e| &e.kind) { + Some(cadcraft_doc::EntityKind::Insert(i)) if !i.attribs.is_empty() => Some(&i.attribs), + _ => None, + } +} + +/// The drawing and its name epoch, without holding a borrow of the session. +fn doc_and_epoch(ctx: &Ctx<'_>) -> Option<(Arc, u64)> { + let st = ctx.s.state().ok()?; + Some((st.doc.clone(), st.names_epoch)) +} + +/// The INSERT and record the name `name` stands for now (none when it no longer holds). +fn record_of(ctx: &mut Ctx<'_>, name: RecordName) -> Option<(Handle, usize)> { + let (d, epoch) = doc_and_epoch(ctx)?; + ctx.s.record_names()?.lookup(epoch, &d, name) +} + +/// The name of record `slot` after INSERT `owner`'s own (#1660): an ATTRIB, or its SEQEND (one +/// past the last attribute). None when it has no such record, when the host has no record +/// mapping, or when no name is left to give. +fn name_record(ctx: &mut Ctx<'_>, owner: Handle, slot: usize) -> Option { + crate::cmd::file::entity_sub_record()?; + let (d, epoch) = doc_and_epoch(ctx)?; + let attribs = insert_attribs(&d, owner)?; + ctx.s.record_names()?.name(epoch, attribs, owner, slot) +} + +/// An entity list: `head` (its name, type and, for an INSERT's record, its owner), then the +/// groups of its record with the layout name after the AcDbEntity marker, as AutoCAD lists it. +/// The layout is the one object `at` is in; without a layout of its own (an entity of a block +/// definition) it has none. +fn entity_list(d: &cadcraft_doc::Drawing, mut items: Vec, at: Handle, tags: &[Tag], in_block: bool) -> Value { + let layout = match space_of(d, at) { + Some(Space::Paper(name)) => name, + _ => "Model".into(), + }; + let mut placed_layout = in_block; + for v in groups_to_list(tags) { + // The layout name follows the AcDbEntity marker, as AutoCAD lists it. + let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity"); + items.push(v); + if after_marker { + items.push(Value::cons(Value::Int(410), Value::str(&layout))); + placed_layout = true; + } + } + Value::list(items) +} + +/// The list of record `slot` of the reference `owner` named `name`: the DXF writer's record, +/// its name (`-1`), type (`0`) and reference (`-2`). None when the host has no record mapping. +fn record_list(d: &cadcraft_doc::Drawing, name: RecordName, owner: Handle, slot: usize) -> Option<(Value, Vec)> { + let e = d.entity(owner)?; + let (kind, mut tags) = (crate::cmd::file::entity_sub_record()?)(d, e, slot)?; + convert_angles(&kind, &mut tags, f64::to_radians); + let head = vec![ + Value::cons(Value::Int(-1), Value::Record(name)), + Value::cons(Value::Int(0), Value::str(&kind)), + Value::cons(Value::Int(-2), Value::Ename(owner)), + ]; + Some((entity_list(d, head, owner, &tags, false), tags)) +} + +/// `entget` of an INSERT's ATTRIB or SEQEND (#1660), while `name` names one. +fn record_entget(ctx: &mut Ctx<'_>, name: RecordName) -> Option { + let (owner, slot) = record_of(ctx, name)?; + let d = ctx.s.doc().ok()?; + record_list(d, name, owner, slot).map(|(list, _)| list) +} + +/// What an ATTRIB's submitted list asks to change: `Some(None)` when it asks for nothing, and +/// `Some(Some(value))` for its value (group 1). `None` when it asks for any other edit: a group +/// added, dropped, moved or changed other than the attribute's own value. +fn value_edit(now: &[Tag], asked: &[Tag]) -> Option> { + if now.len() != asked.len() { + return None; + } + let mut value = None; + let mut seen = false; + for (n, a) in now.iter().zip(asked) { + if n.code != a.code { + return None; + } + if n.code == 1 { + // A multiline attribute's embedded text has a group 1 of its own, after its marker + // (101): only the attribute's value, before it, may differ. + match (&n.value, &a.value) { + (craft_dxf::Value::Str(old), craft_dxf::Value::Str(new)) if !seen => { + seen = true; + if old != new { + value = Some(new.clone()); + } + } + _ if n == a => {} + _ => return None, + } + } else if n != a { + return None; + } + } + Some(value) +} + +/// The submitted list has the items `entget` would return, in order, except at group 1 (the +/// value): `value_edit` checks which group 1 may differ. Every other group, including the ones +/// an entity cannot set (`-2`, `5`, `330`, `360`, `410`, `102`), must be the same. +fn only_value_diff(expected: &Value, asked: &Value) -> bool { + let (mut expected, mut asked) = (expected.iter(), asked.iter()); + loop { + match (expected.next(), asked.next()) { + (None, None) => return true, + (Some(x), Some(y)) => { + let code = x.car().as_number(); + if code != y.car().as_number() { + return false; + } + if code != Some(1.0) && !equal(&x, &y, 0.0) { + return false; + } + } + _ => return false, + } + } +} + +/// `entmod` of the INSERT's record `name` stands for (#1660): only an ATTRIB's value may change, +/// the group 1 value; its tag, place, flags and properties are the reference's. A SEQEND holds +/// nothing to change, and a name that no longer holds names nothing: both give `nil`, the drawing +/// as it is. +fn entmod_attrib(ctx: &mut Ctx<'_>, list: &Value, name: RecordName) -> Value { + let Some((owner, slot)) = record_of(ctx, name) else { return Value::Nil }; + // An outer list with an atom tail is not the list `entget` returned: iterating it would drop + // the tail and accept the malformed list. The group pairs inside are dotted, as DXF has them. + if !list.is_list() { + return Value::Nil; + } + let Ok((kind, asked)) = list_to_groups(list) else { return Value::Nil }; + if !kind.eq_ignore_ascii_case("ATTRIB") { + return Value::Nil; + } + let Ok(d) = ctx.s.doc() else { return Value::Nil }; + if crate::cmd::blocks::refedit::locked(d, owner) { + return Value::Nil; + } + let Some((expected, now)) = record_list(d, name, owner, slot) else { return Value::Nil }; + // The type, layout, owner, handle and any other group are not the attribute's to change: a + // list that differs from `entget` anywhere but its group 1 value is refused (a SEQEND's + // list too), the drawing untouched. + if !only_value_diff(&expected, list) { + return Value::Nil; + } + match value_edit(&now, &asked) { + None => Value::Nil, + Some(None) => list.clone(), + Some(Some(value)) => { + let ok = ctx.s.doc_mut().is_ok_and(|d| { + d.modify_entity(owner, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind + && let Some(a) = i.attribs.get_mut(slot) + { + a.text.value = value.clone(); + } + }) + .is_ok() + }); + if ok { + ctx.s.touch(); + } + if ok { list.clone() } else { Value::Nil } + } + } +} + pub fn entget(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 2)?; + // An INSERT's ATTRIB or SEQEND (#1660) is not an entity of the drawing: its name reaches it. + if let Value::Record(r) = &a[0] { + return Ok(Flow::Value(record_entget(ctx, *r).unwrap_or_default())); + } let h = ename(&a[0])?; // The applications whose xdata to list: names or wildcard patterns ("*": every application). let apps: Option> = match a.get(1) { @@ -396,21 +700,8 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec) -> Result { let (kind, mut tags) = (codec()?.groups)(d, e); let xdata = apps.map(|apps| xdata_to_list(&e.common.xdata, &apps)).filter(|v| !v.is_nil()); convert_angles(&kind, &mut tags, f64::to_radians); - let layout = match space_of(d, h) { - Some(Space::Paper(name)) => name, - _ => "Model".into(), - }; - let mut items = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))]; - let mut placed_layout = in_block; - for v in groups_to_list(&tags) { - // The layout name follows the AcDbEntity marker, as AutoCAD lists it. - let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity"); - items.push(v); - if after_marker { - items.push(Value::cons(Value::Int(410), Value::str(&layout))); - placed_layout = true; - } - } + let head = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))]; + let mut items = entity_list(d, head, h, &tags, in_block).to_vec(); if let Some(x) = xdata { items.push(Value::cons(Value::Int(-3), x)); } @@ -698,7 +989,12 @@ fn end_block(ctx: &mut Ctx<'_>) -> Value { pub fn entmod(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 1)?; let list = &a[0]; - let Some(Value::Ename(h)) = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr()) else { + let name = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr()); + // An INSERT's record takes a value edit only (#1660); any other edit of one is refused. + if let Some(Value::Record(r)) = name { + return Ok(Flow::Value(entmod_attrib(ctx, list, r))); + } + let Some(Value::Ename(h)) = name else { return Err(LispError::bad_arg("lentityp", &Value::Nil)); }; let Some(old) = ctx.s.doc().ok().and_then(|d| d.entity(h)).cloned() else { return Ok(Flow::Value(Value::Nil)) }; @@ -742,9 +1038,15 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec) -> Result { Ok(Flow::Value(if ok { list.clone() } else { Value::Nil })) } -/// `(entupd ename)`: redraw an entity (the canvas redraws on its own). +/// `(entupd ename)`: redraw an entity (the canvas redraws on its own). For an INSERT's record +/// (#1660) its reference: the record's name while it holds. pub fn entupd(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 1)?; + if let Value::Record(r) = &a[0] { + let holds = record_of(ctx, *r).is_some(); + ctx.s.touch(); + return Ok(Flow::Value(if holds { a[0].clone() } else { Value::Nil })); + } let h = ename(&a[0])?; ctx.s.touch(); Ok(Flow::Value(if ctx.s.doc().is_ok_and(|d| d.entity(h).is_some()) { Value::Ename(h) } else { Value::Nil })) @@ -753,10 +1055,18 @@ pub fn entupd(ctx: &mut Ctx<'_>, a: Vec) -> Result { /// `(entdel ename)`: delete an entity, or bring back one this routine's drawing deleted. pub fn entdel(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 1)?; + // An INSERT's ATTRIB or SEQEND is the reference's: it is not deleted on its own (#1660). + if matches!(a[0], Value::Record(_)) { + return Ok(Flow::Value(Value::Nil)); + } let h = ename(&a[0])?; let Ok(d) = ctx.s.doc_mut() else { return Ok(Flow::Value(Value::Nil)) }; if let Some(space) = d.space_of(h) { if let Some(e) = d.remove_entity(h) { + // The names of its records went with it: `entdel` bringing it back brings none back. + if let Some(names) = ctx.s.record_names() { + names.erased(&e); + } ctx.env.deleted.insert(h, (space, e)); ctx.s.touch(); return Ok(Flow::Value(Value::Ename(h))); @@ -852,24 +1162,41 @@ pub fn entlast(ctx: &mut Ctx<'_>, a: Vec) -> Result { pub fn entnext(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 0, 1)?; - // From an entity of a block definition: the next one in that block, nil after the last (#1700). - if let Some(v) = a.first().filter(|v| !v.is_nil()) { - let h = ename(v)?; - if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none()) - && let Some((_, next)) = block_slots(ctx).get(&h) - { - return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default())); + let after = match a.first() { + None | Some(Value::Nil) => None, + // From a record of an INSERT (#1660): the next record of its run, and after its SEQEND the + // next main entity after the INSERT. A name that no longer holds names nothing. + Some(Value::Record(r)) => { + let Some((owner, slot)) = record_of(ctx, *r) else { return Ok(Flow::Value(Value::Nil)) }; + let attribs = ctx.s.doc().ok().and_then(|d| insert_attribs(d, owner)).map_or(0, <[cadcraft_doc::Attrib]>::len); + if slot < attribs { + return Ok(Flow::Value(name_record(ctx, owner, slot.saturating_add(1)).map(Value::Record).unwrap_or_default())); + } + Some(owner) } - } - let order = handles_in_order(ctx); - let next = match a.first() { - None | Some(Value::Nil) => order.first().copied(), Some(v) => { let h = ename(v)?; - let i = order.partition_point(|x| *x <= h); - order.get(i).copied() + // From an entity of a block definition: the next one in that block, nil after the last (#1700). + if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none()) + && let Some((_, next)) = block_slots(ctx).get(&h) + { + return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default())); + } + // An INSERT with attributes is followed by its ATTRIBs and its SEQEND (#1660): its + // first ATTRIB, or nil when no name is left to give (the walk stops rather than skip + // records it can't name). A host without the optional record mapping has no such + // records: the walk goes on to the next entity, as it always did. + if crate::cmd::file::entity_sub_record().is_some() && ctx.s.doc().is_ok_and(|d| insert_attribs(d, h).is_some()) { + return Ok(Flow::Value(name_record(ctx, h, 0).map(Value::Record).unwrap_or_default())); + } + Some(h) } }; + let order = handles_in_order(ctx); + let next = match after { + Some(h) => order.get(order.partition_point(|x| *x <= h)).copied(), + None => order.first().copied(), + }; Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default())) } @@ -1151,6 +1478,13 @@ fn compare(h: f64, w: f64, op: &str) -> bool { pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 0, 2)?; + // A selection set holds objects of the drawing; an INSERT's record (#1660) is not one. + if matches!(a.first(), Some(Value::Record(_))) { + if let Some(ss) = a.get(1) { + pickset(ss)?; + } + return Ok(Flow::Value(Value::Nil)); + } match (a.first(), a.get(1)) { (None, _) => Ok(Flow::Value(new_pickset(ctx, Vec::new()))), (Some(e), None) => { @@ -1172,6 +1506,11 @@ pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec) -> Result { pub fn ssdel(_ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 2, 2)?; + // Never in a selection set (#1660). + if matches!(a[0], Value::Record(_)) { + pickset(&a[1])?; + return Ok(Flow::Value(Value::Nil)); + } let h = ename(&a[0])?; let p = pickset(&a[1])?; let removed = p.items.lock().map(|mut v| { @@ -1199,6 +1538,11 @@ pub fn ssname(_ctx: &mut Ctx<'_>, a: Vec) -> Result { pub fn ssmemb(_ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 2, 2)?; + // Never in a selection set (#1660). + if matches!(a[0], Value::Record(_)) { + pickset(&a[1])?; + return Ok(Flow::Value(Value::Nil)); + } let h = ename(&a[0])?; Ok(Flow::Value(if items(&pickset(&a[1])?).contains(&h) { Value::Ename(h) } else { Value::Nil })) } diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index 5bb4225bd..26eac62b6 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -1,11 +1,16 @@ #![allow(clippy::unwrap_used)] +use cadcraft_doc::Handle; +use serde_json::json; + use super::value::{Value, to_text}; use crate::Session; -use crate::cmd::file::{EntityCodec, set_entity_codec, set_object_records}; +use crate::cmd::file::{EntityCodec, set_entity_codec, set_entity_sub_record, set_object_records}; pub(super) fn session() -> Session { set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups }); + // ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`. + set_entity_sub_record(cadcraft_io::entity_sub_record); // ... and non-graphic objects (tables, dictionaries, layouts) as DXF records. set_object_records(cadcraft_io::object_records); Session::new() @@ -1966,3 +1971,704 @@ fn append_checks_the_cell_cap_before_building_its_result() { assert!(super::value::live_cells() < before + 50_000, "no oversized result was built"); assert_eq!(ok(&mut s, "(setq l nil m nil) (length (append '(1) '(2 3)))"), "3"); } + +// ---------------- an INSERT's ATTRIBs and SEQEND (#1660) ---------------- + +/// A session with block K: a circle and attributes (tag, DXF flags, default value). `entmake` +/// goes through the DXF codec, as in the app. +fn with_attributes(defs: &[(&str, i32, &str)]) -> Session { + let mut s = session(); + let mut code = + String::from("(entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 3.0)))"); + for (i, (tag, flags, default)) in defs.iter().enumerate() { + let y = 5.0 + 3.0 * i as f64; + code += &format!( + " (entmake '((0 . \"ATTDEF\") (10 0.0 {y:.1} 0.0) (40 . 2.5) (1 . \"{default}\") (3 . \"P{tag}\") (2 . \"{tag}\") (70 . {flags})))" + ); + } + code += " (entmake '((0 . \"ENDBLK\")))"; + s.cmdline(&format!("(progn {code})")).unwrap(); + s.log.clear(); + s +} + +/// `s` with one reference of K at (10,10), its values `attribs`, and the reference's handle; the +/// LISP global `i` names it. +fn inserted(s: &mut Session, attribs: serde_json::Value) -> Handle { + s.execute("insert", &json!({ "name": "K", "at": [10, 10], "attribs": attribs })).unwrap(); + let h = *s.doc().unwrap().model.handles().last().unwrap(); + ok(s, &format!("(setq i (handent \"{}\")) i", h.hex())); + h +} + +/// Every reference's attributes (tag, value) from the model, in order. +fn attribute_values(s: &Session) -> Vec<(String, String)> { + let d = s.doc().unwrap(); + d.model + .iter() + .filter_map(|e| match &e.kind { + cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect::>()), + _ => None, + }) + .flatten() + .collect() +} + +/// The records from `i` in order: (type, tag, value) and the SEQEND's owner. +const WALK: &str = r#"(progn + (setq e (entnext i) out nil) + (while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e)))))) + (setq out (append out (list (list (cdr (assoc 0 ed)) (cdr (assoc 2 ed)) (cdr (assoc 1 ed)) + (if (equal (cdr (assoc -2 ed)) i) T nil)))) + e (entnext e))) + (list out (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i)))"#; + +#[test] +fn entnext_walks_an_inserts_attribs_then_the_seqend_then_the_next_entity() { + let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2"), ("T3", 0, "D3")]); + inserted(&mut s, json!({ "T1": "A1", "T3": "A3" })); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget i)))"), "\"INSERT\""); + assert_eq!(ok(&mut s, "(cdr (assoc 66 (entget i)))"), "1"); + assert_eq!(ok(&mut s, WALK), "(((\"ATTRIB\" \"T1\" \"A1\" T) (\"ATTRIB\" \"T2\" \"P2\" T) (\"ATTRIB\" \"T3\" \"A3\" T)) \"SEQEND\" T)"); + // After the SEQEND the main order goes on: a line made later is next, then nil. + s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap(); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entnext (entnext (entnext (entnext (entnext i))))))))"), "\"LINE\""); + assert_eq!(ok(&mut s, "(entnext (entlast))"), "nil"); + // A reference of a block without attributes is followed by the next main entity, no SEQEND. + let mut s = with_attributes(&[("T1", 0, "D1")]); + s.cmdline("(progn (entmake '((0 . \"BLOCK\") (2 . \"E\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (entmake '((0 . \"ENDBLK\"))))").unwrap(); + s.execute("insert", &json!({ "name": "E", "at": [0, 0] })).unwrap(); + let plain = *s.doc().unwrap().model.handles().last().unwrap(); + s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap(); + assert_eq!(ok(&mut s, &format!("(cdr (assoc 0 (entget (entnext (handent \"{}\")))))", plain.hex())), "\"LINE\""); + // The owner is group -2 in a record's list and not 330, and the reference's own list has + // neither (as `entity_groups` keeps it). + inserted(&mut s, json!({ "T1": "A1" })); + assert_eq!(ok(&mut s, "(assoc 330 (entget (entnext i)))"), "nil"); + assert!(attribute_values(&s).iter().any(|(t, v)| t == "T1" && v == "A1")); +} + +#[test] +fn entmod_of_an_attrib_changes_only_its_value() { + let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]); + inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) d (entget a) seq (entnext (entnext a)))"); + // The value (group 1) is the one edit an ATTRIB's list takes. + let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))"); + assert!(r.contains("(1 . \"A2\")"), "{r}"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\""); + assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\""); + assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]); + // A list asking for anything else, and any edit of the SEQEND, is refused and changes nothing. + for code in [ + "(entmod (subst (cons 2 \"X\") (assoc 2 d) d))", + "(entmod (subst (cons 40 9.0) (assoc 40 d) d))", + "(entmod (subst (cons 8 \"L\") (assoc 8 d) d))", + "(entmod (subst (cons 0 \"SEQEND\") (assoc 0 d) d))", + "(entmod (entget seq))", + // Groups `list_to_groups` does not keep are still the reference's: an edit (or an added + // group) is refused, also when the same list changes group 1. + "(entmod (subst (cons 410 \"Layout2\") (assoc 410 d) d))", + "(entmod (subst (cons -2 a) (assoc -2 d) d))", + "(entmod (append d (list (cons 5 \"FF\"))))", + "(entmod (append d (list (cons 330 a))))", + "(entmod (append d (list (cons 360 \"FF\"))))", + "(entmod (append d (list (cons 102 \"{X\"))))", + "(entmod (subst (cons 1 \"A2\") (assoc 1 d) (subst (cons 410 \"Layout2\") (assoc 410 d) d)))", + // The same items, but the outer list ends in an atom: iterating it would drop the tail + // and accept a list `entget` never returned. + "(progn (setq r \"X\" p (reverse d)) (while p (setq r (cons (car p) r) p (cdr p))) (entmod r))", + ] { + assert_eq!(ok(&mut s, code), "nil", "{code}"); + } + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "no refused edit changed the value"); + // `entdel` of a record, and `entdel` of the SEQEND, do nothing either. + assert_eq!(ok(&mut s, "(progn (entdel a) (entdel seq))"), "nil"); + assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "the name still holds: nothing changed"); + // The edit is one undo step: the value goes back with it. + s.undo().unwrap(); + assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]); +} + +#[test] +fn a_subentity_name_expires_when_its_record_is_rebuilt() { + let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + // Erased: the records go with the reference. + s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap(); + assert_eq!(ok(&mut s, "(list (entget a) (entnext a))"), "(nil nil)"); + // Undone: the reference is back, the name given before the Undo is not. + s.undo().unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + assert_eq!(ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", h.hex())), "\"A1\""); + // ATTSYNC rebuilds the attributes in place: the old name names nothing, the values stay. + ok(&mut s, "(setq b (entnext i))"); + s.execute("attsync", &json!({ "name": "K" })).unwrap(); + assert_eq!(ok(&mut s, "(entget b)"), "nil"); + assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\""); + // A name never resolves to another attribute: when the record at its place has another tag + // now, it names nothing (the change makes no new epoch), and a new walk reaches the new tag. + ok(&mut s, "(setq c (entnext i))"); + assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget c)))"), "\"T1\""); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind + && let Some(a) = i.attribs.first_mut() + { + a.tag = "T9".into(); + } + }) + .unwrap(); + assert_eq!(ok(&mut s, "(entget c)"), "nil", "the record at that place has another tag now"); + assert_eq!(ok(&mut s, "(list (cdr (assoc 0 (entget (entnext i)))) (cdr (assoc 2 (entget (entnext i)))))"), "(\"ATTRIB\" \"T9\")"); +} + +#[test] +fn an_empty_attrib_and_a_seqend_have_distinct_names() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) end (entnext a))"); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget end)))"), "\"SEQEND\""); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + let mut blank = i.attribs[0].clone(); + blank.tag.clear(); + i.attribs.push(blank); + } + }) + .unwrap(); + assert_eq!(ok(&mut s, "(entget end)"), "nil"); + assert_eq!(ok(&mut s, "(setq b (entnext a)) (list (cdr (assoc 0 (entget b))) (eq b (entnext a)))"), "(\"ATTRIB\" T)"); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.attribs.truncate(1); + } + }) + .unwrap(); + assert_eq!(ok(&mut s, "(list (entget b) (cdr (assoc 0 (entget (entnext a)))))"), "(nil \"SEQEND\")"); +} + +#[test] +fn explode_and_burst_retire_the_removed_inserts_record_names() { + for command in ["explode", "burst"] { + let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) end (entnext (entnext a)))"); + let original = s.doc().unwrap().entity(h).unwrap().as_ref().clone(); + inserted(&mut s, json!({ "T1": "B1" })); + ok(&mut s, "(setq b (entnext i))"); + // A host can shorten the run before removal and later reuse the handle. + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + i.attribs.truncate(1); + } + }) + .unwrap(); + let result = s.execute(command, &json!({ "handles": [h.hex()] })).unwrap(); + assert!(!result["handles"].as_array().unwrap().is_empty(), "{command} creates pieces"); + assert!(s.doc().unwrap().entity(h).is_none(), "{command} removes the reference"); + s.doc_mut().unwrap().model.push(original); + assert_eq!(ok(&mut s, "(list (entget a) (entget end) (cdr (assoc 1 (entget b))))"), "(nil nil \"B1\")", "{command}"); + } +} + +#[test] +fn entmod_obeys_the_refedit_working_set_for_attrib_owners() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let editing = inserted(&mut s, json!({ "T1": "E1" })); + let outside = inserted(&mut s, json!({ "T1": "A1" })); + s.execute("refedit", &json!({ "handle": editing.hex() })).unwrap(); + let read = "(cdr (assoc 1 (entget (entnext i))))"; + let edit = r#"(progn (setq d (entget (entnext i))) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#; + assert_eq!(ok(&mut s, read), "\"A1\""); + assert_eq!(ok(&mut s, edit), "nil"); + assert_eq!(ok(&mut s, read), "\"A1\""); + s.execute("refset", &json!({ "add": [outside.hex()] })).unwrap(); + assert_ne!(ok(&mut s, edit), "nil"); + assert_eq!(ok(&mut s, read), "\"A2\""); +} + +#[test] +fn a_restored_reference_does_not_revive_an_old_name() { + // entdel of the reference, then entdel again to bring it back: the name given before the + // first entdel names nothing, also after the reference returns. + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil"); + assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil", "the name must not come back"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\""); + // ERASE, then OOPS: the same. Erasing expires the names it took with it. + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + s.execute("oops", &json!({})).unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil", "OOPS must not revive the name"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\""); +} + +#[test] +fn erasing_another_object_keeps_an_attrib_name() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) d (entget a))"); + s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap(); + let line = *s.doc().unwrap().model.handles().last().unwrap(); + // Erasing another object leaves the reference and its records as they were: the name holds + // and takes the value edit it always took. + s.execute("erase", &json!({ "handles": [line.hex()] })).unwrap(); + assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\""); + let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))"); + assert!(r.contains("(1 . \"A2\")"), "{r}"); + assert_eq!(attribute_values(&s), [("T1".into(), "A2".into())]); + // Erasing the reference itself ends its names, and OOPS bringing it back revives none. + s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + s.execute("oops", &json!({})).unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil", "the name of an erased reference stays dead"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\""); +} + +#[test] +fn entdel_of_another_object_keeps_an_attrib_name() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap(); + ok(&mut s, "(setq line (entlast))"); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget line)))"), "\"LINE\""); + ok(&mut s, "(entdel line)"); + assert_eq!(ok(&mut s, "(entget line)"), "nil"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\""); +} + +#[test] +fn a_name_given_in_the_block_editor_never_resolves_in_the_host() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + s.execute("bedit", &json!({ "name": "K" })).unwrap(); + // A reference made in the editor's drawing, named there. The editor starts from the host's + // drawing, so its handle is the one the host gives its next new object. + s.execute("insert", &json!({ "name": "K", "at": [40, 40], "attribs": { "T1": "E1" } })).unwrap(); + let editor = *s.doc().unwrap().model.handles().last().unwrap(); + ok(&mut s, &format!("(setq a (entnext (handent \"{}\")))", editor.hex())); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"E1\""); + s.execute("bclose", &json!({ "save": false })).unwrap(); + // The host's next reference takes the handle the editor's reference had: the name given in + // the editor must not reach its ATTRIB, or `entmod` through it would edit the wrong one. + s.execute("insert", &json!({ "name": "K", "at": [80, 80], "attribs": { "T1": "H1" } })).unwrap(); + let host = *s.doc().unwrap().model.handles().last().unwrap(); + assert_eq!(host, editor, "the host takes the handle the editor's reference had"); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + assert_eq!(ok(&mut s, "(entdel a)"), "nil"); + assert_eq!( + ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", host.hex())), + "\"H1\"", + "the host's own attribute is untouched" + ); +} + +#[test] +fn without_a_record_provider_entnext_walks_the_next_entity() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap(); + // A host that installed no provider has no records to name: the walk goes on to the next + // main entity as it always did, rather than answering nil at the reference. + let next = crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(entnext i)")); + assert_ne!(next, "nil"); + assert_eq!(crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(cdr (assoc 0 (entget (entnext i))))")), "\"LINE\""); +} + +#[test] +fn a_redo_does_not_revive_an_old_name() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) d (entget a))"); + ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))"); + s.undo().unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + s.redo().unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil", "Redo must not revive the name"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\""); +} + +#[test] +fn a_block_replace_expires_an_old_attrib_name() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + // A replacement block with the same tag as K's first attribute: without the expiry, the old + // name would keep naming that place and return the new record. + s.cmdline( + "(progn (entmake '((0 . \"BLOCK\") (2 . \"L\") (70 . 2) (10 0.0 0.0 0.0))) \ + (entmake '((0 . \"ATTDEF\") (10 0.0 0.0 0.0) (40 . 2.5) (1 . \"Z1\") (3 . \"P\") (2 . \"T1\") (70 . 0))) \ + (entmake '((0 . \"ENDBLK\"))))", + ) + .unwrap(); + inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + s.execute("blockreplace", &json!({ "block": "K", "with": "L" })).unwrap(); + assert_eq!(ok(&mut s, "(entget a)"), "nil", "-BLOCKREPLACE rebuilt the record"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\""); +} + +#[test] +fn a_reinsert_after_undo_takes_the_handle_and_no_old_name() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + // U takes the reference back; INSERT then gives a new one the handle it had. + s.undo().unwrap(); + assert!(s.doc().unwrap().entity(h).is_none()); + let again = inserted(&mut s, json!({ "T1": "B1" })); + assert_eq!(again, h, "the same handle"); + assert_eq!(ok(&mut s, "(list (entget a) (cdr (assoc 1 (entget (entnext i)))))"), "(nil \"B1\")"); +} + +/// A drawing with one reference of `attribs` attributes (all value V), for the bounds. +fn drawing_with_attributes(attribs: usize) -> (Session, Handle) { + let text = |v: &str| cadcraft_doc::Text { + insert: cadcraft_geom::Vec3::ZERO, + align_pt: None, + height: 1.0, + value: v.into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: cadcraft_doc::HAlign::Left, + valign: cadcraft_doc::VAlign::Baseline, + backwards: false, + upside_down: false, + }; + let mut d = cadcraft_doc::Drawing::new_metric(); + let list = (0..attribs) + .map(|i| cadcraft_doc::Attrib { + tag: format!("T{i}"), + text: text("V"), + invisible: false, + constant: false, + prompt: String::new(), + props: cadcraft_doc::AttribProps::default(), + multiline: None, + modes: cadcraft_doc::AttribModes::default(), + }) + .collect(); + let insert = cadcraft_doc::Insert { block: "B".into(), attribs: list, ..cadcraft_doc::Insert::default() }; + let h = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Insert(insert)).expect("add"); + let mut s = session(); + s.open_drawing(d, "attributes", None); + ok(&mut s, &format!("(setq i (handent \"{}\"))", h.hex())); + (s, h) +} + +/// The number of records a walk from `i` names. +const COUNT: &str = "(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)"; + +#[test] +fn a_session_names_at_most_65536_records_and_nothing_changes() { + let (mut s, h) = drawing_with_attributes(65_537); + assert_eq!(ok(&mut s, COUNT), "65536"); + // The names given hold: a second walk is the same, and the drawing kept every attribute. + assert_eq!(ok(&mut s, COUNT), "65536"); + // Erasing and bringing the reference back frees the 65,536 names it held: the old name names + // nothing, and a new walk can name the records again. + ok(&mut s, "(setq a (entnext i))"); + ok(&mut s, "(progn (entdel i) (entdel i))"); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + assert_eq!(ok(&mut s, COUNT), "65536"); + let d = s.doc().unwrap(); + let kept = d.entity(h).and_then(|e| match &e.kind { + cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.len()), + _ => None, + }); + assert_eq!(kept, Some(65_537)); +} + +#[test] +fn a_new_object_at_any_handle_is_never_a_record() { + // A hostile $HANDSEED at the top of the range: the line made after the walk takes that + // handle, and the record keeps its own name, which is no handle. + let (mut s, _) = drawing_with_attributes(1); + s.doc_mut().unwrap().handseed = u64::MAX - 1; + ok(&mut s, "(setq a (entnext i))"); + assert_eq!( + ok(&mut s, r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#), + "\"FFFFFFFFFFFFFFFE\"" + ); + assert_eq!( + ok(&mut s, "(list (cdr (assoc 0 (entget a))) (eq a (entlast)) (entdel a) (cdr (assoc 0 (entget (entlast)))))"), + "(\"ATTRIB\" nil nil \"LINE\")" + ); +} + +#[test] +fn objects_at_the_top_of_the_handle_range_walk_as_objects() { + let (mut s, _) = drawing_with_attributes(1); + { + let d = s.doc_mut().unwrap(); + d.handseed = u64::MAX; + for handle in [Handle(u64::MAX - 1), Handle(u64::MAX)] { + let line = + cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(1.0, 0.0, 0.0) }); + d.model.push(cadcraft_doc::Entity { handle, common: cadcraft_doc::Common::default(), kind: line }); + } + } + ok(&mut s, "(setq a (entnext i))"); + // The lines' handles are theirs: `entnext` of the first finds the second, then the end. + assert_eq!(ok(&mut s, "(equal (entnext (handent \"FFFFFFFFFFFFFFFE\")) (handent \"FFFFFFFFFFFFFFFF\"))"), "T"); + assert_eq!(ok(&mut s, "(entnext (handent \"FFFFFFFFFFFFFFFF\"))"), "nil"); + // The record, a table record and the lines each keep their own name. + assert_eq!( + ok(&mut s, "(list (cdr (assoc 0 (entget a))) (equal a (tblobjname \"LAYER\" \"0\")) (equal a (handent \"FFFFFFFFFFFFFFFE\")))"), + "(\"ATTRIB\" nil nil)" + ); +} + +#[test] +fn a_record_name_is_an_entity_name_but_no_handle() { + let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) b (entnext a))"); + assert_eq!(ok(&mut s, "(type a)"), "ENAME"); + // The same record has the same name on every walk; another record and the reference have + // their own. + assert_eq!(ok(&mut s, "(list (eq a (entnext i)) (equal a (entnext i)) (eq a b) (eq a i) (equal a i))"), "(T T nil nil nil)"); + // It prints as the reference's handle, a dot and its number: never a handle's text. + let printed = ok(&mut s, "a"); + assert!(printed.starts_with(&format!("'), "{printed}"); + // No handle reaches it: its list has no group 5, and `handent` of the reference's handle is + // the reference. + assert_eq!(ok(&mut s, "(list (assoc 5 (entget a)) (eq a (handent (cdr (assoc 5 (entget i))))))"), "(nil nil)"); + // A DXF group cannot point at it: `entmake` of a list that does is refused. + assert_eq!(ok(&mut s, "(entmake (list '(0 . \"LINE\") '(10 0.0 0.0 0.0) '(11 1.0 0.0 0.0) (cons 340 a)))"), "nil"); +} + +#[test] +fn selection_sets_and_commands_take_no_record() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) ss (ssadd i))"); + // A selection set holds objects of the drawing; a record is not one on its own. + assert_eq!(ok(&mut s, "(list (ssadd a) (ssadd a ss) (sslength ss) (ssmemb a ss) (ssdel a ss) (sslength ss))"), "(nil nil 1 nil nil 1)"); + // A command given the name picks nothing: the reference stays, and the name holds. + ok(&mut s, "(command \"_.ERASE\" a \"\")"); + assert!(s.doc().unwrap().entity(h).is_some()); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\""); +} + +#[test] +fn entupd_of_a_record_answers_its_name_while_it_holds() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i) d (entget a))"); + assert_eq!(ok(&mut s, "(progn (entmod (subst (cons 1 \"A2\") (assoc 1 d) d)) (eq (entupd a) a))"), "T"); + s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap(); + assert_eq!(ok(&mut s, "(entupd a)"), "nil"); +} + +#[test] +fn a_record_name_holds_while_commands_keep_its_record() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + // Moving the reference, or changing its colour, keeps its records in their places. + s.execute("move", &json!({ "handles": [h.hex()], "delta": [5, 5] })).unwrap(); + s.execute("chprop", &json!({ "handles": [h.hex()], "color": 1 })).unwrap(); + assert_eq!(ok(&mut s, "(list (cdr (assoc 1 (entget a))) (eq a (entnext i)))"), "(\"A1\" T)"); +} + +#[test] +fn each_record_name_is_one_entry_and_walking_again_adds_none() { + const N: usize = 64; + let (mut s, _) = drawing_with_attributes(N); + let before = s.state().unwrap().doc.clone(); + ok(&mut s, "(setq e nil)"); + // The R3 pattern: each new name, then state access. Nothing is copied or replayed. + for _ in 0..=N { + ok(&mut s, "(setq e (if e (entnext e) (entnext i)))"); + let _ = s.state_mut().unwrap(); + } + let uid = s.state().unwrap().uid; + let held = |s: &Session| s.lisp.records.get(&uid).map_or(0, super::drawing::RecordNames::count); + assert_eq!(held(&s), N + 1, "the attributes and the SEQEND, one entry each"); + assert_eq!(ok(&mut s, COUNT), (N + 1).to_string()); + assert_eq!(held(&s), N + 1, "a walk again gives the same names"); + assert!(std::sync::Arc::ptr_eq(&before, &s.state().unwrap().doc), "naming changes nothing in the drawing"); + // Undo or redo ends them: the next walk starts over with as many. + s.execute("line", &json!({ "points": [[0, -4], [1, -4]] })).unwrap(); + s.undo().unwrap(); + assert_eq!(ok(&mut s, COUNT), (N + 1).to_string()); + assert_eq!(held(&s), N + 1); +} + +/// A saved drawing with one named attribute. The name comes from the command line, which does +/// not run the after-command pass. +fn clean_named() -> Session { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + { + let st = s.state_mut().unwrap(); + st.saved = st.doc.clone(); + st.undo.clear(); + st.redo.clear(); + } + s.cmdline("(setq a (entnext i))").unwrap(); + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget a)))"), "\"ATTRIB\""); + assert!(!s.state().unwrap().is_dirty(), "naming from the command line saves nothing"); + s +} + +#[test] +fn issued_name_reads_keep_the_drawing_clean() { + let mut s = clean_named(); + s.cmdline("(getvar \"DBMOD\")").unwrap(); + assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0"); + assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved)); + // A programmatic read runs the after-command pass. That pass must not make a saved drawing dirty. + s.execute("lisp", &json!({ "code": "(entget a)" })).unwrap(); + assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0"); + assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved)); + assert_eq!(s.state().unwrap().undo.len(), 0, "a read is not an undo step"); +} + +#[test] +fn issued_name_selection_keeps_the_drawing_clean() { + let mut s = clean_named(); + let saved = s.state().unwrap().saved.clone(); + s.execute("select", &json!({ "clear": true })).unwrap(); + assert!(s.state().unwrap().selection.is_empty()); + assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved)); + assert!(!s.state().unwrap().is_dirty()); + assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0"); + assert_eq!(s.state().unwrap().undo.len(), 0, "clearing an empty selection is not an undo step"); +} + +#[test] +fn issued_name_undo_restores_the_saved_drawing() { + let mut s = clean_named(); + let saved = s.state().unwrap().saved.clone(); + // A selection change writes no undo step. If it also changes the drawing, the next command + // records that copy, and undo cannot return to the saved drawing. + s.execute("select", &json!({ "clear": true })).unwrap(); + assert_eq!(s.state().unwrap().undo.len(), 0); + s.execute("line", &json!({ "points": [[0, -3], [1, -3]] })).unwrap(); + assert!(s.undo().unwrap().is_some()); + assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved), "undo returns the saved drawing, not a reservation copy"); + assert!(!s.state().unwrap().is_dirty()); + assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0"); +} + +#[test] +fn a_name_given_in_the_host_never_resolves_in_the_block_editor() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + let mut same = cadcraft_doc::Entity::clone(s.doc().unwrap().entity(h).unwrap()); + if let cadcraft_doc::EntityKind::Insert(ins) = &mut same.kind + && let Some(at) = ins.attribs.first_mut() + { + at.text.value = "E1".into(); + } + s.execute("bedit", &json!({ "name": "K" })).unwrap(); + // An object of the editor's drawing with the handle the host's reference has: the host's + // name must not reach its ATTRIB. + s.doc_mut().unwrap().model.push(same); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + s.execute("bclose", &json!({ "save": false })).unwrap(); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\""); +} + +#[test] +fn a_drawing_put_back_after_a_refused_change_ends_its_names() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let before = s.state().unwrap().doc.clone(); + let h = inserted(&mut s, json!({ "T1": "A1" })); + ok(&mut s, "(setq a (entnext i))"); + // A change with a number that is not finite: the drawing goes back as it was, without the + // reference the name was given for. + let bad = cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(f64::NAN, 0.0, 0.0), b: cadcraft_geom::Vec3::ZERO }); + s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), bad).unwrap(); + assert!(s.refuse_non_finite(None, &before, &[], "line").is_err()); + assert!(s.doc().unwrap().entity(h).is_none()); + // The next reference takes the handle back: the old name names nothing in it. + assert_eq!(inserted(&mut s, json!({ "T1": "B1" })), h); + assert_eq!(ok(&mut s, "(entget a)"), "nil"); + assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"B1\""); +} + +/// MOCORO's own Undo puts the drawing from before the Copy back, handle seed included. +/// The next Copy is given that handle again. The name of the removed copy's attribute +/// must not read it, walk from it, or change it. +#[test] +fn mocoro_undo_does_not_let_an_old_record_name_reach_the_next_copy() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + inserted(&mut s, json!({ "T1": "A1" })); + ok( + &mut s, + r#"(progn + (sssetfirst nil nil) + (command "_.MOCORO" i "" '(0 0) "_Copy" '(10 0)) + (setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c) v (cdr (assoc 1 (entget a)))) + (command "_Undo" "_Copy" '(20 0) "_eXit"))"#, + ); + // The name was given for a copy with a handle of its own, and it read that copy's attribute. + // The copy made after the Undo has the removed copy's handle. + assert_eq!(ok(&mut s, "(list (= ch (cdr (assoc 5 (entget i)))) v (= ch (cdr (assoc 5 (entget (entlast))))))"), "(nil \"A1\" T)"); + assert_eq!( + ok( + &mut s, + r#"(progn + (setq d (entget a) w (entnext a)) + (if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d))) + (list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"# + ), + "(T T \"A1\")" + ); +} + +/// A grip Copy's Undo is the same kind of restore: the next copy reuses the handle. +#[test] +fn grip_copy_undo_does_not_let_an_old_record_name_reach_the_next_copy() { + let mut s = with_attributes(&[("T1", 0, "D1")]); + let h = inserted(&mut s, json!({ "T1": "A1" })); + s.start_grip_edit(&[(h, 0)]).unwrap(); + // Enter leaves STRETCH for MOVE, which copies the reference whole. + s.input(crate::Input::Enter).unwrap(); + s.input(crate::Input::Keyword("Copy".into())).unwrap(); + s.input(crate::Input::Point(cadcraft_geom::Vec2::new(20.0, 10.0))).unwrap(); + // The name is given for a copy with a handle of its own, and it reads that copy's attribute. + assert_eq!( + ok( + &mut s, + r#"(progn + (setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c)) + (list (= ch (cdr (assoc 5 (entget i)))) (cdr (assoc 1 (entget a)))))"# + ), + "(nil \"A1\")" + ); + s.input(crate::Input::Keyword("Undo".into())).unwrap(); + s.input(crate::Input::Point(cadcraft_geom::Vec2::new(30.0, 10.0))).unwrap(); + assert_eq!(ok(&mut s, "(= ch (cdr (assoc 5 (entget (entlast)))))"), "T", "the next copy takes the removed copy's handle"); + assert_eq!( + ok( + &mut s, + r#"(progn + (setq d (entget a) w (entnext a)) + (if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d))) + (list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"# + ), + "(T T \"A1\")" + ); +} diff --git a/crates/engine/src/lisp/value.rs b/crates/engine/src/lisp/value.rs index fd95d2ec7..4ccf5d16c 100644 --- a/crates/engine/src/lisp/value.rs +++ b/crates/engine/src/lisp/value.rs @@ -12,7 +12,7 @@ //! ([`charge_bytes`]). use std::cell::Cell; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use cadcraft_doc::Handle; @@ -207,6 +207,26 @@ pub enum BuiltinKind { Special(super::eval::Special), } +/// The name AutoLISP gives an INSERT's ATTRIB or SEQEND (#1660). Those records have no handle of +/// their own in the drawing, so their names are not handles: `id` comes from one count for the +/// whole process and is never given again, so no object of any drawing, and no other record, +/// ever has it. `owner` is the reference's handle, for printing. What a name stands for is kept +/// by the session; a name that no longer holds names nothing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RecordName { + pub(crate) owner: Handle, + pub(crate) id: u64, +} + +impl RecordName { + /// A name never given before, for a record of `owner`; `None` once the count runs out. + pub(crate) fn fresh(owner: Handle) -> Option { + static NEXT: AtomicU64 = AtomicU64::new(1); + let id = NEXT.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)).ok()?; + Some(RecordName { owner, id }) + } +} + #[derive(Clone, Debug, Default)] pub enum Value { #[default] @@ -217,6 +237,8 @@ pub enum Value { Sym(Sym), Cons(Arc), Ename(Handle), + /// An INSERT's ATTRIB or SEQEND (#1660): an entity name that is no handle. + Record(RecordName), PickSet(PickSet), File(u32), Subr(&'static Builtin), @@ -310,7 +332,7 @@ impl Value { Value::Str(_) => "STR", Value::Sym(_) => "SYM", Value::Cons(_) => "LIST", - Value::Ename(_) => "ENAME", + Value::Ename(_) | Value::Record(_) => "ENAME", Value::PickSet(_) => "PICKSET", Value::File(_) => "FILE", Value::Subr(_) => "SUBR", @@ -423,6 +445,7 @@ fn atom_equal(a: &Value, b: &Value, fuzz: f64) -> bool { (Value::Str(x), Value::Str(y)) => x == y, (Value::Sym(x), Value::Sym(y)) => x == y, (Value::Ename(x), Value::Ename(y)) => x == y, + (Value::Record(x), Value::Record(y)) => x == y, (Value::File(x), Value::File(y)) => x == y, (Value::PickSet(x), Value::PickSet(y)) => x.id == y.id, (Value::Subr(x), Value::Subr(y)) => std::ptr::eq(*x, *y), @@ -567,6 +590,8 @@ fn write_value(out: &mut String, v: &Value, escape: bool, depth: usize) { out.push(')'); } Value::Ename(h) => out.push_str(&format!("", h.0)), + // The reference's handle, a dot and the record's number: never a handle's text. + Value::Record(r) => out.push_str(&format!("", r.owner.0, r.id)), Value::PickSet(p) => out.push_str(&format!("", p.id)), Value::File(f) => out.push_str(&format!("#")), Value::Subr(b) => out.push_str(&format!("#", "0", b.name)), diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 203d13dcb..8ee6a36f3 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -16,7 +16,7 @@ impl Session { if let Some((doc, sel, uid)) = before && let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) { - st.doc = doc; + st.restore_drawing(doc); st.selection = sel; } Err(EngineError::Internal(id.into(), crate::guard::message(&*p))) @@ -50,7 +50,7 @@ impl Session { if let Some((doc, sel, uid)) = &before && let Some(st) = self.docs.iter_mut().find(|d| d.uid == *uid) { - st.doc = doc.clone(); + st.restore_drawing(doc.clone()); st.selection = sel.clone(); } return Err(EngineError::Internal(id.into(), msg)); diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index b2c1eb642..003068a63 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -479,7 +479,7 @@ impl Session { Err(EngineError::Internal(id, m)) => { // Restore and end the command. if let Ok(st) = self.state_mut() { - st.doc = run.before.clone(); + st.restore_drawing(run.before.clone()); } self.echo(format!("Internal error in {id}: {m}")); self.resume_suspended(); @@ -501,7 +501,7 @@ impl Session { let (id, before, selection) = (run.id.clone(), run.before.clone(), run.selection_before.clone()); if let Err(p) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.finish_guarded(run, cancelled))) { if let Ok(st) = self.state_mut() { - st.doc = before; + st.restore_drawing(before); st.selection = selection; } self.echo(format!("Internal error in {id}: {}", crate::guard::message(&*p))); diff --git a/crates/engine/tests/it/attrib_names.rs b/crates/engine/tests/it/attrib_names.rs new file mode 100644 index 000000000..2ae35aef9 --- /dev/null +++ b/crates/engine/tests/it/attrib_names.rs @@ -0,0 +1,203 @@ +//! AutoLISP's name of an INSERT's ATTRIB keeps naming that attribute when a command, another +//! session, another document or another thread gives out handles in the drawing or in a copy of +//! it, and installs the result (#1660). + +use std::sync::Arc; + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{EntityCodec, IoHooks, set_entity_codec, set_entity_sub_record, set_io, set_object_records}; +use cadcraft_engine::doc::geom::Vec3; +use cadcraft_engine::doc::{Block, Common, Drawing, Entity, EntityKind, Handle, Line, Space}; +use cadcraft_engine::lisp::value::to_text; +use serde_json::json; + +use crate::temp_dir::TempDir; + +fn session() -> Session { + set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups }); + set_entity_sub_record(cadcraft_io::entity_sub_record); + set_object_records(cadcraft_io::object_records); + set_io(IoHooks { + read: |bytes, name| cadcraft_io::read(bytes, name).map_err(|e| e.to_string()), + write: |drawing, name| cadcraft_io::write(drawing, name).map_err(|e| e.to_string()), + plot: None, + }); + Session::new() +} + +fn eval(s: &mut Session, code: &str) -> String { + match s.lisp_eval(code, false, true, Vec::new()) { + Ok(Some(Ok(v))) => to_text(&v, true), + Ok(Some(Err(e))) => panic!("{code}: {e}"), + Ok(None) => panic!("{code}: did not finish"), + Err(e) => panic!("{code}: {e}"), + } +} + +/// Block K with one attribute, one reference, and `i` naming that reference. +fn attributed() -> Session { + let mut s = session(); + s.cmdline( + "(progn (entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) \ + (entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 1.0))) \ + (entmake '((0 . \"ATTDEF\") (10 0.0 5.0 0.0) (40 . 2.5) (1 . \"D1\") (3 . \"P\") (2 . \"T1\") (70 . 0))) \ + (entmake '((0 . \"ENDBLK\"))))", + ) + .unwrap(); + let ins = s.execute("insert", &json!({ "name": "K", "at": [10, 10], "attribs": { "T1": "A1" } })).unwrap(); + let href = ins["handle"].as_str().unwrap(); + eval(&mut s, &format!("(setq i (handent \"{href}\"))")); + s +} + +/// The command line names the reference's first ATTRIB `a`, with `$HANDSEED` one below the top: +/// the next handle the drawing, or a copy of it, gives out. The command line does not run the +/// after-command pass. +fn name_at_top(s: &mut Session) { + s.doc_mut().unwrap().handseed = u64::MAX - 1; + s.cmdline("(setq a (entnext i))").unwrap(); + assert_eq!(eval(s, "(cdr (assoc 0 (entget a)))"), "\"ATTRIB\""); +} + +/// Every object's handle: model space, layouts and block definitions. +fn every_handle(d: &Drawing) -> Vec { + let mut v = d.model.handles(); + for l in &d.layouts { + v.extend(l.entities.handles()); + } + for b in d.blocks.values() { + v.extend(b.entities.handles()); + } + v +} + +/// `a` still names the attribute, and no object of the drawing is `a`: whatever handles were +/// given out, each object keeps its own name. +fn assert_kept(s: &mut Session) { + assert_eq!( + eval(s, "(list (cdr (assoc 0 (entget a))) (cdr (assoc 1 (entget a))))"), + "(\"ATTRIB\" \"A1\")", + "the old name still means the attribute" + ); + let handles = every_handle(s.doc().unwrap()); + for h in handles { + let hex = h.hex(); + assert_eq!(eval(s, &format!("(eq a (handent \"{hex}\"))")), "nil", "object {hex} is not the attribute"); + } +} + +/// A line added to `d` with the drawing's next handle. +fn add_line(d: &mut Drawing) -> Handle { + d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).unwrap() +} + +/// After a copy of the drawing took `line`, the name still means the attribute and the line is +/// the line. +fn assert_line_and_name(s: &mut Session, line: Handle) { + assert_kept(s); + let hex = line.hex(); + assert_eq!(eval(s, &format!("(cdr (assoc 0 (entget (handent \"{hex}\"))))")), "\"LINE\""); +} + +fn one_line(dir: &TempDir) -> String { + let mut d = Drawing::new_metric(); + add_line(&mut d); + dir.file("one-line.dxf", cadcraft_io::write_dxf(&d)) +} + +#[test] +fn another_sessions_read_leaves_a_record_name_alone() { + // Session A names an attribute and keeps a copy of its drawing; session B, which named + // nothing, is read; then A's copy gives out a handle and A installs it. + let mut a = attributed(); + let b = attributed(); + name_at_top(&mut a); + let mut copy = a.doc().unwrap().clone(); + let _ = b.doc().unwrap(); + let line = add_line(&mut copy); + *a.doc_mut().unwrap() = copy; + assert_line_and_name(&mut a, line); +} + +#[test] +fn a_copy_edited_on_another_thread_leaves_a_record_name_alone() { + let mut a = attributed(); + name_at_top(&mut a); + let copy = a.doc().unwrap().clone(); + let (copy, line) = std::thread::spawn(move || { + let mut copy = copy; + let line = add_line(&mut copy); + (copy, line) + }) + .join() + .unwrap(); + *a.doc_mut().unwrap() = copy; + assert_line_and_name(&mut a, line); +} + +#[test] +fn a_copy_made_while_another_document_is_current_leaves_a_record_name_alone() { + let mut s = attributed(); + name_at_top(&mut s); + let first = s.active; + let mut copy = s.doc().unwrap().clone(); + s.open_drawing(Drawing::new_metric(), "other", None); + let _ = s.doc().unwrap(); + let line = add_line(&mut copy); + s.active = first; + *s.doc_mut().unwrap() = copy; + assert_line_and_name(&mut s, line); +} + +#[test] +fn insert_from_file_keeps_an_attrib_name() { + let mut s = attributed(); + name_at_top(&mut s); + let dir = TempDir::new("attrib-insert"); + let path = one_line(&dir); + s.execute("insert", &json!({ "file": path, "name": "SRC", "at": [4.0, 4.0] })).unwrap(); + assert_kept(&mut s); +} + +#[test] +fn xattach_keeps_an_attrib_name() { + let mut s = attributed(); + name_at_top(&mut s); + let dir = TempDir::new("attrib-xref"); + let path = one_line(&dir); + s.execute("xattach", &json!({ "path": path, "name": "XR", "at": [8.0, 8.0] })).unwrap(); + assert_kept(&mut s); +} + +#[test] +fn audit_fix_keeps_an_attrib_name() { + let mut s = attributed(); + { + let d = s.doc_mut().unwrap(); + let line = Entity::new(Handle(0xABC), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })); + d.model.push(line.clone()); + let mut b = Block::new("DUP"); + b.entities.push(line); + d.blocks.insert("DUP".into(), Arc::new(b)); + } + name_at_top(&mut s); + s.execute("audit", &json!({ "fix": true })).unwrap(); + assert_kept(&mut s); +} + +#[test] +fn refclose_keeps_an_attrib_name() { + let mut s = attributed(); + s.cmdline( + "(progn (entmake '((0 . \"BLOCK\") (2 . \"R\") (70 . 0) (10 0.0 0.0 0.0))) \ + (entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 2.0 0.0 0.0))) \ + (entmake '((0 . \"ENDBLK\"))))", + ) + .unwrap(); + let r = s.execute("insert", &json!({ "name": "R", "at": [0, 0] })).unwrap(); + s.execute("refedit", &json!({ "handle": r["handle"] })).unwrap(); + s.execute("line", &json!({ "points": [[0, 1], [3, 1]] })).unwrap(); + name_at_top(&mut s); + s.execute("refclose", &json!({ "save": true })).unwrap(); + assert_kept(&mut s); +} diff --git a/crates/engine/tests/it/lisp_findfile.rs b/crates/engine/tests/it/lisp_findfile.rs index 410440177..a7e4c84c3 100644 --- a/crates/engine/tests/it/lisp_findfile.rs +++ b/crates/engine/tests/it/lisp_findfile.rs @@ -4,10 +4,7 @@ use cadcraft_engine::Session; use serde_json::json; -#[path = "../support/temp_dir.rs"] -mod temp_dir; - -use temp_dir::TempDir; +use crate::temp_dir::TempDir; /// `(findfile name)` as LISP prints it. fn findfile(name: &str) -> String { diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 37eee060d..3d6679d95 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -1,3 +1,6 @@ +#[path = "../support/temp_dir.rs"] +mod temp_dir; + mod angle_prompts; mod angle_settings; mod annotate_options; @@ -12,6 +15,7 @@ mod attdef_command; mod attdisp_attsync; mod attedit_prompts; mod attrib_modes; +mod attrib_names; mod attrib_props; mod attribute_tag_matching; mod attribute_tools; diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 83c534ba0..973d865d4 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -19,6 +19,8 @@ use crate::dxf_ext::{self, DimVal, K}; mod assoc; mod blocks; mod common; +#[cfg(test)] +pub(crate) use common::{attdef_definition_visits, reset_attdef_definition_visits}; mod ctx; mod entity; mod header; @@ -166,6 +168,45 @@ fn tags_kept(d: &Drawing, version: Version) -> (Vec, std::collections::Hash (tags, kept) } +/// One record written after an entity's own, at `index`: an INSERT's ATTRIB, then its SEQEND +/// (items of a POLYLINE's sequence are not records `entnext` reaches yet). The record's type name +/// and groups without its `0` group; its handle (5) and owner (330) are left out: it has no +/// handle of its own in the drawing (the writer makes one per file), and its owner is the entity. +/// `None` past the last record, and for an entity written as a single record. AutoLISP's +/// `entnext` and `entget` read one record at a time through it, never writing the entity's other +/// records. +pub fn entity_sub_record(d: &Drawing, e: &Entity, index: usize) -> Option<(String, Vec)> { + let cadcraft_doc::EntityKind::Insert(i) = &e.kind else { return None }; + if i.attribs.is_empty() { + return None; + } + let mut w = W { + t: Vec::new(), + next: d.handseed.max(0x100).saturating_add(0x1000), + used: HashSet::new(), + pstyles: HashMap::new(), + layers: HashMap::new(), + ucss: HashMap::new(), + vport_ucs: Vec::new(), + reactors: HashMap::new(), + xdicts: HashMap::new(), + }; + let cx = Ctx { target: Version::R2018, legacy_columns: true, ..Ctx::default() }; + match i.attribs.get(index) { + Some(a) => { + let base = d.block(&i.block).and_then(|b| common::attdef_base(b, &a.tag)); + entity::attrib_record(&mut w, d, e, index, a, base, &cx); + } + None if index == i.attribs.len() => entity::seqend_record(&mut w, e), + None => return None, + } + let mut tags = w.t.into_iter(); + let kind = tags.next().filter(|t| t.code == 0).map(|t| t.value.as_str())?; + let mut tags: Vec = tags.filter(|t| t.code != 5 && t.code != 330).collect(); + // Strings as AutoLISP sees them (`10^2`, not the file's `10^ 2`), as in `entity_groups`. + crate::dxf_read::mtext_dxf::map_text_groups(&kind, &mut tags, crate::dxf_read::mtext_dxf::decode_line); + Some((kind, tags)) +} /// The most dash elements a linetype keeps in a DWG. The DWG writer (acadrust) stores the count in /// one byte, so a longer pattern would come back with its count modulo 256 (none at all for 256), /// and a DWG save keeps the first 255 instead ([`dwg_notes`] says so). diff --git a/crates/io/src/dxf_write/common.rs b/crates/io/src/dxf_write/common.rs index 0d1936cf1..e3768c968 100644 --- a/crates/io/src/dxf_write/common.rs +++ b/crates/io/src/dxf_write/common.rs @@ -1,9 +1,138 @@ +use std::cell::RefCell; +use std::collections::BTreeMap; + use super::ctx::{AssocObj, Ctx}; use super::{ - Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, HAlign, HashMap, Lineweight, Text, Transparency, VAlign, Vec3, Version, W, - dxf_ext, + Attrib, Block, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, Handle, HashMap, Lineweight, Text, Transparency, + VAlign, Vec3, Version, W, dxf_ext, }; +/// The most ATTDEF tags the definition indexes on one thread hold in all (a block with none +/// counts as one). An index that fits but would pass this total drops the indexes already +/// stored, then takes their place. A definition with more distinct tags than this is not indexed: +/// its state is remembered as too large, and each read of it scans the definition for the first +/// matching ATTDEF and keeps nothing, so one block cannot grow the cache past the budget, and the +/// written file still takes its properties from the right definition. +const MAX_INDEXED_TAGS: usize = 1 << 18; + +/// The most block states remembered as too large to index; past it the list starts again. +const MAX_TOO_LARGE: usize = 1 << 10; + +/// For each state of a block definition's entities read on this thread, by its content token +/// ([`cadcraft_doc::EntityStore::content_token`]): the handle of the first ATTDEF of each tag +/// (upper case). A token names one state of one store, so an index is never used for another +/// copy or another edit of the block, and blocks read in turn keep their indexes. A definition +/// past [`MAX_INDEXED_TAGS`] has no entry here. +#[derive(Default)] +struct AttdefIndexes { + /// Order tags from the drawing so lookup cost does not depend on hash collisions. + by_store: HashMap>, + /// Tags held in all, for [`MAX_INDEXED_TAGS`]. + tags: usize, + /// States of definitions with more distinct tags than [`MAX_INDEXED_TAGS`], so a read of one + /// goes straight to [`scan_attdef`] without building and dropping an index again. + too_large: std::collections::HashSet, +} + +thread_local! { + static ATTDEF_INDEXES: RefCell = RefCell::new(AttdefIndexes::default()); + /// Entities of a block definition examined while matching an attribute to its ATTDEF. + #[cfg(test)] + static ATTDEF_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The first ATTDEF of each tag in `block`, by upper-case tag, when there are at most `budget` +/// distinct tags. `None` when another distinct tag would pass `budget`: the partial map is +/// dropped, so a prefix is not stored in place of the definition. +fn attdef_index_within(block: &Block, budget: usize) -> Option> { + let mut by_tag = BTreeMap::new(); + for e in block.entities.iter() { + count_attdef_visit(); + if let EntityKind::AttDef(ad) = &e.kind { + let key = ad.tag.to_ascii_uppercase(); + if by_tag.contains_key(&key) { + continue; + } + if by_tag.len() >= budget { + return None; + } + by_tag.insert(key, e.handle); + } + } + Some(by_tag) +} + +/// The first ATTDEF of `block` whose tag matches `tag`, ignoring ASCII case: one pass over the +/// definition at most, stopping at the match. Nothing from the scan is stored. +fn scan_attdef(block: &Block, tag: &str) -> Option { + for e in block.entities.iter() { + count_attdef_visit(); + if let EntityKind::AttDef(ad) = &e.kind + && ad.tag.eq_ignore_ascii_case(tag) + { + return Some(e.handle); + } + } + None +} + +/// The definition properties of the first ATTDEF in `block` whose tag matches `tag`, ignoring +/// ASCII case. Each state of a block's entities that fits in [`MAX_INDEXED_TAGS`] is read once +/// on a thread: later attributes, of this reference or another, find their definition in its +/// index. A definition with more distinct tags is not stored: the first read of that state builds +/// at most [`MAX_INDEXED_TAGS`] index entries, then gives up and remembers the state; every read +/// of it scans the definition once at most, stopping at the first match. +pub(super) fn attdef_base<'a>(block: &'a Block, tag: &str) -> Option<&'a Common> { + let token = block.entities.content_token(); + let want = tag.to_ascii_uppercase(); + let found = ATTDEF_INDEXES + .try_with(|cell| { + let Ok(mut ix) = cell.try_borrow_mut() else { return scan_attdef(block, tag) }; + if let Some(by_tag) = ix.by_store.get(&token) { + return by_tag.get(&want).copied(); + } + if ix.too_large.contains(&token) { + return scan_attdef(block, tag); + } + let Some(by_tag) = attdef_index_within(block, MAX_INDEXED_TAGS) else { + if ix.too_large.len() >= MAX_TOO_LARGE { + ix.too_large.clear(); + } + ix.too_large.insert(token); + return scan_attdef(block, tag); + }; + let found = by_tag.get(&want).copied(); + let cost = by_tag.len().max(1); + if ix.tags.saturating_add(cost) > MAX_INDEXED_TAGS { + ix.by_store.clear(); + ix.tags = 0; + } + ix.tags = ix.tags.saturating_add(cost); + ix.by_store.insert(token, by_tag); + found + }) + .unwrap_or_else(|_| scan_attdef(block, tag)); + block.entities.get(found?).map(|e| &e.common) +} + +/// One more definition entity examined (counted in tests). +fn count_attdef_visit() { + #[cfg(test)] + ATTDEF_VISITS.with(|n| n.set(n.get().saturating_add(1))); +} + +/// How many definition entities attribute reads have examined on this thread. +#[cfg(test)] +pub(crate) fn attdef_definition_visits() -> u64 { + ATTDEF_VISITS.with(std::cell::Cell::get) +} + +/// Start a definition-visit count from zero. +#[cfg(test)] +pub(crate) fn reset_attdef_definition_visits() { + ATTDEF_VISITS.with(|n| n.set(0)); +} + /// `AcadAnnotative` xdata marking an annotative style or block. pub(super) fn annotative_xdata(w: &mut W) { w.s(1001, "AcadAnnotative"); @@ -146,13 +275,10 @@ pub(super) fn layer_and_props(w: &mut W, c: &Common, base: Option<&Common>) { } } -/// The properties attribute `a` of block reference `e` is drawn with: its own, else its -/// definition's, from the block's definitions by tag `defs`; an attribute that takes layer 0 from -/// its definition is on the reference's layer, one set on layer 0 itself stays there. Also the -/// definition's properties. -pub(super) fn attrib_common(e: &Entity, defs: &std::collections::BTreeMap, &Entity>, a: &Attrib) -> (Common, Common) { - let def = defs.get(&cadcraft_doc::TagKey(&a.tag)); - let base = def.map(|de| de.common.clone()).unwrap_or_default(); +/// Attribute `a` takes its own properties over its definition's. A layer 0 inherited from the +/// definition takes the reference's layer; an explicit layer 0 stays. Return both properties. +pub(super) fn attrib_common(e: &Entity, a: &Attrib, base: Option<&Common>) -> (Common, Common) { + let base = base.cloned().unwrap_or_default(); let mut c = a.props.over(&base); if a.props.layer.is_none() && c.layer == "0" { c.layer.clone_from(&e.common.layer); diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 4668434cb..fb7494983 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -3,7 +3,8 @@ use super::common::{attrib_common, common, common_x, dim_xdata, layer_and_props, use super::ctx::Ctx; use super::layout::paper_view; use super::{ - Bounds2, Color, DimKind, Drawing, Entity, EntityKind, Gradient, Handle, HashMap, Hatch, Leader, MLeader, Point, Vec2, Vec3, Version, W, dxf_ext, + Attrib, Bounds2, Color, Common, DimKind, Drawing, Entity, EntityKind, Gradient, Handle, HashMap, Hatch, Leader, MLeader, Point, Vec2, Vec3, + Version, W, dxf_ext, }; /// The persistent reactors of boundary objects: each source object of an associative hatch in @@ -425,33 +426,45 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b // The block's definitions by tag, gathered once for all the attributes (#1923). let defs = d.block(&i.block).map(|b| b.attdefs_by_tag()).unwrap_or_default(); for (index, a) in i.attribs.iter().enumerate() { - let ah = w.h(); - w.s(0, "ATTRIB"); - w.s(5, ah); - w.s(330, e.handle.hex()); - w.s(100, "AcDbEntity"); - let (c, base) = attrib_common(e, &defs, a); - layer_and_props(w, &c, Some(&base)); - // Hidden with its definition (a dynamic block's visibility state hides it). - if !base.visible { - w.i(60, 1); - } - w.s(100, "AcDbText"); - text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index)); - if cx.target >= Version::R2007 { - multiline_tags(w, a, false); - } + let base = defs.get(&cadcraft_doc::TagKey(&a.tag)).map(|de| &de.common); + attrib_record(w, d, e, index, a, base, cx); } - let sh = w.h(); - w.s(0, "SEQEND"); - w.s(5, sh); - w.s(330, e.handle.hex()); - w.s(100, "AcDbEntity"); - w.s(8, &e.common.layer); + seqend_record(w, e); } } } +/// One ATTRIB record of the block reference `e`, for its attribute `a` (as written after its +/// INSERT): its handle is a new one, its owner the reference's. +pub(super) fn attrib_record(w: &mut W, d: &Drawing, e: &Entity, index: usize, a: &Attrib, base: Option<&Common>, cx: &Ctx) { + let ah = w.h(); + w.s(0, "ATTRIB"); + w.s(5, ah); + w.s(330, e.handle.hex()); + w.s(100, "AcDbEntity"); + let (c, base) = attrib_common(e, a, base); + layer_and_props(w, &c, Some(&base)); + // Hidden with its definition (a dynamic block's visibility state hides it). + if !base.visible { + w.i(60, 1); + } + w.s(100, "AcDbText"); + text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index)); + if cx.target >= Version::R2007 { + multiline_tags(w, a, false); + } +} + +/// The SEQEND record that ends a block reference's attributes (written after its last ATTRIB). +pub(super) fn seqend_record(w: &mut W, e: &Entity) { + let sh = w.h(); + w.s(0, "SEQEND"); + w.s(5, sh); + w.s(330, e.handle.hex()); + w.s(100, "AcDbEntity"); + w.s(8, &e.common.layer); +} + fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) { if let EntityKind::Dimension(dm) = &e.kind { w.s(0, "DIMENSION"); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 352a4cdc4..776e6d7fb 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -40,7 +40,7 @@ pub use cadcraft_doc::Format; pub use craft_dxf::Version; pub use dxf_raw::{ObjectRecord, object_records}; pub use dxf_read::entity_from_groups; -pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, proxies_lost}; +pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, entity_sub_record, proxies_lost}; pub use pdf::{PdfOptions, pdf, plot}; /// How a drawing is saved as DXF or DWG. diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 305055247..47dcf6816 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -5487,3 +5487,324 @@ fn a_layer_state_saved_before_masks_restores_everything() { let got: Vec<(&str, u32, &str, &str)> = states.iter().map(|s| (s.name.as_str(), s.mask, s.current.as_str(), s.description.as_str())).collect(); assert_eq!(got, [("S", LayerState::ALL, "", "")]); } + +/// The value of group `code` in `tags`. +fn tag_text(tags: &[craft_dxf::Tag], code: i32) -> Option { + tags.iter().find(|t| t.code == code).map(craft_dxf::Tag::str) +} + +/// An INSERT with two attributes, for the records written after it (#1660). +fn insert_with_attribs() -> (Drawing, Handle) { + let text = |value: &str| Text { + insert: Vec3::new(1.0, 2.0, 0.0), + align_pt: None, + height: 2.5, + value: value.into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + backwards: false, + upside_down: false, + }; + let attrib = |tag: &str, value: &str| Attrib { + tag: tag.into(), + text: text(value), + invisible: false, + constant: false, + prompt: String::new(), + props: AttribProps::default(), + multiline: None, + modes: AttribModes::default(), + }; + let mut d = Drawing::new_metric(); + let insert = + Insert { block: "B".into(), insert: Vec3::new(10.0, 10.0, 0.0), attribs: vec![attrib("T1", "A1"), attrib("T2", "A2")], ..Insert::default() }; + let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add"); + (d, h) +} + +#[test] +fn an_inserts_records_are_read_one_at_a_time() { + let (mut d, h) = insert_with_attribs(); + let e = d.entity(h).expect("the reference"); + // The reference's own list is its record, with no attribute in it. + let (kind, own) = entity_groups(&d, e); + assert_eq!(kind, "INSERT"); + assert_eq!(tag_text(&own, 66).as_deref(), Some("1")); + // The records after it: each attribute, then the SEQEND. + let first = entity_sub_record(&d, e, 0).expect("the first attribute"); + assert_eq!(first.0, "ATTRIB"); + assert_eq!((tag_text(&first.1, 2).as_deref(), tag_text(&first.1, 1).as_deref()), (Some("T1"), Some("A1"))); + assert_eq!(tag_text(&first.1, 10).as_deref(), Some("1.0"), "its place is written as for the file"); + let second = entity_sub_record(&d, e, 1).expect("the second attribute"); + assert_eq!((tag_text(&second.1, 2).as_deref(), tag_text(&second.1, 1).as_deref()), (Some("T2"), Some("A2"))); + let seqend = entity_sub_record(&d, e, 2).expect("the SEQEND"); + assert_eq!(seqend.0, "SEQEND"); + assert!(entity_sub_record(&d, e, 3).is_none(), "past the last record"); + // They have no handle or owner of their own in the drawing: their names are LISP's. + for tags in [&first.1, &second.1, &seqend.1] { + assert!(tags.iter().all(|t| t.code != 5 && t.code != 330), "{tags:?}"); + } + // An entity with no records after it has none, at any index. + let line = d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).expect("line"); + let e = d.entity(line).expect("the line"); + assert!(entity_sub_record(&d, e, 0).is_none()); +} + +#[test] +fn an_attributes_value_reads_as_lisp_text() { + let (mut d, h) = insert_with_attribs(); + // A caret is written `^ ` and read back as the caret LISP typed: what `entget` lists is + // what `entmod` takes again. + d.modify_entity(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind + && let Some(a) = i.attribs.first_mut() + { + a.text.value = "10^2".into(); + } + }) + .expect("modify"); + let e = d.entity(h).expect("the reference"); + let (_, tags) = entity_sub_record(&d, e, 0).expect("the first attribute"); + assert_eq!(tag_text(&tags, 1).as_deref(), Some("10^2")); +} + +/// Reading every attribute of one reference examines the block definition once, and an edit of +/// the definition once more. +#[test] +fn reading_attributes_scans_the_definition_once() { + const M: usize = 32; + let tags: Vec = (0..M).map(|i| format!("T{i}")).collect(); + let mut d = Drawing::new_metric(); + let h = add_attributed(&mut d, "B", 1, &tags, "WALLS"); + crate::dxf_write::reset_attdef_definition_visits(); + let e = d.entity(h).expect("the reference").clone(); + for i in 0..M { + let (kind, tags) = entity_sub_record(&d, &e, i).expect("attribute"); + assert_eq!(kind, "ATTRIB"); + assert_eq!(tag_text(&tags, 8).as_deref(), Some("WALLS")); + } + assert_eq!(crate::dxf_write::attdef_definition_visits(), M as u64, "one pass over the definition, not one scan per attribute"); + // An edit of the definition is read on the next read, with one more pass. + set_attdef_layer(&mut d, "B", "DOOR"); + let before = crate::dxf_write::attdef_definition_visits(); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("DOOR")); + assert_eq!(crate::dxf_write::attdef_definition_visits() - before, M as u64, "the edit builds the index once"); +} + +/// An attribute with value V and `tag`, for the definition tests below. +fn plain_attrib(tag: &str) -> Attrib { + Attrib { + tag: tag.into(), + text: Text { + insert: Vec3::ZERO, + align_pt: None, + height: 1.0, + value: "V".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + backwards: false, + upside_down: false, + }, + invisible: false, + constant: false, + prompt: String::new(), + props: AttribProps::default(), + multiline: None, + modes: AttribModes::default(), + } +} + +/// Block `name` with an ATTDEF per tag on `layer`, its handles from `first` up, and a reference +/// to it with the same attributes. The reference's handle. +fn add_attributed(d: &mut Drawing, name: &str, first: u64, tags: &[String], layer: &str) -> Handle { + let mut block = Block::new(name); + for (i, tag) in tags.iter().enumerate() { + let mut e = Entity::new(Handle(first + i as u64), EntityKind::AttDef(plain_attrib(tag))); + e.common.layer = layer.into(); + block.entities.push(e); + } + d.blocks.insert(name.into(), std::sync::Arc::new(block)); + let insert = Insert { block: name.into(), attribs: tags.iter().map(|t| plain_attrib(t)).collect(), ..Insert::default() }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add") +} + +/// Block `name`'s first ATTDEF moved to `layer`: one edit of the definition's store. +fn set_attdef_layer(d: &mut Drawing, name: &str, layer: &str) { + let b = std::sync::Arc::make_mut(d.blocks.get_mut(name).expect("block")); + let h = b.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_))).map(|e| e.handle).expect("an ATTDEF"); + assert!(b.entities.modify(h, |e| e.common.layer = layer.into())); +} + +/// Block B with ATTDEF T on layer BASE and ATTDEF U on layer DOOR, and a reference to it with +/// both attributes. The reference's handle. +fn add_on_two_layers(d: &mut Drawing) -> Handle { + let h = add_attributed(d, "B", 1, &["T".to_string(), "U".to_string()], "DOOR"); + set_attdef_layer(d, "B", "BASE"); + h +} + +/// Block `name`'s ATTDEFs given `tags` in their order, so a tag can pass to another ATTDEF's +/// handle: one edit of the definition's store for each ATTDEF. +fn set_attdef_tags(d: &mut Drawing, name: &str, tags: &[&str]) { + let b = std::sync::Arc::make_mut(d.blocks.get_mut(name).expect("block")); + let handles: Vec = b.entities.iter().filter(|e| matches!(e.kind, EntityKind::AttDef(_))).map(|e| e.handle).collect(); + assert_eq!(handles.len(), tags.len(), "a tag for each ATTDEF"); + for (h, tag) in handles.into_iter().zip(tags) { + assert!(b.entities.modify(h, |e| { + if let EntityKind::AttDef(ad) = &mut e.kind { + ad.tag = (*tag).into(); + } + })); + } +} + +/// The layer reference `h`'s first ATTRIB record is read on. +fn read_attrib_layer(d: &Drawing, h: Handle) -> Option { + let e = d.entity(h)?; + let (_, tags) = entity_sub_record(d, e, 0)?; + tag_text(&tags, 8) +} + +/// The layer the first ATTRIB of `d`'s DXF is written on. +fn written_attrib_layer(d: &Drawing) -> Option { + let text = write_dxf(d); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let at = lines.windows(2).position(|w| w == ["0", "ATTRIB"])?; + let pairs = lines.get(at + 2..)?.chunks(2); + pairs.take_while(|p| p.first() != Some(&"0")).find(|p| p.first() == Some(&"8")).and_then(|p| p.get(1)).map(|s| s.to_string()) +} + +/// Two copies of one drawing, each with its definition edited: each reads and writes its own +/// definition's properties, whichever was read first. T stays with the first ATTDEF in one copy +/// and passes to the second in the other, so an index kept from one copy names the wrong ATTDEF +/// in the other. +#[test] +fn copies_edited_apart_read_their_own_definitions() { + let mut d = Drawing::new_metric(); + let h = add_on_two_layers(&mut d); + let (mut a, mut b) = (d.clone(), d.clone()); + set_attdef_layer(&mut a, "B", "WALLS"); + set_attdef_tags(&mut b, "B", &["U", "T"]); + assert_eq!(read_attrib_layer(&a, h).as_deref(), Some("WALLS")); + assert_eq!(read_attrib_layer(&b, h).as_deref(), Some("DOOR"), "the other copy's edit is its own"); + assert_eq!(written_attrib_layer(&b).as_deref(), Some("DOOR")); + assert_eq!(written_attrib_layer(&a).as_deref(), Some("WALLS")); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("BASE"), "the drawing both came from is unchanged"); +} + +/// Undo back to a state, then a different edit of the definition: the edit that was undone is +/// not read or written again. The second edit passes T to the other ATTDEF, so the index of +/// the undone edit names the wrong one. +#[test] +fn an_edit_after_undo_reads_its_own_definition() { + let mut d = Drawing::new_metric(); + let h = add_on_two_layers(&mut d); + let mut undone = d.clone(); + set_attdef_layer(&mut undone, "B", "WALLS"); + assert_eq!(read_attrib_layer(&undone, h).as_deref(), Some("WALLS")); + // Undo: the drawing before the edit, then another edit, read nothing in between. + let mut redone = d.clone(); + set_attdef_tags(&mut redone, "B", &["U", "T"]); + assert_eq!(written_attrib_layer(&redone).as_deref(), Some("DOOR")); + assert_eq!(read_attrib_layer(&redone, h).as_deref(), Some("DOOR")); +} + +/// Reads that alternate between two references of two blocks examine each definition once. +#[test] +fn alternating_definitions_are_each_indexed_once() { + const M: usize = 64; + let tags: Vec = (0..M).map(|i| format!("T{i}")).collect(); + let mut d = Drawing::new_metric(); + let first = add_attributed(&mut d, "B1", 1, &tags, "ONE"); + let second = add_attributed(&mut d, "B2", 1 + M as u64, &tags, "TWO"); + let (first, second) = (d.entity(first).expect("first").clone(), d.entity(second).expect("second").clone()); + crate::dxf_write::reset_attdef_definition_visits(); + for i in 0..M { + for (e, layer) in [(&first, "ONE"), (&second, "TWO")] { + let (_, tags) = entity_sub_record(&d, e, i).expect("attribute"); + assert_eq!(tag_text(&tags, 8).as_deref(), Some(layer)); + } + } + assert_eq!(crate::dxf_write::attdef_definition_visits(), 2 * M as u64, "each definition is read once, not once per read"); +} + +/// Of two ATTDEFs whose tags differ only in case, the first is the attribute's definition. +#[test] +fn the_first_definition_of_a_tag_in_any_case_is_used() { + let mut block = Block::new("C"); + for (i, (tag, layer)) in [("t", "FIRST"), ("T", "SECOND")].into_iter().enumerate() { + let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(tag))); + e.common.layer = layer.into(); + block.entities.push(e); + } + let mut d = Drawing::new_metric(); + d.blocks.insert("C".into(), std::sync::Arc::new(block)); + let insert = Insert { block: "C".into(), attribs: vec![plain_attrib("T")], ..Insert::default() }; + let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add"); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST")); +} + +/// A definition with more distinct tags than the index may store (`1 << 18`) is not cached. +/// The first read builds and drops one bounded index and remembers the state; later reads go +/// straight to one scan that stops at the first match. The first ATTDEF of the tag still wins, +/// in any case. +#[test] +fn an_oversized_definition_is_not_indexed() { + const LIMIT: usize = 1 << 18; + // One extra distinct tag past the budget, plus a second ATTDEF of the first tag in + // another case, so the first match is not the only entity of that tag. + let mut tags = Vec::with_capacity(LIMIT + 2); + tags.push("Ab".to_string()); + tags.push("AB".to_string()); + for i in 0..LIMIT { + tags.push(format!("U{i}")); + } + let mut block = Block::new("HUGE"); + for (i, tag) in tags.iter().enumerate() { + let layer = if i == 0 { "FIRST" } else { "SECOND" }; + let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(tag))); + e.common.layer = layer.into(); + block.entities.push(e); + } + let mut d = Drawing::new_metric(); + d.blocks.insert("HUGE".into(), std::sync::Arc::new(block)); + let insert = Insert { block: "HUGE".into(), attribs: vec![plain_attrib("ab")], ..Insert::default() }; + let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add"); + crate::dxf_write::reset_attdef_definition_visits(); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST")); + let first = crate::dxf_write::attdef_definition_visits(); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST")); + let second = crate::dxf_write::attdef_definition_visits() - first; + // The failed index walks every entity (the last tag is the one past the budget), then + // the scan reads the first entity, where the tag matches. + assert_eq!(first, (LIMIT as u64) + 3, "one bounded pass, then the first match"); + assert_eq!(second, 1, "the state is remembered as too large: the next read scans to the first match only"); +} + +/// An attribute whose ATTDEF lies past the index budget, at the end of an oversized definition, +/// still reads and writes that definition's properties: the scan for a definition past the +/// budget covers all of it. +#[test] +fn a_definition_past_the_index_budget_matches_its_last_tag() { + const LIMIT: usize = 1 << 18; + let mut block = Block::new("HUGE"); + for i in 0..=LIMIT { + let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(&format!("U{i}")))); + e.common.layer = if i == LIMIT { "LAST".into() } else { "OTHER".into() }; + block.entities.push(e); + } + let mut d = Drawing::new_metric(); + d.blocks.insert("HUGE".into(), std::sync::Arc::new(block)); + let insert = Insert { block: "HUGE".into(), attribs: vec![plain_attrib(&format!("u{LIMIT}"))], ..Insert::default() }; + let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add"); + assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("LAST"), "entget reads the matching definition"); + assert_eq!(written_attrib_layer(&d).as_deref(), Some("LAST"), "the written ATTRIB keeps the definition's layer"); +} diff --git a/docs/autolisp.md b/docs/autolisp.md index 3ce9703f4..7d3fd1cfe 100644 --- a/docs/autolisp.md +++ b/docs/autolisp.md @@ -134,6 +134,32 @@ xref (flag 4), an invalid name, a block that inserts itself and a block being ed (REFEDIT) return nil. A definition stays open across routines until ENDBLK, but a routine that fails drops the one it began. +An INSERT in the drawing (not one inside a block definition) has its attributes as records +after it, and `entnext` reaches them: from the block reference to its first ATTRIB, from an +ATTRIB to the next, and from the last one to the SEQEND (group `-2`, its reference's name), then +on to the next main entity or nil. `entget` of an ATTRIB lists its groups with `-2` (its +reference) beside its name (group `-1`). CADCraft keeps no handle of its own for these records (a +DXF file's are the writer's), so their names are not handles: such a name is an entity name +(`type` gives `ENAME`) that no object of any drawing can ever have, printed as the reference's +handle, a dot and a number (``). `handent` never returns one, and its list has +no group 5. `entmod` of an ATTRIB takes its value (group 1) only, as one undo step, and leaves its +tag, place, flags and properties as they are; any other edit, including one of the layout, owner, +handle or other groups the entity can't set, a `SEQEND` list, `entdel` and `entmake` of one +return nil and change nothing. `entupd` of one returns its name while it holds. A selection set +holds objects of the drawing only: `ssadd`, `ssdel` and `ssmemb` of such a name return nil, and +`command` given one picks nothing. `trans` does not take a record name: the coordinate system +has to be a number, an entity name or an extrusion direction, and a record name is an argument +error. `eq` and `equal` are true only for the same record name, the one a later walk returns +while that record holds, and they are false for another record and for an entity name. A fuzz +distance does not change that result. A name holds while its reference keeps that record in its +place with that tag: erasing the reference (also when OOPS or `entdel` brings it back), ATTSYNC, +-BLOCKREPLACE, opening and closing the Block Editor, Undo, Redo, a change taken back (a +refused or failed command) and a command that puts an earlier drawing back (MOCORO's Undo, a +grip copy's Undo, and the other restores of a saved drawing) end it (erasing another object +does not), and a name that ended names nothing (nil), never another record. A drawing holds at +most 65,536 such names at once; at the limit `entnext` gives no new one (nil) until names end +and make room. + Non-graphic objects (the named object dictionary and its dictionaries, layouts, table records) are listed as a DXF file of the drawing holds them, pointers as entity names and group 5 (105 for a DIMSTYLE) as the object's own name. An object read from a file keeps that file's handle as its name, so