Compare commits

...
Author SHA1 Message Date
Tanish Manku cda891fb4e UNDO stops at a REFCLOSE Save that wrote an xref's file, instead of bringing back an edit it can't save 2026-11-23 13:30:21 -07:00
Tanish Manku 39fca9e2a7 Xref baseline: keep the file's modification time as the system gives it, so a time before 1970 counts 2026-11-23 13:30:21 -07:00
Tanish Manku 506ad531eb REFEDIT: refuse a reference with several columns or rows instead of opening its first instance 2026-11-23 13:30:21 -07:00
Tanish Manku 003ab113c2 REFCLOSE Save: refuse a host block the xref's drawing defines differently under its name 2026-11-23 13:20:39 -07:00
Tanish Manku 273437af7a REFCLOSE Save: a host linetype brings the text styles its dashes are drawn in 2026-11-23 13:17:36 -07:00
Tanish Manku d0d027ac8f REFCLOSE Save: a dangling reference the xref's file already had is written as it was 2026-11-23 13:15:38 -07:00
Tanish Manku 4c004d5dd5 REFCLOSE Save: count only the xref's dimensions that are written as losing their associations 2026-11-23 13:13:09 -07:00
Tanish Manku 3e98ef30e7 REFEDIT: an xref's version and form come from the read that gave its drawing and stamp 2026-11-23 13:10:19 -07:00
Tanish Manku 4840d576a5 REFEDIT: an outer reference REFEDIT can't open offers no nested level 2026-11-23 13:08:04 -07:00
Tanish Manku 07bdd66b1d REFEDIT docs: an xref's backup is kept only when ISAVEBAK is on 2026-11-23 12:55:51 -07:00
Tanish Manku 9e7663b25c REFEDIT.LEVELS is classified for the automation roots: it touches no file
The PR's new command was on no list, which main's every_command_is_classified
test refuses. Its "path" is a path of nested references, not a file.
2026-11-20 19:25:05 -07:00
Tanish Manku 10727f5025 REFEDIT: a nested reference is offered only when it opens with its parents
Discovery checked each reference's own transform, while opening it checks the
transform with everything above it: two small uniform scales together could be
offered and then refused.
2026-11-20 18:55:52 -07:00
Tanish Manku 1515833f2c REFCLOSE Save: an xref's backup follows ISAVEBAK, as SAVE's does
With ISAVEBAK off, SAVE keeps no .bak; the write-back of an xref kept one anyway.
2026-11-20 18:53:05 -07:00
Tanish Manku 28d8ba72c5 REFCLOSE Save: name the dimension associations an xref's write-back leaves out
Loading an xref drops its dimensions' associations, so writing it back leaves
them out of the file. When the part written back had associative dimensions,
the save says so and lists "dimension associations" in notSaved, pointing at
the backup that keeps them. A dimension drawn during the edit attaches to the
host's copies, whose handles mean nothing in the xref's file: it is written
without those associations, and counted too.
2026-11-20 18:51:28 -07:00
Tanish Manku 5af8fc020a REFCLOSE Save: an xref is not written naming a block it doesn't define
A host dimension style copied into the xref's drawing brings the blocks its
arrowheads are drawn with. A block the written objects still name that the
drawing lacks, such as another xref of the host added with REFSET, refuses the
save: the file, its backup and the edit stay as they were.
2026-11-20 18:47:03 -07:00
Tanish Manku a3e04070be REFCLOSE Save: test that an xref's write-back reports what SAVE would
The merge replaced the PR's own loss report with main's lost_writing and
lost_message (the conflict was in cmd/file.rs). This covers a case the PR's copy
missed: a proxy an R2000 DXF xref can't keep is named, with the reason and the
backup that still has it.
2026-11-20 18:44:39 -07:00
Tanish Manku 210a99ecc8 REFEDIT xref tests: the tests that read and write DWG allow the in-process converter themselves
main now refuses to convert a DWG in process unless the caller allows it, so these
two tests failed after the merge.
2026-11-20 18:43:25 -07:00
Tanish Manku bc703cb134 REFEDIT and REFCLOSE: an xref is read and written only inside the automation roots
refedit and refclose touch files, so they move to the FILES list. REFEDIT checks
that the xref's file may be read and written before an edit begins; REFCLOSE Save
checks the file it writes and its .bak before anything is read or written, so
roots put in force since the edit began hold too. A refused save leaves the xref,
its backup and the host as they were, and the edit stays open.
2026-11-20 18:42:31 -07:00
Tanish Manku 84eb20b5c0 Merge #2355: blocks: REFEDIT edits xrefs in place and writes their drawing back; nested references, faded drawing and Edit Reference bar
# Conflicts:
#	crates/engine/src/cmd/file.rs
#	crates/render/src/draw.rs
#	crates/render/src/lib.rs
#	crates/render/src/pipeline.rs
#	crates/render/src/viewports.rs
2026-11-20 18:32:01 -07:00
Francesco BV 27e408d91b REFEDIT/REFCLOSE on xrefs: per-drawing baseline, safer save checks
From the second automated review of #2355:

- The "loaded" stamp was one per file for the whole process, taken from
  the path after the bytes were read. Each xref block now keeps its own
  baseline (Block::xref_stamp, session state), taken from the opened
  file before and after the read (None when it changed meanwhile), and
  another drawing loading the file no longer moves it. REFEDIT uses the
  stamp of the one read its handles and version come from, and refuses
  unless that is the drawing's baseline; an unknown stamp counts as
  changed. The process-wide LOADED cache is gone.
- REFCLOSE Save checks the stamp before reading, of the read itself,
  and once more just before the file is replaced (narrowing, not
  closing, the window for another program's save).
- It refuses while the xref's file is open in another drawing tab (it
  was checked only when the edit began).
- It refuses a file the xref could no longer load (more than
  MAX_XREF_OBJECTS, counted as import counts: load::object_count).
- bring_symbols counts distinct symbols only, and refuses the save past
  the budget instead of writing with symbols missing; it copies host
  multileader styles (with their text style) and table styles (with
  their cell styles' text styles) too.
- refedit.levels no longer offers a nested reference REFEDIT would
  refuse (scaled differently in X and Y, flat), nor what is below it.
- Faded copies keep the object's own transparency; the renderer fades
  them by the current XFADECTL, so changing it during the edit shows.
2026-11-20 10:11:24 +01:00
Francesco BV 195c052931 REFEDIT xref tests: folders cleaned up on every exit; a host-only layer
Each test's folder is now an owned guard removed on drop, so a skipped
symlink test or a failed assertion no longer leaves its files behind.

The save test drew its new line after a `layer` call that does nothing
in JSON (`.ok()` hid it), so the line stayed on layer 0 and the check
that host layers come along could not fail. It makes "Added" current
first (layer.new) and asserts the line and the file's layer table.

Review of #2355 (CodeRabbit, tests/it/refedit_xref.rs:30 and :117).
2026-11-20 09:56:07 +01:00
Francesco BV 7d1d0ba55b render: the REFEDIT fade looks the working set up once per display list
entity_parts asked RefEdit::is_working, a scan of the working set, for
every object drawn, and read XFADECTL from the header each time: 50,000
working objects meant about a billion handle comparisons per rebuild.
The working set is now a hash set built with XFADECTL once per display
list (render::Fade) and shared by the serial, parallel and viewport
builders.

Review of #2355 (CodeRabbit, render/src/draw.rs:50).
2026-11-20 09:55:38 +01:00
Francesco BV 8920c0fb6f i18n: Chinese label for Reference Nesting Levels
main now requires every command label in zh.tsv (#1129); refedit.levels
came in with this branch.
2026-11-20 09:14:55 +01:00
Francesco BV 68fbe896a7 render: XFADECTL fade in its own function
After the merge with main, entity_parts went past clippy's cognitive
complexity limit (32/30) with the REFEDIT fade in it.
2026-11-20 08:36:48 +01:00
Francesco BV f9756d5083 rustfmt the REFCLOSE write-back and its tests 2026-11-20 08:32:24 +01:00
Francesco BV 7a199cc2e1 REFCLOSE: say what the xref's file couldn't keep
SAVE and SAVEAS list what the writer drops; the write-back wrote the
source drawing straight through and said nothing, so a DWG xref holding
types the DWG writer can't keep (or a 2013+ DXF one holding solids with
SAT-text geometry) lost them silently.

REFCLOSE now counts them as SAVE does, for the version the file is
written in (file::loss_writing: not_saved_as for DWG, sat_text_dropped
for 2013+ DXF), echoes the same warning prefixed with the file and
naming the backup that still has them, and lists them in the result's
notSaved. Nothing lost, no warning.

Review of #2355, point 3.
2026-11-20 08:29:25 +01:00
Francesco BV 88ef222cdf REFEDIT xref tests: follow main's io and Insert after the merge
cadcraft_io::read and write take a path now, and Insert has a clip.
2026-11-20 08:29:18 +01:00
Francesco BV 64e0b5c2a4 REFCLOSE: write an xref back in the version it was read in
The write-back used IoHooks::write, which picks the version from the
drawing: an R2000 DWG xref came back as a 2004 DWG (a DWG is written at
2004 or later by default) and an R12 DXF one as R2000. An xref is often
someone else's file, and a version change can lock its author out.

REFEDIT now records the file's version (a DWG's from its first bytes, a
DXF's $ACADVER) and whether it is a binary DXF, and REFCLOSE writes it
back through the write_as hook at that version and form. A version
CADCraft doesn't write (R12) is refused before the edit begins, so no
work is lost; so is a build without the write_as hook. REFEDIT's result
names the version.

Review of #2355, point 2.
2026-11-20 08:22:23 +01:00
Francesco BV b27cc3ce22 REFCLOSE: write an xref back the way SAVE writes a drawing
The write-back made its own temporary file (`<file>.cadcraft-tmp`, opened
with a plain truncating write) and copied the backup with fs::copy, so a
symbolic link planted at either path took the write: the drawing went
into the link's target and the xref's path became that link (CWE-59).

It now goes through what SAVE uses: the backup is file::backup (written
atomically, a link at the .bak replaced, never written through) and the
new file atomic_write::write_atomic_with (an exclusively created
temporary file renamed over the file). The file written is the one the
xref's path led to when the edit began; REFCLOSE refuses when the path
leads elsewhere by then (a link put there during the edit).

The backup is named by file::backup_path, as SAVE names it: site.dwg's
is site.bak, site.dxf's site.dxf.bak, so two xrefs of one name in one
folder no longer share (and overwrite) one site.bak.

Review of #2355, points 1 and 4.
2026-11-20 08:20:51 +01:00
Francesco BV b355f1e14a Merge origin/main into pr/xref-edit-in-place
Conflicts: the doc re-export (Raster next to XrefSource), the system
variable table (XCLIPFRAME next to XFADECTL), the canvas paint calls
(painter is a reference now), the Italian and Ukrainian labels (both
sides kept), and docs/gaps.md and docs/target-app-parity.md, taken from
main: pull requests don't edit those docs any more (AGENTS.md), so the
rows this change affects are named in the PR instead.
2026-11-20 08:16:53 +01:00
Francesco BVandClaude Opus 5.5 ad6314967f blocks: REFEDIT edits xrefs in place and writes their drawing back
REFEDIT on an xref (or a block that came with one) edits it in place, and
REFCLOSE Save writes the change into the source drawing (the old file
kept as .bak, symbol prefixes removed, host symbols copied, handles kept)
and reloads the xref. Refused for read-only files, files locked by
another program or open in another tab, and files changed since they
were loaded or during the edit. Nested references are picked through
their parents (path, nested, refedit.levels, "Select nesting level
[OK/Next]"). Everything outside the working set is drawn faded
(XFADECTL), and an Edit Reference bar offers Add to/Remove from Working
Set and Save/Discard Changes. Gap F2.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-27 19:58:37 +01:00
25 changed files with 2210 additions and 80 deletions
+1 -1
View File
@@ -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};
+30
View File
@@ -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<Entity>,
/// 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<Handle>,
/// Set when the edited block comes from an external reference: REFCLOSE Save writes it back
/// into its source drawing.
pub xref: Option<XrefSource>,
}
/// 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<String>,
/// 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<String>,
/// The file's size and modification time when the edit began.
pub stamp: Option<(u64, std::time::SystemTime)>,
/// 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 {
+6
View File
@@ -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<crate::ArrayParams>,
/// An xref's file as its loaded objects were read from it: size and modification time (as the
/// system gives it, so a time before 1970 is kept too). 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, std::time::SystemTime)>,
}
/// The load state of an external reference.
@@ -774,6 +779,7 @@ impl Block {
explodable: true,
units: 0,
array: None,
xref_stamp: None,
}
}
}
File diff suppressed because it is too large Load Diff
+69 -11
View File
@@ -134,7 +134,7 @@ struct Ctx {
}
/// The folder of the host drawing at `host` (a file path).
fn folder(host: Option<&Path>) -> Option<PathBuf> {
pub(crate) fn folder(host: Option<&Path>) -> Option<PathBuf> {
let p = host?.parent()?;
Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() })
}
@@ -293,8 +293,17 @@ fn case_insensitive(p: &Path) -> Result<Option<PathBuf>, ()> {
Ok(out.is_file().then_some(out))
}
/// The first bytes of a file [`read`] keeps with the drawing (enough for a DWG's version and the
/// binary DXF sentinel).
const HEAD_BYTES: usize = 4096;
/// 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<Drawing, String> {
/// 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.
/// And the first [`HEAD_BYTES`] of those bytes, so what is told from them (a DWG's version, a
/// binary DXF) describes the same read.
fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>), 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 +312,9 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
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 +332,10 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
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);
let head = bytes.get(..HEAD_BYTES).unwrap_or(&bytes).to_vec();
Ok(((hooks.read)(&bytes, &file.to_string_lossy())?, read_as, head))
}
#[cfg(target_arch = "wasm32")]
{
@@ -330,6 +344,33 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
}
}
/// A file's size and modification time: how an edit in place (REFEDIT) tells whether an xref's
/// file changed since it was read ([`cadcraft_doc::Block::xref_stamp`]). The time is kept as the
/// system gives it: counted from 1970, a file dated before then would have none and always look
/// changed.
pub(crate) type Stamp = (u64, std::time::SystemTime);
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn stamp_of(m: &std::fs::Metadata) -> Option<Stamp> {
Some((m.len(), m.modified().ok()?))
}
/// The [`Stamp`] of the file at `file` now.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn stamp(file: &Path) -> Option<Stamp> {
stamp_of(&std::fs::metadata(file).ok()?)
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn stamp(_file: &Path) -> Option<Stamp> {
None
}
/// Read the drawing file `file` (with the size limits of xref loading), with the [`Stamp`] and the
/// first bytes of the bytes read (see [`read`]).
pub(crate) fn read_file(file: &Path) -> Result<(Drawing, Option<Stamp>, Vec<u8>), 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<Outcome> {
@@ -393,8 +434,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 +456,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<Stamp>), (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 +476,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<String> =
x.blocks.values().filter(|b| b.xref_path.is_some() && !b.xref_overlay && !b.name.contains('|')).map(|b| b.name.clone()).collect();
@@ -434,15 +487,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"));
}
+7 -5
View File
@@ -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<bool> {
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
+6 -5
View File
@@ -48,6 +48,8 @@ pub const FILES: &[&str] = &[
"publish",
"qsave",
"recover",
"refclose",
"refedit",
"reinit",
"saveas",
"script",
@@ -260,9 +262,8 @@ pub const NO_FILES: &[&str] = &[
"attdisp.normal",
"attdisp.on",
"attdisp.off",
"refedit",
"refedit.levels",
"refset",
"refclose",
"bedit",
"bsave",
"bsaveas",
@@ -514,9 +515,9 @@ mod tests {
use std::collections::BTreeSet;
/// Words in a command's parameter doc that usually name a file. In these commands they don't:
/// `array` and `arraypath` follow a path of objects, and `blocks.reference.grips` reports a
/// direction.
const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"];
/// `array` and `arraypath` follow a path of objects, `refedit.levels` reports paths of nested
/// references, and `blocks.reference.grips` reports a direction.
const NOT_FILES: &[&str] = &["array", "arraypath", "refedit.levels", "blocks.reference.grips"];
/// The words of a command's documentation, lower case.
fn words(doc: &str) -> BTreeSet<String> {
+3
View File
@@ -108,6 +108,9 @@ impl Session {
return Ok(Some(label));
}
let st = self.state_mut()?;
if let Some(why) = st.undo.last().and_then(|snap| cmd::blocks::refedit::undo_barrier(&st.doc, &snap.doc)) {
return Err(EngineError::Other(why));
}
let Some(snap) = st.undo.pop() else { return Ok(None) };
let cur = st.swap_in(snap);
let label = cur.label.clone();
+1
View File
@@ -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 })));
+2
View File
@@ -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.
+1
View File
@@ -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;
+1
View File
@@ -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| {
+3 -2
View File
@@ -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}");
}
File diff suppressed because it is too large Load Diff
+33
View File
@@ -305,3 +305,36 @@ fn drawings_sharing_a_name_keep_their_own_backups() {
assert_eq!(name("x/plan.dxf"), "x/plan.dxf.bak");
assert_eq!(name("x/plan.dwt"), "x/plan.dwt.bak");
}
/// REFCLOSE Save writes an xref back the way SAVE writes a drawing: with ISAVEBAK off it keeps
/// no `.bak` (and reports none), with it on it keeps the previous file.
#[test]
fn an_xref_written_back_by_refclose_keeps_a_backup_as_save_does() {
let _g = saving();
hooks();
let dir = temp_dir("refclose");
let site = dir.join("site.dxf");
let mut x = Session::new();
add_circle(&mut x, 0.0);
x.execute("saveas", &json!({ "path": site.to_string_lossy() })).unwrap();
let host = dir.join("host.dxf");
let mut s = Session::new();
s.execute("saveas", &json!({ "path": host.to_string_lossy() })).unwrap();
let insert = s.execute("xattach", &json!({ "path": "site.dxf", "at": [100, 0] })).unwrap()["handle"].as_str().unwrap().to_string();
let bak = backup_path(&site);
cadcraft_engine::autosave::set_isavebak(false);
s.execute("refedit", &json!({ "handle": insert })).unwrap();
add_circle(&mut s, 110.0);
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
assert_eq!(circles(&site), 2, "the edit is written");
assert!(out["backup"].is_null() && !bak.exists(), "ISAVEBAK off keeps no backup: {out}");
cadcraft_engine::autosave::set_isavebak(true);
s.execute("refedit", &json!({ "handle": insert })).unwrap();
add_circle(&mut s, 120.0);
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
assert_eq!((circles(&site), circles(&bak)), (3, 2), "{out}");
assert_eq!(files(&dir), ["host.dxf", "site.dxf", "site.dxf.bak"], "no staging files are left");
let _ = std::fs::remove_dir_all(&dir);
}
+2
View File
@@ -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");
+10
View File
@@ -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)) {
+19
View File
@@ -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<Handle>,
percent: u8,
}
impl Fade {
fn of(d: &Drawing) -> Option<Fade> {
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
+8 -3
View File
@@ -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<Entity>> = 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<DisplayList> = 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<Item = &'a Entity>>(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<Item = &'a Entity>>(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);
+7 -3
View File
@@ -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<Entity>> = 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<DisplayList> = 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)) {
+3
View File
@@ -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;
+72
View File
@@ -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<String>, 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<String> = 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 => {}
}
}
+6
View File
@@ -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
1 # CADCraft Italian interface catalog — original translations by Emanuele Bottelli (AI-assisted, Claude).
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
+6
View File
@@ -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. Додайте теку з кресленнями або файл креслення, щоб використовувати його блоки.
Can't render this file because it contains an unexpected character in line 1403 and column 24.
+1
View File
@@ -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 外部参照和块的就地编辑
1 # CADCraft Simplified Chinese interface catalog — original translations.
683
684
685
686
687
688
689