Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
68d29dd
RENAME keeps a layer's, block's or style's xdata, extension dictionar…
mattlafy Oct 13, 2026
0fbc35f
Merge remote-tracking branch 'upstream/main' into fix/rename-keeps-ex…
mattlafy Oct 20, 2026
38c9747
A case-only rename leaves the shared foreign data uncloned
mattlafy Oct 20, 2026
b01bef1
A case-only rename test checks the saved layer and block names exactly
mattlafy Oct 20, 2026
2514e14
Merge remote-tracking branch 'upstream/main' into pr/rename-keeps-extras
mattlafy Oct 25, 2026
a725c40
Merge remote-tracking branch 'upstream/main' into pr/rename-keeps-extras
mattlafy Nov 3, 2026
4dc76df
docs: RENAME keeps the foreign data of layers, blocks, linetypes, tex…
mattlafy Nov 3, 2026
11c3a9d
Merge remote-tracking branch 'upstream/main' into pr/rename-keeps-extras
mattlafy Nov 5, 2026
41663ad
Merge remote-tracking branch 'upstream/main' into pr/rename-keeps-extras
mattlafy Nov 8, 2026
3d9e323
Merge remote-tracking branch 'upstream/main' into pr/rename-keeps-extras
mattlafy Nov 11, 2026
ffd5c9c
Merge branch 'main' into pr/rename-keeps-extras
FredApps Nov 28, 2026
4e675e9
Merge branch 'main' into pr/rename-keeps-extras
FredApps Nov 28, 2026
9f4a7e3
Merge branch 'main' into pr/rename-keeps-extras
FredApps Nov 28, 2026
57174e8
Merge branch 'main' into pr/rename-keeps-extras
FredApps Nov 28, 2026
698fabb
Merge branch 'main' into pr/rename-keeps-extras
FredApps Nov 28, 2026
9264bea
Merge branch 'main' into pr/rename-keeps-extras
FredApps Nov 28, 2026
78e8f9e
Merge branch 'main' into pr/rename-keeps-extras
FredApps Nov 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions crates/doc/src/foreign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,84 @@ impl Foreign {
&& self.data_store.is_empty()
}

/// Re-key what is kept for the record named `from` under each of `kinds` (e.g. `["LAYER"]`, or
/// `["BLOCK_RECORD", "BLOCK", "ENDBLK"]` for a block) to the name `to`, after a rename: its
/// extras ([`Foreign::records`]) and the roles of its file handles ([`Foreign::targets`]), so
/// saving writes its xdata, extension dictionary and reactors on the renamed record. Names
/// compare trimmed and upper-case, as the reader keys them, so a rename that only changes case
/// changes nothing.
pub fn rename(&mut self, kinds: &[&str], from: &str, to: &str) {
let (from, to) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase());
if from == to {
return;
}
for kind in kinds {
let old: ForeignKey = ((*kind).to_string(), from.clone());
let new: ForeignKey = ((*kind).to_string(), to.clone());
if let Some(extra) = self.records.remove(&old) {
self.records.insert(new.clone(), extra);
}
self.targets.values_mut().filter(|k| **k == old).for_each(|k| *k = new.clone());
}
}

/// Whether anything is kept for the record named `from` under one of `kinds`: what
/// [`Foreign::rename`] would re-key.
pub fn names(&self, kinds: &[&str], from: &str) -> bool {
let from = from.trim().to_ascii_uppercase();
let hit = |k: &ForeignKey| k.1 == from && kinds.contains(&k.0.as_str());
self.records.keys().any(hit) || self.targets.values().any(hit)
}

/// [`Foreign::rename`] on a drawing's shared copy, which is cloned only when it keeps
/// something for the renamed record.
pub fn rename_shared(this: &mut std::sync::Arc<Foreign>, kinds: &[&str], from: &str, to: &str) {
if this.names(kinds, from) {
std::sync::Arc::make_mut(this).rename(kinds, from, to);
}
}

/// The entities the data store has records for (their 320 handles).
pub fn data_store_entities(&self) -> std::collections::BTreeSet<Handle> {
self.data_store.iter().filter(|t| t.code == 320).filter_map(|t| Handle::parse_hex(t.value.trim())).collect()
}
}

#[cfg(test)]
mod tests {
use super::*;

fn key(k: &str, n: &str) -> ForeignKey {
(k.to_string(), n.to_string())
}

#[test]
fn rename_rekeys_records_and_targets_of_the_given_kinds_only() {
let mut f = Foreign::default();
let xdict = ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() };
f.records.insert(key("BLOCK_RECORD", "DOOR"), xdict.clone());
f.records.insert(key("LAYER", "DOOR"), ForeignExtra { reactors: vec![Handle(0x41)], ..ForeignExtra::default() });
f.targets.insert(Handle(0x10), key("BLOCK_RECORD", "DOOR"));
f.targets.insert(Handle(0x11), key("BLOCK", "DOOR"));
f.targets.insert(Handle(0x12), key("LAYER", "DOOR"));
f.rename(&["BLOCK_RECORD", "BLOCK", "ENDBLK"], "Door", "Gate");
assert_eq!(f.records.get(&key("BLOCK_RECORD", "GATE")), Some(&xdict));
assert!(!f.records.contains_key(&key("BLOCK_RECORD", "DOOR")));
assert!(f.records.contains_key(&key("LAYER", "DOOR")), "another kind with the same name stays");
assert_eq!(f.targets.get(&Handle(0x10)), Some(&key("BLOCK_RECORD", "GATE")));
assert_eq!(f.targets.get(&Handle(0x11)), Some(&key("BLOCK", "GATE")));
assert_eq!(f.targets.get(&Handle(0x12)), Some(&key("LAYER", "DOOR")));
}

#[test]
fn rename_shared_leaves_an_unrelated_drawing_shared() {
let mut f = Foreign::default();
f.records.insert(key("LAYER", "A"), ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() });
let mut a = std::sync::Arc::new(f);
let snapshot = a.clone();
Foreign::rename_shared(&mut a, &["LAYER"], "B", "C");
assert!(std::sync::Arc::ptr_eq(&a, &snapshot));
Foreign::rename_shared(&mut a, &["LAYER"], "a", "c");
assert!(a.records.contains_key(&key("LAYER", "C")) && snapshot.records.contains_key(&key("LAYER", "A")));
}
}
1 change: 1 addition & 0 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
*l = updated;
if let Some(nn) = new_name {
l.name = nn.clone();
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["LAYER"], &old, &nn);
// Re-point entities in model space, every layout and every block definition.
repoint(&mut d.model, &old, &nn);
for layout in &mut d.layouts {
Expand Down
3 changes: 3 additions & 0 deletions crates/engine/src/cmd/props.rs
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,7 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
let st = d.text_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("style.rename", "no such style"))?;
st.name = to.clone();
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["STYLE"], &from, &to);
// References follow the new name.
let fix = |n: &mut String| {
if n.eq_ignore_ascii_case(&from) {
Expand Down Expand Up @@ -826,6 +827,7 @@ fn run_dimstyle_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
let st = d.dim_styles.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
st.name = to.clone();
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["DIMSTYLE"], &from, &to);
if d.header.str("DIMSTYLE", "Standard").eq_ignore_ascii_case(&from) {
d.header.set_str("DIMSTYLE", &to);
}
Expand Down Expand Up @@ -1044,6 +1046,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
let st = d.linetypes.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("rename", "no such linetype"))?;
st.name = to.clone();
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["LTYPE"], &from, &to);
// References follow the new name.
let fix = |n: &mut String| {
if n.eq_ignore_ascii_case(&from) {
Expand Down
9 changes: 9 additions & 0 deletions crates/engine/src/cmd/props/rename.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use std::sync::Arc;

use cadcraft_doc::foreign::Foreign;
use cadcraft_doc::{Drawing, EntityKind, EntityStore, Handle};
use serde_json::json;

Expand Down Expand Up @@ -54,6 +55,7 @@ pub(super) fn block(s: &mut Session, from: &str, to: &str) -> Result<()> {
let mut b = d.blocks.remove(&key).ok_or_else(|| bad("rename", "no such block"))?;
Arc::make_mut(&mut b).name = to.clone();
d.blocks.insert(to.clone(), b);
Foreign::rename_shared(&mut d.foreign, &["BLOCK_RECORD", "BLOCK", "ENDBLK"], &key, &to);
let uses = |k: &EntityKind| match k {
EntityKind::Insert(i) => i.block.eq_ignore_ascii_case(&key),
EntityKind::MLeader(m) => m.block.as_ref().is_some_and(|b| b.block.eq_ignore_ascii_case(&key)),
Expand Down Expand Up @@ -100,6 +102,13 @@ pub(super) fn simple(s: &mut Session, table: &str, from: &str, to: &str) -> Resu
}
let n = names.iter_mut().find(|n| n.eq_ignore_ascii_case(from)).ok_or_else(|| bad("rename", format!("no {table} `{from}`")))?;
let old = std::mem::replace(&mut **n, to.clone());
let kind = match table {
"mleaderstyle" => "NOD/ACAD_MLEADERSTYLE",
"tablestyle" => "NOD/ACAD_TABLESTYLE",
"view" => "VIEW",
_ => "UCS",
};
Foreign::rename_shared(&mut d.foreign, &[kind], &old, &to);
let current = match table {
"mleaderstyle" => "CMLEADERSTYLE",
"tablestyle" => "CTABLESTYLE",
Expand Down
85 changes: 85 additions & 0 deletions crates/engine/tests/rename_keeps_extras.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
//! RENAME keeps what a renamed layer, block or style carries beyond what CADCraft models, as
//! AutoCAD does: other applications' xdata, its extension dictionary and reactors. A renamed
//! dynamic block stays dynamic, and saving writes the kept data on the new name.

use cadcraft_engine::Session;
use cadcraft_engine::doc::Drawing;
use cadcraft_engine::doc::dynblock::dynamic_block;
use serde_json::json;

/// DXF text from lines of `code value` (the value may be empty).
fn dxf(src: &str) -> String {
let mut out = String::new();
for line in src.lines().map(str::trim).filter(|l| !l.is_empty()) {
let (code, value) = line.split_once(' ').unwrap_or((line, ""));
out.push_str(&format!("{code}\n{value}\n"));
}
out
}

/// The dynamic DOOR block drawing (its BLOCK_RECORD has an extension dictionary holding the
/// block's evaluation graph), plus a layer WALLS carrying another application's xdata.
fn session() -> Session {
let layer = "0 TABLE\n2 LAYER\n5 2\n330 0\n100 AcDbSymbolTable\n70 1\n\
0 LAYER\n5 10\n330 2\n100 AcDbSymbolTableRecord\n100 AcDbLayerTableRecord\n2 Walls\n70 0\n62 3\n6 Continuous\n\
1001 ACME_TAGS\n1000 W-01\n1070 7\n0 ENDTAB\n";
let src = include_str!("../../io/tests/data/dynblock_door.txt").replace("\r\n", "\n").replacen(
"0 TABLE\n2 BLOCK_RECORD\n",
&format!("{layer}0 TABLE\n2 BLOCK_RECORD\n"),
1,
);
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "rename", None);
s
}

fn layer_xdata(d: &Drawing, name: &str) -> Vec<(i32, String)> {
let key = ("LAYER".to_string(), name.to_string());
d.foreign.records.get(&key).map(|x| x.xdata.iter().map(|t| (t.code, t.value.trim().to_string())).collect()).unwrap_or_default()
}

fn saved_and_read(s: &Session) -> Drawing {
cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap()
}

fn acme() -> Vec<(i32, String)> {
vec![(1001, "ACME_TAGS".into()), (1000, "W-01".into()), (1070, "7".into())]
}

#[test]
fn a_renamed_layer_keeps_its_xdata_through_a_save() {
let mut s = session();
assert_eq!(layer_xdata(s.doc().unwrap(), "WALLS"), acme());
s.execute("rename", &json!({ "table": "layer", "from": "Walls", "to": "Partitions" })).unwrap();
assert_eq!(layer_xdata(s.doc().unwrap(), "PARTITIONS"), acme());
let d = saved_and_read(&s);
assert!(d.layer("Partitions").is_some());
assert_eq!(layer_xdata(&d, "PARTITIONS"), acme());
s.execute("undo", &json!({})).unwrap();
assert_eq!(layer_xdata(s.doc().unwrap(), "WALLS"), acme(), "undo puts it back under the old name");
}

#[test]
fn a_renamed_dynamic_block_stays_dynamic_through_a_save() {
let mut s = session();
let before = dynamic_block(s.doc().unwrap(), "Door").expect("Door is a dynamic block");
s.execute("rename", &json!({ "table": "block", "from": "Door", "to": "Gate" })).unwrap();
let d = s.doc().unwrap();
assert!(d.block("Gate").is_some() && d.block("Door").is_none());
assert_eq!(dynamic_block(d, "Gate").map(|m| m.parameters.len()), Some(before.parameters.len()));
let d = saved_and_read(&s);
let after = dynamic_block(&d, "Gate").expect("Gate is still a dynamic block after a save");
assert_eq!(after.parameters.len(), before.parameters.len());
assert_eq!(after.actions.len(), before.actions.len());
}

#[test]
fn a_rename_that_only_changes_case_keeps_everything() {
let mut s = session();
s.execute("rename", &json!({ "table": "layer", "from": "Walls", "to": "WALLS" })).unwrap();
s.execute("rename", &json!({ "table": "block", "from": "Door", "to": "DOOR" })).unwrap();
let d = saved_and_read(&s);
assert_eq!(layer_xdata(&d, "WALLS"), acme());
assert!(dynamic_block(&d, "Door").is_some());
}
3 changes: 2 additions & 1 deletion docs/file-format-parity.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG
| Objects: LAYOUT, DICTIONARY, XRECORD, TABLESTYLE, DIMASSOC | yes | yes | |
| Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | |
| Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read | not editable |
| Foreign xdata, extension dictionaries, reactors, unmodelled objects, colour books | kept raw (#528); an entity's xdata is part of the entity, so COPY, MIRROR, ARRAY and paste keep it on the copies (EXPLODE pieces don't) | written back, handles remapped, references to deleted objects dropped | through DWG: xdata on table records and blocks, entity colour books and reactors, custom-class objects lost (acadrust) |
| 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 or 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) |
| Objects: dynamic block data (ACAD_EVALUATION_GRAPH, BLOCK…PARAMETER, BLOCK…ACTION, grips) | read into a model (`dynblock`, `blocks.dynamic`): parameters, visibility states, value sets, stretch and lookup actions; references: their dynamic block, values and custom properties (`blocks.reference`, Properties ▸ Custom, read-only); kept raw (#528) | written back as read; a changed visibility state is written as AutoCAD writes it (a new anonymous block with its `AcDbBlockRepBTag`, the objects' `AcDbBlockRepETag`, the reference's representation data) | visibility states (and lookups that set only them) can be changed (`blocks.reference.set`, Properties ▸ Custom); distances, positions and the actions they drive not yet; DWG open and save keep it too (checked with an AutoCAD dynamic block) |
| Handles and owners | entity handles kept; others regenerated | consistent | stable across CADCraft re-saves (#495); other programs' table and object handles renumbered once |

Expand Down Expand Up @@ -139,6 +139,7 @@ our output in AutoCAD black-box.
| Date | Change | Summary |
|---|---|---|
| 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) |
| 2026-10-13 | minor | RENAME keeps a layer's, block's or style's xdata, extension dictionary and reactors; a renamed dynamic block stays dynamic |
| 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) |
Expand Down