From ad6314967fab363a4bb987ce43cff3f27c06b7c7 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Tue, 27 Oct 2026 19:58:37 +0100 Subject: [PATCH 01/11] blocks: REFEDIT edits xrefs in place and writes their drawing back REFEDIT on an xref (or a block that came with one) edits it in place, and REFCLOSE Save writes the change into the source drawing (the old file kept as .bak, symbol prefixes removed, host symbols copied, handles kept) and reloads the xref. Refused for read-only files, files locked by another program or open in another tab, and files changed since they were loaded or during the edit. Nested references are picked through their parents (path, nested, refedit.levels, "Select nesting level [OK/Next]"). Everything outside the working set is drawn faded (XFADECTL), and an Edit Reference bar offers Add to/Remove from Working Set and Save/Discard Changes. Gap F2. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/doc/src/lib.rs | 2 +- crates/doc/src/refedit.rs | 22 + crates/engine/src/cmd/blocks/refedit.rs | 580 ++++++++++++++++++++-- crates/engine/src/cmd/blocks/xref/load.rs | 50 +- crates/engine/src/sysvars/table.rs | 2 + crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/refedit.rs | 5 +- crates/engine/tests/it/refedit_xref.rs | 243 +++++++++ crates/render/src/draw.rs | 9 + crates/ui-egui/src/canvas.rs | 3 + crates/ui-egui/src/canvas/refedit.rs | 72 +++ crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + docs/gaps.md | 7 +- docs/target-app-parity.md | 5 +- 15 files changed, 956 insertions(+), 57 deletions(-) create mode 100644 crates/engine/tests/it/refedit_xref.rs create mode 100644 crates/ui-egui/src/canvas/refedit.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index eafea9e27..49cd46863 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -31,7 +31,7 @@ pub use gdt::*; pub use header::{HVal, Header}; pub use plotstyle::*; pub use plotter::*; -pub use refedit::{RefEdit, WorkItem}; +pub use refedit::{RefEdit, WorkItem, XrefSource}; pub use store::EntityStore; pub use tables::*; diff --git a/crates/doc/src/refedit.rs b/crates/doc/src/refedit.rs index eb0927365..78dfa1764 100644 --- a/crates/doc/src/refedit.rs +++ b/crates/doc/src/refedit.rs @@ -42,6 +42,28 @@ pub struct RefEdit { /// Block objects taken out of the working set with their edits (block coordinates, the block /// object's handle). pub released: Vec, + /// The nested references picked through to reach the edited block: block references inside + /// block definitions, outermost first. Empty when the picked reference's own block is edited. + pub path: Vec, + /// Set when the edited block comes from an external reference: REFCLOSE Save writes it back + /// into its source drawing. + pub xref: Option, +} + +/// Where an xref edited in place is written back to. +#[derive(Clone, Debug, PartialEq)] +pub struct XrefSource { + /// The xref (its block name in this drawing). + pub xref: String, + /// The source drawing file. + pub file: String, + /// The block of the source drawing being edited; `None` for its model space. + pub block: Option, + /// The file's size and modification time (nanoseconds since 1970) when the edit began. + pub stamp: Option<(u64, u128)>, + /// Edited block objects (their handles in this drawing) and the objects of the source + /// drawing they were loaded from. + pub sources: Vec<(Handle, Handle)>, } impl RefEdit { diff --git a/crates/engine/src/cmd/blocks/refedit.rs b/crates/engine/src/cmd/blocks/refedit.rs index 0a61122a5..1e3b213db 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -1,42 +1,57 @@ -//! REFEDIT, REFSET and REFCLOSE: edit a block reference in place. +//! REFEDIT, REFSET and REFCLOSE: edit a block reference or an xref in place. //! //! REFEDIT hides the picked reference and puts the block's objects (all, or the ones named) into //! the drawing where the reference shows them: the *working set*, ordinary objects that every //! command edits. The rest of the block stands there as faded copies, and everything else in the -//! drawing is locked ([`crate::cmd::curves::is_locked`], enforced by [`after_command`]). Objects -//! drawn while editing join the working set. REFSET adds objects to or removes them from it. -//! REFCLOSE writes the working set back into the block definition, so every reference to the -//! block shows the change, or discards the edit. +//! drawing is locked ([`crate::cmd::curves::is_locked`], enforced by [`after_command`]) and drawn +//! faded (XFADECTL). Objects drawn while editing join the working set. REFSET adds objects to or +//! removes them from it. REFCLOSE writes the working set back into the block definition, so every +//! reference to the block shows the change, or discards the edit. +//! +//! A reference nested in another block is picked through its parents (`path`, or "Select nesting +//! level [OK/Next]" at the command line): its own block is edited, the parents' other objects +//! stand faded around it. +//! +//! An xref (or a block that came with one) is edited the same way, and REFCLOSE Save writes the +//! change into its source drawing: the previous file is kept as `name.bak`, and the save is +//! refused when the file is read-only, open in another program (or another drawing tab), or +//! changed since it was loaded. The xref is then loaded again from the file it wrote. //! //! The state is [`Drawing::refedit`]: it travels with undo, is never written to a file (files //! are written from [`Drawing::committed`]) and ends with the drawing it belongs to. //! -//! Not yet: external references (their source drawing would have to be written back), nested -//! references picked at a depth, annotative scale contexts and attribute synchronisation. +//! Not yet: annotative scale contexts, attribute synchronisation and xrefs nested in xrefs (open +//! those with XOPEN). -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use cadcraft_doc::{Drawing, Entity, EntityStore, Handle, RefEdit, Transparency, WorkItem}; +use cadcraft_doc::{Block, Drawing, Entity, EntityKind, EntityStore, Handle, RefEdit, Transparency, WorkItem, XrefSource, XrefStatus}; use cadcraft_geom::Mat3; use serde_json::{Value, json}; use super::super::curves::handle_value; -use super::super::machines::{SelOutcome, SelectPhase, SelectRun}; +use super::super::machines::{SelOutcome, SelectPhase}; use super::references_block; +use super::xref::load::{self, Sym}; use crate::cmd::{CommandSpec, bad, bool_or, has_doc, str_param, targets}; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; -/// Transparency of the faded copies of the block's other objects. -const GHOST_FADE: u8 = 70; +/// Most nesting levels offered for one picked reference. +const MAX_LEVELS: usize = 256; pub(super) fn specs() -> Vec { vec![ CommandSpec::new("refedit", "Edit Reference In-Place", run_refedit) .menu(&["Tools", "Xref and Block In-place Editing", "Edit Reference In-Place"]) - .params("{handle? | handles? | name? (a block reference, default the selection), objects?: [block object handles] (default all)} → {block, insert, working: [handles], faded}") + .alias(&["-refedit"]) + .params("{handle? | handles? | name? (a block or xref reference, default the selection), path?: [handles of nested block references, outermost first] | nested?: block name (the first nested reference to it), objects?: [block object handles] (default all)} → {block, insert, working: [handles], faded, path, xref?: {name, file}}. Editing an xref writes its file back on REFCLOSE Save.") .enabled(has_doc) - .interactive(|_| Ok(Box::new(SelectRun::single("refedit", "REFEDIT", "Select reference")))), + .interactive(|_| Ok(Box::new(RefeditM::default()))), + CommandSpec::new("refedit.levels", "Reference Nesting Levels", run_levels) + .params("{handle (a block or xref reference)} → {levels: [{name, path: [handles], xref}]} (the picked reference first, then the references nested in it)") + .enabled(has_doc) + .noundo(), CommandSpec::new("refset", "Working Set", run_refset) .menu(&["Tools", "Xref and Block In-place Editing", "Add to Working Set"]) .params("{add?: [handles], remove?: [handles]} (or {handles, mode?: \"add\"|\"remove\"}); with neither: lists the working set → {working: [handles], added, removed}") @@ -44,7 +59,7 @@ pub(super) fn specs() -> Vec { .interactive(|_| Ok(Box::new(RefsetM::default()))), CommandSpec::new("refclose", "Save Reference Edits", run_refclose) .menu(&["Tools", "Xref and Block In-place Editing", "Save Reference Edits"]) - .params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects}") + .params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects, file? (an xref's source drawing written), backup?}") .enabled(editing) .interactive(|_| Ok(Box::new(RefcloseM))), ] @@ -59,13 +74,19 @@ fn active(s: &Session, cmd: &str) -> Result { s.doc()?.refedit.clone().ok_or_else(|| bad(cmd, "no block reference is being edited (REFEDIT)")) } -/// A block object as the drawing shows it through the edited reference. -fn to_host(to_world: &Mat3, e: &Entity, h: Handle, ghost: bool) -> Entity { +/// How much the block's other objects fade (XFADECTL, 0–90 percent). +fn xfadectl(s: &Session) -> Result { + Ok(u8::try_from(s.doc()?.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50)) +} + +/// A block object as the drawing shows it through the edited reference; `fade` (XFADECTL, a +/// percentage) shows the block's other objects faded. +fn to_host(to_world: &Mat3, e: &Entity, h: Handle, fade: Option) -> Entity { let mut c = e.clone(); c.handle = h; c.kind.transform(to_world); - if ghost { - c.common.transparency = Transparency::Percent(GHOST_FADE); + if let Some(f) = fade { + c.common.transparency = Transparency::Percent(f.min(90)); } c } @@ -88,6 +109,173 @@ fn hexes(hs: impl IntoIterator) -> Vec { hs.into_iter().map(|h| h.hex()).collect() } +// ---------------- nesting ---------------- + +/// One level of a picked reference: a block, how its objects show in the drawing, and the +/// reference inside it that leads to the next level (none at the last). +struct Level { + block: Arc, + to_world: Mat3, + next: Option, +} + +/// Whether a reference with transform `m` can be edited in place (finite, not flat, scaled the +/// same in X and Y). +fn editable_transform(m: &Mat3, sx: f64, sy: f64) -> bool { + let finite = [m.a, m.b, m.c, m.d, m.e, m.f].iter().all(|v| v.is_finite()); + finite && m.det().abs() >= 1e-12 && (sx.abs() - sy.abs()).abs() <= 1e-9 * sx.abs().max(sy.abs()) +} + +/// The levels from top reference `ins` down `path` (references inside the block definitions). +fn levels(d: &Drawing, ins: &cadcraft_doc::Insert, path: &[Handle]) -> Result> { + let mut block = d.block(&ins.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", ins.block)))?; + let mut m = ins.transform(block.base.xy()); + if !editable_transform(&m, ins.scale.x, ins.scale.y) { + return Err(bad("refedit", "the reference must be scaled equally in X and Y (and not flat) to be edited in place")); + } + if path.len() >= cadcraft_doc::MAX_BLOCK_DEPTH { + return Err(bad("refedit", "the reference is nested too deeply")); + } + let mut out = Vec::with_capacity(path.len() + 1); + for h in path { + let e = block.entities.get(*h).ok_or_else(|| bad("refedit", format!("object {} is not a reference in block \"{}\"", h.hex(), block.name)))?; + let EntityKind::Insert(child) = &e.kind else { return Err(bad("refedit", format!("object {} is not a block reference", h.hex()))) }; + let cb = d.block(&child.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", child.block)))?; + let cm = m.then_before(child.transform(cb.base.xy())); + if !editable_transform(&cm, child.scale.x, child.scale.y) { + return Err(bad("refedit", format!("the nested reference to \"{}\" must be scaled equally in X and Y", cb.name))); + } + out.push(Level { block, to_world: m, next: Some(*h) }); + block = cb; + m = cm; + } + out.push(Level { block, to_world: m, next: None }); + Ok(out) +} + +/// The references nested in block `name` (depth first): (path of handles, block name). +fn nested(d: &Drawing, name: &str, path: &mut Vec, out: &mut Vec<(Vec, String)>) { + if path.len() + 1 >= cadcraft_doc::MAX_BLOCK_DEPTH || out.len() >= MAX_LEVELS { + return; + } + let Some(b) = d.block(name) else { return }; + for e in b.entities.iter() { + let EntityKind::Insert(i) = &e.kind else { continue }; + // Generated geometry (dimensions, arrays) is not offered. + if i.block.starts_with('*') || d.block(&i.block).is_none_or(|c| c.array.is_some()) || out.len() >= MAX_LEVELS { + continue; + } + path.push(e.handle); + out.push((path.clone(), i.block.clone())); + nested(d, &i.block, path, out); + path.pop(); + } +} + +/// The nesting levels of reference `ih`: the reference itself, then every reference nested in it. +fn level_list(d: &Drawing, ih: Handle) -> Result, String)>> { + let Some(EntityKind::Insert(ins)) = d.entity(ih).map(|e| &e.kind) else { return Err(bad("refedit", "select a block reference")) }; + let mut out = vec![(Vec::new(), ins.block.clone())]; + nested(d, &ins.block, &mut Vec::new(), &mut out); + Ok(out) +} + +fn run_levels(s: &mut Session, p: &Value) -> Result { + let ih = targets(s, p)?.into_iter().next().ok_or_else(|| bad("refedit.levels", "select a block reference"))?; + let d = s.doc()?; + let levels: Vec = level_list(d, ih)? + .into_iter() + .map(|(path, name)| json!({ "name": name, "path": hexes(path), "xref": xref_of(d, &name).is_some() })) + .collect(); + Ok(json!({ "levels": levels })) +} + +// ---------------- xrefs ---------------- + +/// The xref block `name` belongs to: (the xref's name, the block of its source drawing or `None` +/// for its model space). `None` for a block of this drawing. +fn xref_of(d: &Drawing, name: &str) -> Option<(String, Option)> { + let b = d.block(name)?; + if b.xref_path.is_some() { + return Some((b.name.clone(), None)); + } + let (root, rest) = name.split_once('|')?; + let x = d.block(root).filter(|x| x.xref_path.is_some())?; + Some((x.name.clone(), Some(rest.to_string()))) +} + +/// The source file of xref `name`, checked for an edit in place: found, not open in another +/// drawing tab, writable, not changed since it was loaded. +fn xref_file(s: &Session, name: &str) -> Result { + if cfg!(target_arch = "wasm32") { + return Err(bad("refedit", "editing xrefs in place is not available on the web; open the xref's drawing instead")); + } + let d = s.doc()?; + let b = d.block(name).ok_or_else(|| bad("refedit", format!("no xref \"{name}\"")))?; + if b.xref_status != XrefStatus::Loaded { + return Err(bad("refedit", format!("xref \"{}\" is not loaded ({}); reload it first", b.name, b.xref_status.label()))); + } + let path = b.xref_path.clone().unwrap_or_default(); + let host = s.state().ok().and_then(|st| st.path.clone()); + let file = load::find(&path, host.as_deref().map(std::path::Path::new), false).map_err(|_| bad("refedit", format!("{path}: file not found")))?; + let canon = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + let me = canon(&file); + for (i, st) in s.docs.iter().enumerate() { + if i != s.active && st.path.as_deref().is_some_and(|p| canon(std::path::Path::new(p)) == me) { + return Err(bad("refedit", format!("{} is open in another drawing tab: edit it there, or close it first", file.display()))); + } + } + writable(&file).map_err(|e| bad("refedit", e))?; + if let (Some(then), Some(now)) = (load::loaded_stamp(&file), load::stamp(&file)) + && then != now + { + return Err(bad("refedit", format!("{} changed since xref \"{}\" was loaded; reload it first", file.display(), b.name))); + } + Ok(file) +} + +/// Whether `file` may be written: not read-only and not open in another program (AutoCAD's +/// `.dwl` lock file beside it, or a file that can't be opened for writing). +fn writable(file: &std::path::Path) -> std::result::Result<(), String> { + #[cfg(target_arch = "wasm32")] + { + let _ = file; + Err("files are not available on the web".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let meta = std::fs::metadata(file).map_err(|e| format!("{}: {e}", file.display()))?; + if meta.permissions().readonly() { + return Err(format!("{} is read-only", file.display())); + } + let lock = file.with_extension("dwl"); + if lock.is_file() { + return Err(format!("{} is open in another program (lock file {})", file.display(), lock.display())); + } + std::fs::OpenOptions::new().append(true).open(file).map(|_| ()).map_err(|e| format!("{} can't be written: {e}", file.display())) + } +} + +/// The objects of the source drawing a block of xref `x` came from, matched one to one with the +/// block's objects (the order loading keeps). Refused when they no longer match. +fn source_handles(blk: &Block, src: &Drawing, inner: Option<&str>) -> Result> { + let store = match inner { + None => &src.model, + Some(n) => { + let b = src.block(n).ok_or_else(|| bad("refedit", format!("block \"{n}\" is no longer in the xref's drawing; reload the xref")))?; + if b.xref_path.is_some() { + return Err(bad("refedit", format!("\"{n}\" is an xref of the xref's drawing: open it with XOPEN to edit it"))); + } + &b.entities + } + }; + let kind = |e: &Entity| std::mem::discriminant(&e.kind); + if store.len() != blk.entities.len() || store.iter().zip(blk.entities.iter()).any(|(a, b)| kind(a) != kind(b)) { + return Err(bad("refedit", "the xref's drawing no longer matches what was loaded; reload the xref first")); + } + Ok(blk.entities.iter().zip(store.iter()).map(|(a, b)| (a.handle, b.handle)).collect()) +} + // ---------------- REFEDIT ---------------- fn run_refedit(s: &mut Session, p: &Value) -> Result { @@ -100,34 +288,45 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { .model .iter() .chain(d.layouts.iter().flat_map(|l| l.entities.iter())) - .find(|e| matches!(&e.kind, cadcraft_doc::EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(n))) + .find(|e| matches!(&e.kind, EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(n))) .map(|e| e.handle), - None => targets(s, p)?.into_iter().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, cadcraft_doc::EntityKind::Insert(_)))), + None => targets(s, p)?.into_iter().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Insert(_)))), }; let ih = picked.ok_or_else(|| bad("refedit", "select a block reference"))?; let (ins, space) = match d.entity(ih).map(|e| &e.kind) { - Some(cadcraft_doc::EntityKind::Insert(i)) => (i.clone(), d.space_of(ih).ok_or_else(|| bad("refedit", "the reference is in no space"))?), + Some(EntityKind::Insert(i)) => (i.clone(), d.space_of(ih).ok_or_else(|| bad("refedit", "the reference is in no space"))?), _ => return Err(bad("refedit", "select a block reference")), }; - let blk = d.block(&ins.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", ins.block)))?; - if blk.xref_path.is_some() { - return Err(bad( - "refedit", - format!( - "\"{}\" is an external reference: editing it in place would write its source drawing, which is not available yet. Open it with XOPEN, edit and save it, then reload.", - blk.name - ), - )); - } + let path: Vec = match (p.get("path"), str_param(p, "nested")) { + (Some(Value::Array(a)), _) => { + a.iter().map(|v| handle_value(v).ok_or_else(|| bad("refedit", format!("`path`: {v} is not an object handle")))).collect::>()? + } + (Some(Value::Null) | None, Some(n)) => level_list(d, ih)? + .into_iter() + .find(|(path, name)| !path.is_empty() && name.eq_ignore_ascii_case(n)) + .map(|(path, _)| path) + .ok_or_else(|| bad("refedit", format!("no reference to \"{n}\" is nested in this one")))?, + (Some(Value::Null) | None, None) => Vec::new(), + (Some(v), _) => return Err(bad("refedit", format!("`path` must be an array of object handles, got {v}"))), + }; + let levels = levels(d, &ins, &path)?; + let Some(edit) = levels.last() else { return Err(bad("refedit", "select a block reference")) }; + let blk = edit.block.clone(); + let to_world = edit.to_world; if blk.name.starts_with('*') || blk.array.is_some() { return Err(bad("refedit", format!("\"{}\" is generated geometry and can't be edited in place", blk.name))); } - let to_world = ins.transform(blk.base.xy()); - let (sx, sy) = (ins.scale.x.abs(), ins.scale.y.abs()); - let finite = [to_world.a, to_world.b, to_world.c, to_world.d, to_world.e, to_world.f].iter().all(|v| v.is_finite()); - if !finite || to_world.det().abs() < 1e-12 || (sx - sy).abs() > 1e-9 * sx.max(sy) { - return Err(bad("refedit", "the reference must be scaled equally in X and Y (and not flat) to be edited in place")); - } + // An xref's block: where it is written back. + let xref = match xref_of(d, &blk.name) { + Some((x, inner)) => { + let file = xref_file(s, &x)?; + let src = load::read_file(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; + let sources = source_handles(&blk, &src, inner.as_deref())?; + Some(XrefSource { xref: x, file: file.to_string_lossy().into_owned(), block: inner, stamp: load::stamp(&file), sources }) + } + None => None, + }; + let d = s.doc()?; let chosen: Option> = match p.get("objects") { None | Some(Value::Null) => None, Some(Value::String(a)) if a.eq_ignore_ascii_case("all") => None, @@ -157,20 +356,38 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { items: Vec::new(), ghosts: Vec::new(), released: Vec::new(), + path: path.clone(), + xref, }; + let fade = xfadectl(s)?; let doc = s.doc_mut()?; for e in blk.entities.iter() { let working = chosen.as_ref().is_none_or(|c| c.contains(&e.handle)); let h = doc.new_handle(); - put(doc, &r, to_host(&to_world, e, h, !working))?; + put(doc, &r, to_host(&to_world, e, h, (!working).then_some(fade)))?; if working { r.items.push(WorkItem { copy: h, source: Some(e.handle) }); } else { r.ghosts.push((h, e.handle)); } } + // The parents' other objects stand faded around a nested block. + for level in levels.iter().filter(|l| l.next.is_some()) { + for e in level.block.entities.iter().filter(|e| Some(e.handle) != level.next && !matches!(e.kind, EntityKind::AttDef(_))) { + let h = doc.new_handle(); + put(doc, &r, to_host(&level.to_world, e, h, Some(fade)))?; + r.ghosts.push((h, e.handle)); + } + } doc.modify_entity(ih, |e| e.common.visible = false).map_err(|e| bad("refedit", e.to_string()))?; - let out = json!({ "block": r.block, "insert": ih.hex(), "working": hexes(r.items.iter().map(|i| i.copy)), "faded": r.ghosts.len() }); + let out = json!({ + "block": r.block, + "insert": ih.hex(), + "working": hexes(r.items.iter().map(|i| i.copy)), + "faded": r.ghosts.len(), + "path": hexes(r.path.iter().copied()), + "xref": r.xref.as_ref().map(|x| json!({ "name": x.xref, "file": x.file })), + }); let sel: Vec = r.items.iter().map(|i| i.copy).collect(); doc.refedit = Some(r); s.set_selection(sel); @@ -214,22 +431,26 @@ fn apply_refset(s: &mut Session, add: &[Handle], remove: &[Handle]) -> Result Some(r.released.remove(i)), None => blk.entities.get(src).map(|e| (**e).clone()), }; if let Some(cur) = cur { let c = doc.new_handle(); - put(doc, &r, to_host(&r.to_world, &cur, c, false))?; + put(doc, &r, to_host(&r.to_world, &cur, c, None))?; r.items.push(WorkItem { copy: c, source: Some(src) }); added += 1; } @@ -248,7 +469,7 @@ fn apply_refset(s: &mut Session, add: &[Handle], remove: &[Handle]) -> Result Result { // Work on a copy: the drawing changes only when everything went through. let mut nd: Drawing = s.doc()?.clone(); let mut objects = 0; + let mut written = None; if save { objects = commit_block(&mut nd, &r)?; + if let Some(x) = &r.xref { + // The file first: when it can't be written the edit stays open (Discard ends it). + written = Some(write_back(&nd, &r, x)?); + } } nd.end_refedit_discard(&r); + let mut notes = Vec::new(); + if let (Some(x), Some(_)) = (&r.xref, &written) { + let host = s.state().ok().and_then(|st| st.path.clone()); + notes = load::load(&mut nd, &x.xref, host.as_deref(), false); + } *s.doc_mut()? = nd; s.set_selection(Vec::new()); - Ok(json!({ "block": r.block, "saved": save, "objects": objects })) + for o in notes { + s.echo(o.message()); + } + let mut out = json!({ "block": r.block, "saved": save, "objects": objects }); + if let (Some(x), Some(backup)) = (&r.xref, written) { + out["file"] = json!(x.file); + out["backup"] = json!(backup); + } + Ok(out) } /// Replace the block's objects by the working set (and move the drawing objects added to it @@ -331,6 +570,158 @@ fn commit_block(nd: &mut Drawing, r: &RefEdit) -> Result { Ok(n) } +// ---------------- writing an xref back ---------------- + +/// Write the edited block of `nd` (committed) into xref source `x`. Returns the backup's path. +fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result { + let file = std::path::Path::new(&x.file); + writable(file).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?; + if load::stamp(file) != x.stamp { + return Err(bad( + "refclose", + format!("{} changed since the edit began; it is not overwritten (REFCLOSE Discard ends the edit)", file.display()), + )); + } + let hooks = crate::cmd::file::io().ok_or_else(|| bad("refclose", "file formats are not available in this build"))?; + let mut src = load::read_file(file).map_err(|e| bad("refclose", format!("{}: {e}", file.display())))?; + let blk = nd.block(&r.block).ok_or_else(|| bad("refclose", format!("block \"{}\" is gone", r.block)))?; + let prefix = format!("{}|", x.xref); + let map: HashMap = x.sources.iter().copied().collect(); + let mut store = EntityStore::new(); + let mut wanted: Vec<(Sym, String)> = Vec::new(); + for e in blk.entities.iter() { + let mut e = (**e).clone(); + e.handle = match map.get(&e.handle) { + Some(h) => *h, + None => src.new_handle(), + }; + rename_into_source(&mut e, &prefix, &mut wanted); + store.push(e); + } + bring_symbols(nd, &mut src, &prefix, wanted); + match &x.block { + None => src.model = store, + Some(name) => { + let key = src + .blocks + .keys() + .find(|k| k.eq_ignore_ascii_case(name)) + .cloned() + .ok_or_else(|| bad("refclose", format!("block \"{name}\" is gone from {}", file.display())))?; + if let Some(b) = src.blocks.get_mut(&key) { + Arc::make_mut(b).entities = store; + } + } + } + let bytes = (hooks.write)(&src, &x.file).map_err(|e| bad("refclose", format!("writing {}: {e}", file.display())))?; + replace_file(file, &bytes).map_err(|e| bad("refclose", e)) +} + +/// Symbol names of a host object as the xref's drawing has them: `xref|name` loses its prefix; +/// the host's own symbols keep their names and are noted in `wanted` (copied into the drawing). +fn rename_into_source(e: &mut Entity, prefix: &str, wanted: &mut Vec<(Sym, String)>) { + let found = std::cell::RefCell::new(Vec::new()); + load::rename_refs(e, &|sym, n| { + if load::has_prefix(n, prefix) { + return n.get(prefix.len()..).map(str::to_string); + } + found.borrow_mut().push((sym, n.to_string())); + None + }); + wanted.extend(found.into_inner()); +} + +/// Copy the host's symbols that objects written into `src` use and `src` lacks (layers, +/// linetypes, text and dimension styles, and blocks with what they use in turn). +fn bring_symbols(host: &Drawing, src: &mut Drawing, prefix: &str, mut wanted: Vec<(Sym, String)>) { + let mut seen: HashSet<(Sym, String)> = HashSet::new(); + let mut guard = 0usize; + while let Some((sym, name)) = wanted.pop() { + guard += 1; + if guard > 100_000 || name.is_empty() || !seen.insert((sym, name.to_ascii_uppercase())) { + continue; + } + match sym { + Sym::Layer => { + if name != "0" + && src.layer(&name).is_none() + && let Some(l) = host.layer(&name) + { + wanted.push((Sym::Linetype, l.linetype.clone())); + src.layers.push(l.clone()); + } + } + Sym::Linetype => { + let builtin = ["ByLayer", "ByBlock", "Continuous"].iter().any(|n| n.eq_ignore_ascii_case(&name)); + if !builtin + && src.linetype(&name).is_none() + && let Some(t) = host.linetype(&name) + { + src.linetypes.push(t.clone()); + } + } + Sym::Style => { + if src.text_style(&name).is_none() + && let Some(t) = host.text_style(&name) + { + src.text_styles.push(t.clone()); + } + } + Sym::DimStyle => { + if src.dim_style(&name).is_none() + && let Some(t) = host.dim_style(&name) + { + wanted.push((Sym::Style, t.text_style.clone())); + src.dim_styles.push(t.clone()); + } + } + Sym::Block => { + if src.block(&name).is_none() + && let Some(b) = host.block(&name) + && b.xref_path.is_none() + { + let mut nb = (**b).clone(); + let mut store = EntityStore::new(); + for e in b.entities.iter() { + let mut e = (**e).clone(); + e.handle = src.new_handle(); + rename_into_source(&mut e, prefix, &mut wanted); + store.push(e); + } + nb.entities = store; + src.blocks.insert(nb.name.clone(), Arc::new(nb)); + } + } + Sym::MLeaderStyle | Sym::TableStyle => {} + } + } +} + +/// Replace `file` by `bytes`: the old file is kept as `name.bak`, the new one is written beside +/// it and moved over it. Returns the backup's path. +fn replace_file(file: &std::path::Path, bytes: &[u8]) -> std::result::Result { + #[cfg(target_arch = "wasm32")] + { + let _ = (file, bytes); + Err("files are not available on the web".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let backup = file.with_extension("bak"); + std::fs::copy(file, &backup) + .map_err(|e| format!("the backup {} can't be written: {e}; {} is unchanged", backup.display(), file.display()))?; + let mut tmp = file.as_os_str().to_owned(); + tmp.push(".cadcraft-tmp"); + let tmp = std::path::PathBuf::from(tmp); + std::fs::write(&tmp, bytes).map_err(|e| format!("{} can't be written: {e}", tmp.display()))?; + if let Err(e) = std::fs::rename(&tmp, file) { + let _ = std::fs::remove_file(&tmp); + return Err(format!("{} can't be replaced: {e}; it is unchanged", file.display())); + } + Ok(backup.to_string_lossy().into_owned()) + } +} + // ---------------- while editing ---------------- /// After a command ran: objects it created join the working set, and a command that changed @@ -374,6 +765,94 @@ pub(crate) fn locked(d: &Drawing, h: Handle) -> bool { // ---------------- interactive ---------------- +/// REFEDIT at the command line: "Select reference", then "Select nesting level [OK/Next]" when +/// the reference has others nested in it. +#[derive(Default)] +struct RefeditM { + sel: SelectPhase, + picked: Option, + levels: Vec<(Vec, String)>, + at: usize, +} + +impl RefeditM { + fn picked(&mut self, s: &mut Session, hs: &[Handle]) -> Result { + let d = s.doc()?; + let Some(h) = hs.iter().copied().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Insert(_)))) else { + s.echo("Select a block or xref reference."); + self.sel = SelectPhase::single(); + return Ok(Step::Continue); + }; + self.levels = level_list(d, h)?; + self.picked = Some(h); + if self.levels.len() > 1 { + self.echo_level(s); + return Ok(Step::Continue); + } + self.finish(s) + } + fn echo_level(&self, s: &mut Session) { + if let Some((path, name)) = self.levels.get(self.at) { + s.echo(format!("Reference name: {name}{}", if path.is_empty() { String::new() } else { format!(" (nested {} deep)", path.len()) })); + } + } + fn finish(&mut self, s: &mut Session) -> Result { + let Some(h) = self.picked else { return Ok(Step::Cancel) }; + let path = self.levels.get(self.at).map(|(p, _)| hexes(p.iter().copied())).unwrap_or_default(); + let r = run_refedit(s, &json!({ "handle": h.hex(), "path": path }))?; + let n = r["working"].as_array().map_or(0, Vec::len); + s.set_selection(Vec::new()); + s.echo(format!("{n} object(s) in the working set. Use REFCLOSE to save or discard the changes.")); + Ok(Step::Done) + } +} + +impl Interactive for RefeditM { + fn name(&self) -> &'static str { + "REFEDIT" + } + fn begin(&mut self, s: &mut Session) -> Result { + self.sel = SelectPhase::begin(s); + self.sel.single = true; + if self.sel.done { + let hs = self.sel.picked.clone(); + return self.picked(s, &hs); + } + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + if self.picked.is_none() { + return Prompt::new("Select reference", Accept::SELECT); + } + Prompt::new("Select nesting level", Accept::TEXT).kw(&["OK", "Next"]).default("Next") + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + if self.picked.is_none() { + return match self.sel.feed(s, &i)? { + SelOutcome::More => Ok(Step::Continue), + SelOutcome::Empty => Ok(Step::Done), + SelOutcome::Done(hs) => self.picked(s, &hs), + }; + } + let k = match &i { + Input::Keyword(k) | Input::Text(k) => k.trim().to_ascii_lowercase(), + Input::Enter => "next".into(), + _ => return Ok(Step::Continue), + }; + if k.starts_with('o') { + return self.finish(s); + } + if k.starts_with('n') { + self.at = (self.at + 1) % self.levels.len().max(1); + self.echo_level(s); + } + Ok(Step::Continue) + } +} + #[derive(Default)] enum RStage { #[default] @@ -462,8 +941,13 @@ impl Interactive for RefcloseM { _ => return Ok(Step::Cancel), }; let r = close(s, save)?; - s.echo(if save { "Reference changes saved." } else { "Reference changes discarded." }); - let _ = r; + s.echo(match (save, r.get("file").and_then(Value::as_str)) { + (true, Some(f)) => { + format!("Reference changes saved to {f} (the previous file is kept as {}).", r["backup"].as_str().unwrap_or("a .bak file")) + } + (true, None) => "Reference changes saved.".to_string(), + (false, _) => "Reference changes discarded.".to_string(), + }); Ok(Step::Done) } } diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index fac289f23..a6073d50a 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -133,7 +133,7 @@ struct Ctx { } /// The folder of the host drawing at `host` (a file path). -fn folder(host: Option<&Path>) -> Option { +pub(crate) fn folder(host: Option<&Path>) -> Option { let p = host?.parent()?; Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() }) } @@ -244,6 +244,10 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { return Err(too_big()); } cx.bytes = cx.bytes.saturating_add(n); + // Remembered so an edit in place can tell whether the file changed since (REFEDIT). + if let Some(st) = stamp(file) { + remember(file, st); + } (hooks.read)(&bytes, &file.to_string_lossy()) } #[cfg(target_arch = "wasm32")] @@ -253,6 +257,50 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { } } +/// Size and modification time (nanoseconds since 1970) of each referenced file when it was last +/// read, by canonical path. +#[cfg(not(target_arch = "wasm32"))] +static LOADED: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +/// Most files [`LOADED`] remembers. +#[cfg(not(target_arch = "wasm32"))] +const MAX_REMEMBERED: usize = 10_000; + +/// The size and modification time of `file` (nanoseconds since 1970). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn stamp(file: &Path) -> Option<(u64, u128)> { + let m = std::fs::metadata(file).ok()?; + let t = m.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos(); + Some((m.len(), t)) +} +#[cfg(target_arch = "wasm32")] +pub(crate) fn stamp(_file: &Path) -> Option<(u64, u128)> { + None +} + +#[cfg(not(target_arch = "wasm32"))] +fn remember(file: &Path, st: (u64, u128)) { + let mut m = LOADED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if m.len() >= MAX_REMEMBERED { + m.clear(); + } + m.insert(canonical(file), st); +} + +/// The size and modification time `file` had when it was last loaded as an xref. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn loaded_stamp(file: &Path) -> Option<(u64, u128)> { + LOADED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&canonical(file)).copied() +} +#[cfg(target_arch = "wasm32")] +pub(crate) fn loaded_stamp(_file: &Path) -> Option<(u64, u128)> { + None +} + +/// Read the drawing file `file` (with the size limits of xref loading). +pub(crate) fn read_file(file: &Path) -> Result { + read(file, &mut Ctx::new(None)) +} + /// Load every xref of `d` that isn't unloaded from the paths saved in it; `host` is the drawing's /// own path. pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec { diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index fa319d3f1..3fe1298fd 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -74,6 +74,8 @@ const HEADER: &[(&str, Kind, Def)] = &[ ("TRIMEXTENDMODE", Kind::Choice(&[0, 1]), Def::Int(1)), ("TRIMMODE", Kind::Choice(&[0, 1]), Def::Int(1)), ("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)), + // How much objects outside the working set fade while a reference is edited in place (REFEDIT). + ("XFADECTL", Kind::Int(0, 90), Def::Int(50)), ]; /// The standard lineweights in hundredths of a millimetre. diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c4c4a1ce6..21e4ef08b 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -104,6 +104,7 @@ mod quickcalc; mod recent_commands; mod rectang_ortho; mod refedit; +mod refedit_xref; mod region; mod rename_cmdline; mod rotate_reference; diff --git a/crates/engine/tests/it/refedit.rs b/crates/engine/tests/it/refedit.rs index df3aa5ea1..8bc9b981b 100644 --- a/crates/engine/tests/it/refedit.rs +++ b/crates/engine/tests/it/refedit.rs @@ -277,7 +277,7 @@ fn interactive_refedit_refset_and_refclose() { } #[test] -fn xrefs_are_refused_with_a_message() { +fn an_xref_that_is_not_loaded_is_refused_with_a_message() { let mut s = Session::new(); s.doc_mut().unwrap().blocks.insert( "X".into(), @@ -289,5 +289,6 @@ fn xrefs_are_refused_with_a_message() { ); let x = insert(&mut s, "X", (0.0, 0.0), 1.0, 0.0); let e = s.execute("refedit", &json!({ "handle": x })).unwrap_err(); - assert!(e.to_string().contains("external reference"), "{e}"); + // Xrefs are edited in place and written back (refedit_xref.rs); one not loaded can't be. + assert!(e.to_string().contains("not loaded"), "{e}"); } diff --git a/crates/engine/tests/it/refedit_xref.rs b/crates/engine/tests/it/refedit_xref.rs new file mode 100644 index 000000000..ef6b93c7c --- /dev/null +++ b/crates/engine/tests/it/refedit_xref.rs @@ -0,0 +1,243 @@ +//! REFEDIT on xrefs and nested references (gap F2): the source drawing written back on REFCLOSE +//! Save (with a backup; refused for read-only, locked or changed files) and nesting levels. +//! Files go in a folder under Cargo's temporary directory for integration tests. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::geom::{Vec2, Vec3}; +use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, Insert, Layer, Line, XrefStatus}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn hooks() { + set_io(IoHooks { + read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), + write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: None, + }); +} + +/// A fresh folder for one test. +fn folder(tag: &str) -> PathBuf { + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("refedit-xref").join(format!("{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn save(d: &Drawing, path: &Path) { + std::fs::write(path, cadcraft_io::write(d, &path.to_string_lossy()).unwrap()).unwrap(); +} + +fn read(path: &Path) -> Drawing { + cadcraft_io::read(&std::fs::read(path).unwrap(), &path.to_string_lossy()).unwrap() +} + +fn line(d: &mut Drawing, layer: &str, a: (f64, f64), b: (f64, f64)) -> Handle { + let h = d.new_handle(); + let mut e = Entity::new(h, EntityKind::Line(Line { a: Vec3::new(a.0, a.1, 0.0), b: Vec3::new(b.0, b.1, 0.0) })); + e.common.layer = layer.into(); + d.model.push(e); + h +} + +fn insert(block: &str, at: Vec3) -> Insert { + Insert { + block: block.into(), + insert: at, + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + } +} + +/// A site plan: a line on layer Walls and a reference to its block Tree (a circle). +fn site() -> (Drawing, Handle) { + let mut d = Drawing::new_metric(); + d.layers.push(Layer { name: "Walls".into(), ..Layer::default() }); + let wall = line(&mut d, "Walls", (0.0, 0.0), (10.0, 0.0)); + let mut tree = Block::new("Tree"); + let c = d.new_handle(); + tree.entities.push(Entity::new(c, EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 1.0 }))); + d.blocks.insert("Tree".into(), Arc::new(tree)); + let h = d.new_handle(); + d.model.push(Entity::new(h, EntityKind::Insert(insert("Tree", Vec3::new(5.0, 0.0, 0.0))))); + (d, wall) +} + +/// A host drawing (saved as host.dxf) with site.dxf attached at (100, 0). +fn attached(tag: &str) -> (Session, PathBuf, Handle, String) { + hooks(); + let dir = folder(tag); + let (d, wall) = site(); + save(&d, &dir.join("site.dxf")); + let host = dir.join("host.dxf"); + save(&Drawing::new_metric(), &host); + let mut s = Session::new(); + s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap(); + let r = s.execute("xattach", &json!({ "path": "site.dxf", "at": [100, 0] })).unwrap(); + let insert = r["handle"].as_str().unwrap().to_string(); + (s, dir, wall, insert) +} + +fn hx(v: Value) -> String { + v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_string() +} + +fn working(r: &Value) -> Vec { + r["working"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect() +} + +fn find_line(s: &Session, hs: &[String]) -> String { + let d = s.doc().unwrap(); + hs.iter().find(|h| matches!(d.entity(Handle::parse_hex(h).unwrap()).unwrap().kind, EntityKind::Line(_))).unwrap().clone() +} + +#[test] +fn editing_an_xref_writes_its_drawing_back_with_a_backup() { + let (mut s, dir, wall, insert) = attached("save"); + let file = dir.join("site.dxf"); + let r = s.execute("refedit", &json!({ "handle": insert })).unwrap(); + assert_eq!(r["xref"]["name"], "site"); + let work = working(&r); + assert_eq!(work.len(), 2); + // Everything but the working set is locked while editing, and drawn faded. + let l = find_line(&s, &work); + s.execute("move", &json!({ "handles": [l], "delta": [0, 5] })).unwrap(); + s.execute("layer", &json!({ "option": "make", "name": "Added" })).ok(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(out["objects"], 3); + assert!(out["file"].as_str().unwrap().ends_with("site.dxf")); + assert!(dir.join("site.bak").is_file(), "the previous file is kept"); + // The file holds the edit, in its own coordinates, with the line's own handle. + let back = read(&file); + assert_eq!(back.model.len(), 3); + let moved = back.entity(wall).expect("the edited line keeps its handle"); + let EntityKind::Line(ln) = &moved.kind else { panic!() }; + assert!((ln.a.y - 5.0).abs() < 1e-9 && (ln.a.x).abs() < 1e-9, "{ln:?}"); + assert_eq!(moved.common.layer, "Walls", "the xref's layer loses its prefix"); + let new_line = back.model.iter().find(|e| matches!(&e.kind, EntityKind::Line(l) if (l.a.y - 20.0).abs() < 1e-9)).unwrap(); + assert!(back.layer(&new_line.common.layer).is_some(), "a host layer the new line uses comes along"); + // The host shows the xref as written (loaded again), and nothing of the edit is left. + let d = s.doc().unwrap(); + assert!(d.refedit.is_none()); + assert_eq!(d.block("site").unwrap().entities.len(), 3); + assert_eq!(d.block("site").unwrap().xref_status, XrefStatus::Loaded); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_block_of_the_xref_is_written_into_that_block() { + let (mut s, dir, _, insert) = attached("nested"); + let levels = s.execute("refedit.levels", &json!({ "handle": insert })).unwrap(); + let names: Vec<&str> = levels["levels"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["site", "site|Tree"]); + let r = s.execute("refedit", &json!({ "handle": insert, "nested": "site|Tree" })).unwrap(); + assert_eq!(r["block"], "site|Tree"); + assert_eq!(r["path"].as_array().unwrap().len(), 1); + assert!(r["faded"].as_u64().unwrap() >= 1, "the site's other objects stand faded around it"); + let c = working(&r)[0].clone(); + // The circle shows at the tree's place in the drawing: (100 + 5, 0). + let EntityKind::Circle(circle) = &s.doc().unwrap().entity(Handle::parse_hex(&c).unwrap()).unwrap().kind else { panic!() }; + assert!((circle.center.x - 105.0).abs() < 1e-9); + s.execute("scale", &json!({ "handles": [c], "base": [105, 0], "factor": 2 })).unwrap(); + s.execute("refclose", &json!({})).unwrap(); + let back = read(&dir.join("site.dxf")); + let EntityKind::Circle(c) = &back.block("Tree").unwrap().entities.iter().next().unwrap().kind else { panic!() }; + assert!((c.radius - 2.0).abs() < 1e-9); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn locked_read_only_or_changed_files_are_not_overwritten() { + // A lock file of another program: refused at the start. + let (mut s, dir, _, insert) = attached("locked"); + let file = dir.join("site.dxf"); + std::fs::write(dir.join("site.dwl"), b"lock").unwrap(); + let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("open in another program"), "{e}"); + std::fs::remove_file(dir.join("site.dwl")).unwrap(); + + // Changed on disk while editing: the save is refused, the edit stays, Discard ends it. + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + let mut other = read(&file); + line(&mut other, "0", (0.0, 50.0), (1.0, 50.0)); + std::thread::sleep(std::time::Duration::from_millis(20)); + save(&other, &file); + let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string(); + assert!(e.contains("changed since"), "{e}"); + assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open"); + s.execute("refclose", &json!({ "option": "discard" })).unwrap(); + assert_eq!(read(&file).model.len(), 3, "the other program's change is kept"); + + // Changed since it was loaded: reload first. + let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("since") && e.contains("reload"), "{e}"); + s.execute("-xref", &json!({ "option": "reload", "names": "site" })).unwrap(); + + // Read-only: refused. + let mut perm = std::fs::metadata(&file).unwrap().permissions(); + perm.set_readonly(true); + std::fs::set_permissions(&file, perm.clone()).unwrap(); + let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("read-only"), "{e}"); + #[allow(clippy::permissions_set_readonly_false)] + perm.set_readonly(false); + std::fs::set_permissions(&file, perm).unwrap(); + + // Open in another drawing tab of this session: refused. + s.execute("qsave", &json!({})).unwrap(); + let host = s.state().unwrap().path.clone().unwrap(); + s.execute("open", &json!({ "path": file.to_string_lossy() })).unwrap(); + s.execute("open", &json!({ "path": host })).unwrap(); + let ih = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Insert(_))).unwrap().handle; + let e = s.execute("refedit", &json!({ "handle": ih.hex() })).unwrap_err().to_string(); + assert!(e.contains("another drawing tab"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn nested_block_references_are_picked_through_their_parents() { + let mut s = Session::new(); + let c = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Inner", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap(); + let i = hx(s.execute("insert", &json!({ "name": "Inner", "at": [10, 0] })).unwrap()); + let l = hx(s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()); + s.execute("block", &json!({ "name": "Outer", "base": [0, 0], "handles": [i, l], "keep": "delete" })).unwrap(); + let o = hx(s.execute("insert", &json!({ "name": "Outer", "at": [100, 100] })).unwrap()); + + // At the command line: pick, Next to the nested level, OK. + s.start("refedit").unwrap(); + s.input(Input::Pick(vec![Handle::parse_hex(&o).unwrap()])).unwrap(); + assert!(s.prompt_text().contains("Select nesting level"), "{}", s.prompt_text()); + assert!(s.log.iter().any(|m| m.contains("Reference name: Outer"))); + s.input(Input::Enter).unwrap(); // Next + assert!(s.log.iter().any(|m| m.contains("Reference name: Inner"))); + s.cmdline("o").unwrap(); + let d = s.doc().unwrap(); + let r = d.refedit.clone().unwrap(); + assert_eq!(r.block, "Inner"); + assert_eq!(r.items.len(), 1); + assert_eq!(r.ghosts.len(), 1, "Outer's line stands faded"); + let EntityKind::Circle(circle) = &d.entity(r.items[0].copy).unwrap().kind else { panic!() }; + assert!(circle.center.xy().near(Vec2::new(110.0, 100.0), 1e-9)); + // Only the working set can change: Outer's faded line is locked. + s.execute("move", &json!({ "handles": [r.items[0].copy.hex()], "delta": [0, 3] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Circle(c) = &d.block("Inner").unwrap().entities.iter().next().unwrap().kind else { panic!() }; + assert!(c.center.xy().near(Vec2::new(0.0, 3.0), 1e-9), "{c:?}"); + assert_eq!(d.block("Outer").unwrap().entities.len(), 2, "the parent is untouched"); + // Bad paths are refused. + assert!(s.execute("refedit", &json!({ "handle": o, "path": ["FFFFF"] })).is_err()); + assert!(s.execute("refedit", &json!({ "handle": o, "path": "x" })).is_err()); + assert!(s.execute("refedit", &json!({ "handle": o, "nested": "Nope" })).is_err()); + let _ = Vec2::ZERO; +} diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 5ce0bd6c0..08ae08be0 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -66,6 +66,15 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { if b.opts.transparency { b.transparency = transparency(e.common.transparency, layer_transparency, ctx.block_transparency); } + // While a reference is edited in place (REFEDIT) everything outside the working set is + // faded by XFADECTL percent on screen. + if !b.plotting + && let Some(r) = &ctx.d.refedit + && !r.is_working(if ctx.depth == 0 { e.handle } else { ctx.top }) + { + let fade = u8::try_from(ctx.d.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50); + b.transparency = b.transparency.max(fade); + } // A plot style's linetype replaces the object's. let lt = match b.styles.and_then(|s| s.linetype(rgb, b.named)) { Some(over) => over, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 787aa1a2f..d7bfa33b8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -778,6 +778,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.canvas.draw_ms = crate::now_ms() - t0; compare::paint(app, ui.ctx(), &painter, &xf_paper, rect); blockedit::paint(app, ui.ctx(), &painter, &xf_paper, rect); + refedit::paint(app, ui.ctx(), rect); // Constraint bars and dynamic dimensional constraints (model space, or inside a viewport). if sheet.is_none() || active_vp.is_some() { let clip = match &active_vp { @@ -939,3 +940,5 @@ mod compare; /// Background rebuilds of the display list for a new view. mod rebuild; +/// The Edit Reference bar while a reference is edited in place (REFEDIT). +mod refedit; diff --git a/crates/ui-egui/src/canvas/refedit.rs b/crates/ui-egui/src/canvas/refedit.rs new file mode 100644 index 000000000..de9250205 --- /dev/null +++ b/crates/ui-egui/src/canvas/refedit.rs @@ -0,0 +1,72 @@ +//! Editing a reference in place (REFEDIT) on the canvas: a bar over the drawing with the +//! reference's name (and, for an xref, the file it writes to), the working set's size, Add to / +//! Remove from Working Set, and Save Changes / Discard Changes (REFCLOSE). The rest of the +//! drawing is drawn faded by the renderer (XFADECTL) and locked by the engine. + +use egui::{Rect, RichText, Stroke, vec2}; +use serde_json::json; + +use crate::CadApp; +use crate::theme::Tokens; + +fn id() -> egui::Id { + egui::Id::unique("cadcraft-refedit-bar") +} + +/// The edit shown: (block, xref file, working-set size). +fn editing(app: &CadApp) -> Option<(String, Option, usize)> { + let r = app.session.state().ok()?.doc.refedit.clone()?; + Some((r.block, r.xref.map(|x| x.file), r.items.len())) +} + +/// What a bar button asks for. +enum Act { + Start(&'static str), + Run(&'static str, serde_json::Value), +} + +/// The bar (over the drawing, at its top). +pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, rect: Rect) { + let Some((name, file, count)) = editing(app) else { return }; + let t = Tokens::get(); + let sel: Vec = app.session.selection().iter().map(|h| h.hex()).collect(); + let mut act = None; + egui::Area::new(id()).order(egui::Order::Foreground).pivot(egui::Align2::CENTER_TOP).fixed_pos(rect.center_top() + vec2(0.0, 8.0)).show( + ctx, + |ui| { + egui::Frame::new().fill(t.cmd_bg).stroke(Stroke::new(1.0, t.accent)).corner_radius(4.0).inner_margin(6.0).show(ui, |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(crate::tl!("Edit Reference")).color(t.accent).strong()); + let shown = ui.label(RichText::new(&name).color(t.text)); + if let Some(f) = &file { + shown.on_hover_text(crate::tf!("Saving writes {file}", file = f)); + } + ui.label(RichText::new(crate::tf!("{n} in the working set", n = count)).color(t.text_dim)); + ui.separator(); + if ui.button(crate::tl!("Add to Working Set")).clicked() { + act = Some(if sel.is_empty() { Act::Start("refset") } else { Act::Run("refset", json!({ "add": sel })) }); + } + if ui.button(crate::tl!("Remove from Working Set")).clicked() { + act = Some(if sel.is_empty() { Act::Start("refset") } else { Act::Run("refset", json!({ "remove": sel })) }); + } + ui.separator(); + if ui.button(RichText::new(crate::tl!("Save Changes")).color(t.accent)).clicked() { + act = Some(Act::Run("refclose", json!({ "option": "save" }))); + } + if ui.button(crate::tl!("Discard Changes")).clicked() { + act = Some(Act::Run("refclose", json!({ "option": "discard" }))); + } + }); + }); + }, + ); + match act { + Some(Act::Start(id)) => app.start(id), + Some(Act::Run(id, p)) => { + if let Err(e) = app.run(id, p) { + app.set_status(e); + } + } + None => {} + } +} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 634249093..bde314339 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1367,3 +1367,9 @@ menu Modify Edita Check for Updates… Verifica aggiornamenti… CADCraft is up to date. CADCraft è aggiornato. Could not check for updates. Impossibile verificare gli aggiornamenti. + Edit Reference Modifica riferimento + Saving writes {file} Il salvataggio scrive {file} + {n} in the working set {n} nel gruppo di lavoro + Remove from Working Set Rimuovi dal gruppo di lavoro + Save Changes Salva modifiche + Discard Changes Annulla modifiche diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d71b3ccd7..0503ef6d4 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1373,3 +1373,9 @@ Check for Updates… Перевірити оновлення… CADCraft is up to date. Встановлено найновішу версію CADCraft. Could not check for updates. Не вдалося перевірити оновлення. + Edit Reference Редагування посилання + Saving writes {file} Збереження записує {file} + {n} in the working set {n} у робочому наборі + Remove from Working Set Вилучити з робочого набору + Save Changes Зберегти зміни + Discard Changes Скасувати зміни diff --git a/docs/gaps.md b/docs/gaps.md index 9c0bf3630..7a3ffb1f5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (REFEDIT on xrefs and nested references: F2 and top-10 row 4 narrowed) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -16,7 +16,7 @@ do them first. | 1 | **[alpha blocker]** **Saving DWG drops what we don't model** (DXF now writes back unknown entities and objects, foreign xdata, extension dictionaries, reactors, layer states and colour books, #528, and native MULTILEADERs, #459 (not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour books and reactors) | Opening a colleague's DWG and saving it still deletes some content: the one thing a CAD user can't forgive | 6–10 | [file formats](file-format-parity.md) | | 2 | **[alpha blocker]** **No real-file test corpus and no check in AutoCAD** | All 36 file tests are synthetic; nobody has verified a CADCraft DWG/DXF opens cleanly in AutoCAD | 10–15 + human | [file formats](file-format-parity.md#tests) | | 3 | **Ellipse and spline geometry is tessellated** (intersections, offsets, closest points; polyline offset ignores bulges) | Coordinates are subtly wrong; offsets of ellipses come out as polylines | 30–50 | [geometry](geometry-parity.md) | -| 4 | **[alpha blocker]** **No dynamic blocks or REFEDIT; xrefs can't be edited in place or clipped** (xrefs, #525, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) | +| 4 | **[alpha blocker]** **No dynamic blocks or REFEDIT; xrefs can't be clipped** (xrefs, #525, REFEDIT on blocks and xrefs, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) | | 5 | **No autosave in the web build** (the desktop app has SAVETIME autosave, Drawing Recovery, AUDIT and RECOVER since #406) | Browser users lose unsaved work when the tab or the browser goes down | 3–5 | [features](#features) | | 6 | **No CI runs the Rust tests on pull requests** (`cargo fmt` on main is fixed) | open PRs land without a gate; regressions go unseen | 2–3 | [stability](#stability) | @@ -25,7 +25,7 @@ do them first. | # | Gap | Evidence | User impact | Est. | |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | -| F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | +| F2 | XREF clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813). An xref, or a block that came with one, is edited in place too and REFCLOSE Save writes its source drawing back (the old file kept as `.bak`; refused when the file is read-only, locked by another program, open in another tab or changed since it was loaded), nested references are picked through their parents ("Select nesting level [OK/Next]", `refedit.levels`), the rest of the drawing is drawn faded (XFADECTL) and an Edit Reference bar offers Add to/Remove from Working Set and Save/Discard Changes (2026-10-27); left: attribute sync of other references (ATTSYNC) and xrefs nested in xrefs (XOPEN opens them). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs`, `cmd/blocks/refedit.rs` | Medium: xrefs can't be clipped | 8–14 | | F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | REFEDIT on xrefs writes the source drawing back on REFCLOSE Save (backup, refused for read-only, locked, open or changed files, the xref reloaded from what was written), nested references picked through their parents (`path`, `nested`, `refedit.levels`, "Select nesting level [OK/Next]"), everything outside the working set drawn faded (XFADECTL), and the Edit Reference bar with Add to/Remove from Working Set and Save/Discard Changes: F2 and top-10 row 4 narrowed | | 2026-10-25 | minor | Named Viewports (View ▸ Viewports ▸ Named Viewports..., `vports.named`) lists the saved viewport configurations with a preview and the current one's name, and restores or deletes one; in a layout Restore places it as MVIEW Restore does: U11 narrowed. F15 and U11 no longer list MVIEW Restore (#633), and F21 no longer says PURGE skips multiline styles | | 2026-10-25 | minor | DIMTFILL limits: with DIMTFILL 1 (the drawing's background color) the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI: F7 updated | | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b5407d60..d9d593dab 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: CADCraft vs AutoCAD 2027 -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (COMPAREEXPORT; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (REFEDIT on xrefs; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 The authoritative assessment of how close CADCraft is to AutoCAD, and how much Opus 5.5 work remains. [ROADMAP.md](../ROADMAP.md) summarises it, [gaps.md](gaps.md) lists every shortfall, @@ -154,7 +154,7 @@ presence: an option that prints "not available yet" doesn't count. | Text and MTEXT | 6% | 35% | 30–45 | TrueType, formatting codes, stacking; MTEXT prompt options (#408), indents, tabs, bullets, numbering and columns (#547), annotative scaling (#468); editor is a dialog, not in place; no fields or SPELL (open PR #551), no SHX | [gaps](gaps.md#features) | | Leaders, tables, fields | 4% | 25% | 25–35 | MLEADER options and block content (#408), native MULTILEADER in DXF (#459); tables with cell styles, formulas, breaking and CSV data links (#534); no MLEADEREDIT/ALIGN/COLLECT, no FIELD | [gaps](gaps.md#features) | | Hatch and gradients | 5% | 35% | 15–25 | pick points with islands; 23 patterns of ~85; gradients render flat; origin, gap tolerance, separate hatches, island styles and HATCHEDIT options (#451); Hatch and Gradient / Hatch Edit dialogs (no Preview or Inherit Properties) | [gaps](gaps.md#features) | -| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; no dynamic-block authoring, XCLIP, DesignCenter | [gaps](gaps.md#features) | +| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT on blocks, nested references and xrefs (the xref's drawing written back); dynamic block references read and edited; no dynamic-block authoring, XCLIP, DesignCenter | [gaps](gaps.md#features) | | Layouts, viewports, plotting | 9% | 35% | 35–50 | layouts, per-VP layers, page setups, plot styles (CTB/STB), Plot dialog (#160), Plot Preview and PUBLISH (#186), plotter devices (#564), PDF with text, layers and sheets (#567, #571), polygonal/object/clipped viewports (#453), annotative scales (#468); no MVIEW Restore, no system printers | [gaps](gaps.md#features) | | Inquiry and utilities | 4% | 30% | 30–45 | DIST, AREA, ID, LIST, MEASUREGEOM, CAL, FIND, COUNT across layouts, QuickCalc, COMPARE (#563) and COMPAREEXPORT, MASSPROP on regions (#510), autosave/recovery, AUDIT, RECOVER (#406), OPTIONS (#23); no SPELL (open PR #551), ETRANSMIT | [gaps](gaps.md#features) | | Parametric constraints | 2% | 50% | 20–30 | all 12 geometric and the dimensional constraints, own solver; DOF report, G2 Smooth, ellipse/spline/block geometry and CONSTRAINTINFER landed (#546) | [geometry-parity](geometry-parity.md#constraint-solver--50) | @@ -223,6 +223,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Blocks, attributes, xrefs, groups row: REFEDIT edits nested references and xrefs in place, writing the xref's drawing back; parity percentages and hours not re-measured | | 2026-10-24 | minor | Inquiry and utilities row: COMPAREEXPORT exports a comparison to a new drawing; parity percentages and hours not re-measured | | 2026-10-22 | minor | Draw row: RECTANG gained a centre construction mode (`Center` keyword, `center: true`) beside its corner mode (#1127); parity percentages and hours not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured | From b27cc3ce22a8f2db7c9b16b5f59b337f2fdf1f45 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Fri, 20 Nov 2026 08:20:51 +0100 Subject: [PATCH 02/11] REFCLOSE: write an xref back the way SAVE writes a drawing The write-back made its own temporary file (`.cadcraft-tmp`, opened with a plain truncating write) and copied the backup with fs::copy, so a symbolic link planted at either path took the write: the drawing went into the link's target and the xref's path became that link (CWE-59). It now goes through what SAVE uses: the backup is file::backup (written atomically, a link at the .bak replaced, never written through) and the new file atomic_write::write_atomic_with (an exclusively created temporary file renamed over the file). The file written is the one the xref's path led to when the edit began; REFCLOSE refuses when the path leads elsewhere by then (a link put there during the edit). The backup is named by file::backup_path, as SAVE names it: site.dwg's is site.bak, site.dxf's site.dxf.bak, so two xrefs of one name in one folder no longer share (and overwrite) one site.bak. Review of #2355, points 1 and 4. --- crates/doc/src/refedit.rs | 3 + crates/engine/src/cmd/blocks/refedit.rs | 82 ++++++++++++------ crates/engine/src/cmd/file.rs | 12 +-- crates/engine/tests/it/refedit_xref.rs | 109 +++++++++++++++++++++++- 4 files changed, 173 insertions(+), 33 deletions(-) diff --git a/crates/doc/src/refedit.rs b/crates/doc/src/refedit.rs index 78dfa1764..80ac1635a 100644 --- a/crates/doc/src/refedit.rs +++ b/crates/doc/src/refedit.rs @@ -57,6 +57,9 @@ pub struct XrefSource { pub xref: String, /// The source drawing file. pub file: String, + /// `file` with every symbolic link resolved when the edit began: the file that is written. + /// The save is refused when `file` leads somewhere else by then. + pub real: String, /// The block of the source drawing being edited; `None` for its model space. pub block: Option, /// The file's size and modification time (nanoseconds since 1970) when the edit began. diff --git a/crates/engine/src/cmd/blocks/refedit.rs b/crates/engine/src/cmd/blocks/refedit.rs index c75807aea..f75630b61 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -13,9 +13,11 @@ //! stand faded around it. //! //! An xref (or a block that came with one) is edited the same way, and REFCLOSE Save writes the -//! change into its source drawing: the previous file is kept as `name.bak`, and the save is -//! refused when the file is read-only, open in another program (or another drawing tab), or -//! changed since it was loaded. The xref is then loaded again from the file it wrote. +//! change into its source drawing the way SAVE writes a drawing: the previous file is kept as its +//! `.bak`, the new one replaces it atomically, and a symbolic link planted beside it or put at its +//! path during the edit never redirects the write. The save is refused when the file is +//! read-only, open in another program (or another drawing tab), or changed since it was loaded. +//! The xref is then loaded again from the file it wrote. //! //! The state is [`Drawing::refedit`]: it travels with undo, is never written to a file (files //! are written from [`Drawing::committed`]) and ends with the drawing it belongs to. @@ -59,7 +61,7 @@ pub(super) fn specs() -> Vec { .interactive(|_| Ok(Box::new(RefsetM::default()))), CommandSpec::new("refclose", "Save Reference Edits", run_refclose) .menu(&["Tools", "Xref and Block In-place Editing", "Save Reference Edits"]) - .params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects, file? (an xref's source drawing written), backup?}") + .params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects, file? (an xref's source drawing written), backup? (its previous file, as SAVE names it; null when none was kept)}") .enabled(editing) .interactive(|_| Ok(Box::new(RefcloseM))), ] @@ -322,7 +324,15 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { let file = xref_file(s, &x)?; let src = load::read_file(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; let sources = source_handles(&blk, &src, inner.as_deref())?; - Some(XrefSource { xref: x, file: file.to_string_lossy().into_owned(), block: inner, stamp: load::stamp(&file), sources }) + let real = std::fs::canonicalize(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; + Some(XrefSource { + xref: x, + file: file.to_string_lossy().into_owned(), + real: real.to_string_lossy().into_owned(), + block: inner, + stamp: load::stamp(&file), + sources, + }) } None => None, }; @@ -521,6 +531,7 @@ fn close(s: &mut Session, save: bool) -> Result { let mut out = json!({ "block": r.block, "saved": save, "objects": objects }); if let (Some(x), Some(backup)) = (&r.xref, written) { out["file"] = json!(x.file); + // `null` when the file didn't look like a whole drawing and the `.bak` there was kept. out["backup"] = json!(backup); } Ok(out) @@ -574,10 +585,13 @@ fn commit_block(nd: &mut Drawing, r: &RefEdit) -> Result { // ---------------- writing an xref back ---------------- -/// Write the edited block of `nd` (committed) into xref source `x`. Returns the backup's path. -fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result { +/// Write the edited block of `nd` (committed) into xref source `x`. Returns the backup's path +/// (`None` when none was kept). +fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result> { let file = std::path::Path::new(&x.file); + let real = std::path::Path::new(&x.real); writable(file).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?; + still_leads_to(file, real).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?; if load::stamp(file) != x.stamp { return Err(bad( "refclose", @@ -616,7 +630,19 @@ fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result { } } let bytes = (hooks.write)(&src, &x.file).map_err(|e| bad("refclose", format!("writing {}: {e}", file.display())))?; - replace_file(file, &bytes).map_err(|e| bad("refclose", e)) + replace_file(file, real, &bytes).map_err(|e| bad("refclose", e)) +} + +/// Refuse a save when `file` no longer leads to `real` (the file the edit began with), or `real` +/// is no longer a plain file: a symbolic link put at either since would send the edit to another +/// file. +fn still_leads_to(file: &std::path::Path, real: &std::path::Path) -> std::result::Result<(), String> { + let now = std::fs::canonicalize(file).map_err(|e| format!("{}: {e}", file.display()))?; + let plain = std::fs::symlink_metadata(real).is_ok_and(|m| m.is_file()); + if now != real || !plain { + return Err(format!("{} leads to another file than when the edit began (a symbolic link was put there); it is not overwritten", file.display())); + } + Ok(()) } /// Symbol names of a host object as the xref's drawing has them: `xref|name` loses its prefix; @@ -699,28 +725,29 @@ fn bring_symbols(host: &Drawing, src: &mut Drawing, prefix: &str, mut wanted: Ve } } -/// Replace `file` by `bytes`: the old file is kept as `name.bak`, the new one is written beside -/// it and moved over it. Returns the backup's path. -fn replace_file(file: &std::path::Path, bytes: &[u8]) -> std::result::Result { +/// Replace the xref's file (`file` as the xref names it, `real` the file it leads to) by `bytes`, +/// the way SAVE replaces a drawing: the old file is kept as its `.bak` +/// ([`crate::cmd::file::backup_path`]: `site.dwg` as `site.bak`, `site.dxf` as `site.dxf.bak`), +/// and the new one goes into a fresh, exclusively created temporary file that is renamed over +/// `real` ([`crate::atomic_write`]). A symbolic link planted at the temporary or backup path is +/// never written through, and a link at `real` is replaced, not followed. Returns the backup's +/// path (`None` when none was kept). +fn replace_file(file: &std::path::Path, real: &std::path::Path, bytes: &[u8]) -> std::result::Result, String> { #[cfg(target_arch = "wasm32")] { - let _ = (file, bytes); + let _ = (file, real, bytes); Err("files are not available on the web".into()) } #[cfg(not(target_arch = "wasm32"))] { - let backup = file.with_extension("bak"); - std::fs::copy(file, &backup) - .map_err(|e| format!("the backup {} can't be written: {e}; {} is unchanged", backup.display(), file.display()))?; - let mut tmp = file.as_os_str().to_owned(); - tmp.push(".cadcraft-tmp"); - let tmp = std::path::PathBuf::from(tmp); - std::fs::write(&tmp, bytes).map_err(|e| format!("{} can't be written: {e}", tmp.display()))?; - if let Err(e) = std::fs::rename(&tmp, file) { - let _ = std::fs::remove_file(&tmp); - return Err(format!("{} can't be replaced: {e}; it is unchanged", file.display())); - } - Ok(backup.to_string_lossy().into_owned()) + let kept = crate::cmd::file::backup(real) + .map_err(|e| format!("the backup copy of {} could not be written ({e}); it is unchanged", file.display()))?; + let permissions = std::fs::symlink_metadata(real).ok().filter(std::fs::Metadata::is_file).map(|m| m.permissions()); + crate::atomic_write::write_atomic_with(real, permissions, |f| std::io::Write::write_all(f, bytes)) + .map_err(|e| format!("{} can't be replaced: {e}; it is unchanged", file.display()))?; + // Named beside the file as the xref names it, unless that name is itself a link. + let shown = if std::fs::symlink_metadata(file).is_ok_and(|m| m.file_type().is_symlink()) { real } else { file }; + Ok(kept.then(|| crate::cmd::file::backup_path(shown).to_string_lossy().into_owned())) } } @@ -944,9 +971,10 @@ impl Interactive for RefcloseM { }; let r = close(s, save)?; s.echo(match (save, r.get("file").and_then(Value::as_str)) { - (true, Some(f)) => { - format!("Reference changes saved to {f} (the previous file is kept as {}).", r["backup"].as_str().unwrap_or("a .bak file")) - } + (true, Some(f)) => match r["backup"].as_str() { + Some(b) => format!("Reference changes saved to {f} (the previous file is kept as {b})."), + None => format!("Reference changes saved to {f}."), + }, (true, None) => "Reference changes saved.".to_string(), (false, _) => "Reference changes discarded.".to_string(), }); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index cb28c2d45..821fb0306 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -681,19 +681,20 @@ fn adopt_source_group(out: &std::fs::File, src: &std::fs::Metadata) -> std::io:: /// ([`crate::atomic_write::write_atomic_with`]). Nothing /// to keep when there is no file yet. A file that doesn't look like a drawing /// ([`looks_like_drawing`]) is not backed up, and the `.bak` already there is left alone. +/// Returns whether the backup was written. Also used for an xref REFEDIT writes back. #[cfg(not(target_arch = "wasm32"))] -fn backup(path: &std::path::Path) -> std::io::Result<()> { +pub(crate) fn backup(path: &std::path::Path) -> std::io::Result { let mut src = match std::fs::File::open(path) { Ok(f) if f.metadata()?.is_file() => f, - Ok(_) => return Ok(()), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Ok(_) => return Ok(false), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), Err(e) => return Err(e), }; let (head, tail, len) = ends(&mut src)?; let bak = backup_path(path); if !backup_replaced(&head, &tail, len, bak.exists()) { log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display()); - return Ok(()); + return Ok(false); } // The backup is no more readable than the drawing, nor than the .bak it replaces (a private // 0600 drawing or .bak stays private). The mode is set as the new file is created, so a @@ -719,7 +720,8 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> { } std::io::Write::write_all(out, &head)?; std::io::copy(&mut src, out).map(|_| ()) - }) + })?; + Ok(true) } /// Store the bytes, then mark the drawing saved under `path`. If storing fails the drawing keeps diff --git a/crates/engine/tests/it/refedit_xref.rs b/crates/engine/tests/it/refedit_xref.rs index ef6b93c7c..591046341 100644 --- a/crates/engine/tests/it/refedit_xref.rs +++ b/crates/engine/tests/it/refedit_xref.rs @@ -115,7 +115,9 @@ fn editing_an_xref_writes_its_drawing_back_with_a_backup() { let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); assert_eq!(out["objects"], 3); assert!(out["file"].as_str().unwrap().ends_with("site.dxf")); - assert!(dir.join("site.bak").is_file(), "the previous file is kept"); + let bak = dir.join("site.dxf.bak"); + assert!(out["backup"].as_str().unwrap().ends_with("site.dxf.bak"), "{out}"); + assert_eq!(read(&bak).model.len(), 2, "the previous file is kept"); // The file holds the edit, in its own coordinates, with the line's own handle. let back = read(&file); assert_eq!(back.model.len(), 3); @@ -241,3 +243,108 @@ fn nested_block_references_are_picked_through_their_parents() { assert!(s.execute("refedit", &json!({ "handle": o, "nested": "Nope" })).is_err()); let _ = Vec2::ZERO; } + +/// A symbolic link at `link` to `target`; `None` where the system doesn't let a test make one +/// (Windows without the privilege), and the test is skipped there. CI runs it on Linux. +fn symlink(target: &Path, link: &Path) -> Option<()> { + #[cfg(unix)] + let made = std::os::unix::fs::symlink(target, link); + #[cfg(windows)] + let made = std::os::windows::fs::symlink_file(target, link); + #[cfg(not(any(unix, windows)))] + let made: std::io::Result<()> = Err(std::io::Error::other("no symbolic links")); + match made { + Ok(()) => Some(()), + Err(e) => { + eprintln!("skipped: symbolic links can't be made here ({e})"); + None + } + } +} + +fn is_plain_file(p: &Path) -> bool { + std::fs::symlink_metadata(p).is_ok_and(|m| m.is_file()) +} + +/// Review of #2355: a link planted at the temporary or backup path beside the xref must not take +/// the write (CWE-59). Before, the new bytes went into `victim.txt` through `site.dxf.cadcraft-tmp` +/// and `site.dxf` itself became that link. +#[test] +fn links_planted_beside_the_xref_are_not_written_through() { + let (mut s, dir, _, insert) = attached("planted"); + let file = dir.join("site.dxf"); + let (victim, other) = (dir.join("victim.txt"), dir.join("other.txt")); + std::fs::write(&victim, b"victim").unwrap(); + std::fs::write(&other, b"other").unwrap(); + if symlink(&victim, &dir.join("site.dxf.cadcraft-tmp")).is_none() { + return; + } + symlink(&other, &dir.join("site.dxf.bak")).unwrap(); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(std::fs::read(&victim).unwrap(), b"victim", "nothing is written through the planted link"); + assert_eq!(std::fs::read(&other).unwrap(), b"other", "nor through a link at the backup"); + assert!(is_plain_file(&file), "the xref's file is still a file, not a link"); + assert_eq!(read(&file).model.len(), 3, "and holds the edit"); + assert!(is_plain_file(&dir.join("site.dxf.bak")), "the link at the backup is replaced by the backup"); + assert_eq!(read(&dir.join("site.dxf.bak")).model.len(), 2); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Review of #2355: the xref's own path turned into a link to another file during the edit (here +/// a byte-identical copy with the same time, so the change check can't tell) is not written. +#[test] +fn an_xref_path_turned_into_a_link_during_the_edit_is_not_written() { + let (mut s, dir, _, insert) = attached("swapped"); + let file = dir.join("site.dxf"); + let elsewhere = dir.join("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + let target = elsewhere.join("victim.dxf"); + if symlink(&file, &dir.join("probe")).is_none() { + return; + } + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + let modified = std::fs::metadata(&file).unwrap().modified().unwrap(); + std::fs::copy(&file, &target).unwrap(); + std::fs::OpenOptions::new().write(true).open(&target).unwrap().set_modified(modified).unwrap(); + std::fs::rename(&file, dir.join("moved.dxf")).unwrap(); + symlink(&target, &file).unwrap(); + let before = std::fs::read(&target).unwrap(); + let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string(); + assert!(e.contains("leads to another file"), "{e}"); + assert_eq!(std::fs::read(&target).unwrap(), before, "the link's target is untouched"); + assert!(!elsewhere.join("victim.dxf.bak").exists() && !dir.join("site.dxf.bak").exists(), "no backup either"); + assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open"); + s.execute("refclose", &json!({ "option": "discard" })).unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Review of #2355: `site.dxf` and `site.dwg` in one folder both used to back up to `site.bak`, +/// so editing one and then the other lost the first one's old copy. They keep their own now, named +/// as SAVE names them (`site.dxf.bak`, `site.bak`). +#[test] +fn xrefs_of_one_name_in_one_folder_keep_their_own_backups() { + hooks(); + let dir = folder("two-backups"); + let (d, _) = site(); + let (dxf, dwg) = (dir.join("site.dxf"), dir.join("site.dwg")); + save(&d, &dxf); + save(&d, &dwg); + let (old_dxf, old_dwg) = (std::fs::read(&dxf).unwrap(), std::fs::read(&dwg).unwrap()); + let host = dir.join("host.dxf"); + save(&Drawing::new_metric(), &host); + let mut s = Session::new(); + s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap(); + for (path, name, x) in [("site.dxf", "a", 0), ("site.dwg", "b", 100)] { + let r = s.execute("xattach", &json!({ "path": path, "name": name, "at": [x, 0] })).unwrap(); + s.execute("refedit", &json!({ "handle": r["handle"] })).unwrap(); + s.execute("line", &json!({ "points": [[x, 20], [x + 10, 20]] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + } + assert_eq!(std::fs::read(dir.join("site.dxf.bak")).unwrap(), old_dxf, "the DXF's previous file"); + assert_eq!(std::fs::read(dir.join("site.bak")).unwrap(), old_dwg, "the DWG's previous file"); + assert_eq!((read(&dxf).model.len(), read(&dwg).model.len()), (3, 3), "both hold their edit"); + let _ = std::fs::remove_dir_all(&dir); +} From 64e0b5c2a48ce3622f3ebcd723ebb1d87e2af989 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Fri, 20 Nov 2026 08:22:23 +0100 Subject: [PATCH 03/11] REFCLOSE: write an xref back in the version it was read in The write-back used IoHooks::write, which picks the version from the drawing: an R2000 DWG xref came back as a 2004 DWG (a DWG is written at 2004 or later by default) and an R12 DXF one as R2000. An xref is often someone else's file, and a version change can lock its author out. REFEDIT now records the file's version (a DWG's from its first bytes, a DXF's $ACADVER) and whether it is a binary DXF, and REFCLOSE writes it back through the write_as hook at that version and form. A version CADCraft doesn't write (R12) is refused before the edit begins, so no work is lost; so is a build without the write_as hook. REFEDIT's result names the version. Review of #2355, point 2. --- crates/doc/src/refedit.rs | 5 ++ crates/engine/src/cmd/blocks/refedit.rs | 53 ++++++++++++- crates/engine/tests/it/refedit_xref.rs | 99 ++++++++++++++++++++++++- 3 files changed, 153 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/refedit.rs b/crates/doc/src/refedit.rs index 80ac1635a..fcf1b60e7 100644 --- a/crates/doc/src/refedit.rs +++ b/crates/doc/src/refedit.rs @@ -60,6 +60,11 @@ pub struct XrefSource { /// `file` with every symbolic link resolved when the edit began: the file that is written. /// The save is refused when `file` leads somewhere else by then. pub real: String, + /// The version the file was in when the edit began, as its `$ACADVER` code ("AC1015"): it + /// is written back in that version (`None`: in the drawing's own). + pub version: Option, + /// Whether the file is a binary DXF (written back as one). + pub binary: bool, /// The block of the source drawing being edited; `None` for its model space. pub block: Option, /// The file's size and modification time (nanoseconds since 1970) when the edit began. diff --git a/crates/engine/src/cmd/blocks/refedit.rs b/crates/engine/src/cmd/blocks/refedit.rs index f75630b61..3928c59c1 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -36,6 +36,7 @@ use super::super::curves::handle_value; use super::super::machines::{SelOutcome, SelectPhase}; use super::references_block; use super::xref::load::{self, Sym}; +use crate::cmd::file::Version; use crate::cmd::{CommandSpec, bad, bool_or, has_doc, str_param, targets}; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; @@ -47,7 +48,7 @@ pub(super) fn specs() -> Vec { CommandSpec::new("refedit", "Edit Reference In-Place", run_refedit) .menu(&["Tools", "Xref and Block In-place Editing", "Edit Reference In-Place"]) .alias(&["-refedit"]) - .params("{handle? | handles? | name? (a block or xref reference, default the selection), path?: [handles of nested block references, outermost first] | nested?: block name (the first nested reference to it), objects?: [block object handles] (default all)} → {block, insert, working: [handles], faded, path, xref?: {name, file}}. Editing an xref writes its file back on REFCLOSE Save.") + .params("{handle? | handles? | name? (a block or xref reference, default the selection), path?: [handles of nested block references, outermost first] | nested?: block name (the first nested reference to it), objects?: [block object handles] (default all)} → {block, insert, working: [handles], faded, path, xref?: {name, file, version: its $ACADVER, binary}}. Editing an xref writes its file back on REFCLOSE Save, in the version and form it was read in (refused for versions CADCraft does not write, such as R12).") .enabled(has_doc) .interactive(|_| Ok(Box::new(RefeditM::default()))), CommandSpec::new("refedit.levels", "Reference Nesting Levels", run_levels) @@ -278,6 +279,40 @@ fn source_handles(blk: &Block, src: &Drawing, inner: Option<&str>) -> Result Result<(Option, bool)> { + use std::io::Read; + let mut head = Vec::new(); + std::fs::File::open(file) + .and_then(|f| f.take(4096).read_to_end(&mut head)) + .map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; + let dwg = head + .get(..6) + .filter(|t| t.starts_with(b"AC") && t.get(2..).is_some_and(|d| d.iter().all(u8::is_ascii_digit))) + .map(|t| String::from_utf8_lossy(t).into_owned()); + let declared = || src.foreign.version.clone().or_else(|| src.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).map(str::to_string)); + let version = dwg.or_else(declared).map(|v| v.trim().to_ascii_uppercase()); + if let Some(code) = &version + && Version::parse(code).is_none_or(|v| v.code() != code) + { + return Err(bad( + "refedit", + format!( + "{} is an {code} file, and CADCraft writes only 2000 to 2018 files, so the edit couldn't be saved in the file's own version; open it with XOPEN instead", + file.display() + ), + )); + } + let binary = craft_dxf::is_binary(&head); + if (version.is_some() || binary) && crate::cmd::file::write_as().is_none() { + return Err(bad("refedit", "saving an xref in its own version is not available in this build; open it with XOPEN instead")); + } + Ok((version, binary)) +} + // ---------------- REFEDIT ---------------- fn run_refedit(s: &mut Session, p: &Value) -> Result { @@ -325,10 +360,13 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { let src = load::read_file(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; let sources = source_handles(&blk, &src, inner.as_deref())?; let real = std::fs::canonicalize(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; + let (version, binary) = file_form(&file, &src)?; Some(XrefSource { xref: x, file: file.to_string_lossy().into_owned(), real: real.to_string_lossy().into_owned(), + version, + binary, block: inner, stamp: load::stamp(&file), sources, @@ -396,7 +434,7 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { "working": hexes(r.items.iter().map(|i| i.copy)), "faded": r.ghosts.len(), "path": hexes(r.path.iter().copied()), - "xref": r.xref.as_ref().map(|x| json!({ "name": x.xref, "file": x.file })), + "xref": r.xref.as_ref().map(|x| json!({ "name": x.xref, "file": x.file, "version": x.version, "binary": x.binary })), }); let sel: Vec = r.items.iter().map(|i| i.copy).collect(); doc.refedit = Some(r); @@ -629,7 +667,16 @@ fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result (Session, String) { + let host = dir.join("host.dxf"); + save(&Drawing::new_metric(), &host); + let mut s = Session::new(); + s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap(); + let r = s.execute("xattach", &json!({ "path": file, "name": name, "at": [100, 0] })).unwrap(); + (s, r["handle"].as_str().unwrap().to_string()) +} + +/// The `$ACADVER` an ASCII DXF declares. +fn dxf_version(bytes: &[u8]) -> Option { + let text = String::from_utf8_lossy(bytes); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + lines.windows(3).find(|w| w[0] == "$ACADVER" && w[1] == "1").map(|w| w[2].to_string()) +} + +/// Review of #2355: the xref was saved in the writer's default version (an R2000 DWG came back +/// as 2004, AC1018). It is written back in the version, and form, it was read in. +#[test] +fn an_xref_is_written_back_in_the_version_it_was_read_in() { + hooks(); + let dir = folder("versions"); + let (d, _) = site(); + let write = |name: &str, version: Version, binary: bool| { + let p = dir.join(name); + let opts = cadcraft_io::SaveOptions { version: Some(version), binary }; + std::fs::write(&p, cadcraft_io::write_with(&d, &p, &opts).unwrap()).unwrap(); + p + }; + let dwg = write("old.dwg", Version::R2000, false); + let dxf = write("old.dxf", Version::R2004, false); + let bin = write("bin.dxf", Version::R2010, true); + assert_eq!((&std::fs::read(&dwg).unwrap()[..6], dxf_version(&std::fs::read(&dxf).unwrap()).as_deref()), (&b"AC1015"[..], Some("AC1018"))); + for (file, name) in [("old.dwg", "a"), ("old.dxf", "b"), ("bin.dxf", "c")] { + let (mut s, insert) = host_with(&dir, file, name); + let r = s.execute("refedit", &json!({ "handle": insert })).unwrap(); + assert_eq!(r["xref"]["binary"], file == "bin.dxf", "{r}"); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + } + let (dwg_bytes, dxf_bytes, bin_bytes) = (std::fs::read(&dwg).unwrap(), std::fs::read(&dxf).unwrap(), std::fs::read(&bin).unwrap()); + assert_eq!(&dwg_bytes[..6], b"AC1015", "the R2000 DWG stays R2000"); + assert_eq!(dxf_version(&dxf_bytes).as_deref(), Some("AC1018"), "the 2004 DXF stays 2004"); + assert!(bin_bytes.starts_with(b"AutoCAD Binary DXF"), "the binary DXF stays binary"); + assert_eq!(read(&bin).header.get("ACADVER").and_then(cadcraft_engine::doc::HVal::as_str), Some("AC1024"), "and 2010"); + assert_eq!((read(&dwg).model.len(), read(&dxf).model.len(), read(&bin).model.len()), (3, 3, 3), "each holds its edit"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Review of #2355: an R12 DXF xref came back as an R2000 one. CADCraft doesn't write R12, so the +/// edit is refused before it begins (no work lost), and the file is left as it is. +#[test] +fn an_xref_in_a_version_cadcraft_cannot_write_is_not_edited_in_place() { + hooks(); + let dir = folder("r12"); + let r12 = "0 +SECTION +2 +HEADER +9 +$ACADVER +1 +AC1009 +0 +ENDSEC +0 +SECTION +2 +ENTITIES +0 +LINE +8 +0 +10 +0 +20 +0 +11 +1 +21 +1 +0 +ENDSEC +0 +EOF +"; + std::fs::write(dir.join("r12.dxf"), r12).unwrap(); + let (mut s, insert) = host_with(&dir, "r12.dxf", "old"); + let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("AC1009") && e.contains("XOPEN"), "{e}"); + assert!(s.doc().unwrap().refedit.is_none()); + assert_eq!(std::fs::read_to_string(dir.join("r12.dxf")).unwrap(), r12, "the file is untouched"); + let _ = std::fs::remove_dir_all(&dir); +} From 88ef222cdfc60a46d922999885ea73da4d5da97d Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Fri, 20 Nov 2026 08:29:18 +0100 Subject: [PATCH 04/11] REFEDIT xref tests: follow main's io and Insert after the merge cadcraft_io::read and write take a path now, and Insert has a clip. --- crates/engine/tests/it/refedit_xref.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/it/refedit_xref.rs b/crates/engine/tests/it/refedit_xref.rs index a55aa8391..e06ed82bb 100644 --- a/crates/engine/tests/it/refedit_xref.rs +++ b/crates/engine/tests/it/refedit_xref.rs @@ -29,11 +29,11 @@ fn folder(tag: &str) -> PathBuf { } fn save(d: &Drawing, path: &Path) { - std::fs::write(path, cadcraft_io::write(d, &path.to_string_lossy()).unwrap()).unwrap(); + std::fs::write(path, cadcraft_io::write(d, path).unwrap()).unwrap(); } fn read(path: &Path) -> Drawing { - cadcraft_io::read(&std::fs::read(path).unwrap(), &path.to_string_lossy()).unwrap() + cadcraft_io::read(&std::fs::read(path).unwrap(), path).unwrap() } fn line(d: &mut Drawing, layer: &str, a: (f64, f64), b: (f64, f64)) -> Handle { @@ -55,6 +55,7 @@ fn insert(block: &str, at: Vec3) -> Insert { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, } } From 7a199cc2e1ef9219142e1d58c4ca8046ef39a69c Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Fri, 20 Nov 2026 08:29:25 +0100 Subject: [PATCH 05/11] REFCLOSE: say what the xref's file couldn't keep SAVE and SAVEAS list what the writer drops; the write-back wrote the source drawing straight through and said nothing, so a DWG xref holding types the DWG writer can't keep (or a 2013+ DXF one holding solids with SAT-text geometry) lost them silently. REFCLOSE now counts them as SAVE does, for the version the file is written in (file::loss_writing: not_saved_as for DWG, sat_text_dropped for 2013+ DXF), echoes the same warning prefixed with the file and naming the backup that still has them, and lists them in the result's notSaved. Nothing lost, no warning. Review of #2355, point 3. --- crates/engine/src/cmd/blocks/refedit.rs | 29 ++++++++--- crates/engine/src/cmd/file.rs | 38 +++++++++++--- crates/engine/tests/it/refedit_xref.rs | 67 +++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/blocks/refedit.rs b/crates/engine/src/cmd/blocks/refedit.rs index 3928c59c1..adf4b72d5 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -62,7 +62,7 @@ pub(super) fn specs() -> Vec { .interactive(|_| Ok(Box::new(RefsetM::default()))), CommandSpec::new("refclose", "Save Reference Edits", run_refclose) .menu(&["Tools", "Xref and Block In-place Editing", "Save Reference Edits"]) - .params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects, file? (an xref's source drawing written), backup? (its previous file, as SAVE names it; null when none was kept)}") + .params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects, file? (an xref's source drawing written), backup? (its previous file, as SAVE names it; null when none was kept), notSaved?: {type: count} (what the file couldn't keep, also echoed)}") .enabled(editing) .interactive(|_| Ok(Box::new(RefcloseM))), ] @@ -567,14 +567,27 @@ fn close(s: &mut Session, save: bool) -> Result { s.echo(o.message()); } let mut out = json!({ "block": r.block, "saved": save, "objects": objects }); - if let (Some(x), Some(backup)) = (&r.xref, written) { + if let (Some(x), Some(w)) = (&r.xref, written) { out["file"] = json!(x.file); // `null` when the file didn't look like a whole drawing and the `.bak` there was kept. - out["backup"] = json!(backup); + out["backup"] = json!(w.backup); + // What the file couldn't keep, said as SAVE says it (nothing is dropped silently). + if let Some(msg) = crate::cmd::file::loss_message(&x.file, &w.lost) { + let kept = w.backup.as_ref().map(|b| format!(" The previous file, with them, is kept as {b}.")).unwrap_or_default(); + s.echo(format!("{}: {msg}.{kept}", x.file)); + out["notSaved"] = json!(w.lost); + } } Ok(out) } +/// What writing an xref back did: the backup it kept, and what the file couldn't keep +/// ([`crate::cmd::file::loss_writing`]). +struct Written { + backup: Option, + lost: std::collections::BTreeMap, +} + /// Replace the block's objects by the working set (and move the drawing objects added to it /// into the block). Returns the number of objects the block has now. fn commit_block(nd: &mut Drawing, r: &RefEdit) -> Result { @@ -623,9 +636,8 @@ fn commit_block(nd: &mut Drawing, r: &RefEdit) -> Result { // ---------------- writing an xref back ---------------- -/// Write the edited block of `nd` (committed) into xref source `x`. Returns the backup's path -/// (`None` when none was kept). -fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result> { +/// Write the edited block of `nd` (committed) into xref source `x`. +fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result { let file = std::path::Path::new(&x.file); let real = std::path::Path::new(&x.real); writable(file).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?; @@ -677,7 +689,10 @@ fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result std::collections::BTreeMap std::collections::BTreeMap { + if is_dxf_file(path) { + return if version >= Version::R2013 { cadcraft_doc::foreign::sat_text_dropped(d) } else { Default::default() }; + } + if drops_unknown(path) { not_saved_as(d, version) } else { Default::default() } +} + +/// The command-line warning for [`loss_writing`] of `path`, or `None` when the file keeps everything. +pub fn loss_message(path: &str, lost: &std::collections::BTreeMap) -> Option { + if is_dxf_file(path) { sat_text_message(lost) } else { not_saved_message(lost) } +} + +/// The warning for solid modeler entities a DXF of 2013 or later leaves out, or `None`. +fn sat_text_message(lost: &std::collections::BTreeMap) -> Option { + if lost.is_empty() { + return None; + } + let list: Vec = lost.iter().map(|(t, n)| format!("{n} {t}")).collect(); + Some(format!( + "Not saved in the DXF file (2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them): {}", + list.join(", ") + )) +} + /// Report what the file `path`, just written at the drawing's own version, left out. pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) { if is_dxf_file(path) { @@ -935,14 +963,8 @@ fn is_dxf_file(path: impl AsRef) -> bool { fn report_sat_text_dropped(s: &mut Session, r: &mut Value) { // The drawing a file holds: the host while the Block Editor is open. let lost = s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default(); - if lost.is_empty() { - return; - } - let list: Vec = lost.iter().map(|(t, n)| format!("{n} {t}")).collect(); - s.echo(format!( - "Not saved in the DXF file (2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them): {}", - list.join(", ") - )); + let Some(msg) = sat_text_message(&lost) else { return }; + s.echo(msg); if let Some(o) = r.as_object_mut() { o.insert("notSaved".into(), json!(lost)); } diff --git a/crates/engine/tests/it/refedit_xref.rs b/crates/engine/tests/it/refedit_xref.rs index e06ed82bb..2ea4294d5 100644 --- a/crates/engine/tests/it/refedit_xref.rs +++ b/crates/engine/tests/it/refedit_xref.rs @@ -116,6 +116,7 @@ fn editing_an_xref_writes_its_drawing_back_with_a_backup() { s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); assert_eq!(out["objects"], 3); + assert!(out.get("notSaved").is_none() && !s.log.iter().any(|m| m.contains("Not saved")), "the file keeps everything: no warning"); assert!(out["file"].as_str().unwrap().ends_with("site.dxf")); let bak = dir.join("site.dxf.bak"); assert!(out["backup"].as_str().unwrap().ends_with("site.dxf.bak"), "{out}"); @@ -446,3 +447,69 @@ EOF assert_eq!(std::fs::read_to_string(dir.join("r12.dxf")).unwrap(), r12, "the file is untouched"); let _ = std::fs::remove_dir_all(&dir); } + +/// Review of #2355: SAVE says what a file can't keep; the write-back said nothing. A 2013 DXF xref +/// holding a solid whose ACIS geometry is SAT text (no data store record) loses it when written: +/// the save says so, names it in `notSaved`, and points at the backup that still has it. +#[test] +fn what_the_xref_file_cannot_keep_is_reported() { + hooks(); + let dir = folder("lost"); + let dxf = "0 +SECTION +2 +HEADER +9 +$ACADVER +1 +AC1027 +0 +ENDSEC +0 +SECTION +2 +ENTITIES + 0 +LINE +5 +20 +8 +0 +10 +0 +20 +0 +11 +1 +21 +1 + 0 +3DSOLID +5 +21 +100 +AcDbEntity +8 +0 +100 +AcDbModelerGeometry +70 +1 +1 +400 0 1 0 + 0 +ENDSEC +0 +EOF +"; + std::fs::write(dir.join("solid.dxf"), dxf).unwrap(); + let (mut s, insert) = host_with(&dir, "solid.dxf", "solid"); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); + assert_eq!(out["notSaved"], json!({ "3DSOLID": 1 }), "{out}"); + let warning = s.log.iter().find(|m| m.contains("Not saved in the DXF file")).expect("a warning on the command line"); + assert!(warning.contains("1 3DSOLID") && warning.contains("solid.dxf.bak"), "{warning}"); + assert!(std::fs::read_to_string(dir.join("solid.dxf.bak")).unwrap().contains("3DSOLID"), "the backup still has it"); + let _ = std::fs::remove_dir_all(&dir); +} From f9756d50832849d4057a237940324d248e672845 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Fri, 20 Nov 2026 08:32:24 +0100 Subject: [PATCH 06/11] rustfmt the REFCLOSE write-back and its tests --- crates/engine/src/cmd/blocks/refedit.rs | 12 +++++++----- crates/engine/tests/it/refedit_xref.rs | 4 +++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/blocks/refedit.rs b/crates/engine/src/cmd/blocks/refedit.rs index adf4b72d5..f285b2093 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -286,9 +286,7 @@ fn source_handles(blk: &Block, src: &Drawing, inner: Option<&str>) -> Result Result<(Option, bool)> { use std::io::Read; let mut head = Vec::new(); - std::fs::File::open(file) - .and_then(|f| f.take(4096).read_to_end(&mut head)) - .map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; + std::fs::File::open(file).and_then(|f| f.take(4096).read_to_end(&mut head)).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; let dwg = head .get(..6) .filter(|t| t.starts_with(b"AC") && t.get(2..).is_some_and(|d| d.iter().all(u8::is_ascii_digit))) @@ -689,7 +687,8 @@ fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result { w(&src, &x.file, &crate::cmd::file::SaveAs { version, binary: x.binary, portable_fonts: false }) }; let bytes = bytes.map_err(|e| bad("refclose", format!("writing {}: {e}", file.display())))?; - let as_version = version.unwrap_or_else(|| src.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver).unwrap_or_default()); + let as_version = + version.unwrap_or_else(|| src.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver).unwrap_or_default()); let lost = crate::cmd::file::loss_writing(&src, &x.file, as_version); let backup = replace_file(file, real, &bytes).map_err(|e| bad("refclose", e))?; Ok(Written { backup, lost }) @@ -702,7 +701,10 @@ fn still_leads_to(file: &std::path::Path, real: &std::path::Path) -> std::result let now = std::fs::canonicalize(file).map_err(|e| format!("{}: {e}", file.display()))?; let plain = std::fs::symlink_metadata(real).is_ok_and(|m| m.is_file()); if now != real || !plain { - return Err(format!("{} leads to another file than when the edit began (a symbolic link was put there); it is not overwritten", file.display())); + return Err(format!( + "{} leads to another file than when the edit began (a symbolic link was put there); it is not overwritten", + file.display() + )); } Ok(()) } diff --git a/crates/engine/tests/it/refedit_xref.rs b/crates/engine/tests/it/refedit_xref.rs index 2ea4294d5..bcf842c80 100644 --- a/crates/engine/tests/it/refedit_xref.rs +++ b/crates/engine/tests/it/refedit_xref.rs @@ -17,7 +17,9 @@ fn hooks() { write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), plot: None, }); - set_write_as(|d, name, o| cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())); + set_write_as(|d, name, o| { + cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) + }); } /// A fresh folder for one test. From 68fbe896a7faac3ef5afc3403c3af6911a53023f Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Fri, 20 Nov 2026 08:36:48 +0100 Subject: [PATCH 07/11] render: XFADECTL fade in its own function After the merge with main, entity_parts went past clippy's cognitive complexity limit (32/30) with the REFEDIT fade in it. --- crates/render/src/draw.rs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index beea878e1..83116217e 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -43,6 +43,17 @@ pub(crate) fn entity(b: &mut Builder, ctx: &Ctx, e: &Entity) { } } +/// While a reference is edited in place (REFEDIT), everything outside the working set is faded by +/// XFADECTL percent on screen: how much `e` fades (0 when it doesn't). +fn refedit_fade(b: &Builder, ctx: &Ctx, e: &Entity) -> u8 { + match &ctx.d.refedit { + Some(r) if !b.plotting && !r.is_working(if ctx.depth == 0 { e.handle } else { ctx.top }) => { + u8::try_from(ctx.d.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50) + } + _ => 0, + } +} + fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { // A top-level annotative object draws at the view's annotation scale: a viewport's scale for // model space seen through it, else the drawing's (CANNOSCALE in model space, 1:1 on paper). @@ -69,15 +80,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { if b.opts.transparency { b.transparency = transparency(e.common.transparency, layer_transparency, ctx.block_transparency); } - // While a reference is edited in place (REFEDIT) everything outside the working set is - // faded by XFADECTL percent on screen. - if !b.plotting - && let Some(r) = &ctx.d.refedit - && !r.is_working(if ctx.depth == 0 { e.handle } else { ctx.top }) - { - let fade = u8::try_from(ctx.d.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50); - b.transparency = b.transparency.max(fade); - } + b.transparency = b.transparency.max(refedit_fade(b, ctx, e)); // A plot style's linetype replaces the object's. let lt = match b.styles.and_then(|s| s.linetype(rgb, b.named)) { Some(over) => over, From 8920c0fb6fd5efc1850746b232f457612de26af3 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Fri, 20 Nov 2026 09:14:55 +0100 Subject: [PATCH 08/11] i18n: Chinese label for Reference Nesting Levels main now requires every command label in zh.tsv (#1129); refedit.levels came in with this branch. --- crates/ui-egui/src/i18n/zh.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 1e6d29bba..dbd6f4a4a 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -682,6 +682,7 @@ Select an object to measure Select an object to measure Add to Working Set 添加到工作集 Edit Reference In-Place 就地编辑参照 + Reference Nesting Levels 参照嵌套级别 Save Reference Edits 保存参照编辑 Working Set 工作集 Xref and Block In-place Editing 外部参照和块的就地编辑 From 7d1d0ba55b2a34820bc43e3b23509e054d787cfc Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Fri, 20 Nov 2026 09:55:38 +0100 Subject: [PATCH 09/11] render: the REFEDIT fade looks the working set up once per display list entity_parts asked RefEdit::is_working, a scan of the working set, for every object drawn, and read XFADECTL from the header each time: 50,000 working objects meant about a billion handle comparisons per rebuild. The working set is now a hash set built with XFADECTL once per display list (render::Fade) and shared by the serial, parallel and viewport builders. Review of #2355 (CodeRabbit, render/src/draw.rs:50). --- crates/render/src/draw.rs | 6 ++--- crates/render/src/lib.rs | 19 ++++++++++++++++ crates/render/src/pipeline.rs | 40 +++++++++++++++++++++++++++++----- crates/render/src/viewports.rs | 21 ++++++++++++++---- 4 files changed, 72 insertions(+), 14 deletions(-) diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 83116217e..1bd3c5b58 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -46,10 +46,8 @@ pub(crate) fn entity(b: &mut Builder, ctx: &Ctx, e: &Entity) { /// While a reference is edited in place (REFEDIT), everything outside the working set is faded by /// XFADECTL percent on screen: how much `e` fades (0 when it doesn't). fn refedit_fade(b: &Builder, ctx: &Ctx, e: &Entity) -> u8 { - match &ctx.d.refedit { - Some(r) if !b.plotting && !r.is_working(if ctx.depth == 0 { e.handle } else { ctx.top }) => { - u8::try_from(ctx.d.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50) - } + match b.fade { + Some(f) if !b.plotting && !f.working.contains(&if ctx.depth == 0 { e.handle } else { ctx.top }) => f.percent, _ => 0, } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 7d5da3358..9643ed560 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -125,6 +125,24 @@ struct Builder<'a> { shared_budget: Option<&'a std::sync::atomic::AtomicUsize>, /// Transparency (percent) of the entity being drawn. transparency: u8, + /// While a reference is edited in place: what is drawn faded ([`Fade::of`]). + fade: Option<&'a Fade>, +} + +/// While a reference is edited in place (REFEDIT), everything outside the working set is drawn +/// faded by XFADECTL percent on screen. Built once per display list: a lookup per object drawn +/// would scan the working set each time. +struct Fade { + working: std::collections::HashSet, + percent: u8, +} + +impl Fade { + fn of(d: &Drawing) -> Option { + let r = d.refedit.as_ref()?; + let percent = u8::try_from(d.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50); + Some(Fade { working: r.items.iter().map(|i| i.copy).collect(), percent }) + } } /// Upper bound on the block contents drawn per display list (each block reference, MINSERT copy @@ -340,6 +358,7 @@ impl<'a> Builder<'a> { named: self.named, shared_budget: self.shared_budget, transparency: self.transparency, + fade: self.fade, } } /// Take one unit of the block-expansion budget; false once it is spent. diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 3fc72f518..aabfb2a57 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -3,7 +3,7 @@ use super::display::append; use super::display::{DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT}; use super::draw::entity; use super::viewports::{MAX_VIEWPORTS, viewport}; -use super::{Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Handle, Lineweight, Mat3, Space, Vec2, paper, pen, plotstyle, point}; +use super::{Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Fade, Handle, Lineweight, Mat3, Space, Vec2, paper, pen, plotstyle, point}; /// Build options. #[derive(Clone, Debug)] @@ -101,7 +101,17 @@ pub(crate) fn top_ctx<'a>(d: &'a Drawing, xf: Mat3, top: Handle, frozen: &'a [St fn build_space(d: &Drawing, space: &Space, opts: &Options, plotting: bool) -> DisplayList { let opts = &with_point_view(d, space, opts); let styler = style_table(d, space, opts, plotting).map(|t| plotstyle::Styler::new(d, t)); - let mut b = Builder { list: DisplayList::default(), opts, plotting, styles: styler.as_ref(), named: None, shared_budget: None, transparency: 0 }; + let fade = Fade::of(d); + let mut b = Builder { + list: DisplayList::default(), + opts, + plotting, + styles: styler.as_ref(), + named: None, + shared_budget: None, + transparency: 0, + fade: fade.as_ref(), + }; if let Space::Paper(name) = space { b.list.sheet = paper::sheet(d, name); } @@ -148,12 +158,20 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor use rayon::prelude::*; let ents: Vec<&std::sync::Arc> = store.iter().collect(); let budget = std::sync::atomic::AtomicUsize::new(0); - let (opts, plotting) = (b.opts, b.plotting); + let (opts, plotting, fade) = (b.opts, b.plotting, b.fade); let parts: Vec = ents .par_chunks(PARALLEL_CHUNK) .map(|chunk| { - let mut part = - Builder { list: DisplayList::default(), opts, plotting, styles: None, named: None, shared_budget: Some(&budget), transparency: 0 }; + let mut part = Builder { + list: DisplayList::default(), + opts, + plotting, + styles: None, + named: None, + shared_budget: Some(&budget), + transparency: 0, + fade, + }; for e in chunk { entity(&mut part, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e); } @@ -205,7 +223,17 @@ pub fn build_entities<'a, I: IntoIterator>(d: &Drawing, ents: } else { opts }; - let mut b = Builder { list: DisplayList::default(), opts, plotting: false, styles: None, named: None, shared_budget: None, transparency: 0 }; + let fade = Fade::of(d); + let mut b = Builder { + list: DisplayList::default(), + opts, + plotting: false, + styles: None, + named: None, + shared_budget: None, + transparency: 0, + fade: fade.as_ref(), + }; for e in ents { entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e); } diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index 82885b85f..0b217a82e 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -5,7 +5,9 @@ use super::draw::entity; #[cfg(not(target_arch = "wasm32"))] use super::pipeline::PARALLEL_CHUNK; use super::pipeline::{Options, style_table, top_ctx, with_point_view}; -use super::{Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_EXPANSION, Mat3, Pen, Space, Vec2, clip, paper, pen, plotstyle}; +use super::{ + Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Fade, Handle, MAX_BLOCK_EXPANSION, Mat3, Pen, Space, Vec2, clip, paper, pen, plotstyle, +}; /// Upper bound on viewports drawn per layout (hostile files). pub(crate) const MAX_VIEWPORTS: usize = 256; @@ -67,8 +69,17 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds } let opts = &with_point_view(d, space, opts); let styler = style_table(d, space, opts, false).map(|t| plotstyle::Styler::new(d, t)); - let mut b = - Builder { list: DisplayList::default(), opts, plotting: false, styles: styler.as_ref(), named: None, shared_budget: None, transparency: 0 }; + let fade = Fade::of(d); + let mut b = Builder { + list: DisplayList::default(), + opts, + plotting: false, + styles: styler.as_ref(), + named: None, + shared_budget: None, + transparency: 0, + fade: fade.as_ref(), + }; contents(&mut b, d, vp, area, &Clip::Rect(area), paper::unit_mm_of(d, handle)); b.list } @@ -120,6 +131,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou named: None, shared_budget: Some(&budget), transparency: 0, + fade: b.fade, }; #[cfg(not(target_arch = "wasm32"))] let parallel = !b.plotting && b.styles.is_none() && d.model.len() >= 2 * PARALLEL_CHUNK; @@ -131,7 +143,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou // As `build_parallel`: chunks built side by side, joined in drawing order. use rayon::prelude::*; let ents: Vec<&std::sync::Arc> = d.model.iter().collect(); - let opts = b.opts; + let (opts, fade) = (b.opts, b.fade); let parts: Vec = ents .par_chunks(PARALLEL_CHUNK) .map(|chunk| { @@ -143,6 +155,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou named: None, shared_budget: Some(&budget), transparency: 0, + fade, }; let c = ctx(); for me in chunk.iter().filter(|me| seen(me)) { From 195c0529314b64e610340ef8fba849c04eb9771d Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Fri, 20 Nov 2026 09:56:07 +0100 Subject: [PATCH 10/11] REFEDIT xref tests: folders cleaned up on every exit; a host-only layer Each test's folder is now an owned guard removed on drop, so a skipped symlink test or a failed assertion no longer leaves its files behind. The save test drew its new line after a `layer` call that does nothing in JSON (`.ok()` hid it), so the line stayed on layer 0 and the check that host layers come along could not fail. It makes "Added" current first (layer.new) and asserts the line and the file's layer table. Review of #2355 (CodeRabbit, tests/it/refedit_xref.rs:30 and :117). --- crates/engine/tests/it/refedit_xref.rs | 40 ++++++++++++++++---------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/crates/engine/tests/it/refedit_xref.rs b/crates/engine/tests/it/refedit_xref.rs index bcf842c80..691b14e84 100644 --- a/crates/engine/tests/it/refedit_xref.rs +++ b/crates/engine/tests/it/refedit_xref.rs @@ -22,12 +22,28 @@ fn hooks() { }); } -/// A fresh folder for one test. -fn folder(tag: &str) -> PathBuf { +/// A fresh folder for one test, removed when the test ends however it ends (a skip, a failed +/// assertion). +struct Folder(PathBuf); + +impl std::ops::Deref for Folder { + type Target = Path; + fn deref(&self) -> &Path { + &self.0 + } +} + +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn folder(tag: &str) -> Folder { let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("refedit-xref").join(format!("{}-{tag}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); - dir + Folder(dir) } fn save(d: &Drawing, path: &Path) { @@ -76,7 +92,7 @@ fn site() -> (Drawing, Handle) { } /// A host drawing (saved as host.dxf) with site.dxf attached at (100, 0). -fn attached(tag: &str) -> (Session, PathBuf, Handle, String) { +fn attached(tag: &str) -> (Session, Folder, Handle, String) { hooks(); let dir = folder(tag); let (d, wall) = site(); @@ -107,6 +123,8 @@ fn find_line(s: &Session, hs: &[String]) -> String { fn editing_an_xref_writes_its_drawing_back_with_a_backup() { let (mut s, dir, wall, insert) = attached("save"); let file = dir.join("site.dxf"); + // A layer of the host only, current for what is drawn during the edit. + s.execute("layer.new", &json!({ "name": "Added", "current": true })).unwrap(); let r = s.execute("refedit", &json!({ "handle": insert })).unwrap(); assert_eq!(r["xref"]["name"], "site"); let work = working(&r); @@ -114,7 +132,6 @@ fn editing_an_xref_writes_its_drawing_back_with_a_backup() { // Everything but the working set is locked while editing, and drawn faded. let l = find_line(&s, &work); s.execute("move", &json!({ "handles": [l], "delta": [0, 5] })).unwrap(); - s.execute("layer", &json!({ "option": "make", "name": "Added" })).ok(); s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); let out = s.execute("refclose", &json!({ "option": "save" })).unwrap(); assert_eq!(out["objects"], 3); @@ -131,13 +148,13 @@ fn editing_an_xref_writes_its_drawing_back_with_a_backup() { assert!((ln.a.y - 5.0).abs() < 1e-9 && (ln.a.x).abs() < 1e-9, "{ln:?}"); assert_eq!(moved.common.layer, "Walls", "the xref's layer loses its prefix"); let new_line = back.model.iter().find(|e| matches!(&e.kind, EntityKind::Line(l) if (l.a.y - 20.0).abs() < 1e-9)).unwrap(); - assert!(back.layer(&new_line.common.layer).is_some(), "a host layer the new line uses comes along"); + assert_eq!(new_line.common.layer, "Added"); + assert!(back.layer("Added").is_some(), "a host layer the new line uses comes along"); // The host shows the xref as written (loaded again), and nothing of the edit is left. let d = s.doc().unwrap(); assert!(d.refedit.is_none()); assert_eq!(d.block("site").unwrap().entities.len(), 3); assert_eq!(d.block("site").unwrap().xref_status, XrefStatus::Loaded); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -159,7 +176,6 @@ fn a_block_of_the_xref_is_written_into_that_block() { let back = read(&dir.join("site.dxf")); let EntityKind::Circle(c) = &back.block("Tree").unwrap().entities.iter().next().unwrap().kind else { panic!() }; assert!((c.radius - 2.0).abs() < 1e-9); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -207,7 +223,6 @@ fn locked_read_only_or_changed_files_are_not_overwritten() { let ih = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Insert(_))).unwrap().handle; let e = s.execute("refedit", &json!({ "handle": ih.hex() })).unwrap_err().to_string(); assert!(e.contains("another drawing tab"), "{e}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -294,7 +309,6 @@ fn links_planted_beside_the_xref_are_not_written_through() { assert_eq!(read(&file).model.len(), 3, "and holds the edit"); assert!(is_plain_file(&dir.join("site.dxf.bak")), "the link at the backup is replaced by the backup"); assert_eq!(read(&dir.join("site.dxf.bak")).model.len(), 2); - let _ = std::fs::remove_dir_all(&dir); } /// Review of #2355: the xref's own path turned into a link to another file during the edit (here @@ -323,7 +337,6 @@ fn an_xref_path_turned_into_a_link_during_the_edit_is_not_written() { assert!(!elsewhere.join("victim.dxf.bak").exists() && !dir.join("site.dxf.bak").exists(), "no backup either"); assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open"); s.execute("refclose", &json!({ "option": "discard" })).unwrap(); - let _ = std::fs::remove_dir_all(&dir); } /// Review of #2355: `site.dxf` and `site.dwg` in one folder both used to back up to `site.bak`, @@ -351,7 +364,6 @@ fn xrefs_of_one_name_in_one_folder_keep_their_own_backups() { assert_eq!(std::fs::read(dir.join("site.dxf.bak")).unwrap(), old_dxf, "the DXF's previous file"); assert_eq!(std::fs::read(dir.join("site.bak")).unwrap(), old_dwg, "the DWG's previous file"); assert_eq!((read(&dxf).model.len(), read(&dwg).model.len()), (3, 3), "both hold their edit"); - let _ = std::fs::remove_dir_all(&dir); } /// A host drawing (host.dxf in `dir`) with `file` of `dir` attached as xref `name` at (100, 0). @@ -401,7 +413,6 @@ fn an_xref_is_written_back_in_the_version_it_was_read_in() { assert!(bin_bytes.starts_with(b"AutoCAD Binary DXF"), "the binary DXF stays binary"); assert_eq!(read(&bin).header.get("ACADVER").and_then(cadcraft_engine::doc::HVal::as_str), Some("AC1024"), "and 2010"); assert_eq!((read(&dwg).model.len(), read(&dxf).model.len(), read(&bin).model.len()), (3, 3, 3), "each holds its edit"); - let _ = std::fs::remove_dir_all(&dir); } /// Review of #2355: an R12 DXF xref came back as an R2000 one. CADCraft doesn't write R12, so the @@ -447,7 +458,6 @@ EOF assert!(e.contains("AC1009") && e.contains("XOPEN"), "{e}"); assert!(s.doc().unwrap().refedit.is_none()); assert_eq!(std::fs::read_to_string(dir.join("r12.dxf")).unwrap(), r12, "the file is untouched"); - let _ = std::fs::remove_dir_all(&dir); } /// Review of #2355: SAVE says what a file can't keep; the write-back said nothing. A 2013 DXF xref @@ -513,5 +523,5 @@ EOF let warning = s.log.iter().find(|m| m.contains("Not saved in the DXF file")).expect("a warning on the command line"); assert!(warning.contains("1 3DSOLID") && warning.contains("solid.dxf.bak"), "{warning}"); assert!(std::fs::read_to_string(dir.join("solid.dxf.bak")).unwrap().contains("3DSOLID"), "the backup still has it"); - let _ = std::fs::remove_dir_all(&dir); } + From 27e408d91b1f9a1e5e86ae4724be38b0eb84abe0 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Fri, 20 Nov 2026 10:11:24 +0100 Subject: [PATCH 11/11] REFEDIT/REFCLOSE on xrefs: per-drawing baseline, safer save checks From the second automated review of #2355: - The "loaded" stamp was one per file for the whole process, taken from the path after the bytes were read. Each xref block now keeps its own baseline (Block::xref_stamp, session state), taken from the opened file before and after the read (None when it changed meanwhile), and another drawing loading the file no longer moves it. REFEDIT uses the stamp of the one read its handles and version come from, and refuses unless that is the drawing's baseline; an unknown stamp counts as changed. The process-wide LOADED cache is gone. - REFCLOSE Save checks the stamp before reading, of the read itself, and once more just before the file is replaced (narrowing, not closing, the window for another program's save). - It refuses while the xref's file is open in another drawing tab (it was checked only when the edit began). - It refuses a file the xref could no longer load (more than MAX_XREF_OBJECTS, counted as import counts: load::object_count). - bring_symbols counts distinct symbols only, and refuses the save past the budget instead of writing with symbols missing; it copies host multileader styles (with their text style) and table styles (with their cell styles' text styles) too. - refedit.levels no longer offers a nested reference REFEDIT would refuse (scaled differently in X and Y, flat), nor what is below it. - Faded copies keep the object's own transparency; the renderer fades them by the current XFADECTL, so changing it during the edit shows. --- crates/doc/src/tables.rs | 6 + crates/engine/src/cmd/blocks/refedit.rs | 248 +++++++++++++++------- crates/engine/src/cmd/blocks/xref/load.rs | 96 +++++---- crates/engine/src/spatial.rs | 1 + crates/engine/tests/it/pick_text.rs | 1 + crates/engine/tests/it/refedit_xref.rs | 111 ++++++++++ crates/io/tests/it/roundtrip/compare.rs | 2 + 7 files changed, 342 insertions(+), 123 deletions(-) diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index a240f98ca..e599835d8 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -728,6 +728,11 @@ pub struct Block { /// The parameters of an associative array when this is an array block. #[serde(default, skip_serializing_if = "Option::is_none")] pub array: Option, + /// An xref's file as its loaded objects were read from it: size and modification time + /// (nanoseconds since 1970). Kept per drawing, so an edit in place (REFEDIT) can tell whether + /// the file changed since this drawing loaded it (session state; not saved). + #[serde(skip)] + pub xref_stamp: Option<(u64, u128)>, } /// The load state of an external reference. @@ -774,6 +779,7 @@ impl Block { explodable: true, units: 0, array: None, + xref_stamp: None, } } } diff --git a/crates/engine/src/cmd/blocks/refedit.rs b/crates/engine/src/cmd/blocks/refedit.rs index f285b2093..aa28f30df 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -28,7 +28,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use cadcraft_doc::{Block, Drawing, Entity, EntityKind, EntityStore, Handle, RefEdit, Transparency, WorkItem, XrefSource, XrefStatus}; +use cadcraft_doc::{Block, Drawing, Entity, EntityKind, EntityStore, Handle, RefEdit, WorkItem, XrefSource, XrefStatus}; use cadcraft_geom::Mat3; use serde_json::{Value, json}; @@ -77,20 +77,13 @@ fn active(s: &Session, cmd: &str) -> Result { s.doc()?.refedit.clone().ok_or_else(|| bad(cmd, "no block reference is being edited (REFEDIT)")) } -/// How much the block's other objects fade (XFADECTL, 0–90 percent). -fn xfadectl(s: &Session) -> Result { - Ok(u8::try_from(s.doc()?.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50)) -} - -/// A block object as the drawing shows it through the edited reference; `fade` (XFADECTL, a -/// percentage) shows the block's other objects faded. -fn to_host(to_world: &Mat3, e: &Entity, h: Handle, fade: Option) -> Entity { +/// A block object as the drawing shows it through the edited reference. The copy keeps the +/// object's own transparency: the renderer fades what is outside the working set by the current +/// XFADECTL, so changing XFADECTL during the edit shows at once. +fn to_host(to_world: &Mat3, e: &Entity, h: Handle) -> Entity { let mut c = e.clone(); c.handle = h; c.kind.transform(to_world); - if let Some(f) = fade { - c.common.transparency = Transparency::Percent(f.min(90)); - } c } @@ -164,8 +157,11 @@ fn nested(d: &Drawing, name: &str, path: &mut Vec, out: &mut Vec<(Vec= MAX_LEVELS { + // Generated geometry (dimensions, arrays) is not offered, nor a reference `levels` would + // refuse (scaled differently in X and Y, flat): nothing below it can be edited either. + let Some(c) = d.block(&i.block) else { continue }; + let editable = editable_transform(&i.transform(c.base.xy()), i.scale.x, i.scale.y); + if i.block.starts_with('*') || c.array.is_some() || out.len() >= MAX_LEVELS || !editable { continue; } path.push(e.handle); @@ -207,9 +203,17 @@ fn xref_of(d: &Drawing, name: &str) -> Option<(String, Option)> { Some((x.name.clone(), Some(rest.to_string()))) } +/// Whether a drawing tab other than the active one has `file` open. +fn open_in_another_tab(s: &Session, file: &std::path::Path) -> bool { + let canon = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + let me = canon(file); + s.docs.iter().enumerate().any(|(i, st)| i != s.active && st.path.as_deref().is_some_and(|p| canon(std::path::Path::new(p)) == me)) +} + /// The source file of xref `name`, checked for an edit in place: found, not open in another -/// drawing tab, writable, not changed since it was loaded. -fn xref_file(s: &Session, name: &str) -> Result { +/// drawing tab, writable, not changed since this drawing loaded it. Also returns the +/// [`load::Stamp`] it had then (this drawing's own baseline, [`Block::xref_stamp`]). +fn xref_file(s: &Session, name: &str) -> Result<(std::path::PathBuf, load::Stamp)> { if cfg!(target_arch = "wasm32") { return Err(bad("refedit", "editing xrefs in place is not available on the web; open the xref's drawing instead")); } @@ -221,20 +225,15 @@ fn xref_file(s: &Session, name: &str) -> Result { let path = b.xref_path.clone().unwrap_or_default(); let host = s.state().ok().and_then(|st| st.path.clone()); let file = load::find(&path, host.as_deref().map(std::path::Path::new), false).map_err(|_| bad("refedit", format!("{path}: file not found")))?; - let canon = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); - let me = canon(&file); - for (i, st) in s.docs.iter().enumerate() { - if i != s.active && st.path.as_deref().is_some_and(|p| canon(std::path::Path::new(p)) == me) { - return Err(bad("refedit", format!("{} is open in another drawing tab: edit it there, or close it first", file.display()))); - } + if open_in_another_tab(s, &file) { + return Err(bad("refedit", format!("{} is open in another drawing tab: edit it there, or close it first", file.display()))); } writable(&file).map_err(|e| bad("refedit", e))?; - if let (Some(then), Some(now)) = (load::loaded_stamp(&file), load::stamp(&file)) - && then != now - { - return Err(bad("refedit", format!("{} changed since xref \"{}\" was loaded; reload it first", file.display(), b.name))); + // Unknown (the system can't tell, or the file changed while it was read) counts as changed. + match (b.xref_stamp, load::stamp(&file)) { + (Some(then), Some(now)) if then == now => Ok((file, then)), + _ => Err(bad("refedit", format!("{} changed since xref \"{}\" was loaded; reload it first", file.display(), b.name))), } - Ok(file) } /// Whether `file` may be written: not read-only and not open in another program (AutoCAD's @@ -354,8 +353,13 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { // An xref's block: where it is written back. let xref = match xref_of(d, &blk.name) { Some((x, inner)) => { - let file = xref_file(s, &x)?; - let src = load::read_file(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; + let (file, baseline) = xref_file(s, &x)?; + let (src, read_as) = load::read_file(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; + // The handles, version and stamp all come from this one read, which must be of the + // file this drawing loaded. + if read_as != Some(baseline) { + return Err(bad("refedit", format!("{} changed since xref \"{x}\" was loaded; reload it first", file.display()))); + } let sources = source_handles(&blk, &src, inner.as_deref())?; let real = std::fs::canonicalize(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?; let (version, binary) = file_form(&file, &src)?; @@ -366,7 +370,7 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { version, binary, block: inner, - stamp: load::stamp(&file), + stamp: read_as, sources, }) } @@ -405,12 +409,11 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { path: path.clone(), xref, }; - let fade = xfadectl(s)?; let doc = s.doc_mut()?; for e in blk.entities.iter() { let working = chosen.as_ref().is_none_or(|c| c.contains(&e.handle)); let h = doc.new_handle(); - put(doc, &r, to_host(&to_world, e, h, (!working).then_some(fade)))?; + put(doc, &r, to_host(&to_world, e, h))?; if working { r.items.push(WorkItem { copy: h, source: Some(e.handle) }); } else { @@ -421,7 +424,7 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { for level in levels.iter().filter(|l| l.next.is_some()) { for e in level.block.entities.iter().filter(|e| Some(e.handle) != level.next && !matches!(e.kind, EntityKind::AttDef(_))) { let h = doc.new_handle(); - put(doc, &r, to_host(&level.to_world, e, h, Some(fade)))?; + put(doc, &r, to_host(&level.to_world, e, h))?; r.ghosts.push((h, e.handle)); } } @@ -477,7 +480,6 @@ fn apply_refset(s: &mut Session, add: &[Handle], remove: &[Handle]) -> Result Result Result Result { if save { objects = commit_block(&mut nd, &r)?; if let Some(x) = &r.xref { + // Opened in another tab since the edit began: that tab would hold a stale drawing. + if open_in_another_tab(s, std::path::Path::new(&x.file)) { + return Err(bad( + "refclose", + format!("{} is open in another drawing tab: close it there first; the edit stays open (REFCLOSE Discard ends it)", x.file), + )); + } // The file first: when it can't be written the edit stays open (Discard ends it). written = Some(write_back(&nd, &r, x)?); } @@ -640,43 +649,24 @@ fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result { let real = std::path::Path::new(&x.real); writable(file).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?; still_leads_to(file, real).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?; - if load::stamp(file) != x.stamp { + unchanged(file, x, load::stamp(file))?; + let hooks = crate::cmd::file::io().ok_or_else(|| bad("refclose", "file formats are not available in this build"))?; + let (mut src, read_as) = load::read_file(file).map_err(|e| bad("refclose", format!("{}: {e}", file.display())))?; + // What is written over is what was just read, and that is the file the edit began with. + unchanged(file, x, read_as)?; + put_edit(nd, r, x, &mut src)?; + // The xref is loaded again from the file: one it could no longer load is not written. + let objects = load::object_count(&src); + if objects > load::MAX_XREF_OBJECTS { return Err(bad( "refclose", - format!("{} changed since the edit began; it is not overwritten (REFCLOSE Discard ends the edit)", file.display()), + format!( + "{} would hold {objects} objects, more than an xref loads ({}); it is not written (REFCLOSE Discard ends the edit)", + file.display(), + load::MAX_XREF_OBJECTS + ), )); } - let hooks = crate::cmd::file::io().ok_or_else(|| bad("refclose", "file formats are not available in this build"))?; - let mut src = load::read_file(file).map_err(|e| bad("refclose", format!("{}: {e}", file.display())))?; - let blk = nd.block(&r.block).ok_or_else(|| bad("refclose", format!("block \"{}\" is gone", r.block)))?; - let prefix = format!("{}|", x.xref); - let map: HashMap = x.sources.iter().copied().collect(); - let mut store = EntityStore::new(); - let mut wanted: Vec<(Sym, String)> = Vec::new(); - for e in blk.entities.iter() { - let mut e = (**e).clone(); - e.handle = match map.get(&e.handle) { - Some(h) => *h, - None => src.new_handle(), - }; - rename_into_source(&mut e, &prefix, &mut wanted); - store.push(e); - } - bring_symbols(nd, &mut src, &prefix, wanted); - match &x.block { - None => src.model = store, - Some(name) => { - let key = src - .blocks - .keys() - .find(|k| k.eq_ignore_ascii_case(name)) - .cloned() - .ok_or_else(|| bad("refclose", format!("block \"{name}\" is gone from {}", file.display())))?; - if let Some(b) = src.blocks.get_mut(&key) { - Arc::make_mut(b).entities = store; - } - } - } // In the version and form the file was read in, not the writer's default (a DWG at 2004 or // later): a version change can lock out whoever made the file. let version = x.version.as_deref().and_then(Version::parse); @@ -690,10 +680,62 @@ fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result { let as_version = version.unwrap_or_else(|| src.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver).unwrap_or_default()); let lost = crate::cmd::file::loss_writing(&src, &x.file, as_version); + // Once more just before the file is replaced: another program may have saved it while the + // new file was made. (Without a lock every writer honours, this narrows the window; it + // can't close it.) + unchanged(file, x, load::stamp(file))?; let backup = replace_file(file, real, &bytes).map_err(|e| bad("refclose", e))?; Ok(Written { backup, lost }) } +/// Refuse when `now` (the xref's file as it is, or as just read) is not the file the edit began +/// with; an unknown stamp counts as changed. +fn unchanged(file: &std::path::Path, x: &XrefSource, now: Option) -> Result<()> { + if x.stamp.is_none() || now != x.stamp { + return Err(bad( + "refclose", + format!("{} changed since the edit began; it is not overwritten (REFCLOSE Discard ends the edit)", file.display()), + )); + } + Ok(()) +} + +/// Put the edited block of `nd` (committed) into `src`, the xref's drawing as read: its objects +/// with their source handles and names, and the host symbols they use. +fn put_edit(nd: &Drawing, r: &RefEdit, x: &XrefSource, src: &mut Drawing) -> Result<()> { + let file = std::path::Path::new(&x.file); + let blk = nd.block(&r.block).ok_or_else(|| bad("refclose", format!("block \"{}\" is gone", r.block)))?; + let prefix = format!("{}|", x.xref); + let map: HashMap = x.sources.iter().copied().collect(); + let mut store = EntityStore::new(); + let mut wanted: Vec<(Sym, String)> = Vec::new(); + for e in blk.entities.iter() { + let mut e = (**e).clone(); + e.handle = match map.get(&e.handle) { + Some(h) => *h, + None => src.new_handle(), + }; + rename_into_source(&mut e, &prefix, &mut wanted); + store.push(e); + } + bring_symbols(nd, src, &prefix, wanted, MAX_SYMBOLS)?; + match &x.block { + None => src.model = store, + Some(name) => { + let key = src + .blocks + .keys() + .find(|k| k.eq_ignore_ascii_case(name)) + .cloned() + .ok_or_else(|| bad("refclose", format!("block \"{name}\" is gone from {}", file.display())))?; + if let Some(b) = src.blocks.get_mut(&key) { + Arc::make_mut(b).entities = store; + } + } + } + Ok(()) +} + /// Refuse a save when `file` no longer leads to `real` (the file the edit began with), or `real` /// is no longer a plain file: a symbolic link put at either since would send the edit to another /// file. @@ -723,16 +765,32 @@ fn rename_into_source(e: &mut Entity, prefix: &str, wanted: &mut Vec<(Sym, Strin wanted.extend(found.into_inner()); } +/// Most distinct symbols [`bring_symbols`] looks at for one save (hostile drawings: blocks naming +/// blocks naming blocks…). +const MAX_SYMBOLS: usize = 100_000; + /// Copy the host's symbols that objects written into `src` use and `src` lacks (layers, -/// linetypes, text and dimension styles, and blocks with what they use in turn). -fn bring_symbols(host: &Drawing, src: &mut Drawing, prefix: &str, mut wanted: Vec<(Sym, String)>) { +/// linetypes, text, dimension, multileader and table styles, and blocks with what they use in +/// turn). Only distinct names count against `cap`; past it the save is refused rather than +/// written with symbols missing. +fn bring_symbols(host: &Drawing, src: &mut Drawing, prefix: &str, mut wanted: Vec<(Sym, String)>, cap: usize) -> Result<()> { let mut seen: HashSet<(Sym, String)> = HashSet::new(); - let mut guard = 0usize; while let Some((sym, name)) = wanted.pop() { - guard += 1; - if guard > 100_000 || name.is_empty() || !seen.insert((sym, name.to_ascii_uppercase())) { + if name.is_empty() || !seen.insert((sym, name.to_ascii_uppercase())) { continue; } + if seen.len() > cap { + return Err(bad("refclose", format!("the edit uses more than {cap} symbols; the xref is not written (REFCLOSE Discard ends the edit)"))); + } + bring_symbol(host, src, prefix, sym, &name, &mut wanted); + } + Ok(()) +} + +/// Copy host symbol `name` of kind `sym` into `src` when `src` lacks it, queueing what it uses. +fn bring_symbol(host: &Drawing, src: &mut Drawing, prefix: &str, sym: Sym, name: &str, wanted: &mut Vec<(Sym, String)>) { + let name = name.to_string(); + { match sym { Sym::Layer => { if name != "0" @@ -777,14 +835,27 @@ fn bring_symbols(host: &Drawing, src: &mut Drawing, prefix: &str, mut wanted: Ve for e in b.entities.iter() { let mut e = (**e).clone(); e.handle = src.new_handle(); - rename_into_source(&mut e, prefix, &mut wanted); + rename_into_source(&mut e, prefix, wanted); store.push(e); } nb.entities = store; src.blocks.insert(nb.name.clone(), Arc::new(nb)); } } - Sym::MLeaderStyle | Sym::TableStyle => {} + Sym::MLeaderStyle => { + let have = src.mleader_styles.iter().any(|t| t.name.eq_ignore_ascii_case(&name)); + if !have && let Some(t) = host.mleader_styles.iter().find(|t| t.name.eq_ignore_ascii_case(&name)) { + wanted.push((Sym::Style, t.text_style.clone())); + src.mleader_styles.push(t.clone()); + } + } + Sym::TableStyle => { + let have = src.table_styles.iter().any(|t| t.name.eq_ignore_ascii_case(&name)); + if !have && let Some(t) = host.table_styles.iter().find(|t| t.name.eq_ignore_ascii_case(&name)) { + wanted.extend(t.cell_styles.iter().map(|c| (Sym::Style, c.text_style.clone()))); + src.table_styles.push(t.clone()); + } + } } } } @@ -1045,3 +1116,28 @@ impl Interactive for RefcloseM { Ok(Step::Done) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Review of #2355: the budget counted every queued reference, so a host-only layer queued + /// first was skipped once enough repeated ones followed it, and the file was written without + /// it. Only distinct names count now, and running out refuses the save. + #[test] + fn repeated_symbols_do_not_use_up_the_budget() { + let mut host = Drawing::new_metric(); + host.layers.push(cadcraft_doc::Layer { name: "Added".into(), ..cadcraft_doc::Layer::default() }); + let mut wanted = vec![(Sym::Layer, "Added".to_string())]; + for _ in 0..1000 { + wanted.push((Sym::Layer, "0".into())); + wanted.push((Sym::Linetype, "ByLayer".into())); + } + // Distinct: ByLayer, 0, Added and its linetype. + let mut src = Drawing::new_metric(); + bring_symbols(&host, &mut src, "x|", wanted.clone(), 4).unwrap(); + assert!(src.layer("Added").is_some(), "the layer queued first is copied"); + let mut src = Drawing::new_metric(); + assert!(bring_symbols(&host, &mut src, "x|", wanted, 2).is_err(), "past the budget the save is refused"); + } +} diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index a0b7e5ce0..277463a38 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -256,7 +256,10 @@ fn case_insensitive(p: &Path) -> Option { } /// Read a drawing file through the host's io hooks, counting its bytes against the load's total. -fn read(file: &Path, cx: &mut Ctx) -> Result { +/// Also returns the [`Stamp`] of the bytes read: taken from the opened file, so it describes them +/// even when the path is pointed at another file meanwhile; `None` when the file changed while it +/// was read (or the system can't tell its time), so an edit in place refuses until it is reloaded. +fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option), String> { let hooks = super::super::super::file::io().ok_or("file formats are not available in this build")?; #[cfg(not(target_arch = "wasm32"))] { @@ -264,7 +267,9 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes); let limit = MAX_XREF_BYTES.min(left); let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?; - let len = f.metadata().map_err(|e| e.to_string())?.len(); + let meta = f.metadata().map_err(|e| e.to_string())?; + let len = meta.len(); + let before = stamp_of(&meta); let too_big = || { if limit < MAX_XREF_BYTES { format!("the referenced files are larger than {} MB together", MAX_XREF_TOTAL_BYTES >> 20) @@ -282,11 +287,9 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { return Err(too_big()); } cx.bytes = cx.bytes.saturating_add(n); - // Remembered so an edit in place can tell whether the file changed since (REFEDIT). - if let Some(st) = stamp(file) { - remember(file, st); - } - (hooks.read)(&bytes, &file.to_string_lossy()) + let after = f.metadata().ok().as_ref().and_then(stamp_of); + let read_as = before.filter(|b| Some(*b) == after); + Ok(((hooks.read)(&bytes, &file.to_string_lossy())?, read_as)) } #[cfg(target_arch = "wasm32")] { @@ -295,47 +298,29 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { } } -/// Size and modification time (nanoseconds since 1970) of each referenced file when it was last -/// read, by canonical path. -#[cfg(not(target_arch = "wasm32"))] -static LOADED: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); -/// Most files [`LOADED`] remembers. -#[cfg(not(target_arch = "wasm32"))] -const MAX_REMEMBERED: usize = 10_000; +/// A file's size and modification time (nanoseconds since 1970): how an edit in place (REFEDIT) +/// tells whether an xref's file changed since it was read ([`cadcraft_doc::Block::xref_stamp`]). +pub(crate) type Stamp = (u64, u128); -/// The size and modification time of `file` (nanoseconds since 1970). -#[cfg(not(target_arch = "wasm32"))] -pub(crate) fn stamp(file: &Path) -> Option<(u64, u128)> { - let m = std::fs::metadata(file).ok()?; +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +fn stamp_of(m: &std::fs::Metadata) -> Option { let t = m.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos(); Some((m.len(), t)) } + +/// The [`Stamp`] of the file at `file` now. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn stamp(file: &Path) -> Option { + stamp_of(&std::fs::metadata(file).ok()?) +} #[cfg(target_arch = "wasm32")] -pub(crate) fn stamp(_file: &Path) -> Option<(u64, u128)> { +pub(crate) fn stamp(_file: &Path) -> Option { None } -#[cfg(not(target_arch = "wasm32"))] -fn remember(file: &Path, st: (u64, u128)) { - let mut m = LOADED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if m.len() >= MAX_REMEMBERED { - m.clear(); - } - m.insert(canonical(file), st); -} - -/// The size and modification time `file` had when it was last loaded as an xref. -#[cfg(not(target_arch = "wasm32"))] -pub(crate) fn loaded_stamp(file: &Path) -> Option<(u64, u128)> { - LOADED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&canonical(file)).copied() -} -#[cfg(target_arch = "wasm32")] -pub(crate) fn loaded_stamp(_file: &Path) -> Option<(u64, u128)> { - None -} - -/// Read the drawing file `file` (with the size limits of xref loading). -pub(crate) fn read_file(file: &Path) -> Result { +/// Read the drawing file `file` (with the size limits of xref loading), with the [`Stamp`] of the +/// bytes read (see [`read`]). +pub(crate) fn read_file(file: &Path) -> Result<(Drawing, Option), String> { read(file, &mut Ctx::new(None)) } @@ -402,8 +387,14 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: & let Some(path) = b.xref_path.clone() else { return (XrefStatus::Unresolved, "not an xref".into()) }; clear(d, &key); let (status, detail) = match fetch(&path, host, chosen, cx, depth) { - Ok((x, file)) => match import(d, &key, &x, cx) { - Ok(()) => (XrefStatus::Loaded, file.to_string_lossy().into_owned()), + Ok((x, file, read_as)) => match import(d, &key, &x, cx) { + Ok(()) => { + // This drawing's own baseline: another drawing loading the file later doesn't move it. + if let Some(b) = d.blocks.get_mut(&key) { + Arc::make_mut(b).xref_stamp = read_as; + } + (XrefStatus::Loaded, file.to_string_lossy().into_owned()) + } Err(e) => { // Whatever made it in before the failure goes again. A fetch that failed imported // nothing, so it doesn't pay for a second scan of the block table. @@ -418,7 +409,13 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: & } /// Read the drawing referenced as `path` and load its own attached xrefs into it. -fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usize) -> Result<(Drawing, PathBuf), (XrefStatus, String)> { +fn fetch( + path: &str, + host: Option<&Path>, + chosen: bool, + cx: &mut Ctx, + depth: usize, +) -> Result<(Drawing, PathBuf, Option), (XrefStatus, String)> { let unresolved = |m: &str| (XrefStatus::Unresolved, m.to_string()); if depth >= MAX_BLOCK_DEPTH { return Err(unresolved("xrefs are nested too deeply")); @@ -432,7 +429,7 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi return Err(unresolved("too many referenced files")); } cx.files += 1; - let mut x = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?; + let (mut x, read_as) = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?; cx.chain.push(canon); let nested: Vec = x.blocks.values().filter(|b| b.xref_path.is_some() && !b.xref_overlay && !b.name.contains('|')).map(|b| b.name.clone()).collect(); @@ -443,15 +440,20 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi } } cx.chain.pop(); - Ok((x, file)) + Ok((x, file, read_as)) +} + +/// The objects loading drawing `x` as an xref counts against [`MAX_XREF_OBJECTS`]: its model +/// space and every block's. +pub(crate) fn object_count(x: &Drawing) -> usize { + x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len())) } /// Bring referenced drawing `x` into xref `key`: its model space becomes the block's objects, its /// symbols and blocks are added as `key|name` (dependent symbols the host already has keep the /// host's settings, so layer changes survive a reload). fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), String> { - let count = x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len())); - cx.objects = cx.objects.saturating_add(count); + cx.objects = cx.objects.saturating_add(object_count(x)); if cx.objects > MAX_XREF_OBJECTS { return Err(format!("more than {MAX_XREF_OBJECTS} objects")); } diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index 10888f5cf..fcbb33187 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -311,6 +311,7 @@ mod tests { explodable: true, units: 0, array: None, + xref_stamp: None, }; blk.entities .push(Entity::new(cadcraft_doc::Handle(1_000_000), EntityKind::Circle(cadcraft_doc::Circle { center: v3(0.0, 0.0), radius: 1.0 }))); diff --git a/crates/engine/tests/it/pick_text.rs b/crates/engine/tests/it/pick_text.rs index b0df6d8a3..7fe708420 100644 --- a/crates/engine/tests/it/pick_text.rs +++ b/crates/engine/tests/it/pick_text.rs @@ -104,6 +104,7 @@ fn a_dimension_drawn_from_its_block_is_picked_on_the_block_text() { explodable: true, units: 0, array: None, + xref_stamp: None, }; d.blocks.insert("*D1".into(), std::sync::Arc::new(block)); d.model.modify(dim, |e| { diff --git a/crates/engine/tests/it/refedit_xref.rs b/crates/engine/tests/it/refedit_xref.rs index 691b14e84..2c926320a 100644 --- a/crates/engine/tests/it/refedit_xref.rs +++ b/crates/engine/tests/it/refedit_xref.rs @@ -525,3 +525,114 @@ EOF assert!(std::fs::read_to_string(dir.join("solid.dxf.bak")).unwrap().contains("3DSOLID"), "the backup still has it"); } +/// Review of #2355: a reference nested with different X and Y scales was offered as a level, and +/// OK then refused it. It isn't offered (nor anything below it); a uniformly scaled one is. +#[test] +fn nested_references_refedit_cannot_open_are_not_offered() { + let mut s = Session::new(); + let c = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Leaf", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap(); + let uniform = hx(s.execute("insert", &json!({ "name": "Leaf", "at": [10, 0], "scale": 2 })).unwrap()); + let stretched = hx(s.execute("insert", &json!({ "name": "Leaf", "at": [20, 0], "scale": [2, 1] })).unwrap()); + s.execute("block", &json!({ "name": "Holder", "base": [0, 0], "handles": [uniform, stretched], "keep": "delete" })).unwrap(); + let o = hx(s.execute("insert", &json!({ "name": "Holder", "at": [0, 0] })).unwrap()); + let levels = s.execute("refedit.levels", &json!({ "handle": o })).unwrap(); + let names: Vec<&str> = levels["levels"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Holder", "Leaf"], "{levels}"); + // The one offered opens. + let path = levels["levels"][1]["path"].clone(); + s.execute("refedit", &json!({ "handle": o, "path": path })).unwrap(); +} + +/// Review of #2355: the faded copies carried XFADECTL in their own transparency, so lowering +/// XFADECTL during the edit left them faded. They keep the object's own transparency now; the +/// fade is drawn from the current XFADECTL. +#[test] +fn faded_copies_keep_their_own_transparency() { + let mut s = Session::new(); + let a = hx(s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()); + let b = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap()); + s.execute("block", &json!({ "name": "Pair", "base": [0, 0], "handles": [a, b], "keep": "delete" })).unwrap(); + let i = hx(s.execute("insert", &json!({ "name": "Pair", "at": [0, 0] })).unwrap()); + let d = s.doc().unwrap(); + let blk = d.block("Pair").unwrap(); + let line = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::Line(_))).unwrap().handle; + let own = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::Circle(_))).unwrap().common.transparency; + s.execute("refedit", &json!({ "handle": i, "objects": [line.hex()] })).unwrap(); + let d = s.doc().unwrap(); + let r = d.refedit.clone().unwrap(); + let ghost = d.entity(r.ghosts[0].0).unwrap(); + assert_eq!(ghost.common.transparency, own, "the circle's copy is faded by the renderer, not by its own transparency"); + s.execute("refclose", &json!({ "option": "discard" })).unwrap(); +} + +/// Review of #2355: the xref's file opened in another tab after the edit began was overwritten +/// by REFCLOSE Save; the save is refused while it is open there. +#[test] +fn an_xref_opened_in_another_tab_during_the_edit_is_not_written() { + let (mut s, dir, _, insert) = attached("tab-later"); + let file = dir.join("site.dxf"); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap(); + let host = s.active; + s.execute("open", &json!({ "path": file.to_string_lossy() })).unwrap(); + s.execute("document.switch", &json!({ "index": host })).unwrap(); + let before = std::fs::read(&file).unwrap(); + let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string(); + assert!(e.contains("another drawing tab"), "{e}"); + assert_eq!(std::fs::read(&file).unwrap(), before, "the file is untouched"); + assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open"); +} + +/// Review of #2355: the "loaded" stamp was one per file for the whole process, so a second drawing +/// loading the xref later moved the first drawing's baseline. Here the file changes (same objects, +/// moved) after the first drawing loaded it: that drawing still shows the old geometry, and REFEDIT +/// there must refuse rather than pair the old geometry with the new file. +#[test] +fn each_drawing_keeps_its_own_xref_baseline() { + let (mut first, dir, _, insert) = attached("baseline"); + let file = dir.join("site.dxf"); + let mut moved = read(&file); + let h = moved.model.iter().find(|e| matches!(e.kind, EntityKind::Line(_))).unwrap().handle; + moved + .modify_entity(h, |e| { + if let EntityKind::Line(l) = &mut e.kind { + l.b.y += 1.0; + } + }) + .unwrap(); + std::thread::sleep(std::time::Duration::from_millis(20)); + save(&moved, &file); + // Another drawing loads the changed file. + let other_host = dir.join("other.dxf"); + save(&Drawing::new_metric(), &other_host); + let mut second = Session::new(); + second.execute("open", &json!({ "path": other_host.to_string_lossy() })).unwrap(); + let r = second.execute("xattach", &json!({ "path": "site.dxf", "at": [0, 0] })).unwrap(); + second.execute("refedit", &json!({ "handle": r["handle"] })).unwrap(); + second.execute("refclose", &json!({ "option": "discard" })).unwrap(); + // The first drawing loaded the earlier file. + let e = first.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string(); + assert!(e.contains("changed since") && e.contains("reload"), "{e}"); +} + +/// Review of #2355: multileader and table styles of the host that objects drawn during the edit +/// use were not copied into the xref's file, so they lost their style there. +#[test] +fn host_multileader_and_table_styles_come_along() { + let (mut s, dir, _, insert) = attached("styles"); + s.execute("mleaderstyle", &json!({ "name": "Callout", "textHeight": 7, "current": true })).unwrap(); + s.execute("tablestyle", &json!({ "name": "Schedule", "textHeight": 4, "current": true })).unwrap(); + s.execute("refedit", &json!({ "handle": insert })).unwrap(); + s.execute("mleader", &json!({ "points": [[100, 30], [110, 40]], "text": "A" })).unwrap(); + s.execute("table", &json!({ "at": [120, 30], "rows": 1, "cols": 1 })).unwrap(); + s.execute("refclose", &json!({ "option": "save" })).unwrap(); + let back = read(&dir.join("site.dxf")); + let mleader = back.model.iter().find_map(|e| if let EntityKind::MLeader(m) = &e.kind { Some(m.style.clone()) } else { None }).unwrap(); + let table = back.model.iter().find_map(|e| if let EntityKind::Table(t) = &e.kind { Some(t.style.clone()) } else { None }).unwrap(); + assert_eq!((mleader.as_str(), table.as_str()), ("Callout", "Schedule")); + let ml = back.mleader_styles.iter().find(|t| t.name == "Callout").expect("the multileader style is in the file"); + assert!((ml.text_height - 7.0).abs() < 1e-9); + let ts = back.table_styles.iter().find(|t| t.name == "Schedule").expect("the table style is in the file"); + assert!((ts.text_height - 4.0).abs() < 1e-9); +} diff --git a/crates/io/tests/it/roundtrip/compare.rs b/crates/io/tests/it/roundtrip/compare.rs index e263f47f8..739081a59 100644 --- a/crates/io/tests/it/roundtrip/compare.rs +++ b/crates/io/tests/it/roundtrip/compare.rs @@ -39,6 +39,8 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) { explodable, units, array, + // Session state (when an xref was read), never in a file. + xref_stamp: _, } = block.as_ref(); equal(name, &back.name, &path, "name"); equal(annotative, &back.annotative, &path, "annotative");