diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index ee17f1fca..454e03c0a 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -39,7 +39,7 @@ pub use header::{HVal, Header}; pub use plotstyle::*; pub use plotter::*; pub use raster::{Raster, Rasters}; -pub use refedit::{RefEdit, WorkItem}; +pub use refedit::{RefEdit, WorkItem, XrefSource}; pub use store::EntityStore; pub use tables::*; pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES}; diff --git a/crates/doc/src/refedit.rs b/crates/doc/src/refedit.rs index eb0927365..fcf1b60e7 100644 --- a/crates/doc/src/refedit.rs +++ b/crates/doc/src/refedit.rs @@ -42,6 +42,36 @@ 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, + /// `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. + 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/doc/src/tables.rs b/crates/doc/src/tables.rs index 8ae080f59..d9ea001d8 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 18d0d436b..d3f3e18eb 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -1,42 +1,60 @@ -//! 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 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. //! -//! 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, 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::file::Version; 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, 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(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 +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}") + .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))), ] @@ -59,14 +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)")) } -/// 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 { +/// 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 ghost { - c.common.transparency = Transparency::Percent(GHOST_FADE); - } c } @@ -88,6 +105,211 @@ 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, 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); + 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()))) +} + +/// 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 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")); + } + 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")))?; + 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))?; + // 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))), + } +} + +/// 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()) +} + +/// The version (`$ACADVER` code) and form (binary DXF or not) of the xref's file `file`, read as +/// `src`, so it is written back as it was: a DWG's version is its first bytes, a DXF's the +/// `$ACADVER` it was read with. Refused when CADCraft can't write that version (an R12 DXF, +/// AC1009): saving would change it, and the xref is often someone else's file. +fn file_form(file: &std::path::Path, src: &Drawing) -> 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 { @@ -100,34 +322,61 @@ 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, 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)?; + Some(XrefSource { + xref: x, + file: file.to_string_lossy().into_owned(), + real: real.to_string_lossy().into_owned(), + version, + binary, + block: inner, + stamp: read_as, + 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 +406,37 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result { items: Vec::new(), ghosts: Vec::new(), released: Vec::new(), + path: path.clone(), + xref, }; 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))?; 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))?; + 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, "version": x.version, "binary": x.binary })), + }); let sel: Vec = r.items.iter().map(|i| i.copy).collect(); doc.refedit = Some(r); s.set_selection(sel); @@ -220,16 +486,19 @@ 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))?; r.items.push(WorkItem { copy: c, source: Some(src) }); added += 1; } @@ -248,7 +517,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 { + // 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)?); + } } 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; // The objects the edit managed were its own: OOPS doesn't bring them back after it. s.state_mut()?.erased.forget(|h| r.owns(h)); 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(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!(w.backup); + // What the file couldn't keep, said as SAVE says it (nothing is dropped silently). + if let Some(msg) = crate::cmd::file::lost_message(&x.file, w.version, &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, the version it was written at, and what the +/// file couldn't keep ([`crate::cmd::file::lost_writing`]). +struct Written { + backup: Option, + version: Version, + lost: std::collections::BTreeMap, } /// Replace the block's objects by the working set (and move the drawing objects added to it @@ -333,6 +642,251 @@ 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`. +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)")))?; + 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!( + "{} would hold {objects} objects, more than an xref loads ({}); it is not written (REFCLOSE Discard ends the edit)", + file.display(), + load::MAX_XREF_OBJECTS + ), + )); + } + // 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); + let bytes = if version.is_none() && !x.binary { + (hooks.write)(&src, &x.file) + } else { + let w = crate::cmd::file::write_as().ok_or_else(|| bad("refclose", "saving an xref in its own version is not available in this build"))?; + 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 lost = crate::cmd::file::lost_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, version: as_version, 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. +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; +/// 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()); +} + +/// 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, 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(); + while let Some((sym, name)) = wanted.pop() { + 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" + && 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, wanted); + store.push(e); + } + nb.entities = store; + src.blocks.insert(nb.name.clone(), Arc::new(nb)); + } + } + 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()); + } + } + } + } +} + +/// 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, real, bytes); + Err("files are not available on the web".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + 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())) + } +} + // ---------------- while editing ---------------- /// After a command ran: objects it created join the working set, and a command that changed @@ -376,6 +930,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] @@ -464,8 +1106,39 @@ 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)) => 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(), + }); 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 e543b34e7..c3e6a2b0d 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -134,7 +134,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() }) } @@ -294,7 +294,10 @@ fn case_insensitive(p: &Path) -> Result, ()> { } /// 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"))] { @@ -303,7 +306,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) @@ -321,7 +326,9 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { return Err(too_big()); } cx.bytes = cx.bytes.saturating_add(n); - (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")] { @@ -330,6 +337,32 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { } } +/// 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); + +#[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 { + None +} + +/// 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)) +} + /// 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 { @@ -393,8 +426,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. @@ -409,7 +448,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")); @@ -423,7 +468,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(); @@ -434,15 +479,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/cmd/file.rs b/crates/engine/src/cmd/file.rs index 47acb3a08..85f2ccffe 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -721,12 +721,13 @@ 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)?; @@ -735,7 +736,7 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> { // the roots (or to another computer) isn't looked at. if !backup_replaced(&head, &tail, len, std::fs::symlink_metadata(&bak).is_ok()) { 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 @@ -761,7 +762,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/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/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index c171f4b8f..4acfe8c31 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -81,6 +81,8 @@ const HEADER: &[(&str, Kind, Def)] = &[ ("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)), // XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted. ("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)), + // 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 2f3f9630d..5a4a89953 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -143,6 +143,7 @@ mod recent_commands; mod rectang_ortho; mod rectang_polygon_order; mod refedit; +mod refedit_xref; mod region; mod rename_cmdline; mod rotate_reference; 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.rs b/crates/engine/tests/it/refedit.rs index 0eb63c29f..3ea4a17bf 100644 --- a/crates/engine/tests/it/refedit.rs +++ b/crates/engine/tests/it/refedit.rs @@ -279,7 +279,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(), @@ -291,5 +291,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..2c926320a --- /dev/null +++ b/crates/engine/tests/it/refedit_xref.rs @@ -0,0 +1,638 @@ +//! 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, Version, set_io, set_write_as}; +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, + }); + 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, 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(); + Folder(dir) +} + +fn save(d: &Drawing, path: &Path) { + 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).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, + clip: None, + } +} + +/// 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, Folder, 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"); + // 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); + 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("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}"); + 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); + 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_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); +} + +#[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); +} + +#[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}"); +} + +#[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; +} + +/// 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); +} + +/// 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(); +} + +/// 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"); +} + +/// A host drawing (host.dxf in `dir`) with `file` of `dir` attached as xref `name` at (100, 0). +fn host_with(dir: &Path, file: &str, name: &str) -> (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"); +} + +/// 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"); +} + +/// 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"); +} + +/// 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"); diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 934a033f6..8a6cd82da 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -58,6 +58,15 @@ fn shown_transparency(b: &mut Builder, ctx: &Ctx, e: &Entity, layer_transparency own } +/// 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 b.fade { + Some(f) if !b.plotting && !f.working.contains(&if ctx.depth == 0 { e.handle } else { ctx.top }) => f.percent, + _ => 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). @@ -81,6 +90,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { if !visible { return; } + let fade = fade.max(refedit_fade(b, ctx, e)); let own = shown_transparency(b, ctx, e, layer_transparency, fade); // A plot style's linetype replaces the object's. let lt = match b.styles.and_then(|s| s.linetype(rgb, b.named)) { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 1adaaddd5..f00f23a43 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -130,6 +130,24 @@ struct Builder<'a> { points: &'a std::sync::atomic::AtomicUsize, /// The most points the build may hold: [`MAX_DISPLAY_POINTS`] (less in tests). max_points: usize, + /// 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 @@ -370,6 +388,7 @@ impl<'a> Builder<'a> { transparency: self.transparency, points: self.points, max_points: self.max_points, + fade: self.fade, } } /// Take one unit of the block-expansion budget; false once it is spent, or once the build diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 86a45b15c..684c6d149 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -4,8 +4,8 @@ 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, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper, pen, plotstyle, - point, + Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Fade, Handle, Lineweight, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper, pen, + plotstyle, point, }; /// Build options. @@ -114,6 +114,7 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo let opts = &with_point_view(d, space, opts); let styler = style_table(d, space, opts, plotting).map(|t| plotstyle::Styler::new(d, t)); let points = std::sync::atomic::AtomicUsize::new(0); + let fade = Fade::of(d); let mut b = Builder { list: DisplayList::default(), opts, @@ -124,6 +125,7 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo transparency: 0, points: &points, max_points, + fade: fade.as_ref(), }; if let Space::Paper(name) = space { b.list.sheet = paper::sheet(d, name); @@ -171,7 +173,7 @@ 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, points, max_points) = (b.opts, b.plotting, b.points, b.max_points); + let (opts, plotting, points, max_points, fade) = (b.opts, b.plotting, b.points, b.max_points, b.fade); let parts: Vec = ents .par_chunks(PARALLEL_CHUNK) .map(|chunk| { @@ -185,6 +187,7 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor transparency: 0, points, max_points, + fade, }; for e in chunk { entity(&mut part, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e); @@ -238,6 +241,7 @@ pub fn build_entities<'a, I: IntoIterator>(d: &Drawing, ents: opts }; let points = std::sync::atomic::AtomicUsize::new(0); + let fade = Fade::of(d); let mut b = Builder { list: DisplayList::default(), opts, @@ -248,6 +252,7 @@ pub fn build_entities<'a, I: IntoIterator>(d: &Drawing, ents: transparency: 0, points: &points, max_points: MAX_DISPLAY_POINTS, + 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 6a1629029..4e83a557d 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -6,8 +6,8 @@ use super::draw::entity; 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, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2, clip, paper, pen, - plotstyle, + Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Fade, Handle, MAX_BLOCK_EXPANSION, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2, clip, paper, + pen, plotstyle, }; /// Upper bound on viewports drawn per layout (hostile files). @@ -71,6 +71,7 @@ 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 points = std::sync::atomic::AtomicUsize::new(0); + let fade = Fade::of(d); let mut b = Builder { list: DisplayList::default(), opts, @@ -81,6 +82,7 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds transparency: 0, points: &points, max_points: MAX_DISPLAY_POINTS, + fade: fade.as_ref(), }; contents(&mut b, d, vp, area, &Clip::Rect(area), paper::unit_mm_of(d, handle)); b.list @@ -135,6 +137,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou transparency: 0, points: b.points, max_points: b.max_points, + fade: b.fade, }; #[cfg(not(target_arch = "wasm32"))] let parallel = !b.plotting && b.styles.is_none() && d.model.len() >= 2 * PARALLEL_CHUNK; @@ -146,7 +149,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, points, max_points) = (b.opts, b.points, b.max_points); + let (opts, points, max_points, fade) = (b.opts, b.points, b.max_points, b.fade); let parts: Vec = ents .par_chunks(PARALLEL_CHUNK) .map(|chunk| { @@ -160,6 +163,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou transparency: 0, points, max_points, + fade, }; let c = ctx(); for me in chunk.iter().filter(|me| seen(me)) { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8aa940ea0..7dddf81a0 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1189,6 +1189,7 @@ fn paint_canvas(frame: CanvasPaint<'_>) { 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 { @@ -1323,3 +1324,5 @@ mod compare; /// Background rebuilds of the display list for a new view. mod images; 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 43635e2b1..8b75f0ef9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1367,6 +1367,12 @@ 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 Add a drawing file as a block library Aggiungi un file di disegno come libreria di blocchi Add a folder of drawings or a drawing file to use its blocks. Aggiungi una cartella di disegni o un file di disegno per usarne i blocchi. Block Libraries Librerie di blocchi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 9939a3c28..095a9ce0e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1394,6 +1394,12 @@ 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 Скасувати зміни Save changes to block "{name}"? Зберегти зміни в блоці «{name}»? Add a drawing file as a block library Додати файл креслення як бібліотеку блоків Add a folder of drawings or a drawing file to use its blocks. Додайте теку з кресленнями або файл креслення, щоб використовувати його блоки. diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 5d5972061..915e6fc98 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -683,6 +683,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 外部参照和块的就地编辑