Compare commits

..
21 Commits
Author SHA1 Message Date
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) <noreply@anthropic.com>
2026-10-27 19:58:37 +01:00
40 changed files with 2007 additions and 1541 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 (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 {
+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
/// (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,
}
}
}
+800 -49
View File
@@ -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<CommandSpec> {
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<CommandSpec> {
.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<RefEdit> {
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,219 @@ fn hexes(hs: impl IntoIterator<Item = Handle>) -> Vec<String> {
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<Block>,
to_world: Mat3,
next: Option<Handle>,
}
/// 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<Vec<Level>> {
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). `m` is how
/// the block shows in the drawing: a reference is checked with everything above it, as [`levels`]
/// checks it.
fn nested(d: &Drawing, name: &str, m: &Mat3, path: &mut Vec<Handle>, out: &mut Vec<(Vec<Handle>, 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 cm = m.then_before(i.transform(c.base.xy()));
let editable = editable_transform(&cm, 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, &cm, 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<Vec<(Vec<Handle>, 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())];
let m = d.block(&ins.block).map_or(Mat3::IDENTITY, |b| ins.transform(b.base.xy()));
nested(d, &ins.block, &m, &mut Vec::new(), &mut out);
Ok(out)
}
fn run_levels(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> = 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<String>)> {
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")))?;
// Under the automation roots: the file is read for the edit, and written by REFCLOSE Save, so
// an edit that couldn't be saved doesn't begin.
crate::file_access::check_read(&file).map_err(|e| bad("refedit", e))?;
crate::file_access::check_write(&file).map_err(|e| bad("refedit", format!("{e}; open it with XOPEN instead")))?;
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<Vec<(Handle, Handle)>> {
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<String>, 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<Value> {
@@ -100,34 +330,61 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result<Value> {
.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<Handle> = 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::<Result<_>>()?
}
(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<HashSet<Handle>> = match p.get("objects") {
None | Some(Value::Null) => None,
Some(Value::String(a)) if a.eq_ignore_ascii_case("all") => None,
@@ -157,20 +414,37 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result<Value> {
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<Handle> = r.items.iter().map(|i| i.copy).collect();
doc.refedit = Some(r);
s.set_selection(sel);
@@ -220,16 +494,19 @@ fn apply_refset(s: &mut Session, add: &[Handle], remove: &[Handle]) -> Result<Va
continue;
}
if let Some(pos) = r.ghosts.iter().position(|(g, _)| g == h) {
// A faded block object joins the working set (with the edits it had before).
let (g, src) = r.ghosts.remove(pos);
doc.remove_entity(g);
// A faded object of the edited block joins the working set (with the edits it had
// before); a parent's faded object (nested edits) can't.
let src = r.ghosts.get(pos).map(|g| g.1);
let Some(src) = src.filter(|src| blk.entities.get(*src).is_some()) else { continue };
r.ghosts.remove(pos);
doc.remove_entity(*h);
let cur = match r.released.iter().position(|e| e.handle == src) {
Some(i) => 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 +525,7 @@ fn apply_refset(s: &mut Session, add: &[Handle], remove: &[Handle]) -> Result<Va
let kept = to_block(&inv, &e, src);
doc.remove_entity(*h);
let g = doc.new_handle();
put(doc, &r, to_host(&r.to_world, &kept, g, true))?;
put(doc, &r, to_host(&r.to_world, &kept, g))?;
r.ghosts.push((g, src));
r.released.push(kept);
}
@@ -276,15 +553,78 @@ fn close(s: &mut Session, save: bool) -> Result<Value> {
// 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).
let kept = w.backup.as_ref().map(|b| format!(" The previous file, with them, is kept as {b}.")).unwrap_or_default();
let mut not_saved = w.lost.clone();
if let Some(msg) = crate::cmd::file::lost_message(&x.file, w.version, &w.lost) {
s.echo(format!("{}: {msg}.{kept}", x.file));
}
if w.associations > 0 {
s.echo(format!(
"{}: Not saved in the file: the dimension associations of {} dimension(s), which tie them to the objects they measure (an xref edited in place doesn't keep them yet).{kept}",
x.file, w.associations
));
not_saved.insert("dimension associations".into(), w.associations);
}
if !not_saved.is_empty() {
out["notSaved"] = json!(not_saved);
}
}
Ok(out)
}
/// What writing an xref back did: the backup it kept, the version it was written at, what the
/// file couldn't keep ([`crate::cmd::file::lost_writing`]), and how many dimensions were written
/// without their associations ([`associations_dropped`]).
struct Written {
backup: Option<String>,
version: Version,
lost: std::collections::BTreeMap<String, usize>,
associations: usize,
}
/// The dimensions of the part of `src` (the xref's drawing as read) that the write-back replaces
/// which are attached to objects: loading the xref dropped those associations, so the file is
/// written without them.
fn associations_dropped(src: &Drawing, x: &XrefSource) -> usize {
let store = match &x.block {
None => Some(&src.model),
Some(n) => src.block(n).map(|b| &b.entities),
};
store.map_or(0, |st| st.iter().filter(|e| matches!(&e.kind, EntityKind::Dimension(dm) if !dm.assoc.is_empty())).count())
}
/// Replace the block's objects by the working set (and move the drawing objects added to it
@@ -333,6 +673,298 @@ fn commit_block(nd: &mut Drawing, r: &RefEdit) -> Result<usize> {
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<Written> {
let file = std::path::Path::new(&x.file);
let real = std::path::Path::new(&x.real);
// Under the automation roots, the file written and its backup, before anything is read or
// written: roots put in force since the edit began hold too.
for target in [real.to_path_buf(), crate::cmd::file::backup_path(real)] {
crate::file_access::check_write(&target).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?;
}
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)?;
let dropped = associations_dropped(&src, x);
let cleared = 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, associations: dropped.saturating_add(cleared) })
}
/// 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<load::Stamp>) -> 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. A dimension attached to
/// objects of the host (drawn during the edit) is written without those associations: the
/// host's handles mean nothing in the xref's file. Returns how many were.
fn put_edit(nd: &Drawing, r: &RefEdit, x: &XrefSource, src: &mut Drawing) -> Result<usize> {
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<Handle, Handle> = x.sources.iter().copied().collect();
let mut store = EntityStore::new();
let mut wanted: Vec<(Sym, String)> = Vec::new();
let mut cleared = 0usize;
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);
if let EntityKind::Dimension(dm) = &mut e.kind
&& !dm.assoc.is_empty()
{
dm.assoc.clear();
cleared = cleared.saturating_add(1);
}
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(cleared)
}
/// 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();
let mut blocks: Vec<String> = Vec::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)")));
}
if sym == Sym::Block {
blocks.push(name.clone());
}
bring_symbol(host, src, prefix, sym, &name, &mut wanted);
}
// A block the written objects name that the drawing still lacks (an xref of the host, added
// with REFSET) would leave a reference to nothing in the file: refused, nothing written.
if let Some(name) = blocks.iter().find(|n| src.block(n).is_none()) {
return Err(bad(
"refclose",
format!(
"the edit uses block \"{name}\", which can't be written into the xref's drawing (an xref of this drawing, or a block it doesn't define); remove it from the working set (REFSET) or use REFCLOSE Discard"
),
));
}
Ok(())
}
/// The blocks dimension style `t` of `host` draws its arrowheads with: the names `host` defines as
/// blocks (a built-in arrowhead name is drawn in code, not a block), as the xref's drawing names
/// them.
fn arrow_blocks(host: &Drawing, t: &cadcraft_doc::DimStyle, prefix: &str) -> Vec<(Sym, String)> {
[&t.arrow_block, &t.arrow_block1, &t.arrow_block2, &t.leader_arrow_block]
.into_iter()
.map(|n| n.trim())
.filter(|n| !n.is_empty() && host.block(n).is_some())
.map(|n| (Sym::Block, if load::has_prefix(n, prefix) { n.get(prefix.len()..).unwrap_or(n).to_string() } else { n.to_string() }))
.collect()
}
/// 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()));
wanted.extend(arrow_blocks(host, t, prefix));
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` (when ISAVEBAK is on)
/// ([`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<Option<String>, String> {
#[cfg(target_arch = "wasm32")]
{
let _ = (file, real, bytes);
Err("files are not available on the web".into())
}
#[cfg(not(target_arch = "wasm32"))]
{
// As SAVE: ISAVEBAK off keeps no backup.
let kept = if crate::autosave::isavebak() {
crate::cmd::file::backup(real)
.map_err(|e| format!("the backup copy of {} could not be written ({e}); it is unchanged", file.display()))?
} else {
false
};
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 +1008,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<Handle>,
levels: Vec<(Vec<Handle>, String)>,
at: usize,
}
impl RefeditM {
fn picked(&mut self, s: &mut Session, hs: &[Handle]) -> Result<Step> {
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<Step> {
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<Step> {
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<Step> {
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 +1184,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");
}
}
+61 -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() })
}
@@ -294,7 +294,10 @@ fn case_insensitive(p: &Path) -> Result<Option<PathBuf>, ()> {
}
/// 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.
fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>), 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<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 +326,9 @@ 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);
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<Drawing, String> {
}
}
/// 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<Stamp> {
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> {
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`] of the
/// bytes read (see [`read`]).
pub(crate) fn read_file(file: &Path) -> Result<(Drawing, Option<Stamp>), 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 +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<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 +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<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 +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"));
}
-8
View File
@@ -343,11 +343,6 @@ fn eq_variants(o: &TanObj) -> Vec<Eq3> {
/// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations).
pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
ttt_where(objs, |_| true)
}
/// [`ttt`] among the circles `ok` accepts.
pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Option<Circle> {
let [(o1, p1), (o2, p2), (o3, p3)] = objs;
let mut starts: Vec<[f64; 3]> = Vec::new();
let cen = (p1 + p2 + p3) / 3.0;
@@ -384,9 +379,6 @@ pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Opt
continue;
}
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
if !ok(&c) {
continue;
}
let sc = score(&c, &objs);
if best.is_none_or(|(b, _)| sc < b - 1e-12) {
best = Some((sc, c));
+5 -74
View File
@@ -2,7 +2,6 @@ use super::{
Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number,
point_param, size_param,
};
use crate::snap;
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
let c = if let Some(center) = point_param(p, "center") {
@@ -52,8 +51,6 @@ pub(super) fn run_arc(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) struct CircleM {
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
pts: Vec<Vec2>,
/// 3P: the circle or arc each point was picked on with a tangent snap, by point.
tans: Vec<Option<snap::SnapCurve>>,
diameter: bool,
/// The `Ttr` option hands over to the tangent-circle machine.
delegate: Option<Box<dyn Interactive>>,
@@ -72,22 +69,18 @@ impl Interactive for CircleM {
match (self.mode, n) {
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
(0, _) if self.diameter => {
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance().deferred()
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance()
}
(0, _) => {
let p = Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER)
.kw(&["Diameter"])
.base_opt(self.pts.first().copied())
.distance()
.deferred();
let p =
Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER).kw(&["Diameter"]).base_opt(self.pts.first().copied()).distance();
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
}
(1, k) => Prompt::new(
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
Accept::POINT,
)
.base_opt(self.pts.last().copied())
.deferred(),
.base_opt(self.pts.last().copied()),
(2, k) => Prompt::new(
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
Accept::POINT,
@@ -127,14 +120,7 @@ impl Interactive for CircleM {
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
Some(Circle::new(*c, r))
}
1 if self.pts.len() == 3 => match self.three_points() {
Some(c) => Some(c),
None => {
self.pts.pop();
self.tans.truncate(self.pts.len());
return Err(crate::EngineError::Other("Circle does not exist.".into()));
}
},
1 if self.pts.len() == 3 => Circle::from_3_points(self.pts[0], self.pts[1], self.pts[2]),
2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])),
_ => None,
};
@@ -144,29 +130,6 @@ impl Interactive for CircleM {
}
Ok(Step::Continue)
}
// 3P: a point picked with a tangent snap makes the circle tangent to that curve (#1512).
Input::Deferred(d) if self.mode == 1 => {
let tan = (d.mode == snap::mode::TAN && !matches!(d.curve, snap::SnapCurve::Line { .. })).then_some(d.curve);
self.tans.resize(self.pts.len(), None);
self.tans.push(tan);
self.input(s, Input::Point(d.at))
}
// A tangent picked for the radius: the circle around the center that touches the
// curve, on the side it was picked (#1512).
Input::Deferred(d) if self.mode == 0 && self.pts.len() == 1 => {
let Some(&c) = self.pts.first() else { return Ok(Step::Continue) };
// Around the picked curve's own center the circle would lie on it, not touch it.
let concentric =
matches!(d.curve, snap::SnapCurve::Circle { center, .. } | snap::SnapCurve::Arc { center, .. } if center.near(c, 1e-9));
let touch = d.curve.perpendiculars(c, d.at).into_iter().filter(|_| !concentric).min_by(|a, b| a.dist(d.at).total_cmp(&b.dist(d.at)));
match touch.map(|t| c.dist(t)).filter(|r| *r > 1e-12 && r.is_finite()) {
Some(r) => {
finish_circle(s, Circle::new(c, r))?;
Ok(Step::Done)
}
None => Err(crate::EngineError::Other("No circle around the center is tangent there.".into())),
}
}
Input::Text(t) if self.mode == 0 && self.pts.len() == 1 => {
let v = number(&t).ok_or_else(|| crate::EngineError::Other("Requires numeric distance or second point.".into()))?;
let r = if self.diameter { v / 2.0 } else { v };
@@ -211,38 +174,6 @@ impl Interactive for CircleM {
}
}
impl CircleM {
/// The 3P circle: through the three points, or tangent to the curves picked with TAN.
fn three_points(&self) -> Option<Circle> {
let [a, b, c] = <[Vec2; 3]>::try_from(self.pts.as_slice()).ok()?;
if self.tans.iter().all(Option::is_none) {
return Circle::from_3_points(a, b, c);
}
let tan = |i: usize| self.tans.get(i).copied().flatten();
// A plain point is a circle of radius zero to pass through; an arc is solved as its circle.
let target = |i: usize, p: Vec2| {
let circle = match tan(i) {
Some(snap::SnapCurve::Circle { center, radius } | snap::SnapCurve::Arc { center, radius, .. }) => Circle::new(center, radius),
_ => Circle::new(p, 0.0),
};
crate::cmd::curves::TanObj::Circle(circle)
};
let pts = [a, b, c];
// The circle must touch an arc within its sweep, not elsewhere on the arc's circle, and
// not be the picked circle itself (which lies on it rather than touching it).
let touches = |found: &Circle| {
pts.iter().enumerate().all(|(i, p)| {
tan(i).is_none_or(|t| {
let same = matches!(target(i, *p), crate::cmd::curves::TanObj::Circle(o)
if o.center.dist(found.center) + (o.radius - found.radius).abs() <= 1e-9 * o.radius);
!same && t.contains(target(i, *p).touch(found))
})
})
};
crate::cmd::curves::ttt_where([(target(0, a), a), (target(1, b), b), (target(2, c), c)], touches)
}
}
fn finish_circle(s: &mut Session, c: Circle) -> Result<()> {
s.add_entity(circle(c.center, c.radius))?;
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
+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
-58
View File
@@ -466,61 +466,3 @@ fn plot_path_extension_picks_the_format_like_export() {
assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn osnap_in_mspace_skips_vplayer_frozen_layers() {
let mut s = Session::new();
s.execute("layer.new", &json!({"name": "Hidden"})).unwrap();
s.execute("line", &json!({"points": [[60, -25], [70, -25]]})).unwrap();
let line_h = s.doc().unwrap().model.iter().last().unwrap().handle;
s.execute("properties.set", &json!({"handles": [line_h], "layer": "Hidden"})).unwrap();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.execute("mview", &json!({"p1": [20, 20], "p2": [220, 120]})).unwrap();
let vp_h = viewports(&s, "Layout1").last().unwrap().0;
s.execute("vplayer", &json!({"handles": [vp_h], "freeze": ["Hidden"]})).unwrap();
s.execute("mspace", &json!({"handle": vp_h})).unwrap();
let ap = s.pixel_size() * s.settings.aperture.max(1.0);
let d = ap * 0.5;
let model_before = s.doc().unwrap().model.len();
for (ovr, pt, name) in [
("end", format!("{},-25", 60.0 + d), "Endpoint"),
("mid", format!("{},-25", 65.0 + d), "Midpoint"),
("nea", format!("63,{}", -25.0 + d), "Nearest"),
] {
s.cmdline("line").unwrap();
s.cmdline(ovr).unwrap();
s.cmdline(&pt).unwrap();
assert_eq!(
s.log.last().map(String::as_str),
Some(format!("No {name} found for specified point.").as_str()),
"{ovr} should not snap to a line on a VPLAYER-frozen layer; log: {:?}",
s.log
);
s.cmdline("").unwrap();
}
assert_eq!(s.doc().unwrap().model.len(), model_before, "no new line should be created");
// Running osnaps through snap_cursor must also ignore the VPLAYER-frozen layer.
s.settings.osmode = crate::snap::mode::END | crate::snap::mode::MID | crate::snap::mode::NEA;
let cs = s.snap_cursor(
cadcraft_geom::Vec2::new(60.0 + d, -25.0),
&crate::snap::tracking::CursorQuery { base: None, deferred: false, corner: false, aperture: ap, tol: ap, now: 0.0, shift: false },
);
assert!(cs.snap.is_none(), "running osnap should not snap to a VPLAYER-frozen line: {:?}", cs.snap);
// A block reference on layer "0" containing an entity on "Hidden" must also not snap.
s.execute("block", &json!({"name": "B", "base": [60, -25], "handles": [line_h]})).unwrap();
let model_with_block = s.doc().unwrap().model.len();
s.cmdline("line").unwrap();
s.cmdline("end").unwrap();
s.cmdline(&format!("{},-25", 60.0 + d)).unwrap();
assert_eq!(
s.log.last().map(String::as_str),
Some("No Endpoint found for specified point."),
"end should not snap to a block entity on a VPLAYER-frozen layer; log: {:?}",
s.log
);
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().model.len(), model_with_block);
}
+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> {
+11 -27
View File
@@ -127,31 +127,18 @@ pub fn snap_name(m: u32) -> &'static str {
}
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
/// first, then every other snap of the modes in `osmode` under the aperture (each endpoint of
/// each object, each intersection …; [`crate::snap::osnap_all`]), best first, without repeats.
/// first, then the closest snap of each other mode in `osmode`, nearest first, without repeats.
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
snap_candidates_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
}
/// [`snap_candidates`] skipping entities (and block leaves) on `frozen` layers in `space`.
#[allow(clippy::too_many_arguments)]
pub fn snap_candidates_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> Vec<SnapHit> {
// A base that is not a number would give meaningless perpendiculars and tangents.
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 || base.is_some_and(|b| !b.is_finite()) {
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
return Vec::new();
}
let mut out: Vec<SnapHit> = crate::snap::osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen).into_iter().collect();
for h in crate::snap::osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen) {
if !out.iter().any(|o| o.same(&h, aperture)) {
let osnap = |m: u32| crate::snap::osnap(d, space, cursor, aperture, m, base, deferred);
let extra = osmode & mode::HATCH;
let mut per_mode: Vec<SnapHit> = mode::ALL.iter().filter(|(b, _)| osmode & b != 0).filter_map(|(b, _)| osnap(*b | extra)).collect();
per_mode.sort_by(|a, b| a.point.dist(cursor).total_cmp(&b.point.dist(cursor)));
let mut out: Vec<SnapHit> = osnap(osmode).into_iter().collect();
for h in per_mode {
if !out.iter().any(|o| o.mode == h.mode && o.point.near(h.point, aperture * 1e-6)) {
out.push(h);
}
}
@@ -365,15 +352,12 @@ impl Session {
Frame::Snap { mode } => {
// Snap the point with this mode alone, within the aperture.
let prompt = self.current_prompt();
let (doc, space, frozen) = {
let st = self.state()?;
(st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec())
};
let space = self.space();
let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
let base = prompt.as_ref().and_then(|q| q.base);
let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
let hit = crate::snap::osnap_with_frozen(&doc, &space, p, aperture, mode | hatch, base, deferred, &frozen);
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred);
match hit {
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
Some(h) => p = h.point,
+2 -3
View File
@@ -75,9 +75,8 @@ pub struct Prompt {
/// Rubber-band origin (for direct distance entry, ortho and polar).
pub base: Option<Vec2>,
/// The command resolves deferred tangent/perpendicular snaps ([`Input::Deferred`]) at this
/// prompt (a point with no base yet, e.g. the first point of a line; with a base, only
/// tangents, e.g. a circle's radius). Elsewhere a deferred pick arrives as the plain point it
/// was picked at.
/// prompt (a point with no base yet, e.g. the first point of a line). Elsewhere a deferred
/// pick arrives as the plain point it was picked at.
pub deferred: bool,
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
/// cell): ortho does not bend the opposite corner, so the rectangle keeps its area.
+97 -520
View File
@@ -65,21 +65,6 @@ pub struct SnapHit {
}
impl SnapHit {
fn plain(mode: u32, point: Vec2) -> SnapHit {
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
}
/// The same snap as `o`, for a Tab list without repeats: the same mode at the same point
/// (within a millionth of `aperture`), deferred or not alike, and from the same source (this
/// space, or one viewport). Overlapping viewports can show different model points at one paper
/// point; each stays a candidate, since DIST measures in the model units of the viewport picked.
pub(crate) fn same(&self, o: &SnapHit, aperture: f64) -> bool {
self.mode == o.mode
&& self.deferred.is_some() == o.deferred.is_some()
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
&& self.point.near(o.point, aperture * 1e-6)
}
/// The command input a pick at this snap gives: a deferred snap or a plain point.
pub fn input(&self) -> crate::Input {
match self.deferred {
@@ -125,7 +110,7 @@ impl SnapCurve {
}
/// Points on the curve whose perpendicular passes through `p`; `picked` is where the curve
/// was picked, kept when `p` is the center of a circle or arc (every radius is perpendicular).
pub(crate) fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
match self {
SnapCurve::Circle { center, radius } | SnapCurve::Arc { center, radius, .. } => {
let u = (p - *center).normalized();
@@ -217,34 +202,15 @@ fn prim_segments(p: &Prim) -> Vec<Segment> {
/// Tangent and perpendicular snaps need the base point (the other end of the line). With no
/// base and `deferred` set (the prompt says it can resolve them, `Prompt.deferred`),
/// they snap as *deferred*: the hit carries the curve and is resolved once the other end is
/// known. With a base and `deferred` set, tangents to circles and circular arcs are deferred too
/// (CIRCLE's radius: the circle around the base that touches the curve, #1512); an elliptical arc
/// or a spline keeps its ordinary tangent from the base. Deferred hits only win
/// where no other snap does (they are as unspecific as Nearest).
/// known. Deferred hits only win where no other snap does (they are as unspecific as Nearest).
pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Option<SnapHit> {
osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
}
/// [`osnap`] skipping entities (and block leaves) on `frozen` layers in `space`.
#[allow(clippy::too_many_arguments)]
pub fn osnap_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> Option<SnapHit> {
if osmode == 0 || osmode & mode::OFF != 0 {
return None;
}
let ix = crate::spatial::index(d, space);
osnap_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred, frozen).0
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
}
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn osnap_with(
d: &Drawing,
@@ -256,7 +222,7 @@ pub(crate) fn osnap_with(
base: Option<Vec2>,
deferred: bool,
) -> Option<SnapHit> {
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred, &[]).0
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred).0
}
/// Find the best object snap and retain the local-space primitives gathered for that query.
@@ -270,18 +236,17 @@ pub(crate) fn osnap_with_neighborhood(
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
return (None, None);
}
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, None) {
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
Some((hit, prims)) => (hit, Some(prims)),
None => (None, None),
};
let views = viewport::near(d, space, cursor, aperture);
if views.is_empty() {
return (best.map(|(h, _)| h), near_prims);
return (best, near_prims);
}
let model = Space::Model;
let model_ix = crate::spatial::index(d, &model);
@@ -304,35 +269,14 @@ pub(crate) fn osnap_with_neighborhood(
&view.viewport.frozen_layers,
Some(view.model_clip),
)
// The rank was found in model units: paper units are model units times the scale.
.and_then(|(h, r)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r })));
if let Some((hit, rank)) = hit
&& best.as_ref().is_none_or(|(_, b)| rank.beats(b))
.and_then(|h| view.hit(h));
if let Some(hit) = hit
&& best.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
{
best = Some((hit, rank));
best = Some(hit);
}
}
(best.map(|(h, _)| h), near_prims)
}
/// How a hit ranks against the hits of another space (paper space, another viewport) and, for
/// Tab, against the other candidates: first the order [`finish`] tries them in (snap points, then
/// a perpendicular or tangent on the object under the cursor or a center found from its curve,
/// then deferred snaps, then Nearest), then its score within that tier, in the units of the cursor.
#[derive(Clone, Copy, Debug)]
struct Rank {
tier: u8,
score: f64,
}
impl Rank {
fn cmp(&self, other: &Rank) -> std::cmp::Ordering {
self.tier.cmp(&other.tier).then(self.score.total_cmp(&other.score))
}
fn beats(&self, other: &Rank) -> bool {
self.cmp(other).is_lt()
}
(best, near_prims)
}
#[allow(clippy::too_many_arguments)]
@@ -347,7 +291,7 @@ fn osnap_in(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(SnapHit, Rank)> {
) -> Option<SnapHit> {
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit)
}
@@ -363,92 +307,7 @@ fn osnap_in_with_prims(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Option<(SnapHit, Rank)>, Vec<Prim>)> {
let (cands, near_prims) = collect_in(d, space, ix, cursor, aperture, osmode, frozen)?;
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hit, near_prims))
}
/// Every snap of `osmode` under the aperture round `cursor`, best first: Tab cycles through
/// these. Each mode's points of every object nearby, the intersections, perpendicular and
/// tangent points from `base`, the centers found from their curves, the deferred snaps and the
/// nearest point of each object, ranked as [`osnap`] ranks them, without repeats and at most
/// [`MAX_CYCLE`]; in viewports too, as [`osnap`] snaps.
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
}
/// [`osnap_all`] skipping entities (and block leaves) on `frozen` layers in `space`.
#[allow(clippy::too_many_arguments)]
pub fn osnap_all_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> Vec<SnapHit> {
if osmode == 0
|| osmode & mode::OFF != 0
|| !cursor.is_finite()
|| !(aperture.is_finite() && aperture > 0.0)
|| base.is_some_and(|b| !b.is_finite())
{
return Vec::new();
}
let ix = crate::spatial::index(d, space);
let mut out: Vec<(SnapHit, Rank)> = Vec::new();
if let Some((cands, prims)) = collect_in(d, space, &ix, cursor, aperture, osmode, frozen) {
out = finish_all(cands, &prims, cursor, aperture, osmode, base, deferred, None);
}
let model = Space::Model;
let views = viewport::near(d, space, cursor, aperture);
if !views.is_empty() {
let model_ix = crate::spatial::index(d, &model);
for view in views {
let (mc, ma, mb) = (view.to_model(cursor), aperture / view.scale, base.map(|p| view.to_model(p)));
if !mc.is_finite() || !(ma.is_finite() && ma > 0.0) || mb.is_some_and(|p| !p.is_finite()) {
continue;
}
let Some((cands, prims)) = collect_in(d, &model, &model_ix, mc, ma, osmode, &view.viewport.frozen_layers) else { continue };
// The rank was found in model units: paper units are model units times the scale.
out.extend(
finish_all(cands, &prims, mc, ma, osmode, mb, deferred, Some(view.model_clip))
.into_iter()
.filter_map(|(h, r)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }))),
);
}
}
out.sort_by(|a, b| a.1.cmp(&b.1));
let mut unique: Vec<SnapHit> = Vec::with_capacity(out.len().min(MAX_CYCLE));
for (h, _) in out {
if unique.len() >= MAX_CYCLE {
break;
}
if !unique.iter().any(|u| u.same(&h, aperture)) {
unique.push(h);
}
}
unique
}
/// Most snaps [`osnap_all`] offers.
const MAX_CYCLE: usize = 256;
/// The candidate snap points near `cursor` (each with its mode) and the primitives near it:
/// [`gather_in`]'s, plus the intersections between those primitives.
#[allow(clippy::too_many_arguments)]
fn collect_in(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
frozen: &[String],
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
) -> Option<(Option<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
@@ -486,7 +345,8 @@ fn collect_in(
}
}
}
Some((cands, near_prims))
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hit, near_prims))
}
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
@@ -530,7 +390,18 @@ pub(crate) fn extendable(p: &Prim) -> bool {
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
/// when the drawing can't be searched.
pub(crate) fn gather_in(
pub(crate) fn gather(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
gather_in(d, space, ix, cursor, aperture, osmode, &[])
}
fn gather_in(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
@@ -587,19 +458,7 @@ pub(crate) fn gather_in(
Some((cands, near_prims))
}
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps, with
/// its [`Rank`].
///
/// In order of preference (the rank's tier):
/// 0. the snap point within `aperture` of the cursor that scores best (see [`snap_score`]),
/// perpendicular and tangent points from the base point included;
/// 1. with a base point, a perpendicular or tangent on an object that passes within `aperture`,
/// wherever its point lies (see [`from_base_on_objects`]), or the center of a circle, arc or
/// ellipse under the cursor (see [`curve_centers`]): the object nearest the cursor;
/// 2. a deferred perpendicular or tangent (no base point yet);
/// 3. Nearest.
///
/// [`finish_all`] keeps every candidate in this order, for Tab.
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps.
#[allow(clippy::too_many_arguments)]
fn finish(
mut cands: Vec<(u32, Vec2)>,
@@ -610,248 +469,87 @@ fn finish(
base: Option<Vec2>,
deferred: bool,
clip: Option<Bounds2>,
) -> Option<(SnapHit, Rank)> {
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
) -> Option<SnapHit> {
// Perpendicular / tangent from the base point.
if let Some(bp) = base {
for p in near_prims {
if osmode & mode::PER != 0 {
match p {
Prim::Seg(Segment::Line(l)) => cands.push((mode::PER, l.project(bp))),
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
// not offered, and the far side is still found.
Prim::Seg(Segment::Arc { arc, .. }) => {
let curve = SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end };
cands.extend(curve.perpendiculars(bp, bp).into_iter().map(|q| (mode::PER, q)));
}
Prim::Circle(c) => cands.push((mode::PER, c.closest(bp))),
Prim::Infinite { base: b0, dir, .. } => cands.push((mode::PER, *b0 + *dir * (bp - *b0).dot(*dir))),
Prim::Ellipse(e) => cands.extend(curves::ellipse_perpendiculars(e, bp).into_iter().map(|q| (mode::PER, q))),
Prim::Spline(s) => cands.extend(curves::spline_perpendiculars(s, bp).into_iter().map(|q| (mode::PER, q))),
_ => {}
}
}
if osmode & mode::TAN != 0 {
let pts = match p {
// Only the tangent points that lie on the arc itself (not its circle).
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
.tangent_points(bp)
.into_iter()
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
.collect(),
Prim::Circle(c) => c.tangent_points(bp),
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
Prim::Spline(s) => curves::spline_tangents(s, bp),
_ => Vec::new(),
};
cands.extend(pts.into_iter().map(|t| (mode::TAN, t)));
}
}
}
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
// Prefer more specific modes when nearly equidistant.
let best = cands
.iter()
.filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture)
.map(|(m, p)| (snap_score(*m, *p, cursor, aperture), *m, *p))
.min_by(|a, b| a.0.total_cmp(&b.0));
if let Some((score, m, p)) = best {
return Some((SnapHit::plain(m, p), Rank { tier: 0, score }));
let best = cands.iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).min_by(|a, b| {
// Prefer more specific modes when nearly equidistant.
let da = snap_score(a.0, a.1, cursor, aperture);
let db = snap_score(b.0, b.1, cursor, aperture);
da.total_cmp(&db)
});
if let Some((m, p)) = best {
return Some(SnapHit { point: *p, mode: *m, name: name_of(*m), viewport: None, deferred: None });
}
// A perpendicular or tangent on the object under the cursor, or the center found from its
// curve, only when no snap point is in the aperture: the Midpoint or Quadrant under the cursor
// wins over the center of the same curve, as in AutoCAD. Of the two, the object nearer the
// cursor; on a tie (the same curve), the perpendicular or tangent.
let on_object = from_base_on_objects(&from_base, near_prims, cursor, aperture, visible)
.into_iter()
.min_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)))
.map(|(h, r, _)| (h, r));
let center = curve_centers(near_prims, cursor, aperture, osmode)
.into_iter()
.filter(|(_, c)| visible(*c))
.min_by(|a, b| a.0.total_cmp(&b.0))
.map(|(score, c)| (SnapHit::plain(mode::CEN, c), Rank { tier: 1, score }));
match (on_object, center) {
(Some(o), Some(c)) => return Some(if c.1.beats(&o.1) { c } else { o }),
(Some(h), None) | (None, Some(h)) => return Some(h),
(None, None) => {}
}
// With a base, perpendiculars are resolved from it above; only tangents are left to defer.
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
if deferred && let Some(h) = deferred_hit(near_prims, cursor, aperture, deferrable, clip) {
let score = h.point.dist(cursor);
return Some((h, Rank { tier: 2, score }));
if base.is_none()
&& deferred
&& let Some(h) = deferred_hit(near_prims, cursor, aperture, osmode, clip)
{
return Some(h);
}
if osmode & mode::NEA != 0 {
// The closest point of all nearby objects, whatever their drawing order.
let nb = near_prims.iter().filter_map(|p| nearest_point(p, cursor, aperture, &visible)).min_by(|a, b| a.0.total_cmp(&b.0));
if let Some((score, p)) = nb {
return Some((SnapHit::plain(mode::NEA, p), Rank { tier: 3, score }));
let mut nb: Option<(f64, Vec2)> = None;
let mut consider = |c: Vec2| {
let dd = c.dist(cursor);
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
nb = Some((dd, c));
}
};
for p in near_prims {
for s in prim_segments(p) {
consider(fix_circle(&s).closest(cursor));
}
if let Prim::Circle(c) = p {
consider(c.closest(cursor));
}
}
if let Some((_, p)) = nb {
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
}
}
None
}
/// [`finish`], keeping every candidate with its [`Rank`], in the order [`finish`] prefers them:
/// the snap points best first, then the perpendiculars and tangents on the objects under the
/// cursor and the centers found from their curves, then the deferred snaps, then the nearest point
/// of each object nearby.
#[allow(clippy::too_many_arguments)]
fn finish_all(
mut cands: Vec<(u32, Vec2)>,
near_prims: &[Prim],
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
clip: Option<Bounds2>,
) -> Vec<(SnapHit, Rank)> {
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
let mut out: Vec<(SnapHit, Rank)> = cands
.iter()
.filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture)
.map(|(m, p)| (SnapHit::plain(*m, *p), Rank { tier: 0, score: snap_score(*m, *p, cursor, aperture) }))
.collect();
// Of several points on one object (a circle's two tangents), the one nearer the cursor first,
// as `finish` picks it; the sort below is stable.
let mut on_object = from_base_on_objects(&from_base, near_prims, cursor, aperture, visible);
on_object.sort_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)));
out.extend(on_object.into_iter().map(|(h, r, _)| (h, r)));
out.extend(
curve_centers(near_prims, cursor, aperture, osmode)
.into_iter()
.filter(|(_, c)| visible(*c))
.map(|(score, c)| (SnapHit::plain(mode::CEN, c), Rank { tier: 1, score })),
);
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
if deferred {
let hits = deferred_hits(near_prims, cursor, aperture, deferrable, clip);
out.extend(hits.into_iter().map(|h| (h, Rank { tier: 2, score: h.point.dist(cursor) })));
}
if osmode & mode::NEA != 0 {
let near = near_prims.iter().filter_map(|p| nearest_point(p, cursor, aperture, &visible));
out.extend(near.map(|(score, p)| (SnapHit::plain(mode::NEA, p), Rank { tier: 3, score })));
}
out.sort_by(|a, b| a.1.cmp(&b.1));
out
}
/// The point of `p` closest to `cursor` among its visible points within `aperture`, with its
/// distance: each segment's closest point is checked before the closest is chosen, so a curve
/// whose closest point is clipped away (outside a viewport) still offers the visible one.
fn nearest_point(p: &Prim, cursor: Vec2, aperture: f64, visible: &impl Fn(Vec2) -> bool) -> Option<(f64, Vec2)> {
let mut nb: Option<(f64, Vec2)> = None;
let mut consider = |c: Vec2| {
let dd = c.dist(cursor);
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
nb = Some((dd, c));
}
};
for s in prim_segments(p) {
consider(fix_circle(&s).closest(cursor));
}
if let Prim::Circle(c) = p {
consider(c.closest(cursor));
}
nb
}
/// The perpendicular and tangent points from the base point `base` (none without one), each
/// with the index in `near_prims` of the object it lies on. At a `deferred` prompt the tangents to
/// circles and arcs are left out: the prompt resolves them itself (CIRCLE's radius, #1512).
fn base_snaps(near_prims: &[Prim], osmode: u32, base: Option<Vec2>, cursor: Vec2, deferred: bool) -> Vec<FromBase> {
let mut from_base: Vec<FromBase> = Vec::new();
let Some(bp) = base else { return from_base };
for (prim, p) in near_prims.iter().enumerate() {
let mut found = |mode: u32, points: Vec<Vec2>| from_base.extend(points.into_iter().map(|point| FromBase { mode, point, prim }));
if osmode & mode::PER != 0 {
let pts = match p {
Prim::Seg(Segment::Line(l)) => vec![l.project(bp)],
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
// not offered, and the far side is still found.
Prim::Seg(Segment::Arc { arc, .. }) => {
SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end }.perpendiculars(bp, bp)
}
// Both antipodes too, so a pick on the far side of the circle snaps there
// rather than across it. From the centre every point is perpendicular: the
// one under the cursor.
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius }.perpendiculars(bp, cursor),
Prim::Infinite { base: b0, dir, .. } => vec![*b0 + *dir * (bp - *b0).dot(*dir)],
Prim::Ellipse(e) => curves::ellipse_perpendiculars(e, bp),
Prim::Spline(s) => curves::spline_perpendiculars(s, bp),
_ => Vec::new(),
};
found(mode::PER, pts);
}
if osmode & mode::TAN != 0 {
let pts = match p {
// A deferred prompt resolves tangents to circles and arcs itself.
Prim::Seg(Segment::Arc { .. }) | Prim::Circle(_) if deferred => Vec::new(),
// Only the tangent points that lie on the arc itself (not its circle).
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
.tangent_points(bp)
.into_iter()
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
.collect(),
Prim::Circle(c) => c.tangent_points(bp),
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
Prim::Spline(s) => curves::spline_tangents(s, bp),
_ => Vec::new(),
};
found(mode::TAN, pts);
}
}
from_base
}
/// Center, as in AutoCAD: with the cursor over a circle, an arc (also a polyline's) or an
/// ellipse, the running Center snap finds its center however far away it is. Each center comes
/// with how far the curve is from `cursor` (its score); [`finish`] tries them only when no snap
/// point is in the aperture. Empty unless Center is among `osmode`.
fn curve_centers(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32) -> Vec<(f64, Vec2)> {
let mut out = Vec::new();
if osmode & mode::CEN == 0 {
return out;
}
// The work limit counts the curves only, so straight segments before them can't hide them.
let curves = prims.iter().filter_map(|p| match p {
Prim::Circle(c) => Some((c.center, c.closest(cursor))),
Prim::Seg(s @ Segment::Arc { arc, .. }) => Some((arc.center, fix_circle(s).closest(cursor))),
Prim::Ellipse(e) => Some((e.center, e.closest(cursor))),
_ => None,
});
for (center, on) in curves.take(2000) {
let d = on.dist(cursor);
if center.is_finite() && d.is_finite() && d <= aperture {
out.push((d, center));
}
}
out
}
fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
}
/// A perpendicular ([`mode::PER`]) or tangent ([`mode::TAN`]) point found from the base point,
/// with the index in `near_prims` of the object it lies on.
struct FromBase {
mode: u32,
point: Vec2,
prim: usize,
}
/// The perpendiculars and tangents from the base point on the objects that pass within
/// `aperture` of the cursor, wherever the foot or tangent point lies (#2800), each with its
/// [`Rank`] (tier 1, scored by the cursor's distance to the object) and its distance to the cursor.
///
/// These snaps name an object, not a spot on it: you can't know in advance where the foot of a
/// perpendicular will be, so, as in AutoCAD, hovering anywhere over the object finds it and the
/// point jumps there. [`finish`] asks for this only when no snap point lies within the aperture,
/// so an endpoint, midpoint or intersection under the cursor still wins.
///
/// [`finish`] takes the object nearest the cursor; of several points on it (an arc's two
/// antipodes, a circle's two tangents), the one nearest the cursor.
fn from_base_on_objects(
found: &[FromBase],
near_prims: &[Prim],
cursor: Vec2,
aperture: f64,
visible: impl Fn(Vec2) -> bool,
) -> Vec<(SnapHit, Rank, f64)> {
let mut out = Vec::new();
if found.is_empty() {
return out;
}
// `near_prims` holds every object whose box comes near the cursor, so the true distance is
// checked here. It is measured once per object, and only for objects with a point to offer:
// an ellipse or a spline is measured on its tessellation.
let mut reach: Vec<Option<f64>> = vec![None; near_prims.len()];
for f in found.iter().filter(|f| visible(f.point)) {
let Some(slot) = reach.get_mut(f.prim) else { continue };
let to_object = *slot.get_or_insert_with(|| near_prims.get(f.prim).map_or(f64::INFINITY, |p| distance_to_prim(p, cursor)));
// A NaN distance (from a degenerate object) never qualifies.
if to_object.is_nan() || to_object > aperture {
continue;
}
out.push((SnapHit::plain(f.mode, f.point), Rank { tier: 1, score: to_object }, f.point.dist(cursor)));
}
out
}
/// The distance from `cursor` to the nearest point of `p`, measured as Nearest measures it.
fn distance_to_prim(p: &Prim, cursor: Vec2) -> f64 {
prim_segments(p).iter().map(|s| fix_circle(s).closest(cursor).dist(cursor)).fold(f64::INFINITY, f64::min)
}
/// Upper bound on the block-reference objects one snap query looks at (hostile files).
const MAX_BLOCK_LEAVES: usize = 20_000;
@@ -1150,47 +848,6 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
}
}
/// Every deferred tangent and perpendicular within `aperture` of `cursor`, for Tab: one per curve
/// and mode, in drawing order (the caller ranks them), so Tab can go from the tangent to the
/// perpendicular on the same circle, and to the deferred snap of each curve nearby. A click takes
/// the nearest one ([`deferred_hit`]).
fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
let mut hits = Vec::new();
if osmode & (mode::TAN | mode::PER) == 0 {
return hits;
}
for p in prims {
let curve = match p {
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
Prim::Seg(Segment::Arc { arc, .. }) => SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end },
Prim::Seg(Segment::Line(l)) => SnapCurve::Line { a: l.a, b: l.b },
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
_ => continue,
};
// Where the curve was picked: a circle's, an arc's or a segment's own span, an xline/ray
// anywhere.
let at = match curve {
SnapCurve::Circle { center, radius } => Circle::new(center, radius).closest(cursor),
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor),
SnapCurve::Line { a, b } => {
let l = cadcraft_geom::Line::new(a, b);
if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) }
}
};
if !(at.is_finite() && clip.is_none_or(|c| c.contains(at)) && at.dist(cursor) <= aperture) {
continue;
}
let modes: &[(u32, &'static str)] = match curve {
SnapCurve::Circle { .. } | SnapCurve::Arc { .. } => &[(mode::TAN, "Deferred Tangent"), (mode::PER, "Deferred Perpendicular")],
SnapCurve::Line { .. } => &[(mode::PER, "Deferred Perpendicular")],
};
for &(m, name) in modes.iter().filter(|(m, _)| osmode & m != 0) {
hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) });
}
}
hits
}
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
let mut best: Option<(f64, SnapHit)> = None;
@@ -1464,17 +1121,6 @@ mod tests {
assert_eq!(h.name, "Intersection");
}
/// Tab cycling sees every deferred snap within the aperture: on a circle with no base point,
/// its quadrant, then the deferred tangent and the deferred perpendicular at the same spot.
#[test]
fn osnap_all_ranks_every_candidate() {
let d = drawing();
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, mode::QUA | mode::TAN | mode::PER, None, true).is_empty());
}
#[test]
fn center_quadrant_tangent() {
let d = drawing();
@@ -1491,70 +1137,6 @@ mod tests {
assert!(h.point.near(Vec2::new(3.0, 0.0), 1e-9));
}
/// #2800: hovering anywhere over the line finds the perpendicular, though its foot (2,0) is
/// six units from the cursor; it used to snap only within the aperture of the foot.
#[test]
fn perpendicular_from_base_anywhere_on_the_line() {
let d = drawing();
let h = osnap(&d, &Space::Model, Vec2::new(8.0, 0.1), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
assert!(h.point.near(Vec2::new(2.0, 0.0), 1e-9), "{h:?}");
assert_eq!(h.mode, mode::PER);
}
/// #2800: the tangent point is found from anywhere on the circle; of its two tangent points
/// from the base, the one nearer the cursor.
#[test]
fn tangent_from_base_anywhere_on_the_circle() {
let d = drawing();
// From (30,0), 10 from the centre (20,0) of the radius-2 circle: the tangent points are
// at cos = 2/10 from the line to the base, (20.4, ±1.9596).
let upper = Vec2::new(20.4, 2.0 * (1.0f64 - 0.04).sqrt());
let on_circle = Vec2::new(20.0 - 2.0 * std::f64::consts::FRAC_1_SQRT_2, 2.0 * std::f64::consts::FRAC_1_SQRT_2);
let h = osnap(&d, &Space::Model, on_circle, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
assert!(h.point.near(upper, 1e-9), "{h:?}");
let mirrored = Vec2::new(on_circle.x, -on_circle.y);
let h = osnap(&d, &Space::Model, mirrored, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
assert!(h.point.near(Vec2::new(upper.x, -upper.y), 1e-9), "{h:?}");
}
/// A circle offers both perpendicular points from the base, so a pick on its far side snaps
/// there, not to the near side across the circle (CodeRabbit on #2825).
#[test]
fn perpendicular_from_base_on_a_circle_takes_the_side_under_the_cursor() {
let d = drawing();
// The circle at (20,0), radius 2, seen from (30,0): perpendicular at (22,0) and (18,0).
let base = Some(Vec2::new(30.0, 0.0));
let far = osnap(&d, &Space::Model, Vec2::new(18.1, 0.1), 0.5, mode::PER, base, false).unwrap();
assert!(far.point.near(Vec2::new(18.0, 0.0), 1e-9), "{far:?}");
// Away from both points, at (19, √3) on the circle: 2 from (18,0) and √12 from (22,0).
let top = osnap(&d, &Space::Model, Vec2::new(19.0, 3.0f64.sqrt()), 0.5, mode::PER, base, false).unwrap();
assert!(top.point.near(Vec2::new(18.0, 0.0), 1e-9), "{top:?}");
let near = osnap(&d, &Space::Model, Vec2::new(21.9, 0.1), 0.5, mode::PER, base, false).unwrap();
assert!(near.point.near(Vec2::new(22.0, 0.0), 1e-9), "{near:?}");
}
/// With several objects under the aperture, the one nearest the cursor gives the
/// perpendicular, even when another object's foot is nearer.
#[test]
fn perpendicular_from_base_takes_the_object_nearest_the_cursor() {
let d = drawing();
// 0.4 above the horizontal line and 0.2 right of the vertical one: the vertical line wins,
// with its foot (5,4) farther from the cursor than the horizontal line's (2,0).
let h = osnap(&d, &Space::Model, Vec2::new(5.2, 0.4), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
assert!(h.point.near(Vec2::new(5.0, 4.0), 1e-9), "{h:?}");
}
/// A snap point under the cursor still beats a perpendicular whose foot is away from it, and
/// an object outside the aperture gives none, though its box is near.
#[test]
fn perpendicular_from_base_yields_to_points_under_the_cursor() {
let d = drawing();
let base = Some(Vec2::new(2.0, 4.0));
let h = osnap(&d, &Space::Model, Vec2::new(9.9, 0.05), 0.5, mode::END | mode::PER, base, false).unwrap();
assert_eq!((h.point, h.mode), (Vec2::new(10.0, 0.0), mode::END));
assert!(osnap(&d, &Space::Model, Vec2::new(8.0, 0.7), 0.5, mode::PER, base, false).is_none());
}
#[test]
fn ortho_and_polar() {
assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0));
@@ -1597,14 +1179,9 @@ mod tests {
let df = h.deferred.unwrap();
assert_eq!(df.curve, SnapCurve::Circle { center: Vec2::new(20.0, 0.0), radius: 2.0 });
assert_eq!(h.input(), crate::Input::Deferred(df));
// With a base it is an ordinary tangent, unless the prompt resolves it (CIRCLE's radius).
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), false).unwrap();
// With a base it is an ordinary tangent.
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
assert!(t.deferred.is_none() && t.name == "Tangent");
let t = osnap(&d, &Space::Model, at, 0.5, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
assert_eq!(t.name, "Deferred Tangent");
// A perpendicular from the base is still resolved from it.
let p = osnap(&d, &Space::Model, Vec2::new(2.0, 0.2), 0.5, mode::PER, Some(Vec2::new(2.0, 5.0)), true).unwrap();
assert!(p.deferred.is_none() && p.point.near(Vec2::new(2.0, 0.0), 1e-9));
// A specific snap still wins over a deferred one.
let q = osnap(&d, &Space::Model, at, 0.5, mode::TAN | mode::QUA, None, true).unwrap();
assert_eq!(q.mode, mode::QUA);
+8 -47
View File
@@ -482,38 +482,13 @@ impl Tracker {
cfg: &TrackConfig,
base: Option<Vec2>,
) -> Option<Track> {
self.track_with_frozen(d, space, cursor, aperture, tol, cfg, base, &[])
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn track_with_frozen(
&mut self,
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
tol: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Track> {
let t = self.find(d, space, cursor, aperture, tol, cfg, base, frozen);
let t = self.find(d, space, cursor, aperture, tol, cfg, base);
self.last = t.clone();
t
}
#[allow(clippy::too_many_arguments)]
fn find(
&self,
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
tol: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Track> {
fn find(&self, d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, tol: f64, cfg: &TrackConfig, base: Option<Vec2>) -> Option<Track> {
if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) {
return None;
}
@@ -563,7 +538,7 @@ impl Tracker {
// 2. A path crossing an object.
if cfg.running(mode::INT | mode::APP) {
let ix = crate::spatial::index(d, space);
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen).map(|(_, p)| p).unwrap_or_default();
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
for prim in prims.iter().take(200) {
let extend = cfg.running(mode::APP) && super::extendable(prim);
for seg in super::prim_segments(prim) {
@@ -613,26 +588,12 @@ pub fn candidate(
aperture: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
) -> Option<Acquired> {
candidate_with_frozen(d, space, cursor, hit, aperture, cfg, base, &[])
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn candidate_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
hit: Option<&SnapHit>,
aperture: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Acquired> {
if !can_acquire(cursor, aperture, cfg) {
return None;
}
let ix = crate::spatial::index(d, space);
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen).map(|(_, p)| p).unwrap_or_default();
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
}
@@ -828,7 +789,7 @@ impl crate::Session {
s.orthomode ^= q.shift;
let angbase = self.angle_settings().angbase;
let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } };
let (doc, space, frozen) = (st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec());
let (doc, space) = (st.doc.clone(), st.edit_space());
if !raw.is_finite() {
return CursorSnap { point: raw, ..Default::default() };
}
@@ -837,10 +798,10 @@ impl crate::Session {
let cfg = TrackConfig::relative_to(&s, angbase, last);
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
let ix = crate::spatial::index(&doc, &space);
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred, &frozen);
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred);
let cand = match (osmode & mode::HATCH, near_prims.as_deref()) {
(0, Some(prims)) => candidate_with_prims(raw, hit.as_ref(), q.aperture, &cfg, q.base, prims),
_ => candidate_with_frozen(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base, &frozen),
_ => candidate(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base),
};
let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift);
if let Some(h) = hit {
@@ -855,7 +816,7 @@ impl crate::Session {
let (origin, angle) = super::grid_frame_in(&doc, &space);
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
}
if let Some(mut t) = self.tracking.track_with_frozen(&doc, &space, p, q.aperture, q.tol, &cfg, q.base, &frozen) {
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) {
// PolarSnap (SNAPTYPE 1): steps of POLARDIST, or of the snap X spacing when it is 0.
let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
if s.snapmode
+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 -3
View File
@@ -115,7 +115,6 @@ mod offset_ellipse_side;
mod offset_move;
mod oops_command;
mod options_profile;
mod osnap_opened_drawings;
mod overkill;
mod parallel_display_list;
mod pedit_multiple;
@@ -144,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;
@@ -158,12 +158,10 @@ mod setvar_coverage;
mod shapes;
mod snap_annotations;
mod snap_blocks;
mod snap_center_on_curve;
mod snap_curves;
mod snap_intersections_aperture;
mod snap_nearest;
mod snap_overrides;
mod snap_tab_cycling;
mod snap_tracking;
mod snaps_more;
mod solid_command;
@@ -1,9 +1,8 @@
//! DIST snaps to the model geometry displayed in paper-space viewports (#516).
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Ellipse, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap};
use cadcraft_engine::{Input, Session};
use serde_json::json;
@@ -279,46 +278,6 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
}
/// Across spaces a click takes the viewport's Endpoint over a paper-space Nearest that scores
/// closer, as within one space a snap point beats Nearest. Tab starts at the click's snap and
/// still reaches the paper-space Nearest.
#[test]
fn a_viewport_endpoint_beats_a_closer_paper_space_nearest() {
let (mut d, paper) = drawing();
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
assert!(hit.mode == mode::END && hit.viewport.is_some() && hit.point.near(Vec2::new(95.0, 50.0), 1e-9), "{hit:?}");
let all = snap_candidates(&d, &paper, cursor, 0.5, modes, None, false);
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
assert!(
all.iter().any(|h| h.mode == mode::NEA && h.viewport.is_none() && h.point.near(Vec2::new(94.7, 50.0), 1e-9)),
"Tab reaches the paper-space Nearest: {all:?}"
);
}
/// Overlapping viewports can show different model points at one paper point; Tab offers each,
/// since DIST measures in the model units of the viewport picked.
#[test]
fn overlapping_viewports_each_offer_their_model_point() {
let (mut d, paper) = drawing();
// This viewport shows the model endpoint (20, 0) at paper (100, 50), a second one over it (0, 0).
edit_viewport(&mut d, &paper, |vp| vp.view_center = Vec2::new(20.0, 0.0));
let mut vp = match &d.entity(viewport(&d, &paper)).unwrap().kind {
EntityKind::Viewport(vp) => vp.clone(),
_ => panic!("viewport fixture"),
};
vp.view_center = Vec2::new(0.0, 0.0);
vp.id = 3;
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
let all = osnap_all(&d, &paper, Vec2::new(100.05, 50.04), 0.5, mode::END, None, false);
let mut models: Vec<Vec2> =
all.iter().filter(|h| h.point.near(Vec2::new(100.0, 50.0), 1e-9)).filter_map(|h| h.viewport).map(|v| v.point).collect();
models.sort_by(|a, b| a.x.total_cmp(&b.x));
assert_eq!(models, [Vec2::new(0.0, 0.0), Vec2::new(20.0, 0.0)], "{all:?}");
}
#[test]
fn viewport_frozen_layers_do_not_hide_paper_space_geometry() {
let (mut d, paper) = drawing();
@@ -430,22 +389,3 @@ fn malformed_and_paper_space_viewports_are_not_snap_sources() {
assert!(osnap(&d, &paper, Vec2::new(95.1, 50.1), 0.5, mode::END, None, false).is_none());
}
}
/// Nearest on a curve that leaves the viewport: the curve's closest point to the cursor is outside
/// the viewport, another point of it within the aperture is inside, and Nearest snaps there.
#[test]
fn nearest_takes_the_visible_part_of_a_curve_crossing_the_viewport_edge() {
let (mut d, paper) = drawing();
// The viewport shows model y up to 20. A tall ellipse peaks at (15, 20.1), just outside.
let ellipse = Ellipse { center: Vec3::new(15.0, 0.0, 0.0), major: Vec3::new(0.0, 20.1, 0.0), ratio: 0.1, start: 0.0, end: std::f64::consts::TAU };
d.add(&Space::Model, Common::default(), EntityKind::Ellipse(ellipse)).unwrap();
// The viewport's border is on a layer that is off, so it offers no Nearest of its own.
d.layers.push(cadcraft_engine::doc::Layer { name: "Border".into(), on: false, ..Default::default() });
let vp = viewport(&d, &paper);
d.modify_entity(vp, |e| e.common.layer = "Border".into()).unwrap();
// Model (15, 19.99): 0.11 from the peak, about 0.2 from where the ellipse comes back inside.
let cursor = Vec2::new(102.5, 59.995);
let hit = osnap(&d, &paper, cursor, 0.5, mode::NEA, None, false).expect("a visible nearest point");
let model = hit.viewport.expect("seen through the viewport").point;
assert!(model.y <= 20.0 + 1e-9 && model.dist(Vec2::new(15.0, 19.99)) <= 1.0, "{hit:?}");
}
@@ -1,114 +0,0 @@
//! Running object snaps in a fresh drawing and in drawings opened from DXF and DWG files, with
//! AutoCAD's default modes (OSMODE 4133: Endpoint, Center, Intersection, Extension).
//!
//! Moving onto a circle, an arc or a polyline arc finds its Center. OSMODE is a profile setting,
//! as in AutoCAD (saved in the registry there, not the drawing): a file's `$OSMODE` header
//! variable, 0 included, never changes the running snaps.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Drawing;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::snap::{mode, tracking::CursorQuery};
use serde_json::json;
/// AutoCAD's default running snaps.
const DEFAULT: u32 = 4133;
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
let a = deg.to_radians();
c + Vec2::new(r * a.cos(), r * a.sin())
}
/// A line crossed by another, a circle, an arc and a polyline with a straight and an arc segment.
fn draw(s: &mut Session) {
s.execute("line", &json!({ "points": [[0, 0], [20, 0]] })).unwrap();
s.execute("line", &json!({ "points": [[5, -5], [5, 5]] })).unwrap();
s.execute("circle", &json!({ "center": [50, 0], "radius": 5 })).unwrap();
s.execute("arc", &json!({ "center": [80, 0], "radius": 5, "start": 0, "end": 180 })).unwrap();
// 100,0 to 110,0 straight, then a half circle (bulge 1) to 130,0 round 120,0, below the axis.
s.execute("pline", &json!({ "vertices": [[100, 0], {"p": [110, 0], "bulge": 1.0}, [130, 0]] })).unwrap();
}
fn drawing() -> Drawing {
let mut s = Session::new();
draw(&mut s);
s.doc().unwrap().clone()
}
/// Where a click at `cursor` lands while LINE asks for its first point (the drawing area's path).
fn snap(s: &mut Session, cursor: Vec2) -> Option<(Vec2, u32)> {
if s.running.is_none() {
s.start("line").unwrap();
}
let q = CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
let r = s.snap_cursor(cursor, &q);
r.snap.map(|h| (r.point, h.mode))
}
fn assert_snaps(s: &mut Session, what: &str) {
assert_eq!(s.settings.osmode, DEFAULT, "{what}: the running snaps are the profile's");
let cases = [
("the line's end", Vec2::new(20.2, 0.1), Vec2::new(20.0, 0.0), &[mode::END][..]),
("the lines' crossing", Vec2::new(5.2, 0.15), Vec2::new(5.0, 0.0), &[mode::INT][..]),
("the circle", polar(Vec2::new(50.0, 0.0), 5.3, 45.0), Vec2::new(50.0, 0.0), &[mode::CEN][..]),
("the arc", polar(Vec2::new(80.0, 0.0), 5.2, 90.0), Vec2::new(80.0, 0.0), &[mode::CEN][..]),
("the arc's end", Vec2::new(85.2, 0.1), Vec2::new(85.0, 0.0), &[mode::END][..]),
("the polyline's vertex", Vec2::new(110.2, 0.1), Vec2::new(110.0, 0.0), &[mode::END][..]),
("the polyline's arc", polar(Vec2::new(120.0, 0.0), 10.2, 270.0), Vec2::new(120.0, 0.0), &[mode::CEN][..]),
];
for (name, cursor, want, modes) in cases {
let (p, m) = snap(s, cursor).unwrap_or_else(|| panic!("{what}: no snap on {name}"));
assert!(modes.contains(&m), "{what}, {name}: mode {m}");
assert!(p.near(want, 1e-6), "{what}, {name}: {p:?}");
}
// Away from everything: nothing.
assert_eq!(snap(s, Vec2::new(35.0, 20.0)), None, "{what}");
// F3 off: nothing; on again: back.
s.execute("osnap", &json!({})).unwrap();
assert_eq!(snap(s, Vec2::new(20.2, 0.1)), None, "{what}: F3 off");
s.execute("osnap", &json!({})).unwrap();
assert_eq!(snap(s, Vec2::new(20.2, 0.1)).map(|h| h.1), Some(mode::END), "{what}: F3 on");
}
#[test]
fn default_snaps_work_in_a_fresh_drawing() {
let mut s = Session::new();
draw(&mut s);
assert_snaps(&mut s, "fresh drawing");
}
/// `text` with `$OSMODE` set to `value` at the top of its header.
fn with_osmode(text: &str, value: u32) -> String {
let at = text.find("HEADER").expect("a header section") + "HEADER".len();
let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
let (head, tail) = text.split_at(at);
format!("{head}{eol} 9{eol}$OSMODE{eol} 70{eol}{value}{tail}")
}
#[test]
fn a_dxf_with_osmode_0_keeps_the_running_snaps() {
let text = String::from_utf8(cadcraft_io::write(&drawing(), "snaps.dxf").unwrap()).unwrap();
let text = with_osmode(&text, 0);
let d = cadcraft_io::read(text.as_bytes(), "snaps.dxf").unwrap();
let mut s = Session::new();
// OSMODE is the profile's: the user's own choice survives opening the file.
s.execute("setvar", &json!({ "name": "OSMODE", "value": DEFAULT })).unwrap();
s.open_drawing(d, "snaps.dxf", None);
assert_snaps(&mut s, "DXF with $OSMODE 0");
// Nor does a file change a profile without Center.
let mut s = Session::new();
s.execute("setvar", &json!({ "name": "OSMODE", "value": mode::END })).unwrap();
s.open_drawing(cadcraft_io::read(with_osmode(&text, DEFAULT).as_bytes(), "x.dxf").unwrap(), "x.dxf", None);
assert_eq!(s.settings.osmode, mode::END);
}
#[test]
fn default_snaps_work_in_a_drawing_opened_from_dwg() {
// The drawing is the test's own, so it is converted in this process.
cadcraft_io::dwg_worker::allow_in_process();
let bytes = cadcraft_io::write(&drawing(), "snaps.dwg").unwrap();
let d = cadcraft_io::read(&bytes, "snaps.dwg").unwrap();
let mut s = Session::new();
s.open_drawing(d, "snaps.dwg", None);
assert_snaps(&mut s, "DWG");
}
+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}");
}
+794
View File
@@ -0,0 +1,794 @@
//! 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<String> {
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() {
// These files are our own: DWG is read and written in this process.
cadcraft_io::dwg_worker::allow_in_process();
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<String> {
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() {
// These files are our own: DWG is read and written in this process.
cadcraft_io::dwg_worker::allow_in_process();
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);
}
/// Automation roots (#1472): an agent confined to its folders can't have REFCLOSE write an xref, or
/// the xref's `.bak`, outside its write root, and can't start an edit in place of one it may not
/// write. The refusals leave the xref, its backup and the host as they were.
#[test]
fn a_confined_session_does_not_write_an_xref_outside_its_write_root() {
use cadcraft_engine::file_access::{AutomationRoots, confine};
let (mut s, dir, _, insert) = attached("confined");
let file = dir.join("site.dxf");
let before = std::fs::read(&file).unwrap();
let out = dir.join("out");
std::fs::create_dir_all(&out).unwrap();
// The xref's folder may be read but not written.
let roots = AutomationRoots::new(Some(&dir), Some(&out)).unwrap();
// REFEDIT of an xref it couldn't save is refused before the edit begins.
let e = confine(roots.as_ref(), || s.execute("refedit", &json!({ "handle": insert }))).unwrap_err().to_string();
assert!(e.contains("outside") || e.contains("write"), "{e}");
assert!(s.doc().unwrap().refedit.is_none(), "no edit began");
// An edit begun without the roots isn't written once they are in force.
s.execute("refedit", &json!({ "handle": insert })).unwrap();
s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap();
let e = confine(roots.as_ref(), || s.execute("refclose", &json!({ "option": "save" }))).unwrap_err().to_string();
assert!(e.contains("outside") || e.contains("write"), "{e}");
assert_eq!(std::fs::read(&file).unwrap(), before, "the xref is unchanged");
assert!(std::fs::symlink_metadata(dir.join("site.dxf.bak")).is_err(), "no backup was written");
assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open");
assert_eq!(s.doc().unwrap().block("site").unwrap().entities.len(), 2, "the host still shows the xref as it was");
s.execute("refclose", &json!({ "option": "discard" })).unwrap();
// Roots that don't reach the xref's folder: it isn't read for an edit either.
let elsewhere = dir.join("elsewhere");
std::fs::create_dir_all(elsewhere.join("out")).unwrap();
let roots = AutomationRoots::new(Some(&elsewhere), Some(&elsewhere.join("out"))).unwrap();
let e = confine(roots.as_ref(), || s.execute("refedit", &json!({ "handle": insert }))).unwrap_err().to_string();
assert!(s.doc().unwrap().refedit.is_none(), "no edit began: {e}");
assert_eq!(std::fs::read(&file).unwrap(), before);
}
/// The write-back reports what a file can't keep as SAVE does (`lost_writing`), not only solids
/// in a 2013 DXF: an R2000 DXF xref has no place for a proxy's separate strings (#3229), so the
/// save names the proxy it leaves out, with the DXF's reason and the backup that keeps it.
#[test]
fn a_proxy_an_r2000_dxf_xref_cannot_keep_is_reported() {
hooks();
let dir = folder("proxy");
let dxf = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n20\n8\n0\n10\n0\n20\n0\n11\n1\n21\n1\n0\nACAD_PROXY_ENTITY\n5\n21\n100\nAcDbEntity\n8\n0\n100\nAcDbProxyEntity\n90\n498\n91\n500\n162\n8\n161\n16\n310\nAABB\n0\nENDSEC\n0\nEOF\n";
std::fs::write(dir.join("proxy.dxf"), dxf).unwrap();
let (mut s, insert) = host_with(&dir, "proxy.dxf", "proxy");
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!({ "ACAD_PROXY_ENTITY": 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("before 2007") && warning.contains("1 ACAD_PROXY_ENTITY") && warning.contains("proxy.dxf.bak"), "{warning}");
}
/// Review of #2355: a reference to another xref of the host, added to the working set with
/// REFSET, would be written into the xref's drawing naming a block that drawing doesn't define.
/// The save is refused instead; the file, its backup and the edit stay as they were.
#[test]
fn a_reference_to_another_xref_of_the_host_is_not_written_into_the_xref() {
let (mut s, dir, _, insert) = attached("other-xref");
let (other, _) = site();
save(&other, &dir.join("other.dxf"));
let r = s.execute("xattach", &json!({ "path": "other.dxf", "at": [0, 100] })).unwrap();
let other_insert = r["handle"].as_str().unwrap().to_string();
let file = dir.join("site.dxf");
let before = std::fs::read(&file).unwrap();
s.execute("refedit", &json!({ "handle": insert })).unwrap();
s.execute("refset", &json!({ "add": [other_insert] })).unwrap();
let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string();
assert!(e.contains("\"other\""), "{e}");
assert_eq!(std::fs::read(&file).unwrap(), before, "the xref is unchanged");
assert!(std::fs::symlink_metadata(dir.join("site.dxf.bak")).is_err(), "no backup was written");
assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open");
s.execute("refclose", &json!({ "option": "discard" })).unwrap();
}
/// A dimension drawn during the edit with a host dimension style whose arrowhead is a block of
/// the host: the block comes along with the style, so the xref's drawing defines what it names.
#[test]
fn a_host_dimension_styles_arrow_block_comes_along() {
let (mut s, dir, _, insert) = attached("arrow-block");
{
let d = s.doc_mut().unwrap();
let mut pin = Block::new("Pin");
let h = d.new_handle();
pin.entities.push(Entity::new(h, EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 0.5 })));
d.blocks.insert("Pin".into(), Arc::new(pin));
d.dim_styles.push(cadcraft_engine::doc::DimStyle { name: "Pinned".into(), arrow_block: "Pin".into(), ..Default::default() });
d.header.set_str("DIMSTYLE", "Pinned");
}
s.execute("refedit", &json!({ "handle": insert })).unwrap();
s.execute("dimlinear", &json!({ "p1": [100, 30], "p2": [110, 30], "at": [105, 40] })).unwrap();
s.execute("refclose", &json!({ "option": "save" })).unwrap();
let back = read(&dir.join("site.dxf"));
assert_eq!(back.dim_style("Pinned").expect("the style comes along").arrow_block, "Pin");
assert!(back.block("Pin").is_some(), "and the block its arrowheads are");
}
/// Whether `d`'s model holds a dimension attached to the objects it measures.
fn associative_dimensions(d: &Drawing) -> usize {
d.model.iter().filter(|e| matches!(&e.kind, EntityKind::Dimension(dm) if !dm.assoc.is_empty())).count()
}
/// Review of #2355: loading an xref drops its dimensions' associations, so the write-back leaves
/// them out of the file. Until that is kept, the save says so, as for anything else the file
/// can't keep, and names the backup that still has 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 them, and counted too.
#[test]
fn dimension_associations_the_write_back_drops_are_reported() {
hooks();
let dir = folder("assoc");
let mut src = Session::new();
src.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
src.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 5] })).unwrap();
let file = dir.join("dims.dxf");
src.execute("saveas", &json!({ "path": file.to_string_lossy() })).unwrap();
assert_eq!(associative_dimensions(&read(&file)), 1, "the file has an associative dimension");
let (mut s, insert) = host_with(&dir, "dims.dxf", "dims");
s.execute("refedit", &json!({ "handle": insert })).unwrap();
// On the copy of the line, at (100, 0)..(110, 0) in the host.
s.execute("dimlinear", &json!({ "p1": [100, 0], "p2": [110, 0], "at": [105, -5] })).unwrap();
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
assert_eq!(out["notSaved"]["dimension associations"], 2, "{out}");
let warning = s.log.iter().find(|m| m.contains("dimension associations")).expect("a warning on the command line");
assert!(warning.contains("dims.dxf.bak"), "{warning}");
let back = read(&file);
assert_eq!(associative_dimensions(&back), 0, "{:?}", back.model.iter().map(|e| &e.kind).collect::<Vec<_>>());
assert_eq!(associative_dimensions(&read(&dir.join("dims.dxf.bak"))), 1, "the backup keeps them");
}
/// Review of #2355 (follow-up): a nested reference is offered only when the reference with
/// everything above it can be opened. Each of two uniform scales of 0.0001 is fine alone, but
/// together they flatten the inner block past what REFEDIT opens, so it isn't offered.
#[test]
fn a_nested_reference_too_small_with_its_parents_is_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 tiny = hx(s.execute("insert", &json!({ "name": "Leaf", "at": [0, 0], "scale": 0.0001 })).unwrap());
let l = hx(s.execute("line", &json!({ "points": [[0, 0], [1, 0]] })).unwrap());
s.execute("block", &json!({ "name": "Holder", "base": [0, 0], "handles": [tiny, l], "keep": "delete" })).unwrap();
let o = hx(s.execute("insert", &json!({ "name": "Holder", "at": [0, 0], "scale": 0.0001 })).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"], "{levels}");
}
@@ -1,202 +0,0 @@
//! Center snaps from the curve, as in AutoCAD: with the cursor over a circle, an arc, an
//! ellipse or a polyline arc (also inside a block reference) the running Center snap finds its
//! center, however far away it is. Before, the center was only found with the cursor on the
//! center itself, so moving onto a circle with the default running snaps (END, CEN, INT, EXT)
//! showed nothing.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, EntityKind, Insert, Space};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::{self, mode};
use serde_json::json;
/// AutoCAD's default running snaps (OSMODE 4133).
const DEFAULT: u32 = 4133;
fn snap_at(s: &Session, cursor: Vec2, aperture: f64, osmode: u32) -> Option<(Vec2, u32)> {
snap::osnap(s.doc().unwrap(), &Space::Model, cursor, aperture, osmode, None, false).map(|h| (h.point, h.mode))
}
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
let a = deg.to_radians();
c + Vec2::new(r * a.cos(), r * a.sin())
}
#[test]
fn cursor_on_a_circle_snaps_to_its_center() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [100, 50], "radius": 20 })).unwrap();
let c = Vec2::new(100.0, 50.0);
for deg in [10.0, 45.0, 130.0, 250.0, 300.0] {
// A hair off the circle, well inside the aperture; the center is 20 units away.
let cursor = polar(c, 20.3, deg);
let (p, m) = snap_at(&s, cursor, 1.0, DEFAULT).unwrap_or_else(|| panic!("no snap on the circle at {deg}°"));
assert_eq!(m, mode::CEN, "at {deg}°");
assert!(p.near(c, 1e-9), "at {deg}°: {p:?}");
}
// Away from the circle (outside the aperture) there is nothing.
assert_eq!(snap_at(&s, polar(c, 23.0, 45.0), 1.0, DEFAULT), None);
// Center off: no center.
assert_eq!(snap_at(&s, polar(c, 20.3, 45.0), 1.0, mode::END), None);
// On the center itself, as before.
assert_eq!(snap_at(&s, c + Vec2::new(0.2, 0.1), 1.0, DEFAULT).map(|h| h.1), Some(mode::CEN));
}
#[test]
fn arcs_ellipses_and_polyline_arcs_snap_to_their_centers() {
let mut s = Session::new();
s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap();
s.execute("ellipse", &json!({ "center": [50, 0], "major": [8, 0], "ratio": 0.5 })).unwrap();
// A polyline with a half-circle bulge from (100,0) to (120,0): center (110,0), radius 10.
s.execute("pline", &json!({ "vertices": [{"p": [100, 0], "bulge": 1.0}, [120, 0]] })).unwrap();
let arc = snap_at(&s, polar(Vec2::ZERO, 10.2, 45.0), 1.0, DEFAULT).unwrap();
assert_eq!(arc.1, mode::CEN);
assert!(arc.0.near(Vec2::ZERO, 1e-9));
// The arc runs 0°-90°: on its circle at 200° (not on the arc) there is no center.
assert_eq!(snap_at(&s, polar(Vec2::ZERO, 10.2, 200.0), 1.0, DEFAULT), None);
let el = snap_at(&s, Vec2::new(50.0, 4.2), 1.0, DEFAULT).unwrap();
assert_eq!(el.1, mode::CEN);
assert!(el.0.near(Vec2::new(50.0, 0.0), 1e-9));
let pl = snap_at(&s, polar(Vec2::new(110.0, 0.0), 10.2, 270.0), 1.0, DEFAULT).unwrap();
assert_eq!(pl.1, mode::CEN, "the bulge's arc");
assert!(pl.0.near(Vec2::new(110.0, 0.0), 1e-9), "{:?}", pl.0);
}
#[test]
fn a_nearer_endpoint_or_intersection_still_wins() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
s.execute("line", &json!({ "points": [[10, 0], [30, 0]] })).unwrap();
// At the line's end on the circle: Endpoint/Intersection, not the far center.
let (p, m) = snap_at(&s, Vec2::new(10.2, 0.1), 1.0, DEFAULT).unwrap();
assert!(m == mode::END || m == mode::INT, "{m}");
assert!(p.near(Vec2::new(10.0, 0.0), 1e-9));
}
#[test]
fn circles_inside_block_references_snap_to_their_centers() {
let mut s = Session::new();
let c = s.execute("circle", &json!({ "center": [5, 0], "radius": 2 })).unwrap()["handle"].as_str().unwrap().to_string();
s.execute("block", &json!({ "name": "H", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap();
let kind = EntityKind::Insert(Insert {
block: "H".into(),
insert: Vec3::new(100.0, 100.0, 0.0),
scale: Vec3::new(3.0, 3.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
});
s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap();
// The circle lands at (115,100) with radius 6.
let (p, m) = snap_at(&s, polar(Vec2::new(115.0, 100.0), 6.2, 60.0), 1.0, DEFAULT).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(115.0, 100.0), 1e-9), "{p:?}");
}
#[test]
fn tab_cycling_offers_the_center_from_the_curve() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
let all = snap_candidates(s.doc().unwrap(), &Space::Model, polar(Vec2::ZERO, 10.2, 30.0), 1.0, DEFAULT, None, false);
assert_eq!(all.iter().filter(|h| h.mode == mode::CEN && h.point.near(Vec2::ZERO, 1e-9)).count(), 1, "{all:?}");
}
#[test]
fn the_cursor_query_snaps_to_the_center_from_the_curve() {
// The path the drawing area uses (Session::snap_cursor): the point a click would take.
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 50 })).unwrap();
s.start("line").unwrap();
let q = snap::tracking::CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
let r = s.snap_cursor(polar(Vec2::ZERO, 50.4, 33.0), &q);
assert_eq!(r.snap.map(|h| h.mode), Some(mode::CEN));
assert!(r.point.near(Vec2::ZERO, 1e-9), "{:?}", r.point);
}
/// The arc of the review of #2347 (and #1114's test): center (100,50), radius 80, 30°-150°.
fn review_arc() -> Session {
let mut s = Session::new();
s.execute("arc", &json!({ "center": [100, 50], "radius": 80, "start": 30, "end": 150 })).unwrap();
s
}
#[test]
fn a_midpoint_under_the_cursor_beats_the_center_from_the_curve() {
let s = review_arc();
// On the arc's midpoint (100,130) with Center and Midpoint running: Midpoint, as in AutoCAD.
for cursor in [Vec2::new(100.05, 130.0), Vec2::new(100.2, 130.1)] {
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
assert_eq!(snap_at(&s, cursor, 0.5, mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
}
// Elsewhere on the arc, with no snap point in the aperture, the center from the curve.
let (p, m) = snap_at(&s, polar(Vec2::new(100.0, 50.0), 80.1, 70.0), 0.5, mode::CEN | mode::MID).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(100.0, 50.0), 1e-9), "{p:?}");
}
#[test]
fn a_quadrant_under_the_cursor_beats_the_center_from_the_curve() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [20, 0], "radius": 2 })).unwrap();
let cursor = Vec2::new(20.1, 2.0);
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
assert_eq!(snap_at(&s, cursor, 0.5, mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
// Away from the quadrants the center from the curve.
let (p, m) = snap_at(&s, polar(Vec2::new(20.0, 0.0), 2.1, 45.0), 0.5, mode::CEN | mode::QUA).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(20.0, 0.0), 1e-9), "{p:?}");
}
#[test]
fn many_straight_segments_do_not_hide_a_circle_from_center() {
// A polyline of 2,500 straight segments zigzagging over the cursor, then a circle: the
// work limit counts circles and arcs only, so the circle's center is still found.
let mut s = Session::new();
let vertices: Vec<[f64; 2]> = (0..=2500).map(|i| [i as f64 * 0.04, if i % 2 == 0 { 0.0 } else { 100.0 }]).collect();
s.execute("pline", &json!({ "vertices": vertices })).unwrap();
s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap();
let (p, m) = snap_at(&s, polar(Vec2::new(50.0, 50.0), 20.2, 100.0), 0.5, mode::CEN).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(50.0, 50.0), 1e-9), "{p:?}");
}
#[test]
fn a_viewport_center_keeps_its_curve_distance_against_paper_space() {
use cadcraft_engine::doc::{Circle, Drawing, Viewport};
let mut d = Drawing::new_imperial();
let paper = Space::Paper("Layout1".into());
// Model circle (10,0) r16 seen through a viewport at half scale: paper center (100,50), radius 8.
d.add(&Space::Model, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(10.0, 0.0, 0.0), radius: 16.0 })).unwrap();
let vp = Viewport {
center: Vec3::new(100.0, 50.0, 0.0),
width: 20.0,
height: 20.0,
view_center: Vec2::new(10.0, 0.0),
view_height: 40.0,
id: 2,
locked: false,
frozen_layers: Vec::new(),
layer_colors: Vec::new(),
clip: None,
on: true,
twist: 0.0,
};
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
// A small paper-space circle whose curve passes 0.3 from the cursor and whose center is
// nearer the cursor (3.3) than the model circle's (8).
d.add(&paper, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(108.0, 53.3, 0.0), radius: 3.0 })).unwrap();
// The cursor is on the model circle (0.1 off in paper units): its center wins.
let h = snap::osnap(&d, &paper, Vec2::new(108.1, 50.0), 0.5, mode::CEN, None, false).unwrap();
assert_eq!(h.mode, mode::CEN);
assert!(h.point.near(Vec2::new(100.0, 50.0), 1e-9), "{h:?}");
assert!(h.viewport.is_some());
// On the paper circle, away from the model one: its center.
let h = snap::osnap(&d, &paper, Vec2::new(108.0, 56.35), 0.5, mode::CEN, None, false).unwrap();
assert!(h.point.near(Vec2::new(108.0, 53.3), 1e-9), "{h:?}");
assert!(h.viewport.is_none());
}
-3
View File
@@ -70,9 +70,6 @@ fn elliptical_arc_perpendicular_and_tangent_from_a_base_point() {
let (q, m) = along_quarter(&s, mode::TAN, Some(base)).expect("a tangent point on the arc");
assert_eq!(m, mode::TAN);
assert!(on_quarter(q) && Vec2::new(q.x / 16.0, q.y / 4.0).dot(q - base).abs() < 1e-9, "{q:?}");
// The same tangent at a prompt that resolves deferred snaps (CIRCLE's 3P points, #1512).
let h = snap::osnap(s.doc().unwrap(), &Space::Model, q, 0.3, mode::TAN, Some(base), true).expect("tangent at a deferred prompt");
assert!(h.mode == mode::TAN && h.deferred.is_none() && h.point.near(q, 1e-9), "{h:?}");
// Perpendicular from (10,10): the line from the base runs along the normal.
let base = Vec2::new(10.0, 10.0);
let (q, m) = along_quarter(&s, mode::PER, Some(base)).expect("a perpendicular foot on the arc");
-111
View File
@@ -21,17 +21,6 @@ fn last_line(s: &Session) -> (Vec2, Vec2) {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).last().unwrap()
}
/// The last circle drawn as (center, radius).
fn last_circle(s: &Session) -> (Vec2, f64) {
s.doc()
.unwrap()
.model
.iter()
.filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some((c.center.xy(), c.radius)) } else { None })
.last()
.unwrap()
}
fn near(p: Vec2, x: f64, y: f64) -> bool {
p.near(Vec2::new(x, y), 1e-9)
}
@@ -91,23 +80,6 @@ fn nothing_to_snap_to_rejects_the_point() {
assert!(near(s.last_point, 10.0, 10.0));
}
/// #2800: a typed PER or TAN finds its point from a pick anywhere on the object, as in AutoCAD.
/// The pick used to have to land within the aperture (0.125 here) of the foot or tangent point,
/// which you can't know in advance; elsewhere it said "No Perpendicular found".
#[test]
fn typed_per_and_tan_snap_from_anywhere_on_the_object() {
let mut s = drawing();
// From (5,5), PER picked at (3,0) on the line 0,0–10,0: two units from the foot (5,0).
s.script("LINE 5,5 PER 3,0\n\n").unwrap();
let (a, b) = last_line(&s);
assert!(near(a, 5.0, 5.0) && near(b, 5.0, 0.0), "{a:?} {b:?}");
// From (30,20), TAN picked at the top of the circle (centre 20,20, radius 3): the tangent
// points are at cos = 3/10 from the line to the base, and the upper one is nearer the pick.
s.script("LINE 30,20 TAN 20,23\n\n").unwrap();
let (a, b) = last_line(&s);
assert!(near(a, 30.0, 20.0) && near(b, 20.9, 20.0 + 3.0 * 0.91f64.sqrt()), "{a:?} {b:?}");
}
#[test]
fn from_nests_with_a_snap_override() {
let mut s = drawing();
@@ -144,86 +116,3 @@ fn a_command_keyword_wins_over_a_snap_word() {
s.cmdline("arc _cen").unwrap();
assert!(s.prompt_text().ends_with("Center of:"), "{}", s.prompt_text());
}
#[test]
fn tan_for_a_circle_radius_touches_the_picked_circle() {
// #1512: the circle around the center that touches the circle at 20,20 radius 3, on the side
// it was picked: the near side (radius 7), the far side (13), and through Diameter.
for (script, center, r) in [
("CIRCLE 30,20 TAN 23.02,20.03\n", (30.0, 20.0), 7.0),
("CIRCLE 30,20 TAN 16.98,19.97\n", (30.0, 20.0), 13.0),
("CIRCLE 20,10 D TAN 20.03,17.02\n", (20.0, 10.0), 7.0),
] {
let mut s = drawing();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
let (c, got) = last_circle(&s);
assert!(near(c, center.0, center.1) && (got - r).abs() < 1e-9, "{script}: {c:?} r={got}");
}
}
#[test]
fn tan_for_a_3p_circle_touches_the_picked_circles() {
// #1512: through two points and tangent to the circle at 20,20 radius 3, the tangent pick
// first or last.
for script in ["CIRCLE 3P 26,20 26,26 TAN 23.02,20.03\n", "CIRCLE 3P TAN 23.02,20.03 26,20 26,26\n"] {
let mut s = drawing();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!((c.dist(Vec2::new(26.0, 20.0)) - r).abs() < 1e-9 && (c.dist(Vec2::new(26.0, 26.0)) - r).abs() < 1e-9, "{script}");
assert!((c.dist(Vec2::new(20.0, 20.0)) - (3.0 + r)).abs() < 1e-9, "{script}: {c:?} r={r}");
}
// Tan, Tan, Tan: the circle between three circles of radius 1, picked on their inner sides.
let mut s = Session::new();
s.script("CIRCLE 0,0 1\nCIRCLE 6,0 1\nCIRCLE 3,5 1\nCIRCLE 3P TAN 0.98,0.2 TAN 5.02,0.2 TAN 3.01,3.98\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
for k in [(0.0, 0.0), (6.0, 0.0), (3.0, 5.0)] {
assert!((c.dist(Vec2::new(k.0, k.1)) - (1.0 + r)).abs() < 1e-9, "{c:?} r={r}");
}
}
#[test]
fn tan_for_a_3p_circle_touches_an_arc_within_its_sweep() {
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
// on the right or the far left, both off an arc swept from 90° to 100°: no circle.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 90, "end": 100})).unwrap();
s.script("CIRCLE 3P 26,20 26,26 TAN 19.74,22.99\n").unwrap();
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
assert!(!s.doc().unwrap().model.iter().any(|e| matches!(e.kind, EntityKind::Circle(_))));
}
#[test]
fn tan_for_a_3p_circle_takes_the_solution_that_touches_the_arc() {
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
// at about 29.6° and -103.3°. Picked at 20° on an arc swept from 200° to 25°, the 29.6°
// circle is nearer the pick but off the arc: the -103.3° one (radius 6.0826) is drawn.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 200, "end": 25})).unwrap();
s.script("CIRCLE 3P 26,20 26,26 TAN 22.82,21.03\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!((c.dist(Vec2::new(20.0, 20.0)) - (r - 3.0)).abs() < 1e-9 && (r - 6.082575694955838).abs() < 1e-9, "{c:?} r={r}");
}
#[test]
fn tan_for_a_circle_radius_refuses_the_picked_circles_own_center() {
// #1512: a circle around 20,20 would lie on the circle there, not touch it.
let mut s = drawing();
s.script("CIRCLE 20,20 TAN 23.02,20.03\n").unwrap();
assert!(s.prompt_text().contains("radius of circle"), "{}", s.prompt_text());
assert!(s.log.iter().any(|l| l.contains("No circle around the center is tangent there.")), "{:?}", s.log);
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
}
#[test]
fn tan_for_a_3p_circle_refuses_the_picked_circle_itself() {
// #1512: tangent twice to the circle and through a point on it is only the circle itself.
let mut s = drawing();
s.script("CIRCLE 3P TAN 23.02,20.03 TAN 16.98,20.03 20,23\n").unwrap();
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
assert!(s.log.iter().any(|l| l.contains("Circle does not exist.")), "{:?}", s.log);
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
}
@@ -1,89 +0,0 @@
//! Tab cycling through object snaps: a crowd of candidates is capped, hostile cursors and
//! apertures give no candidates, and the list never repeats a snap.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Space;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::mode;
use serde_json::json;
#[test]
fn a_crowd_of_snaps_is_capped_and_never_repeats() {
let mut s = Session::new();
// 600 short lines fanning out from points packed round the origin: 1,200 endpoints.
for i in 0..600 {
let a = f64::from(i) * 0.01;
let p = [1e-3 * a.cos(), 1e-3 * a.sin()];
s.execute("line", &json!({ "points": [p, [a.cos(), a.sin()]] })).unwrap();
}
let d = s.doc().unwrap();
let cands = snap_candidates(d, &Space::Model, Vec2::ZERO, 0.5, mode::END | mode::INT | mode::NEA, None, false);
assert!(!cands.is_empty());
assert!(cands.len() <= 257, "{} candidates", cands.len());
for (i, a) in cands.iter().enumerate() {
assert!(a.point.is_finite());
assert!(!cands.iter().skip(i + 1).any(|b| b.mode == a.mode && b.point == a.point), "{a:?} repeats");
}
}
#[test]
fn hostile_cursor_and_aperture_give_no_candidates() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let d = s.doc().unwrap();
let space = Space::Model;
let all = mode::END | mode::MID | mode::INT | mode::NEA | mode::PER;
for (c, ap) in [
(Vec2::new(f64::NAN, 0.0), 0.5),
(Vec2::new(0.0, f64::INFINITY), 0.5),
(Vec2::ZERO, f64::NAN),
(Vec2::ZERO, 0.0),
(Vec2::ZERO, -1.0),
(Vec2::ZERO, f64::INFINITY),
] {
assert!(snap_candidates(d, &space, c, ap, all, None, false).is_empty(), "{c:?} {ap}");
assert!(snap_candidates(d, &space, c, ap, all, Some(Vec2::new(f64::NAN, 1.0)), true).is_empty(), "{c:?} {ap}");
}
// A huge but finite aperture still answers, from the objects there are.
let far = snap_candidates(d, &space, Vec2::ZERO, 1e300, mode::END, None, false);
assert!(far.iter().all(|h| h.point.is_finite()));
// Object snaps off (or only the OFF bit) offer nothing.
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, 0, None, false).is_empty());
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, mode::END | mode::OFF, None, false).is_empty());
}
#[test]
fn every_endpoint_under_the_aperture_is_offered_not_one_per_mode() {
let mut s = Session::new();
// Three line ends close together, all within the aperture of the cursor between them.
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
s.execute("line", &json!({ "points": [a, b] })).unwrap();
}
let d = s.doc().unwrap();
let cands = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false);
let ends: Vec<Vec2> = cands.iter().filter(|h| h.mode == mode::END).map(|h| h.point).collect();
assert_eq!(ends.len(), 3, "{cands:?}");
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
assert!(ends.iter().any(|p| p.near(want, 1e-12)), "{want:?} in {ends:?}");
}
// The first is the snap a click would take.
let first = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).first().map(|h| h.point);
assert_eq!(first, cadcraft_engine::snap::osnap(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).map(|h| h.point));
}
/// A base point that is not a number gives no candidates, though the cursor is on an endpoint: the
/// perpendicular and tangent points from it would be meaningless, as a viewport already treats it.
#[test]
fn a_non_finite_base_gives_no_candidates() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let d = s.doc().unwrap();
let all = mode::END | mode::PER | mode::TAN | mode::NEA;
for base in [Vec2::new(f64::NAN, 1.0), Vec2::new(1.0, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NAN)] {
assert!(snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), false).is_empty(), "{base:?}");
assert!(cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), true).is_empty(), "{base:?}");
}
// A finite base still offers them.
assert!(!snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(Vec2::new(5.0, 5.0)), false).is_empty());
}
+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;
+2 -4
View File
@@ -200,14 +200,12 @@ pub(super) fn override_cursor(app: &mut CadApp, raw: Vec2, xf: &Xf) {
let s = &app.session.settings;
let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 };
let Ok(st) = app.session.state() else { return };
let space = st.edit_space();
let frozen = st.viewport_frozen();
let hit = match cycle {
Some(i) => {
let cands = cadcraft_engine::pointmod::snap_candidates_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen);
let cands = cadcraft_engine::pointmod::snap_candidates(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred);
cands.get(i % cands.len().max(1)).copied()
}
None => snap::osnap_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen),
None => snap::osnap(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred),
};
let p = match (hit, app.canvas.snap) {
(Some(h), _) => {
+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
-1
View File
@@ -42,7 +42,6 @@ mod shared_controls;
mod shortcut_menus;
mod shortcuts_checked;
mod slow_clicks;
mod snap_tab_cycling;
mod space_at_options;
mod status_bar_toggles;
mod style_dialogs;
-136
View File
@@ -1,136 +0,0 @@
//! Tab at a point prompt steps through every object snap under the aperture (each endpoint of
//! each object nearby), not just the closest snap of each running mode, and comes back round.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
use cadcraft_engine::snap::mode;
use cadcraft_geom::Vec2;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
#[test]
fn tab_cycles_through_every_endpoint_under_the_aperture() {
let mut s = Session::new();
// Three line ends close together (within the aperture of the cursor between them).
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
s.execute("line", &json!({ "points": [a, b] })).unwrap();
}
s.execute("setvar", &json!({ "name": "OSMODE", "value": 1 })).unwrap();
s.execute("view.set", &json!({ "center": [0, 0], "height": 20 })).unwrap();
let mut app = CadApp::new(s, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h.state_mut().session.start("line").unwrap();
h.run_steps(2);
let xf = h.state().canvas.xf.unwrap();
let at = xf.to_screen(Vec2::new(0.03, 0.0));
h.event(Event::PointerMoved(at));
h.run_steps(2);
let mut seen: Vec<Vec2> = Vec::new();
for i in 0..4 {
let p = h.state().canvas.snap.map(|s| s.point).unwrap();
if i < 3 {
assert!(!seen.iter().any(|q| q.near(p, 1e-9)), "Tab {i} repeats {p:?} ({seen:?})");
} else {
assert!(seen.first().is_some_and(|q| q.near(p, 1e-9)), "the fourth Tab comes back round");
}
seen.push(p);
h.event(Event::Text("\t".into()));
h.run_steps(2);
}
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
assert!(seen.iter().any(|q| q.near(want, 1e-9)), "{want:?} in {seen:?}");
}
}
/// Three endpoints near 10,0: 10,0 (the nearest to the cursor), 10.03,0 and 9.95,0. Endpoint is
/// the only running snap, so every candidate is an endpoint.
fn three_ends() -> Harness<'static, CadApp> {
let mut d = Drawing::new_imperial();
for (a, b) in [((0.0, 0.0), (10.0, 0.0)), ((10.03, 0.0), (20.0, 0.0)), ((9.95, 0.0), (9.95, -5.0))] {
let line = Line { a: Vec2::new(a.0, a.1).to3(0.0), b: Vec2::new(b.0, b.1).to3(0.0) };
d.add(&Space::Model, Common::default(), EntityKind::Line(line)).unwrap();
}
let mut session = Session::empty();
session.open_drawing(d, "Tab snap cycling", None);
session.execute("view.set", &json!({"center":[10,0],"height":8})).unwrap();
session.settings.osmode = mode::END;
session.settings.snapmode = false;
session.settings.orthomode = false;
let mut app = CadApp::new(session, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
h.state_mut().start("line");
h.run_steps(2);
assert_eq!(h.state().session.running.as_ref().unwrap().id, "line");
let ap = h.state().session.settings.aperture / h.state().canvas.xf.unwrap().scale;
assert!(ap > 0.07, "all three endpoints lie in the aperture ({ap})");
h
}
const CURSOR: Vec2 = Vec2::new(10.01, 0.0);
fn hover(h: &mut Harness<'_, CadApp>, p: Vec2) -> Pos2 {
let pos = h.state().canvas.xf.unwrap().to_screen(p);
h.event(Event::PointerMoved(pos));
h.run_steps(3);
pos
}
/// Tab, as the command line receives it (`cmdline::capture_tab`).
fn tab(h: &mut Harness<'_, CadApp>) {
h.event(Event::Text("\t".into()));
h.run_steps(3);
}
fn snapped(h: &Harness<'_, CadApp>) -> Vec2 {
let hit = h.state().canvas.snap.expect("a snap marker");
assert_eq!(hit.mode, mode::END);
hit.point
}
fn assert_at(got: Vec2, x: f64) {
assert!(got.near(Vec2::new(x, 0.0), 1e-9), "{got:?}, expected {x},0");
}
#[test]
fn moving_the_cursor_away_starts_the_cycle_over() {
let mut h = three_ends();
hover(&mut h, CURSOR);
tab(&mut h);
assert_at(snapped(&h), 10.03);
hover(&mut h, Vec2::new(10.0, 2.0));
assert!(h.state().canvas.snap.is_none());
hover(&mut h, CURSOR);
assert_at(snapped(&h), 10.0);
}
#[test]
fn a_click_places_the_candidate_tab_chose() {
let mut h = three_ends();
let pos = hover(&mut h, CURSOR);
tab(&mut h);
assert_at(snapped(&h), 10.03);
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
let base = h.state().session.current_prompt().and_then(|p| p.base).expect("LINE asks for the next point");
assert_at(base, 10.03);
}