Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -113,6 +113,43 @@ impl Foreign {
&& self.appids.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 and the name really changes (not only its case).
pub fn rename_shared(this: &mut std::sync::Arc<Foreign>, kinds: &[&str], from: &str, to: &str) {
if !from.trim().eq_ignore_ascii_case(to.trim()) && this.names(kinds, from) {
std::sync::Arc::make_mut(this).rename(kinds, from, to);
}
}

/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
/// (320) that holds its `ASM_Data`. A 320 without one doesn't keep an entity's geometry.
pub fn data_store_entities(&self) -> std::collections::BTreeSet<Handle> {
Expand Down Expand Up @@ -390,3 +427,42 @@ pub fn class_number<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)> +
pub fn class_index(number: Option<i64>) -> Option<usize> {
usize::try_from(number?.checked_sub(500)?).ok()
}

#[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 @@ -251,6 +251,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 @@ -556,6 +556,7 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
let st = d.text_styles.by_name_mut(&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 @@ -794,6 +795,7 @@ fn run_dimstyle_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
let st = d.dim_styles.by_name_mut(&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 @@ -1017,6 +1019,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
let st = d.linetypes.by_name_mut(&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 @@ -102,6 +104,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
90 changes: 90 additions & 0 deletions crates/engine/tests/rename_keeps_extras.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
//! 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);
let layers: Vec<&str> = d.layers.iter().map(|l| l.name.as_str()).filter(|n| n.eq_ignore_ascii_case("walls")).collect();
assert_eq!(layers, ["WALLS"], "the layer is saved under the new spelling");
let blocks: Vec<(&str, &str)> =
d.blocks.iter().filter(|(k, _)| k.eq_ignore_ascii_case("door")).map(|(k, b)| (k.as_str(), b.name.as_str())).collect();
assert_eq!(blocks, [("DOOR", "DOOR")], "the block is saved under the new spelling");
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 @@ -114,7 +114,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) | 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 | 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); 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 |

Expand Down Expand Up @@ -170,6 +170,7 @@ our output in AutoCAD black-box.
| 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) |
| 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) |
| 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) |
| 2026-10-13 | minor | RENAME keeps a layer's, block's, linetype's, text style's or dimension style's xdata, extension dictionary and reactors; a renamed dynamic block stays dynamic |
| 2026-11-03 | minor | View twist (group 51) read and written for each tiled viewport (VPORT) and each layout viewport (VIEWPORT); named views' twist (VIEW group 50) now applied on Restore; a twisted view's centre (VIEWPORT and VPORT group 12, VIEW group 10) is read and written in display coordinates, turned by the twist |
| 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 |
Expand Down
Loading