mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-03 11:18:30 -06:00
Merge remote-tracking branch 'origin/main' into yan-3580
This commit is contained in:
@@ -61,6 +61,8 @@ fn install_io() {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
//! An INSERT's ATTRIBs and SEQEND reached from AutoLISP through the CLI (`entnext`, `entget`,
|
||||
//! `entmod`, `entdel`): the walk, a value edit (one Undo step), names that stop holding (erase,
|
||||
//! ATTSYNC, Undo, a reinsert that reuses the parent handle), edits that are refused, and the
|
||||
//! name bounds.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A scratch directory, removed on drop also when an assertion fails.
|
||||
struct Dir(PathBuf);
|
||||
|
||||
impl Dir {
|
||||
fn new(tag: &str) -> Dir {
|
||||
let p = std::env::temp_dir().join(format!("cc-cli-attribs-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&p);
|
||||
std::fs::create_dir_all(&p).expect("create scratch dir");
|
||||
Dir(p)
|
||||
}
|
||||
|
||||
fn path(&self, name: &str) -> PathBuf {
|
||||
self.0.join(name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// One `cadcraft-cli run`: a fresh profile, an optional drawing to open, and the steps to run.
|
||||
struct Run {
|
||||
args: Vec<String>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn new(dir: &Dir, file: Option<&Path>) -> Run {
|
||||
let mut args: Vec<String> = vec!["run".into(), "--config-dir".into(), dir.path("profile").to_string_lossy().into_owned()];
|
||||
match file {
|
||||
Some(f) => args.push(f.to_string_lossy().into_owned()),
|
||||
None => args.push("--metric".into()),
|
||||
}
|
||||
Run { args }
|
||||
}
|
||||
|
||||
fn cmd(&mut self, id: &str, params: Value) -> &mut Run {
|
||||
self.args.push("--cmd".into());
|
||||
self.args.push(format!("{id} {params}"));
|
||||
self
|
||||
}
|
||||
|
||||
fn lisp(&mut self, code: &str) -> &mut Run {
|
||||
self.cmd("lisp", json!({ "code": code }))
|
||||
}
|
||||
|
||||
fn save(&mut self, path: &Path) -> &mut Run {
|
||||
self.args.push("--save".into());
|
||||
self.args.push(path.to_string_lossy().into_owned());
|
||||
self
|
||||
}
|
||||
|
||||
fn output(&self) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&self.args).output().expect("run cadcraft-cli")
|
||||
}
|
||||
|
||||
/// Run it: the value each `lisp` step returned, in order (commands' own results are left out).
|
||||
fn out(&self) -> Vec<Value> {
|
||||
let out = self.output();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{}: {}", self.args.join(" "), err);
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
text.lines()
|
||||
.map(|l| serde_json::from_str::<Value>(l).unwrap_or_else(|e| panic!("not a result: {l}: {e}")))
|
||||
.filter(|v| v.get("value").is_some())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The value a `lisp` step returned, as AutoLISP's `prin1` shows it.
|
||||
fn value(results: &[Value], i: usize) -> String {
|
||||
match results.get(i).and_then(|r| r.get("value")) {
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
other => panic!("step {i}: no value: {other:?} in {results:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` without the quotes `prin1` puts round a string.
|
||||
fn text(results: &[Value], i: usize) -> String {
|
||||
value(results, i).trim_matches('"').to_string()
|
||||
}
|
||||
|
||||
/// TAGBLK.dxf: block TAGBLK with a circle and four attribute definitions (TAG1 D1, TAG2 D2
|
||||
/// verify, TAG3 P3 preset, TAG4 C4 constant). Opening the file again gives the drawing fresh
|
||||
/// names.
|
||||
const FIXTURE: &str = r#"(progn
|
||||
(entmake '((0 . "BLOCK") (2 . "TAGBLK") (70 . 2) (10 0.0 0.0 0.0)))
|
||||
(entmake '((0 . "CIRCLE") (10 -5.0 0.0 0.0) (40 . 2.0)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 0.0 0.0) (40 . 2.5) (1 . "D1") (3 . "P1") (2 . "TAG1") (70 . 0)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 5.0 0.0) (40 . 2.5) (1 . "D2") (3 . "P2") (2 . "TAG2") (70 . 4)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 10.0 0.0) (40 . 2.5) (1 . "P3") (3 . "P3") (2 . "TAG3") (70 . 8)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 15.0 0.0) (40 . 2.5) (1 . "C4") (3 . "P4") (2 . "TAG4") (70 . 2)))
|
||||
(entmake '((0 . "ENDBLK"))))"#;
|
||||
|
||||
/// The first reference: INSERT TAGBLK at (10,10) with TAG1 "A1", TAG2 verified as "B1" and
|
||||
/// TAG3 preset ("P3"); TAG4 is constant, so it is not asked.
|
||||
const INSERT: &str = r#"(command "_.-INSERT" "TAGBLK" '(10 10) 1 1 0 "A1" "B1" "")"#;
|
||||
|
||||
fn fixture(dir: &Dir) -> PathBuf {
|
||||
let file = dir.path("TAGBLK.dxf");
|
||||
let mut run = Run::new(dir, None);
|
||||
let out = run.lisp(FIXTURE).save(&file).out();
|
||||
assert_eq!(text(&out, 0), "TAGBLK");
|
||||
file
|
||||
}
|
||||
|
||||
/// The walk from the entity named `i`: its records' tags and values, then the type of the record
|
||||
/// that ends the run.
|
||||
const WALK: &str = r#"(progn
|
||||
(setq e (entnext i) n 0 ts nil ed nil)
|
||||
(while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e))))))
|
||||
(setq ts (append ts (list (cdr (assoc 2 ed)) (cdr (assoc 1 ed)))) n (1+ n) e (entnext e)))
|
||||
(list n ts (cdr (assoc 0 ed))))"#;
|
||||
|
||||
#[test]
|
||||
fn the_walk_reaches_each_attrib_and_ends_at_the_seqend() {
|
||||
let dir = Dir::new("walk");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(
|
||||
r#"(progn
|
||||
{INSERT}
|
||||
(setq i (entlast))
|
||||
(setvar "ATTREQ" 0)
|
||||
(command "_.-INSERT" "TAGBLK" '(60 10) 1 1 0)
|
||||
(setvar "ATTREQ" 1)
|
||||
(setq second (entlast))
|
||||
"inserted")"#
|
||||
))
|
||||
// Three attributes, then the SEQEND owned by the reference, then the next main entity.
|
||||
.lisp(&format!(
|
||||
r#"(progn {WALK}
|
||||
(list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (equal (entnext e) second) (cdr (assoc 0 (entget (entnext e))))))"#
|
||||
))
|
||||
// The second reference (no attribute answers, ATTREQ 0) took the definitions' values; its
|
||||
// own run ends at its SEQEND, with nothing drawn after it.
|
||||
.lisp(&format!(
|
||||
r#"(progn (setq i second) {WALK}
|
||||
(list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (entnext e)))"#
|
||||
))
|
||||
.out();
|
||||
assert_eq!(text(&out, 0), "inserted");
|
||||
assert_eq!(value(&out, 1), "(3 (\"TAG1\" \"A1\" \"TAG2\" \"B1\" \"TAG3\" \"P3\") \"SEQEND\" T T \"INSERT\")");
|
||||
// Its record ends with its own SEQEND, and nothing is drawn after the reference.
|
||||
assert_eq!(value(&out, 2), "(3 (\"TAG1\" \"D1\" \"TAG2\" \"D2\" \"TAG3\" \"P3\") \"SEQEND\" T nil)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_edit_changes_group_one_only_and_is_one_undo_step() {
|
||||
let dir = Dir::new("value");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 2 (entget a))) (cdr (assoc 1 (entget a)))))"#))
|
||||
.lisp(
|
||||
r#"(progn
|
||||
(setq d (entget a) r (entmod (subst (cons 1 "A2") (assoc 1 d) d)))
|
||||
(list (cdr (assoc 0 r)) (cdr (assoc 1 r)) (cdr (assoc 1 (entget a))) (cdr (assoc 2 (entget a)))
|
||||
(cdr (assoc 40 (entget a))) (cdr (assoc 8 (entget a))) (equal (cdr (assoc -2 (entget a))) i)))"#,
|
||||
)
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
// The edit is one Undo step: the value is back, and the name given before it holds no
|
||||
// longer (the drawing it was given in was restored from another state).
|
||||
.lisp(
|
||||
r#"(list (entget a) (progn (setq e (entnext (entlast)))
|
||||
(list (cdr (assoc 2 (entget e))) (cdr (assoc 1 (entget e))))))"#,
|
||||
)
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(\"TAG1\" \"A1\")");
|
||||
assert_eq!(value(&out, 1), "(\"ATTRIB\" \"A2\" \"A2\" \"TAG1\" 2.5 \"0\" T)");
|
||||
assert_eq!(value(&out, 2), "(nil (\"TAG1\" \"A1\"))");
|
||||
// Redo brings the edit back; the name given before the Undo still names nothing.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i) d (entget a)) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#))
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
.cmd("redo", json!({ "count": 1 }))
|
||||
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(value(&out, 1), "(nil \"A2\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_stops_holding_after_erase_attsync_and_undo() {
|
||||
let dir = Dir::new("stale");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run.lisp(&format!(r#"(progn {INSERT} (setq i (entlast)) (cdr (assoc 5 (entget i))))"#)).out();
|
||||
let handle = text(&out, 0);
|
||||
|
||||
// Erased: the reference's records are gone with it, and the name names nothing.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (cdr (assoc 2 (entget a))))"#))
|
||||
.cmd("erase", json!({ "handles": [handle] }))
|
||||
.lisp("(list (entget a) (entnext a))")
|
||||
// Undone: the reference is back, but a name given before the Undo does not come back with
|
||||
// it: a walk gives its records new ones.
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
// ATTSYNC rebuilds the reference's attributes: the name given before names nothing, and
|
||||
// the rebuilt attribute keeps the value.
|
||||
.lisp("(progn (setq b (entnext (entlast))) (cdr (assoc 2 (entget b))))")
|
||||
.cmd("attsync", json!({ "name": "TAGBLK" }))
|
||||
.lisp("(list (entget b) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "\"TAG1\"");
|
||||
assert_eq!(value(&out, 1), "(nil nil)");
|
||||
assert_eq!(value(&out, 2), "(nil \"A1\")");
|
||||
assert_eq!(value(&out, 3), "\"TAG1\"");
|
||||
assert_eq!(value(&out, 4), "(nil \"A1\")");
|
||||
|
||||
// A reinsert after an Undo takes the parent handle back: the old name must not name its
|
||||
// attribute.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 5 (entget i))) (cdr (assoc 2 (entget a)))))"#))
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
.lisp(&format!(r#"(progn {INSERT} (list (cdr (assoc 5 (entget (entlast)))) (entget a)))"#))
|
||||
.lisp("(list (cdr (assoc 2 (entget (entnext (entlast))))) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(text(&out, 0), format!("(\"{handle}\" \"TAG1\")"));
|
||||
// The same handle, and the old name names nothing in the new reference.
|
||||
assert_eq!(value(&out, 1), format!("(\"{handle}\" nil)"));
|
||||
assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_of_anything_but_the_value_is_refused() {
|
||||
let dir = Dir::new("refused");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(
|
||||
r#"(progn {INSERT} (setq i (entlast) a (entnext i) s (entnext (entnext (entnext a))) p0 (cdr (assoc 10 (entget a)))) "named")"#
|
||||
))
|
||||
.lisp(
|
||||
r#"(progn
|
||||
(setq d (entget a))
|
||||
(list
|
||||
(entmod (subst (cons 2 "TAGX") (assoc 2 d) d))
|
||||
(entmod (subst (cons 40 9.0) (assoc 40 d) d))
|
||||
(entmod (subst (cons 0 "SEQEND") (assoc 0 d) d))
|
||||
(entmod (entget s))
|
||||
(entmod (subst (cons 410 "Layout2") (assoc 410 d) d))
|
||||
(entmod (subst (cons 1 "A2") (assoc 1 d) (subst (cons 410 "Layout2") (assoc 410 d) d)))
|
||||
(entdel a) (entdel s)))"#,
|
||||
)
|
||||
// Nothing changed: the same tag, value, height and place, and the name still holds.
|
||||
.lisp(
|
||||
r#"(progn (setq e (entnext (entlast)) d (entget e))
|
||||
(list (cdr (assoc 2 d)) (cdr (assoc 1 d)) (cdr (assoc 40 d)) (equal p0 (cdr (assoc 10 d))) (equal (entget a) d)))"#,
|
||||
)
|
||||
.out();
|
||||
assert_eq!(text(&out, 0), "named");
|
||||
assert_eq!(value(&out, 1), "(nil nil nil nil nil nil nil nil)");
|
||||
assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\" 2.5 T T)");
|
||||
}
|
||||
|
||||
/// A minimal drawing: `before` (records written as they are), then an INSERT with `attribs`
|
||||
/// ATTRIBs (each tag T, value V) and its SEQEND, last in the file. A header `$HANDSEED` is
|
||||
/// written when `handseed` is given (a hostile file can name any next handle).
|
||||
fn insert_dxf_seed(attribs: usize, before: &str, handseed: Option<&str>) -> String {
|
||||
let mut s = String::with_capacity(before.len().saturating_add(attribs.saturating_mul(96)));
|
||||
if let Some(seed) = handseed {
|
||||
s.push_str("0\nSECTION\n2\nHEADER\n9\n$HANDSEED\n5\n");
|
||||
s.push_str(seed);
|
||||
s.push('\n');
|
||||
s.push_str("0\nENDSEC\n");
|
||||
}
|
||||
s.push_str("0\nSECTION\n2\nENTITIES\n");
|
||||
s.push_str(before);
|
||||
s.push_str("0\nINSERT\n5\n20\n8\n0\n66\n1\n2\nTAGBLK\n10\n0\n20\n0\n30\n0\n");
|
||||
for _ in 0..attribs {
|
||||
s.push_str("0\nATTRIB\n5\n21\n8\n0\n10\n0\n20\n0\n30\n0\n40\n1\n1\nV\n2\nT\n70\n0\n");
|
||||
}
|
||||
s.push_str("0\nSEQEND\n5\n22\n0\nENDSEC\n0\nEOF\n");
|
||||
s
|
||||
}
|
||||
|
||||
fn insert_dxf(attribs: usize, before: &str) -> String {
|
||||
insert_dxf_seed(attribs, before, None)
|
||||
}
|
||||
|
||||
/// The number of records a walk from `i` reaches, counting each `entnext`.
|
||||
const COUNT: &str = r#"(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)"#;
|
||||
|
||||
#[test]
|
||||
fn a_walk_is_stable_and_its_names_are_no_handles() {
|
||||
let dir = Dir::new("stable");
|
||||
// A file's line one below the top of the handle range: it keeps its handle, and the
|
||||
// records' names, which are no handles, never name it.
|
||||
let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n";
|
||||
let file = dir.path("hostile.dxf");
|
||||
std::fs::write(&file, insert_dxf(2, before)).expect("write the DXF");
|
||||
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(
|
||||
r#"(progn
|
||||
(setq i (handent "20") line (handent "FFFFFFFFFFFFFFFE") a (entnext i) b (entnext i))
|
||||
(list (cdr (assoc 5 (entget line))) (equal (handent "FFFFFFFFFFFFFFFE") line)
|
||||
(not (equal a line)) (cdr (assoc 0 (entget a))) (equal a b) (equal (entnext a) (entnext b))))"#,
|
||||
)
|
||||
.lisp(&format!(r#"(progn (setq i (handent "20")) {COUNT})"#))
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(\"FFFFFFFFFFFFFFFE\" T T \"ATTRIB\" T T)");
|
||||
// Two ATTRIBs and the SEQEND, then the line (it sorts last by its handle), then the end.
|
||||
assert_eq!(value(&out, 1), "4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_reference_does_not_revive_an_old_name() {
|
||||
let dir = Dir::new("restored");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(
|
||||
r#"(progn {INSERT} (setq i (entlast) a (entnext i))
|
||||
(entdel i)
|
||||
(setq gone (entget a))
|
||||
(entdel i)
|
||||
(list gone (entget a) (cdr (assoc 1 (entget (entnext i))))))"#
|
||||
))
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(nil nil \"A1\")", "the reference comes back, the old name does not");
|
||||
|
||||
// ERASE, then OOPS: the same. The old name never comes back with the reference.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let handle = text(&run.lisp(&format!(r#"(progn {INSERT} (cdr (assoc 5 (entget (entlast)))))"#)).out(), 0);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq a (entnext (entlast))) "named")"#))
|
||||
.cmd("erase", json!({ "handles": [handle] }))
|
||||
.cmd("oops", json!({}))
|
||||
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(value(&out, 1), "(nil \"A1\")", "OOPS restores the reference, not the old name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_line_is_never_a_record() {
|
||||
let dir = Dir::new("handseed");
|
||||
let file = dir.path("hostile.dxf");
|
||||
// A file's $HANDSEED in the reserved band is the file's own handle and is not followed (#913),
|
||||
// so the line made after the walk gets the drawing's seed. The record's name is no handle:
|
||||
// the line is the line, and the name still names the attribute. The engine's
|
||||
// `a_new_object_at_any_handle_is_never_a_record` puts the seed at the top of the range.
|
||||
std::fs::write(&file, insert_dxf_seed(1, "", Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF");
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(r#"(progn (setq i (handent "20") a (entnext i)) (list (cdr (assoc 0 (entget a))) (cdr (assoc 5 (entget (entlast))))))"#)
|
||||
.lisp(r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#)
|
||||
.lisp(r#"(list (cdr (assoc 0 (entget a))) (entdel a))"#)
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(\"ATTRIB\" \"20\")");
|
||||
assert_eq!(value(&out, 1), "\"100\"");
|
||||
assert_eq!(value(&out, 2), "(\"ATTRIB\" nil)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_at_the_top_of_the_handle_range_walk_as_lines() {
|
||||
let dir = Dir::new("walkrange");
|
||||
let file = dir.path("hostile.dxf");
|
||||
let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n\
|
||||
0\nLINE\n5\nFFFFFFFFFFFFFFFF\n8\n0\n10\n0\n20\n0\n30\n0\n11\n6\n21\n6\n31\n0\n";
|
||||
std::fs::write(&file, insert_dxf_seed(1, before, Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF");
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(r#"(progn (setq i (handent "20")) (entnext i))"#)
|
||||
// The line at the top of the range is in the drawing. Without it, the walk from the line
|
||||
// below would end in nil, and nil equals the nil `handent` gives for a handle not there.
|
||||
.lisp(r#"(progn (setq top (handent "FFFFFFFFFFFFFFFF")) (list (cdr (assoc 0 (entget top))) (cdr (assoc 5 (entget top)))))"#)
|
||||
.lisp(r#"(equal (entnext (handent "FFFFFFFFFFFFFFFE")) top)"#)
|
||||
.lisp("(entnext top)")
|
||||
.out();
|
||||
assert_eq!(value(&out, 1), "(\"LINE\" \"FFFFFFFFFFFFFFFF\")");
|
||||
assert_eq!(value(&out, 2), "T");
|
||||
assert_eq!(value(&out, 3), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_session_names_at_most_65536_records() {
|
||||
let dir = Dir::new("names");
|
||||
let file = dir.path("many.dxf");
|
||||
// One more attribute than the limit of names: the walk stops at the limit, and nothing in the
|
||||
// drawing changed.
|
||||
std::fs::write(&file, insert_dxf(65_537, "")).expect("write the DXF");
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run.lisp(&format!("(progn (setq i (entlast)) {COUNT})")).lisp(&format!("(progn (setq i (entlast)) {COUNT})")).out();
|
||||
assert_eq!(value(&out, 0), "65536");
|
||||
// The names given by the first walk hold: the second walk is the same.
|
||||
assert_eq!(value(&out, 1), "65536");
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
mod block_resources;
|
||||
mod cli;
|
||||
mod dash_limit_note;
|
||||
mod drafting_spacing;
|
||||
|
||||
@@ -136,6 +136,8 @@ mod web {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
|
||||
@@ -199,6 +199,8 @@ pub fn install_io() {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
|
||||
@@ -46,15 +46,21 @@ mod layout;
|
||||
mod proxy;
|
||||
mod text;
|
||||
mod wipeout;
|
||||
mod xdata;
|
||||
|
||||
pub use xdata::{
|
||||
MAX_XDATA_APP_NAME, MAX_XDATA_CHUNK, MAX_XDATA_GROUPS, MAX_XDATA_STRING, RESERVED_XDATA_APPS, XdataError, check_xdata_app_name,
|
||||
check_xdata_groups, is_model_xdata_app, is_reserved_xdata_app, is_xdata_group, set_xdata_app, xdata_apps, xdata_of,
|
||||
};
|
||||
|
||||
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
|
||||
pub use common::{Common, Handle, Lineweight, RawTag, Transparency};
|
||||
pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid};
|
||||
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
|
||||
pub use fill::{Gradient, Hatch, HatchLoop};
|
||||
pub use layout::{Image, Table, TableCell, Viewport};
|
||||
pub use layout::{Image, Table, TableCell, Viewport, ViewportUcs};
|
||||
pub use proxy::{ProxyTables, TableOrder, proxy_entities};
|
||||
pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign};
|
||||
pub use text::{HAlign, MText, MTextBackground, MTextColumnType, MTextColumns, Text, VAlign};
|
||||
pub use wipeout::Wipeout;
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Unknown {
|
||||
|
||||
@@ -154,7 +154,43 @@ impl AttribProps {
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TagKey<'a>(pub &'a str);
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static TAG_CROSS_PROBE: std::cell::Cell<Option<(usize, [usize; 2])>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn record_tag_cross_probe(left: &str, right: &str) {
|
||||
TAG_CROSS_PROBE.with(|probe| {
|
||||
let Some((position, mut counts)) = probe.get() else { return };
|
||||
match (left.as_bytes().get(position), right.as_bytes().get(position)) {
|
||||
(Some(b'A'), Some(b'D')) => counts[0] += 1,
|
||||
(Some(b'D'), Some(b'A')) => counts[1] += 1,
|
||||
_ => return,
|
||||
}
|
||||
probe.set(Some((position, counts)));
|
||||
});
|
||||
}
|
||||
|
||||
impl TagKey<'_> {
|
||||
/// Count comparisons in both directions between the A and D fixture tag sets.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_cross_probes<T>(position: usize, f: impl FnOnce() -> T) -> (T, [usize; 2]) {
|
||||
struct Restore(Option<(usize, [usize; 2])>);
|
||||
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
TAG_CROSS_PROBE.with(|probe| probe.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
TAG_CROSS_PROBE.with(|probe| {
|
||||
let _restore = Restore(probe.replace(Some((position, [0; 2]))));
|
||||
let value = f();
|
||||
(value, probe.get().map_or([0; 2], |(_, counts)| counts))
|
||||
})
|
||||
}
|
||||
|
||||
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
|
||||
/// finds equal.
|
||||
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
|
||||
@@ -164,6 +200,8 @@ impl TagKey<'_> {
|
||||
|
||||
impl PartialEq for TagKey<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
record_tag_cross_probe(self.0, other.0);
|
||||
self.0.eq_ignore_ascii_case(other.0)
|
||||
}
|
||||
}
|
||||
@@ -172,6 +210,8 @@ impl Eq for TagKey<'_> {}
|
||||
|
||||
impl Ord for TagKey<'_> {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
#[cfg(test)]
|
||||
record_tag_cross_probe(self.0, other.0);
|
||||
self.folded().cmp(other.folded())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use cadcraft_geom::Mat3;
|
||||
|
||||
use super::common::Handle;
|
||||
use super::common::{Handle, RawTag};
|
||||
use super::{Color, Deserialize, Serialize, Vec2, Vec3, standard, yes};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -27,6 +27,19 @@ pub struct Viewport {
|
||||
/// Display on (MVIEW ON/OFF). An off viewport shows its border but no model space.
|
||||
#[serde(default = "yes")]
|
||||
pub on: bool,
|
||||
/// The viewport's own UCS (DXF groups 110–112, 79, 146, 345, 346), the one it keeps while
|
||||
/// `ucs_per_viewport` is set.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub ucs: Option<ViewportUcs>,
|
||||
/// UCS per viewport (UCSVP, DXF group 71): the viewport keeps its own UCS instead of
|
||||
/// following the current one.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub ucs_per_viewport: bool,
|
||||
/// The viewport's groups CADCraft doesn't model (snap, grid, lens and clipping, render mode,
|
||||
/// plot style sheet, shade plot, visual style, background, lighting…), as read: written back
|
||||
/// on save and carried by copies, their references pointed at what they named.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub extra: Vec<RawTag>,
|
||||
/// The view twist (DVIEW TWist inside the viewport; DXF group 51): radians counterclockwise,
|
||||
/// the model view seen through the viewport is turned on the sheet by it. 0 is untwisted.
|
||||
#[serde(default, skip_serializing_if = "is_zero_twist")]
|
||||
@@ -62,6 +75,27 @@ impl Viewport {
|
||||
}
|
||||
}
|
||||
|
||||
/// A layout viewport's own UCS.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ViewportUcs {
|
||||
pub origin: Vec3,
|
||||
pub x_axis: Vec3,
|
||||
pub y_axis: Vec3,
|
||||
/// Elevation (DXF group 146).
|
||||
#[serde(default)]
|
||||
pub elevation: f64,
|
||||
/// Orthographic type (DXF group 79): 0 none, 1 top, 2 bottom, 3 front, 4 back, 5 left, 6 right.
|
||||
#[serde(default)]
|
||||
pub ortho: u8,
|
||||
/// The named UCS it is, by UCS table name (DXF group 345).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub named: Option<String>,
|
||||
/// The UCS an orthographic one is based on, by UCS table name (DXF group 346); none: the WCS.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Viewport {
|
||||
fn default() -> Self {
|
||||
Viewport {
|
||||
@@ -76,6 +110,9 @@ impl Default for Viewport {
|
||||
layer_colors: Vec::new(),
|
||||
clip: None,
|
||||
on: true,
|
||||
ucs: None,
|
||||
ucs_per_viewport: false,
|
||||
extra: Vec::new(),
|
||||
twist: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +90,27 @@ pub struct MText {
|
||||
/// one column.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub columns: Option<MTextColumns>,
|
||||
/// Background mask (DXF 90/63/421/45); `None` when off.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub background: Option<MTextBackground>,
|
||||
}
|
||||
|
||||
/// MTEXT background mask (DXF 90, 63/421, 45).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MTextBackground {
|
||||
/// DXF group 90 bitmask: bit 1 = fill colour set, bit 2 = use drawing background colour.
|
||||
pub mask: u8,
|
||||
/// DXF group 63 (ACI) or 421 (true colour); `None` when using drawing background.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<super::Color>,
|
||||
/// DXF group 45 border offset factor (default 1.5, valid 1.0..=5.0).
|
||||
#[serde(default = "default_bg_scale")]
|
||||
pub scale: f64,
|
||||
}
|
||||
|
||||
fn default_bg_scale() -> f64 {
|
||||
1.5
|
||||
}
|
||||
|
||||
fn attach_tl() -> u8 {
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
//! Extended entity data (xdata): the groups 1000–1071 other applications attach to an entity,
|
||||
//! kept raw in [`Common::xdata`](super::Common::xdata) as whole applications, each from its
|
||||
//! `1001` group on. This module reads them per application, replaces or removes one
|
||||
//! application's data, and checks data that comes from outside (a command's parameters, a LISP
|
||||
//! list) before it goes onto an entity: input is hostile, so codes, values, brace nesting and
|
||||
//! sizes are all checked and nothing here panics.
|
||||
|
||||
use super::RawTag;
|
||||
|
||||
/// Most xdata groups one object may carry (AutoCAD allows 16 KB of xdata per object).
|
||||
pub const MAX_XDATA_GROUPS: usize = 16_384;
|
||||
/// Longest application name, in bytes.
|
||||
pub const MAX_XDATA_APP_NAME: usize = 255;
|
||||
/// Longest string value (groups 1000 and 1003), in bytes: what one DXF group holds.
|
||||
pub const MAX_XDATA_STRING: usize = 255;
|
||||
/// Longest binary chunk (group 1004), in bytes.
|
||||
pub const MAX_XDATA_CHUNK: usize = 127;
|
||||
|
||||
/// Applications whose xdata CADCraft writes itself, from its own model, when a drawing is saved.
|
||||
/// It is never kept as an entity's raw xdata (the reader models it) and can't be set as such:
|
||||
/// a copy written beside the generated data would contradict it.
|
||||
pub const RESERVED_XDATA_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"];
|
||||
|
||||
/// Whether `name` (any case) is one of [`RESERVED_XDATA_APPS`].
|
||||
pub fn is_reserved_xdata_app(name: &str) -> bool {
|
||||
let up = name.trim().to_ascii_uppercase();
|
||||
RESERVED_XDATA_APPS.contains(&up.as_str())
|
||||
}
|
||||
|
||||
/// Whether application `name`'s xdata on an entity of `kind` is written from the model rather
|
||||
/// than kept raw: the [`RESERVED_XDATA_APPS`] on any entity, and `ACAD` on a dimension, whose
|
||||
/// `ACAD` run (`DSTYLE`) holds its dimension-style overrides. The reader models those too, so
|
||||
/// raw groups set under such a name would be dropped on save; they are refused instead.
|
||||
pub fn is_model_xdata_app(name: &str, kind: &super::EntityKind) -> bool {
|
||||
is_reserved_xdata_app(name) || (name.trim().eq_ignore_ascii_case("ACAD") && matches!(kind, super::EntityKind::Dimension(_)))
|
||||
}
|
||||
|
||||
/// Why an application name or a run of xdata groups was refused.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct XdataError(pub String);
|
||||
|
||||
impl std::fmt::Display for XdataError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for XdataError {}
|
||||
|
||||
fn err<T>(msg: impl Into<String>) -> Result<T, XdataError> {
|
||||
Err(XdataError(msg.into()))
|
||||
}
|
||||
|
||||
/// Check an application name: not empty, at most [`MAX_XDATA_APP_NAME`] bytes, no control
|
||||
/// characters and none of the characters a symbol table name can't hold.
|
||||
pub fn check_xdata_app_name(name: &str) -> Result<(), XdataError> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return err("an xdata application name must not be empty");
|
||||
}
|
||||
if name.len() > MAX_XDATA_APP_NAME {
|
||||
return err(format!("an xdata application name may have at most {MAX_XDATA_APP_NAME} bytes"));
|
||||
}
|
||||
if name.chars().any(|c| c.is_control() || "<>/\\\":;?*|,=`".contains(c)) {
|
||||
return err(format!("`{name}` is not a valid xdata application name (no control characters or <>/\\\":;?*|,=`)"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `code` is an xdata group code an application's data may hold (`1001`, the
|
||||
/// application name, is not one of them: it starts an application).
|
||||
pub fn is_xdata_group(code: i32) -> bool {
|
||||
matches!(code, 1000 | 1002..=1005 | 1010..=1013 | 1020..=1023 | 1030..=1033 | 1040..=1042 | 1070 | 1071)
|
||||
}
|
||||
|
||||
/// Check the groups of one application (after its `1001`): every code an xdata code with a
|
||||
/// value of its kind, control strings `{` and `}` balanced, points complete (a `101x` group
|
||||
/// followed by its `102x` and `103x`), at most [`MAX_XDATA_GROUPS`] groups.
|
||||
pub fn check_xdata_groups(groups: &[RawTag]) -> Result<(), XdataError> {
|
||||
if groups.len() > MAX_XDATA_GROUPS {
|
||||
return err(format!("at most {MAX_XDATA_GROUPS} xdata groups per application"));
|
||||
}
|
||||
let mut depth: u32 = 0;
|
||||
let mut i = 0;
|
||||
while let Some(t) = groups.get(i) {
|
||||
let v = t.value.trim();
|
||||
match t.code {
|
||||
1000 | 1003 => {
|
||||
if t.value.len() > MAX_XDATA_STRING {
|
||||
return err(format!("group {}: a string may have at most {MAX_XDATA_STRING} bytes", t.code));
|
||||
}
|
||||
if t.value.chars().any(|c| c == '\n' || c == '\r') {
|
||||
return err(format!("group {}: a string may not hold a line break", t.code));
|
||||
}
|
||||
}
|
||||
1002 => match v {
|
||||
"{" => depth = depth.saturating_add(1),
|
||||
"}" => match depth.checked_sub(1) {
|
||||
Some(d) => depth = d,
|
||||
None => return err("group 1002: a `}` without its `{`"),
|
||||
},
|
||||
_ => return err("group 1002 must be `{` or `}`"),
|
||||
},
|
||||
1004 => {
|
||||
if v.len() > MAX_XDATA_CHUNK * 2 || v.len() % 2 != 0 || !v.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return err(format!("group 1004 must be hex text of an even length, at most {MAX_XDATA_CHUNK} bytes"));
|
||||
}
|
||||
}
|
||||
1005 => {
|
||||
if v.is_empty() || v.len() > 16 || !v.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return err("group 1005 must be a hex handle");
|
||||
}
|
||||
}
|
||||
1010..=1013 => {
|
||||
let (y, z) = (groups.get(i + 1), groups.get(i + 2));
|
||||
let complete = y.is_some_and(|y| y.code == t.code + 10) && z.is_some_and(|z| z.code == t.code + 20);
|
||||
if !complete {
|
||||
return err(format!("group {}: a point needs its {} and {} groups", t.code, t.code + 10, t.code + 20));
|
||||
}
|
||||
for p in [Some(t), y, z].into_iter().flatten() {
|
||||
real(p)?;
|
||||
}
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
1020..=1023 | 1030..=1033 => return err(format!("group {} may only follow its {} group", t.code, t.code - (t.code - 1010) / 10 * 10)),
|
||||
1040..=1042 => {
|
||||
real(t)?;
|
||||
}
|
||||
1070 => {
|
||||
let ok = v.parse::<i64>().is_ok_and(|n| i16::try_from(n).is_ok());
|
||||
if !ok {
|
||||
return err("group 1070 must be a 16-bit integer");
|
||||
}
|
||||
}
|
||||
1071 => {
|
||||
let ok = v.parse::<i64>().is_ok_and(|n| i32::try_from(n).is_ok());
|
||||
if !ok {
|
||||
return err("group 1071 must be a 32-bit integer");
|
||||
}
|
||||
}
|
||||
1001 => return err("group 1001 (an application name) can't be inside an application's data"),
|
||||
c => return err(format!("group {c} is not an xdata group code (1000–1071)")),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if depth != 0 {
|
||||
return err("group 1002: a `{` without its `}`");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn real(t: &RawTag) -> Result<f64, XdataError> {
|
||||
match t.value.trim().parse::<f64>() {
|
||||
Ok(v) if v.is_finite() => Ok(v),
|
||||
_ => err(format!("group {} must be a finite number", t.code)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The applications of an xdata run, in order: each name as written and its groups after the
|
||||
/// `1001`. Groups before the first `1001` belong to nobody and are left out.
|
||||
pub fn xdata_apps(xdata: &[RawTag]) -> Vec<(&str, &[RawTag])> {
|
||||
let mut out = Vec::new();
|
||||
let mut start: Option<(usize, &str)> = None;
|
||||
for (i, t) in xdata.iter().enumerate() {
|
||||
if t.code != 1001 {
|
||||
continue;
|
||||
}
|
||||
if let Some((s, name)) = start.take() {
|
||||
out.push((name, xdata.get(s + 1..i).unwrap_or(&[])));
|
||||
}
|
||||
start = Some((i, t.value.trim()));
|
||||
}
|
||||
if let Some((s, name)) = start {
|
||||
out.push((name, xdata.get(s + 1..).unwrap_or(&[])));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The groups of application `app` (any case): those of its first run.
|
||||
pub fn xdata_of<'a>(xdata: &'a [RawTag], app: &str) -> Option<&'a [RawTag]> {
|
||||
xdata_apps(xdata).into_iter().find(|(name, _)| name.eq_ignore_ascii_case(app.trim())).map(|(_, g)| g)
|
||||
}
|
||||
|
||||
/// Replace the xdata of application `app` (any case) with `groups`, or remove it (`None`, or no
|
||||
/// groups). Every run of that application goes; new data is appended after the other
|
||||
/// applications' data, with its `1001` group. The groups are taken as given: check them with
|
||||
/// [`check_xdata_groups`] first when they come from outside.
|
||||
pub fn set_xdata_app(xdata: &mut Vec<RawTag>, app: &str, groups: Option<&[RawTag]>) {
|
||||
let app = app.trim();
|
||||
let mut kept: Vec<RawTag> = Vec::with_capacity(xdata.len());
|
||||
let mut skipping = false;
|
||||
for t in xdata.drain(..) {
|
||||
if t.code == 1001 {
|
||||
skipping = t.value.trim().eq_ignore_ascii_case(app);
|
||||
}
|
||||
if !skipping {
|
||||
kept.push(t);
|
||||
}
|
||||
}
|
||||
if let Some(groups) = groups.filter(|g| !g.is_empty()) {
|
||||
kept.push(RawTag { code: 1001, value: app.to_string() });
|
||||
kept.extend(groups.iter().cloned());
|
||||
}
|
||||
*xdata = kept;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn t(code: i32, value: &str) -> RawTag {
|
||||
RawTag { code, value: value.into() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apps_are_split_at_their_names() {
|
||||
let x = vec![t(1001, "A"), t(1000, "one"), t(1070, "1"), t(1001, "b"), t(1000, "two")];
|
||||
let apps = xdata_apps(&x);
|
||||
assert_eq!(apps.len(), 2);
|
||||
assert_eq!(apps[0].0, "A");
|
||||
assert_eq!(apps[0].1.len(), 2);
|
||||
assert_eq!(apps[1], ("b", &x[4..]));
|
||||
assert_eq!(xdata_of(&x, "B"), Some(&x[4..]));
|
||||
assert_eq!(xdata_of(&x, "c"), None);
|
||||
assert!(xdata_apps(&[t(1000, "stray")]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_replaces_removes_and_appends() {
|
||||
let mut x = vec![t(1001, "A"), t(1000, "one"), t(1001, "B"), t(1000, "two"), t(1001, "a"), t(1000, "dup")];
|
||||
set_xdata_app(&mut x, "a", Some(&[t(1070, "7")]));
|
||||
assert_eq!(x, vec![t(1001, "B"), t(1000, "two"), t(1001, "a"), t(1070, "7")]);
|
||||
set_xdata_app(&mut x, "B", None);
|
||||
assert_eq!(x, vec![t(1001, "a"), t(1070, "7")]);
|
||||
set_xdata_app(&mut x, "C", Some(&[]));
|
||||
assert_eq!(x.len(), 2);
|
||||
set_xdata_app(&mut x, "A", None);
|
||||
assert!(x.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checks_accept_every_kind_and_refuse_bad_data() {
|
||||
let good = vec![
|
||||
t(1000, "text"),
|
||||
t(1002, "{"),
|
||||
t(1003, "Layer"),
|
||||
t(1004, "DEADBEEF"),
|
||||
t(1005, "1A2"),
|
||||
t(1010, "1.5"),
|
||||
t(1020, "2"),
|
||||
t(1030, "0"),
|
||||
t(1040, "2.5"),
|
||||
t(1041, "1e3"),
|
||||
t(1042, "-1"),
|
||||
t(1070, "32767"),
|
||||
t(1071, "2147483647"),
|
||||
t(1002, "}"),
|
||||
];
|
||||
assert_eq!(check_xdata_groups(&good), Ok(()));
|
||||
for bad in [
|
||||
vec![t(1002, "}")],
|
||||
vec![t(1002, "{")],
|
||||
vec![t(1002, "x")],
|
||||
vec![t(1001, "APP")],
|
||||
vec![t(999, "comment")],
|
||||
vec![t(8, "layer")],
|
||||
vec![t(1010, "1"), t(1020, "2")],
|
||||
vec![t(1020, "2")],
|
||||
vec![t(1010, "nan"), t(1020, "2"), t(1030, "3")],
|
||||
vec![t(1040, "inf")],
|
||||
vec![t(1040, "x")],
|
||||
vec![t(1070, "40000")],
|
||||
vec![t(1071, "3000000000")],
|
||||
vec![t(1004, "ABC")],
|
||||
vec![t(1004, "XY")],
|
||||
vec![t(1005, "")],
|
||||
vec![t(1005, "zz")],
|
||||
vec![t(1000, &"x".repeat(256))],
|
||||
vec![t(1000, "a\nb")],
|
||||
vec![t(1000, "x"); MAX_XDATA_GROUPS + 1],
|
||||
] {
|
||||
assert!(check_xdata_groups(&bad).is_err(), "{:?}", bad.first());
|
||||
}
|
||||
assert_eq!(check_xdata_app_name("PE_URL"), Ok(()));
|
||||
assert_eq!(check_xdata_app_name("My App-1.0$"), Ok(()));
|
||||
for bad in ["", " ", "a*b", "a\tb", "x/y", &"n".repeat(256)] {
|
||||
assert!(check_xdata_app_name(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
assert!(is_reserved_xdata_app("cadcraft") && !is_reserved_xdata_app("ACAD"));
|
||||
}
|
||||
}
|
||||
@@ -913,6 +913,7 @@ mod tests {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -988,6 +989,7 @@ mod tests {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
let ml = crate::MLeader {
|
||||
leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0)]],
|
||||
|
||||
@@ -42,11 +42,19 @@ pub struct ForeignExtra {
|
||||
pub color_book: Option<(String, String)>,
|
||||
/// Other unmodelled property groups (material 347, shadow mode 284).
|
||||
pub props: Vec<RawTag>,
|
||||
/// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled
|
||||
/// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them.
|
||||
pub tail: Vec<RawTag>,
|
||||
}
|
||||
|
||||
impl ForeignExtra {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.xdict.is_none() && self.reactors.is_empty() && self.xdata.is_empty() && self.color_book.is_none() && self.props.is_empty()
|
||||
self.xdict.is_none()
|
||||
&& self.reactors.is_empty()
|
||||
&& self.xdata.is_empty()
|
||||
&& self.color_book.is_none()
|
||||
&& self.props.is_empty()
|
||||
&& self.tail.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,11 +97,36 @@ pub struct Foreign {
|
||||
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
|
||||
/// later save must not take it for this one (#2471).
|
||||
pub version: Option<String>,
|
||||
/// Block references with kept annotation scale contexts, as they were read: what a context
|
||||
/// is brought up to date from (see [`KeptPlacement`]), by handle.
|
||||
pub placements: BTreeMap<Handle, KeptPlacement>,
|
||||
/// The file's registered applications (APPID names as read, in file order). Saving writes
|
||||
/// them all back, whether or not any xdata still names them.
|
||||
pub appids: Vec<String>,
|
||||
}
|
||||
|
||||
/// A block reference as read: its insertion point, rotation (radians) and scale, and each of its
|
||||
/// attributes as read, in order. Its kept contexts were written for it then; what it did since
|
||||
/// moves them.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct KeptPlacement {
|
||||
pub insert: crate::geom::Vec3,
|
||||
pub rotation: f64,
|
||||
pub scale: crate::geom::Vec3,
|
||||
pub attribs: Vec<KeptAttrib>,
|
||||
}
|
||||
|
||||
/// An attribute of a block reference as read: its tag, insertion and alignment points and
|
||||
/// rotation (radians). Found again by tag and place among the reference's attributes with that
|
||||
/// tag, since the attributes can be reordered or replaced (ATTSYNC) after the file is read.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct KeptAttrib {
|
||||
pub tag: String,
|
||||
pub insert: crate::geom::Vec3,
|
||||
pub align: crate::geom::Vec3,
|
||||
pub rotation: f64,
|
||||
}
|
||||
|
||||
impl Foreign {
|
||||
/// The class of the file's CLASSES a proxy's group 91 names (see [`class_number`]), if any.
|
||||
/// Saving as DWG keeps a proxy with that class and leaves out one whose class it can't name.
|
||||
@@ -110,6 +143,7 @@ impl Foreign {
|
||||
&& self.targets.is_empty()
|
||||
&& self.class_order.is_empty()
|
||||
&& self.data_store.is_empty()
|
||||
&& self.placements.is_empty()
|
||||
&& self.appids.is_empty()
|
||||
}
|
||||
|
||||
|
||||
+74
-1
@@ -6,12 +6,19 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::{Entity, Handle};
|
||||
|
||||
const CHUNK_MAX: usize = 1024;
|
||||
const SHARDS: usize = 64;
|
||||
|
||||
/// A content token no store has had: one count for the process (a `u64` does not run out).
|
||||
fn next_token() -> u64 {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Chunk {
|
||||
id: u32,
|
||||
@@ -24,11 +31,19 @@ pub struct EntityStore {
|
||||
shards: Vec<Arc<HashMap<Handle, u32>>>,
|
||||
len: usize,
|
||||
next_chunk: u32,
|
||||
/// This state of the entities ([`EntityStore::content_token`]). Not part of [`PartialEq`].
|
||||
token: u64,
|
||||
}
|
||||
|
||||
impl Default for EntityStore {
|
||||
fn default() -> Self {
|
||||
EntityStore { chunks: Vec::new(), shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(), len: 0, next_chunk: 0 }
|
||||
EntityStore {
|
||||
chunks: Vec::new(),
|
||||
shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(),
|
||||
len: 0,
|
||||
next_chunk: 0,
|
||||
token: next_token(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +62,17 @@ impl EntityStore {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
/// A number for this state of the entities: a clone has it too, and every edit gives the
|
||||
/// store a number no store has had, so two stores with one token hold the same entities in
|
||||
/// the same order. What is derived from the entities (a block's ATTDEFs by tag) can be kept
|
||||
/// under it. Not part of [`PartialEq`]: equal stores can have different tokens.
|
||||
pub fn content_token(&self) -> u64 {
|
||||
self.token
|
||||
}
|
||||
/// The entities are about to change: a new token.
|
||||
fn edited(&mut self) {
|
||||
self.token = next_token();
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
@@ -101,6 +127,7 @@ impl EntityStore {
|
||||
self.replace(e);
|
||||
return;
|
||||
}
|
||||
self.edited();
|
||||
let needs_new = self.chunks.last().is_none_or(|c| c.items.len() >= CHUNK_MAX);
|
||||
if needs_new {
|
||||
let c = self.new_chunk();
|
||||
@@ -120,6 +147,7 @@ impl EntityStore {
|
||||
self.replace(e);
|
||||
return;
|
||||
}
|
||||
self.edited();
|
||||
let needs_new = self.chunks.first().is_none_or(|c| c.items.len() >= CHUNK_MAX);
|
||||
if needs_new {
|
||||
let c = self.new_chunk();
|
||||
@@ -137,6 +165,7 @@ impl EntityStore {
|
||||
pub fn replace(&mut self, e: Entity) -> bool {
|
||||
let Some(id) = self.chunk_id(e.handle) else { return false };
|
||||
let Some(pos) = self.chunk_pos(id) else { return false };
|
||||
self.edited();
|
||||
let Some(c) = self.chunks.get_mut(pos) else { return false };
|
||||
let chunk = Arc::make_mut(c);
|
||||
if let Some(slot) = chunk.items.iter_mut().find(|x| x.handle == e.handle) {
|
||||
@@ -149,6 +178,7 @@ impl EntityStore {
|
||||
pub fn remove(&mut self, h: Handle) -> Option<Arc<Entity>> {
|
||||
let id = self.chunk_id(h)?;
|
||||
let pos = self.chunk_pos(id)?;
|
||||
self.edited();
|
||||
let c = self.chunks.get_mut(pos)?;
|
||||
let chunk = Arc::make_mut(c);
|
||||
let i = chunk.items.iter().position(|x| x.handle == h)?;
|
||||
@@ -165,6 +195,7 @@ impl EntityStore {
|
||||
pub fn modify<F: FnOnce(&mut Entity)>(&mut self, h: Handle, f: F) -> bool {
|
||||
let Some(id) = self.chunk_id(h) else { return false };
|
||||
let Some(pos) = self.chunk_pos(id) else { return false };
|
||||
self.edited();
|
||||
let Some(c) = self.chunks.get_mut(pos) else { return false };
|
||||
let chunk = Arc::make_mut(c);
|
||||
match chunk.items.iter_mut().find(|x| x.handle == h) {
|
||||
@@ -219,6 +250,7 @@ impl EntityStore {
|
||||
self.push(Arc::unwrap_or_clone(e));
|
||||
return false;
|
||||
};
|
||||
self.edited();
|
||||
let Some(c) = self.chunks.get_mut(pos) else {
|
||||
// Unreachable in practice too; never lose the object.
|
||||
self.push(Arc::unwrap_or_clone(e));
|
||||
@@ -297,6 +329,47 @@ mod tests {
|
||||
Entity::new(Handle(h), EntityKind::Point(Point { p: Vec2::new(h as f64, 0.0).to3(0.0), angle: 0.0 }))
|
||||
}
|
||||
|
||||
/// One token per state of the entities: shared by clones, new after every kind of edit, and
|
||||
/// different for copies edited apart (#1660's ATTDEF index is kept by it).
|
||||
#[test]
|
||||
fn a_content_token_names_one_state_of_the_entities() {
|
||||
let mut a = EntityStore::new();
|
||||
for h in 1..=3 {
|
||||
a.push(ent(h));
|
||||
}
|
||||
assert_eq!(a.clone().content_token(), a.content_token(), "a clone holds the same entities");
|
||||
let (mut b, mut c) = (a.clone(), a.clone());
|
||||
assert!(b.modify(Handle(1), |e| e.common.layer = "B".into()));
|
||||
assert!(c.modify(Handle(1), |e| e.common.layer = "C".into()));
|
||||
assert_ne!(b.content_token(), c.content_token(), "copies edited apart");
|
||||
assert_ne!(b.content_token(), a.content_token());
|
||||
let edits: [fn(&mut EntityStore); 8] = [
|
||||
|s| s.push(ent(9)),
|
||||
|s| s.push_front(ent(8)),
|
||||
|s| {
|
||||
s.replace(ent(2));
|
||||
},
|
||||
|s| {
|
||||
s.remove(Handle(3));
|
||||
},
|
||||
|s| {
|
||||
s.bring_to_front(Handle(1));
|
||||
},
|
||||
|s| {
|
||||
s.send_to_back(Handle(2));
|
||||
},
|
||||
|s| {
|
||||
s.move_next_to(Handle(1), Handle(2), true);
|
||||
},
|
||||
|s| s.sort_by_key(|e| std::cmp::Reverse(e.handle.0)),
|
||||
];
|
||||
for (i, edit) in edits.iter().enumerate() {
|
||||
let mut s = a.clone();
|
||||
edit(&mut s);
|
||||
assert_ne!(s.content_token(), a.content_token(), "edit {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_get_remove() {
|
||||
let mut s = EntityStore::new();
|
||||
|
||||
@@ -725,6 +725,9 @@ pub struct Block {
|
||||
pub explodable: bool,
|
||||
#[serde(default)]
|
||||
pub units: u8,
|
||||
/// References to this block scale uniformly (the BLOCK_RECORD's group 281).
|
||||
#[serde(default)]
|
||||
pub scale_uniformly: bool,
|
||||
/// 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>,
|
||||
@@ -778,6 +781,7 @@ impl Block {
|
||||
xref_path: None,
|
||||
explodable: true,
|
||||
units: 0,
|
||||
scale_uniformly: false,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
}
|
||||
|
||||
@@ -686,6 +686,7 @@ fn mtext_kind(contents: &str) -> EntityKind {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1075,9 +1076,13 @@ fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
|
||||
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
|
||||
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
assert!(!d.extents(&Space::Model).is_empty());
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
|
||||
let (bounds, cross_probes) = crate::TagKey::with_cross_probes(1000, || d.extents(&Space::Model));
|
||||
assert!(!bounds.is_empty());
|
||||
// Layer inheritance and the constant-value filter each query the opposite set.
|
||||
// With no matches, an unindexed scan bypasses the probe (zero) or compares every pair.
|
||||
for probes in cross_probes {
|
||||
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {cross_probes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
|
||||
|
||||
@@ -280,6 +280,9 @@ impl DocState {
|
||||
self.view_history.clear();
|
||||
self.block_edit = Some(be);
|
||||
self.revision += 1;
|
||||
// The editor's drawing is another drawing with the host's handles: a name given in the
|
||||
// host must not resolve in it (BCLOSE ends the editor's names the same way, #1660).
|
||||
self.expire_names();
|
||||
}
|
||||
|
||||
/// Save the Block Editor's objects into the block (BSAVE), or into a new block `as_name`
|
||||
@@ -346,6 +349,9 @@ impl DocState {
|
||||
self.views = host.views;
|
||||
self.view_history = host.view_history;
|
||||
self.revision += 1;
|
||||
// The editor's drawing shares the host's handles: a name given in it must never resolve
|
||||
// to a host record (or the other way round) after the drawing comes back.
|
||||
self.expire_names();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,6 +151,7 @@ impl Interactive for LeaderM {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
EntityKind::MText(m) => Some(m.clone()),
|
||||
_ => None,
|
||||
@@ -324,6 +325,7 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}))?)
|
||||
}
|
||||
Annotation::Quick { lines, width } => {
|
||||
@@ -341,6 +343,7 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}))?)
|
||||
}
|
||||
Annotation::Copy(m) => {
|
||||
|
||||
@@ -31,6 +31,7 @@ fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option<
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
style: st.name.clone(),
|
||||
arrow_size: st.arrow_size,
|
||||
|
||||
@@ -117,8 +117,10 @@ fn run_recover(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.state_mut()?;
|
||||
let report = crate::audit::fix(Arc::make_mut(&mut st.doc));
|
||||
if report.issues.is_empty() {
|
||||
// Nothing to fix: the drawing opens unchanged, like OPEN.
|
||||
st.doc = st.saved.clone();
|
||||
// Nothing to fix: the drawing opens unchanged, like OPEN. `fix` may already
|
||||
// have copied it, so put the saved one back; no record name exists yet.
|
||||
let saved = st.saved.clone();
|
||||
st.restore_drawing(saved);
|
||||
}
|
||||
if copy && !st.is_dirty() {
|
||||
// An unsaved copy (Drawing Recovery): closing it asks to save it under a name.
|
||||
|
||||
@@ -104,12 +104,17 @@ pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib>
|
||||
let m = ins.transform(blk.base.xy());
|
||||
// The reference's attributes by tag, gathered once for all the definitions (#1923).
|
||||
let carried = ins.attribs_by_tag();
|
||||
#[cfg(test)]
|
||||
let carried = carried.into_iter().map(|(tag, attrib)| (tests::MeasuredTag(tag), attrib)).collect::<std::collections::BTreeMap<_, _>>();
|
||||
defs.iter()
|
||||
.map(|ad| {
|
||||
let mut k = EntityKind::Text(ad.text.clone());
|
||||
k.transform(&m);
|
||||
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
|
||||
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
|
||||
let key = TagKey(&ad.tag);
|
||||
#[cfg(test)]
|
||||
let key = tests::MeasuredTag(key);
|
||||
t.value = carried.get(&key).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
|
||||
Attrib {
|
||||
tag: ad.tag.clone(),
|
||||
text: t,
|
||||
@@ -204,6 +209,8 @@ pub(super) fn sync(s: &mut Session, name: &str) -> Result<(String, usize)> {
|
||||
let defs = attdefs(&blk);
|
||||
let d = s.doc_mut()?;
|
||||
let n = update_references(d, &blk.name, |ins| ins.attribs = synced(&blk, &defs, ins));
|
||||
// The references have new ATTRIBs: names given to the old ones hold no longer (#1660).
|
||||
s.state_mut()?.expire_names();
|
||||
Ok((blk.name.clone(), n))
|
||||
}
|
||||
|
||||
@@ -359,6 +366,74 @@ impl Interactive for AttsyncM {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
std::thread_local! {
|
||||
static SYNC_CROSS_PROBES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// Use the actual tag ordering and count only probes between different fixture sets.
|
||||
pub(super) struct MeasuredTag<'a>(pub(super) TagKey<'a>);
|
||||
|
||||
impl MeasuredTag<'_> {
|
||||
fn record(&self, other: &Self) {
|
||||
let TagKey(left) = self.0;
|
||||
let TagKey(right) = other.0;
|
||||
let sides = (left.as_bytes().first(), right.as_bytes().first());
|
||||
if matches!(sides, (Some(b'A'), Some(b'D')) | (Some(b'D'), Some(b'A'))) {
|
||||
SYNC_CROSS_PROBES.with(|count| count.set(count.get().map(|n| n + 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for MeasuredTag<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.record(other);
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for MeasuredTag<'_> {}
|
||||
|
||||
impl PartialOrd for MeasuredTag<'_> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for MeasuredTag<'_> {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.record(other);
|
||||
self.0.cmp(&other.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_uses_indexed_cross_set_tag_matching() {
|
||||
const N: usize = 512;
|
||||
let mut s = Session::new();
|
||||
s.execute("attdef", &json!({"tag":"T", "default":"d", "at":[0, 1], "height":1.0})).unwrap();
|
||||
s.execute("line", &json!({"points":[[0, 0], [10, 0]]})).unwrap();
|
||||
let ids: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
|
||||
s.execute("block", &json!({"name":"B", "base":[0, 0], "keep":"delete", "handles":ids})).unwrap();
|
||||
let added = s.execute("insert", &json!({"name":"B", "at":[0, 0], "attribs":{"T":"v"}})).unwrap();
|
||||
let handle = Handle::parse_hex(added["handle"].as_str().unwrap()).unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
let blk = doc.block("B").unwrap();
|
||||
let base = (*attdefs(blk)[0]).clone();
|
||||
let EntityKind::Insert(mut ins) = doc.entity(handle).unwrap().kind.clone() else { panic!("insert expected") };
|
||||
let value = ins.attribs[0].clone();
|
||||
let defs: Vec<_> = (0..N).map(|i| Attrib { tag: format!("D{i:05}"), ..base.clone() }).collect();
|
||||
let defs: Vec<_> = defs.iter().collect();
|
||||
ins.attribs = (0..N).map(|i| Attrib { tag: format!("A{i:05}"), ..value.clone() }).collect();
|
||||
|
||||
SYNC_CROSS_PROBES.with(|count| count.set(Some(0)));
|
||||
let result = synced(blk, &defs, &ins);
|
||||
let probes = SYNC_CROSS_PROBES.with(|count| count.replace(None).unwrap());
|
||||
assert_eq!(result.len(), N);
|
||||
assert!(result.iter().all(|a| a.text.value == "d"));
|
||||
// No cross-set comparisons means this lookup was bypassed, whereas a scan does N*N.
|
||||
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {probes}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attdisp_keywords_map_to_attmode() {
|
||||
assert_eq!([attmode("Normal"), attmode("on"), attmode("OFF"), attmode("x")], [Some(1), Some(2), Some(0), None]);
|
||||
|
||||
@@ -81,6 +81,8 @@ fn replace(s: &mut Session, old: &str, new: &str, purge: bool) -> Result<(usize,
|
||||
});
|
||||
let key = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(&old)).cloned();
|
||||
let purged = purge && !referenced(d, &old) && key.is_some_and(|k| d.blocks.remove(&k).is_some());
|
||||
// Replaced references have new ATTRIBs: names given to the old ones hold no longer (#1660).
|
||||
s.state_mut()?.expire_names();
|
||||
Ok((n, purged))
|
||||
}
|
||||
|
||||
|
||||
@@ -1073,7 +1073,7 @@ pub(crate) fn after_command(s: &mut Session, before: &Arc<Drawing>, id: &str) ->
|
||||
.iter()
|
||||
.any(|store| store.iter().any(|e| !owned.contains(&e.handle) && !st.doc.entity(e.handle).is_some_and(|a| Arc::ptr_eq(a, e))));
|
||||
if touched {
|
||||
st.doc = before.clone();
|
||||
st.restore_drawing(before.clone());
|
||||
return Some("Only the working set can be edited during REFEDIT (REFSET adds objects, REFCLOSE ends the edit).".into());
|
||||
}
|
||||
let seed = before.handseed;
|
||||
|
||||
@@ -139,6 +139,7 @@ pub(super) fn run_mtext(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
line_spacing: f64_or(p, "lineSpacing", 1.0),
|
||||
line_spacing_exact: bool_or(p, "lineSpacingExact", false),
|
||||
columns: crate::cmd::mtext_opts::json_columns(p, height, width)?,
|
||||
background: None,
|
||||
});
|
||||
added(s.add_entity(k)?)
|
||||
}
|
||||
|
||||
@@ -108,6 +108,47 @@ pub fn entity_codec() -> Option<&'static EntityCodec> {
|
||||
CODEC.get()
|
||||
}
|
||||
|
||||
/// One record written after an entity's own, at `index` (an INSERT's ATTRIB, then its SEQEND):
|
||||
/// its type name and the groups of its record, without its `0` group. AutoLISP's `entnext` and
|
||||
/// `entget` reach an INSERT's attributes through it, one record at a time (the attributes have no
|
||||
/// handle of their own in the drawing). Installed by the app with the DXF writer, a lower layer;
|
||||
/// optional, so a host without one simply has no such records ([`EntityCodec`] is unchanged).
|
||||
pub type EntitySubRecord = fn(&Drawing, &cadcraft_doc::Entity, usize) -> Option<(String, Vec<craft_dxf::Tag>)>;
|
||||
|
||||
static SUB_RECORD: OnceLock<EntitySubRecord> = OnceLock::new();
|
||||
|
||||
// This thread hid the optional provider ([`without_entity_sub_record`], tests only).
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static SUB_RECORD_HIDDEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
pub fn set_entity_sub_record(f: EntitySubRecord) {
|
||||
let _ = SUB_RECORD.set(f);
|
||||
}
|
||||
pub fn entity_sub_record() -> Option<EntitySubRecord> {
|
||||
#[cfg(test)]
|
||||
if SUB_RECORD_HIDDEN.with(std::cell::Cell::get) {
|
||||
return None;
|
||||
}
|
||||
SUB_RECORD.get().copied()
|
||||
}
|
||||
|
||||
/// Run `f` as a host that did not install [`EntitySubRecord`]: `entnext` must walk the drawing's
|
||||
/// entities as it did before the provider existed. Tests only.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn without_entity_sub_record<R>(f: impl FnOnce() -> R) -> R {
|
||||
struct Unhide;
|
||||
impl Drop for Unhide {
|
||||
fn drop(&mut self) {
|
||||
SUB_RECORD_HIDDEN.with(|h| h.set(false));
|
||||
}
|
||||
}
|
||||
SUB_RECORD_HIDDEN.with(|h| h.set(true));
|
||||
let _unhide = Unhide;
|
||||
f()
|
||||
}
|
||||
|
||||
/// The drawing's non-graphic records as written (tables, BLOCK records, objects): each one's
|
||||
/// type, groups after the type and role (see [`cadcraft_doc::foreign::ForeignKey`]). AutoLISP's
|
||||
/// `namedobjdict`, `tblobjname` and `handent` of non-graphic objects read them (installed by the
|
||||
|
||||
@@ -276,9 +276,10 @@ impl GripEdit {
|
||||
}
|
||||
"Undo" => match self.undo.pop() {
|
||||
Some(doc) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an earlier
|
||||
// one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
|
||||
@@ -574,8 +574,9 @@ fn run_boundary(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for q in pts {
|
||||
out.extend(boundary_at(s, q)?.into_iter().map(|h| h.hex()));
|
||||
if out.len() > MAX_BOUNDARY_OUTPUT {
|
||||
// The refused call leaves no partial result behind.
|
||||
s.state_mut()?.doc = before;
|
||||
// The refused call leaves no partial result behind. Handles it gave out can
|
||||
// be given again, so names of INSERT records end.
|
||||
s.state_mut()?.restore_drawing(before);
|
||||
return Err(bad("boundary", format!("more than {MAX_BOUNDARY_OUTPUT} boundary polylines in one call; split the work")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("status", "Status", run_status).menu(&["Tools", "Inquiry", "Status"]).noundo(),
|
||||
CommandSpec::new("drawing.inspect", "Inspect Drawing", run_inspect).params("{entities?: bool, limit?: n}").noundo(),
|
||||
CommandSpec::new("entities", "Query Entities", run_entities)
|
||||
.params("{type?, layer?, selected?: bool (default false; true = current selection in active space), window?: [[x,y],[x,y]], crossing?: bool (default true; false = entirely inside), limit?, offset?} → {count (all matches), returned, offset, entities}")
|
||||
.params("{type?, layer?, selected?: bool (default false; true = current selection in active space), window?: [[x,y],[x,y]], crossing?: bool (default true; false = entirely inside), xdata?: true | \"APP\" | [\"APP\", …] (add each entity's extended data {\"APP\": [[code, value], …]}; a name also keeps only entities carrying that application's data), limit?, offset?} → {count (all matches), returned, offset, entities}")
|
||||
.noundo(),
|
||||
CommandSpec::new("shapes", "Analyze Shapes", shapes::run).params(shapes::PARAMS).noundo(),
|
||||
CommandSpec::new("usage", "Analyze Usage", usage::run).params(usage::PARAMS).noundo(),
|
||||
@@ -658,6 +658,7 @@ fn run_entities(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.transpose()?;
|
||||
let crossing = given("crossing").map_or(Ok(true), |v| v.as_bool().ok_or_else(|| bad(CMD, "`crossing` must be true or false")))?;
|
||||
let selected = given("selected").map_or(Ok(false), |v| v.as_bool().ok_or_else(|| bad(CMD, "`selected` must be true or false")))?;
|
||||
let xdata = super::props::xdata::XdataSelect::parse(given("xdata")).map_err(|m| bad(CMD, m))?;
|
||||
let limit = count("limit", 500)?;
|
||||
let offset = count("offset", 0)?;
|
||||
let st = s.state()?;
|
||||
@@ -671,8 +672,20 @@ fn run_entities(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.filter(|e| ty.as_ref().is_none_or(|t| e.kind.type_name().to_ascii_lowercase() == *t || e.kind.dxf_name().to_ascii_lowercase() == *t))
|
||||
.filter(|e| layer.as_ref().is_none_or(|l| e.common.layer.to_ascii_lowercase() == *l))
|
||||
.filter(|e| window.as_ref().is_none_or(|w| crate::select::in_window(d, e, None, w, crossing, tol)))
|
||||
.filter(|e| !xdata.filters() || xdata.matches(&e.common.xdata))
|
||||
.collect();
|
||||
let page: Vec<Value> = matches
|
||||
.iter()
|
||||
.skip(offset)
|
||||
.take(limit)
|
||||
.map(|e| {
|
||||
let mut v = entity_summary(e);
|
||||
if let (Some(x), Some(o)) = (xdata.json(&e.common.xdata), v.as_object_mut()) {
|
||||
o.insert("xdata".into(), x);
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
let page: Vec<Value> = matches.iter().skip(offset).take(limit).map(|e| entity_summary(e)).collect();
|
||||
// `count` is every match; `returned` is this page of them (`offset`, `limit`).
|
||||
Ok(json!({ "count": matches.len(), "returned": page.len(), "offset": offset, "entities": page }))
|
||||
}
|
||||
|
||||
@@ -179,6 +179,7 @@ fn explode_dimension(d: &cadcraft_doc::Drawing, e: &Entity, dm: &cadcraft_doc::D
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -266,7 +267,7 @@ pub(crate) fn explode_with(
|
||||
// pieces are copies of the block's objects and keep theirs.
|
||||
let own_pieces = !matches!(e.kind, EntityKind::Insert(_));
|
||||
let d = s.doc_mut()?;
|
||||
d.remove_entity(*h);
|
||||
let Some(removed) = d.remove_entity(*h) else { continue };
|
||||
for mut p in parts {
|
||||
if own_pieces {
|
||||
p.common.xdata.clear();
|
||||
@@ -277,6 +278,9 @@ pub(crate) fn explode_with(
|
||||
st.push(p);
|
||||
}
|
||||
}
|
||||
if !own_pieces && let Some(names) = s.record_names() {
|
||||
names.erased(&removed);
|
||||
}
|
||||
}
|
||||
s.set_selection(Vec::new());
|
||||
Ok(out)
|
||||
|
||||
@@ -328,9 +328,10 @@ impl Interactive for FilletM {
|
||||
Input::Keyword(k) if k == "Undo" => {
|
||||
match self.undo.pop() {
|
||||
Some(doc) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an earlier
|
||||
// one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
}
|
||||
None => s.echo("Nothing to undo."),
|
||||
|
||||
@@ -491,9 +491,10 @@ impl Interactive for OffsetM {
|
||||
(_, Input::Keyword(k)) if k == "Undo" => {
|
||||
match self.undo.pop() {
|
||||
Some((doc, picked)) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an earlier
|
||||
// one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
self.picked = if self.multiple { picked } else { None };
|
||||
if self.picked.is_none() {
|
||||
|
||||
@@ -55,6 +55,13 @@ pub(crate) fn erase_kept(s: &mut Session, hs: &[Handle]) -> Result<usize> {
|
||||
// (`refedit::after_command`), so what OOPS had stays.
|
||||
let refused = taken.iter().any(|t| crate::cmd::blocks::refedit::locked(d, t.entity.handle));
|
||||
if n > 0 && !refused {
|
||||
// The names of the erased references' records went with them: OOPS bringing them back
|
||||
// brings none back. Other references' names keep holding (#1660).
|
||||
if let Some(names) = s.record_names() {
|
||||
for t in &taken {
|
||||
names.erased(&t.entity);
|
||||
}
|
||||
}
|
||||
s.state_mut()?.erased = Erased(taken);
|
||||
}
|
||||
Ok(n)
|
||||
|
||||
@@ -178,9 +178,10 @@ impl MocoroM {
|
||||
fn undo(&mut self, s: &mut Session) -> Result<Step> {
|
||||
match self.history.pop() {
|
||||
Some((doc, base)) => {
|
||||
// Settings changed meanwhile (a transparent command) stay.
|
||||
// Settings changed meanwhile (a transparent command) stay. The drawing put
|
||||
// back is an earlier one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
if s.doc()?.header != header {
|
||||
s.doc_mut()?.header = header;
|
||||
}
|
||||
|
||||
@@ -126,7 +126,8 @@ impl PeditM {
|
||||
"reverse" | "r" => self.apply_all(s, "reverse", &json!({}))?,
|
||||
"undo" | "u" => match self.mundo.pop() {
|
||||
Some((d, multi, morig)) => {
|
||||
*s.doc_mut()? = d;
|
||||
// The saved drawing includes its handle seed.
|
||||
s.state_mut()?.restore_drawing(std::sync::Arc::new(d));
|
||||
self.multi = multi;
|
||||
self.morig = morig;
|
||||
s.set_selection(self.multi.clone());
|
||||
|
||||
@@ -411,6 +411,9 @@ fn chspace_json_and_command_line() {
|
||||
layer_colors: Vec::new(),
|
||||
clip: None,
|
||||
on: true,
|
||||
ucs: None,
|
||||
ucs_per_viewport: false,
|
||||
extra: Vec::new(),
|
||||
twist: 0.0,
|
||||
};
|
||||
s.doc_mut().unwrap().add(&Space::Paper("Layout1".into()), Default::default(), EntityKind::Viewport(vp)).unwrap();
|
||||
|
||||
@@ -48,6 +48,7 @@ pub(crate) fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,6 +96,7 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
Some(TextEditor { mtext, kind: EditorKind::Dimension { measured }, key, extents: None })
|
||||
}
|
||||
|
||||
@@ -95,6 +95,7 @@ impl MTextOpts {
|
||||
line_spacing: self.spacing,
|
||||
line_spacing_exact: self.exact,
|
||||
columns: self.columns.clone().filter(|_| width > 0.0),
|
||||
background: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ mod dash_units;
|
||||
mod matchprop;
|
||||
mod rename;
|
||||
mod set;
|
||||
pub(crate) mod xdata;
|
||||
|
||||
pub use matchprop::MatchProps;
|
||||
use set::run_set;
|
||||
@@ -27,7 +28,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
<geometry fields: radius, center, start, end, text, height, rotation…>, text: style?, justify?, oblique?, backwards?, upsideDown?, positionX/Y/Z?, alignmentX/Y?, \
|
||||
mtext: style?, justify?, lineSpacing?, lineSpacingDistance?, lineSpacingStyle?: atLeast | exactly, positionX/Y/Z?, \
|
||||
dimension: dimStyle?, textOverride?, textRotation?, textPositionX/Y?, prefix?, suffix?, altPrefix?, altSuffix?, dimScale?, precision?, \
|
||||
<dimension style variables (field or DIM* name, e.g. textHeight / DIMTXT) set as overrides of each dimension>, clearOverrides?, clear?: [variable]} \
|
||||
<dimension style variables (field or DIM* name, e.g. textHeight / DIMTXT) set as overrides of each dimension>, clearOverrides?, clear?: [variable], \
|
||||
xdata?: {\"APP\": [[code, value], …] | null} (replaces or removes that application's extended data; codes 1000–1071, points as [1010, [x, y, z]])} \
|
||||
→ {changed, locked, message?, ignored: keys no selected object took} (the keys are those of `properties.describe` rows): objects on locked layers \
|
||||
(and, during REFEDIT, outside the working set) are left out, and `message` says how many",
|
||||
),
|
||||
@@ -125,6 +127,9 @@ pub(super) fn entity_props(d: &cadcraft_doc::Drawing, e: &cadcraft_doc::Entity)
|
||||
o.insert("annotative".into(), json!(cadcraft_doc::is_annotative(e)));
|
||||
o.insert("annotativeScales".into(), json!(e.common.anno_scales.iter().map(|s| s.name.clone()).collect::<Vec<_>>()));
|
||||
}
|
||||
if let (Some(x), Some(o)) = (xdata::xdata_json(&e.common.xdata), v.as_object_mut()) {
|
||||
o.insert("xdata".into(), x);
|
||||
}
|
||||
let geo = serde_json::to_value(&e.kind).unwrap_or(Value::Null);
|
||||
if let (Some(o), Some(g)) = (v.as_object_mut(), geo.as_object()) {
|
||||
o.insert("geometry".into(), Value::Object(g.clone()));
|
||||
|
||||
@@ -48,6 +48,7 @@ const SET_KEYS: &[&str] = &[
|
||||
"suffix",
|
||||
"altPrefix",
|
||||
"altSuffix",
|
||||
"xdata",
|
||||
// An insert's or hatch's scale; a dimension's overall scale is `dimScale` (or DIMSCALE).
|
||||
"scale",
|
||||
];
|
||||
@@ -324,6 +325,32 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|n| d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found"))))
|
||||
.transpose()?;
|
||||
let dim_vars = DimVars::new(d, p)?;
|
||||
// xdata is checked before anything changes (`ensure_layer` below adds a layer the drawing
|
||||
// keeps even when the command then fails): no object may end up with more xdata than a
|
||||
// file holds for one.
|
||||
let xd = p.get("xdata").filter(|v| !v.is_null()).map(super::xdata::xdata_from_json).transpose().map_err(|m| bad("properties.set", m))?;
|
||||
if let Some(changes) = &xd {
|
||||
for h in &hs {
|
||||
let Some(e) = d.entity(*h) else { continue };
|
||||
// A dimension's `ACAD` run is written from its overrides (textHeight, arrowSize…) and
|
||||
// read back into them: raw groups under that name would be lost on save.
|
||||
if let Some((app, _)) = changes.iter().find(|(app, _)| cadcraft_doc::is_model_xdata_app(app, &e.kind)) {
|
||||
return Err(bad(
|
||||
"properties.set",
|
||||
format!(
|
||||
"{}: xdata application {app} of a {} is written from its own properties and can't be set as raw data",
|
||||
h.hex(),
|
||||
e.kind.dxf_name()
|
||||
),
|
||||
));
|
||||
}
|
||||
let mut after = e.common.xdata.clone();
|
||||
super::xdata::apply(&mut after, changes);
|
||||
if after.len() > cadcraft_doc::MAX_XDATA_GROUPS {
|
||||
return Err(bad("properties.set", format!("{}: xdata would exceed {} groups", h.hex(), cadcraft_doc::MAX_XDATA_GROUPS)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// A pattern must be one each hatch can take, as HATCHEDIT refuses others.
|
||||
if let Some(v) = str_param(p, "pattern").filter(|v| !v.trim().is_empty())
|
||||
&& hs.iter().any(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if !crate::cmd::hatch::takes_pattern(x, v)))
|
||||
@@ -373,6 +400,10 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
EntityKind::Hatch(ha) => hatch(ha, &c, &mut used),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(changes) = &xd {
|
||||
super::xdata::apply(&mut e.common.xdata, changes);
|
||||
used.insert("xdata");
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let ignored: Vec<&str> = p
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
//! Xdata as JSON, for `entities`, `properties` and `properties.set`: an object by application,
|
||||
//! `{"APP": [[code, value], …]}`, with each group's value typed by its code: strings for 1000,
|
||||
//! 1002 (`{` / `}`), 1003 (a layer name), 1004 (hex) and 1005 (a handle), a point `[x, y, z]`
|
||||
//! for 1010–1013 (its 1020 and 1030 groups folded in), numbers for 1040–1042, integers for
|
||||
//! 1070 and 1071. Setting takes the same form; `null` for an application removes its data.
|
||||
|
||||
use cadcraft_doc::{MAX_XDATA_GROUPS, RawTag, check_xdata_app_name, check_xdata_groups, is_reserved_xdata_app, set_xdata_app, xdata_apps};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
/// Most applications one `properties.set` call may set.
|
||||
const MAX_APPS_PER_CALL: usize = 256;
|
||||
|
||||
/// Which applications' xdata a query returns.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) enum XdataSelect {
|
||||
/// None (the default).
|
||||
#[default]
|
||||
None,
|
||||
/// Every application's.
|
||||
All,
|
||||
/// These applications' (any case); an entity without any of them doesn't match the query.
|
||||
Apps(Vec<String>),
|
||||
}
|
||||
|
||||
impl XdataSelect {
|
||||
/// The `xdata` parameter of a query: `true`, `false`, an application name or a list of names.
|
||||
pub(crate) fn parse(v: Option<&Value>) -> Result<Self, String> {
|
||||
const MSG: &str = "`xdata` must be true, false, an application name or a list of names";
|
||||
match v {
|
||||
None | Some(Value::Null) => Ok(Self::None),
|
||||
Some(Value::Bool(b)) => Ok(if *b { Self::All } else { Self::None }),
|
||||
Some(Value::String(s)) => Ok(Self::Apps(vec![s.clone()])),
|
||||
Some(Value::Array(a)) if !a.is_empty() && a.len() <= MAX_APPS_PER_CALL => {
|
||||
a.iter().map(|x| x.as_str().map(str::to_string).ok_or_else(|| MSG.to_string())).collect::<Result<Vec<_>, _>>().map(Self::Apps)
|
||||
}
|
||||
Some(_) => Err(MSG.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the selection narrows a query to entities carrying the named applications' data.
|
||||
pub(crate) fn filters(&self) -> bool {
|
||||
matches!(self, Self::Apps(_))
|
||||
}
|
||||
|
||||
/// Whether an entity with this xdata passes the filter.
|
||||
pub(crate) fn matches(&self, xdata: &[RawTag]) -> bool {
|
||||
match self {
|
||||
Self::None | Self::All => true,
|
||||
Self::Apps(apps) => xdata_apps(xdata).iter().any(|(name, _)| apps.iter().any(|a| a.trim().eq_ignore_ascii_case(name))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected applications' data of an entity as JSON; `None` when there is none to show.
|
||||
pub(crate) fn json(&self, xdata: &[RawTag]) -> Option<Value> {
|
||||
let apps = match self {
|
||||
Self::None => return None,
|
||||
Self::All => None,
|
||||
Self::Apps(apps) => Some(apps),
|
||||
};
|
||||
let mut out = Map::new();
|
||||
for (name, groups) in xdata_apps(xdata) {
|
||||
if apps.is_some_and(|apps| !apps.iter().any(|a| a.trim().eq_ignore_ascii_case(name))) {
|
||||
continue;
|
||||
}
|
||||
// A second run of the same application (not something AutoCAD writes; `ACME` and
|
||||
// `acme` are one application, as `set_xdata_app` treats them) joins the first.
|
||||
let key = out.keys().find(|k| k.eq_ignore_ascii_case(name)).cloned();
|
||||
match key.and_then(|k| out.get_mut(&k)) {
|
||||
Some(Value::Array(v)) => v.extend(groups_json(groups)),
|
||||
_ => {
|
||||
out.insert(name.to_string(), Value::Array(groups_json(groups)));
|
||||
}
|
||||
}
|
||||
}
|
||||
(!out.is_empty()).then_some(Value::Object(out))
|
||||
}
|
||||
}
|
||||
|
||||
/// Every application's data of an entity as JSON; `None` when it has none.
|
||||
pub(crate) fn xdata_json(xdata: &[RawTag]) -> Option<Value> {
|
||||
XdataSelect::All.json(xdata)
|
||||
}
|
||||
|
||||
fn number(t: &RawTag) -> Value {
|
||||
t.value.trim().parse::<f64>().ok().filter(|v| v.is_finite()).map_or_else(|| json!(t.value), |v| json!(v))
|
||||
}
|
||||
|
||||
fn integer(t: &RawTag) -> Value {
|
||||
t.value.trim().parse::<i64>().map_or_else(|_| json!(t.value), |v| json!(v))
|
||||
}
|
||||
|
||||
/// One application's groups as `[code, value]` pairs, points folded.
|
||||
fn groups_json(groups: &[RawTag]) -> Vec<Value> {
|
||||
let mut out = Vec::with_capacity(groups.len());
|
||||
let mut i = 0;
|
||||
while let Some(t) = groups.get(i) {
|
||||
let v = match t.code {
|
||||
1010..=1013 => {
|
||||
let y = groups.get(i + 1).filter(|y| y.code == t.code + 10);
|
||||
let z = groups.get(i + 2).filter(|z| z.code == t.code + 20);
|
||||
if let (Some(y), Some(z)) = (y, z) {
|
||||
i += 3;
|
||||
out.push(json!([t.code, [number(t), number(y), number(z)]]));
|
||||
continue;
|
||||
}
|
||||
number(t)
|
||||
}
|
||||
1020..=1033 | 1040..=1042 => number(t),
|
||||
1070 | 1071 => integer(t),
|
||||
_ => json!(t.value),
|
||||
};
|
||||
out.push(json!([t.code, v]));
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What `properties.set`'s `xdata` parameter asks for: per application, its new groups (with
|
||||
/// their `1001` left out) or `None` to remove it. Everything is checked here: names, codes, value
|
||||
/// types and ranges, braces, sizes; reserved applications are refused.
|
||||
pub(crate) fn xdata_from_json(v: &Value) -> Result<Vec<(String, Option<Vec<RawTag>>)>, String> {
|
||||
let Some(obj) = v.as_object() else { return Err("`xdata` must be an object {\"APP\": [[code, value], …] | null}".into()) };
|
||||
if obj.len() > MAX_APPS_PER_CALL {
|
||||
return Err(format!("`xdata` may name at most {MAX_APPS_PER_CALL} applications"));
|
||||
}
|
||||
let mut out = Vec::with_capacity(obj.len());
|
||||
for (app, groups) in obj {
|
||||
check_xdata_app_name(app).map_err(|e| e.to_string())?;
|
||||
if is_reserved_xdata_app(app) {
|
||||
return Err(format!("xdata application `{app}` is reserved: CADCraft writes its data itself"));
|
||||
}
|
||||
let groups = match groups {
|
||||
Value::Null => None,
|
||||
Value::Array(a) => Some(groups_from_json(app, a)?),
|
||||
_ => return Err(format!("xdata of `{app}` must be a list of [code, value] pairs, or null to remove it")),
|
||||
};
|
||||
out.push((app.trim().to_string(), groups));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `[[code, value], …]` of one application as groups, each value checked for its code.
|
||||
fn groups_from_json(app: &str, pairs: &[Value]) -> Result<Vec<RawTag>, String> {
|
||||
if pairs.len() > MAX_XDATA_GROUPS {
|
||||
return Err(format!("xdata of `{app}`: at most {MAX_XDATA_GROUPS} groups"));
|
||||
}
|
||||
let mut out = Vec::with_capacity(pairs.len());
|
||||
for (n, pair) in pairs.iter().enumerate() {
|
||||
let at = || format!("xdata of `{app}`, group {}", n + 1);
|
||||
let (code, value) = match pair.as_array().map(Vec::as_slice) {
|
||||
Some([c, v]) => (c.as_i64().and_then(|c| i32::try_from(c).ok()).ok_or_else(|| format!("{}: the code must be an integer", at()))?, v),
|
||||
_ => return Err(format!("{}: each group is a [code, value] pair", at())),
|
||||
};
|
||||
let real = |x: &Value| x.as_f64().filter(|x| x.is_finite()).map(craft_dxf::format_real);
|
||||
match code {
|
||||
1000 | 1003 => {
|
||||
let s = value.as_str().ok_or_else(|| format!("{}: group {code} takes a string", at()))?;
|
||||
out.push(RawTag { code, value: s.to_string() });
|
||||
}
|
||||
1002 => match value.as_str() {
|
||||
Some(b @ ("{" | "}")) => out.push(RawTag { code, value: b.to_string() }),
|
||||
_ => return Err(format!("{}: group 1002 takes \"{{\" or \"}}\"", at())),
|
||||
},
|
||||
1004 => {
|
||||
let s = value.as_str().ok_or_else(|| format!("{}: group 1004 takes hex text", at()))?;
|
||||
out.push(RawTag { code, value: s.trim().to_ascii_uppercase() });
|
||||
}
|
||||
1005 => {
|
||||
let s = value.as_str().ok_or_else(|| format!("{}: group 1005 takes a hex handle", at()))?;
|
||||
out.push(RawTag { code, value: s.trim().to_ascii_uppercase() });
|
||||
}
|
||||
1010..=1013 => {
|
||||
let p = value.as_array().filter(|a| a.len() == 2 || a.len() == 3).and_then(|a| a.iter().map(real).collect::<Option<Vec<_>>>());
|
||||
let Some(p) = p else { return Err(format!("{}: group {code} takes a point [x, y, z] of finite numbers", at())) };
|
||||
out.push(RawTag { code, value: p.first().cloned().unwrap_or_default() });
|
||||
out.push(RawTag { code: code + 10, value: p.get(1).cloned().unwrap_or_default() });
|
||||
out.push(RawTag { code: code + 20, value: p.get(2).cloned().unwrap_or_else(|| "0.0".into()) });
|
||||
}
|
||||
1020..=1023 | 1030..=1033 => return Err(format!("{}: give the point as [{}, [x, y, z]]", at(), 1010 + (code % 10))),
|
||||
1040..=1042 => {
|
||||
let x = real(value).ok_or_else(|| format!("{}: group {code} takes a finite number", at()))?;
|
||||
out.push(RawTag { code, value: x });
|
||||
}
|
||||
1070 | 1071 => {
|
||||
let i = value.as_i64().ok_or_else(|| format!("{}: group {code} takes an integer", at()))?;
|
||||
out.push(RawTag { code, value: i.to_string() });
|
||||
}
|
||||
_ => return Err(format!("{}: {code} is not an xdata group code (1000–1071)", at())),
|
||||
}
|
||||
}
|
||||
check_xdata_groups(&out).map_err(|e| format!("xdata of `{app}`: {e}"))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Apply a parsed `xdata` parameter to an entity's xdata.
|
||||
pub(crate) fn apply(xdata: &mut Vec<RawTag>, changes: &[(String, Option<Vec<RawTag>>)]) {
|
||||
for (app, groups) in changes {
|
||||
set_xdata_app(xdata, app, groups.as_deref());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn t(code: i32, value: &str) -> RawTag {
|
||||
RawTag { code, value: value.into() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_round_trip_types_every_kind() {
|
||||
let x = vec![
|
||||
t(1001, "ACME"),
|
||||
t(1000, "D-07"),
|
||||
t(1002, "{"),
|
||||
t(1003, "Walls"),
|
||||
t(1004, "0AFF"),
|
||||
t(1005, "2A"),
|
||||
t(1010, "1.5"),
|
||||
t(1020, "2.0"),
|
||||
t(1030, "0.0"),
|
||||
t(1040, "2.5"),
|
||||
t(1070, "3"),
|
||||
t(1071, "70000"),
|
||||
t(1002, "}"),
|
||||
t(1001, "PE_URL"),
|
||||
t(1000, "https://example.com"),
|
||||
];
|
||||
let j = xdata_json(&x).unwrap();
|
||||
assert_eq!(
|
||||
j["ACME"],
|
||||
json!([
|
||||
[1000, "D-07"],
|
||||
[1002, "{"],
|
||||
[1003, "Walls"],
|
||||
[1004, "0AFF"],
|
||||
[1005, "2A"],
|
||||
[1010, [1.5, 2.0, 0.0]],
|
||||
[1040, 2.5],
|
||||
[1070, 3],
|
||||
[1071, 70000],
|
||||
[1002, "}"]
|
||||
])
|
||||
);
|
||||
assert_eq!(j["PE_URL"], json!([[1000, "https://example.com"]]));
|
||||
let back = xdata_from_json(&j).unwrap();
|
||||
let mut y = Vec::new();
|
||||
apply(&mut y, &back);
|
||||
assert_eq!(y, x);
|
||||
assert_eq!(xdata_json(&[]), None);
|
||||
assert_eq!(XdataSelect::Apps(vec!["pe_url".into()]).json(&x).unwrap().as_object().unwrap().len(), 1);
|
||||
assert!(XdataSelect::Apps(vec!["nope".into()]).json(&x).is_none());
|
||||
assert!(!XdataSelect::Apps(vec!["nope".into()]).matches(&x) && XdataSelect::Apps(vec!["acme".into()]).matches(&x));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_input_is_refused() {
|
||||
for bad in [
|
||||
json!([]),
|
||||
json!({"": [[1000, "x"]]}),
|
||||
json!({"CADCRAFT": [[1000, "x"]]}),
|
||||
json!({"A": [[1000, 5]]}),
|
||||
json!({"A": [[1001, "B"]]}),
|
||||
json!({"A": [[8, "layer"]]}),
|
||||
json!({"A": [[1002, "("]]}),
|
||||
json!({"A": [[1002, "{"]]}),
|
||||
json!({"A": [[1010, [1, 2, 3, 4]]]}),
|
||||
json!({"A": [[1010, [1, "x"]]]}),
|
||||
json!({"A": [[1010, 1]]}),
|
||||
json!({"A": [[1020, 1]]}),
|
||||
json!({"A": [[1040, "1"]]}),
|
||||
json!({"A": [[1070, 1.5]]}),
|
||||
json!({"A": [[1070, 70000]]}),
|
||||
json!({"A": [[1071, 1e12]]}),
|
||||
json!({"A": [[1004, "ABC"]]}),
|
||||
json!({"A": [[1005, "xyz"]]}),
|
||||
json!({"A": [1000, "x"]}),
|
||||
json!({"A": "x"}),
|
||||
json!({"A": [[1000, "x".repeat(300)]]}),
|
||||
] {
|
||||
assert!(xdata_from_json(&bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(xdata_from_json(&json!({"A": null})).unwrap(), vec![("A".to_string(), None)]);
|
||||
assert_eq!(xdata_from_json(&json!({"A": []})).unwrap(), vec![("A".to_string(), Some(Vec::new()))]);
|
||||
assert!(XdataSelect::parse(Some(&json!(1))).is_err());
|
||||
assert!(XdataSelect::parse(Some(&json!([]))).is_err());
|
||||
assert!(XdataSelect::parse(Some(&json!([1]))).is_err());
|
||||
assert_eq!(XdataSelect::parse(Some(&json!(true))).unwrap(), XdataSelect::All);
|
||||
assert_eq!(XdataSelect::parse(Some(&json!("A"))).unwrap(), XdataSelect::Apps(vec!["A".into()]));
|
||||
assert_eq!(XdataSelect::parse(None).unwrap(), XdataSelect::None);
|
||||
}
|
||||
}
|
||||
@@ -696,9 +696,10 @@ impl Interactive for TrimM {
|
||||
}
|
||||
"Undo" => match self.undo.pop() {
|
||||
Some(doc) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an
|
||||
// earlier one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
}
|
||||
None => s.echo("Nothing to undo."),
|
||||
|
||||
@@ -107,6 +107,7 @@ fn convert(s: &mut Session, hs: &[Handle], o: &Txt2MtxtOptions) -> Result<(Vec<H
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
let first = *first;
|
||||
let rest: Vec<Handle> = items.iter().skip(1).map(|(h, ..)| *h).collect();
|
||||
@@ -196,6 +197,7 @@ fn single(t: &Text) -> MText {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -302,7 +302,7 @@ fn run_view_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => 0.0,
|
||||
};
|
||||
if !s.state_mut()?.set_view(View { center: c, height: h, twist }) {
|
||||
s.state_mut()?.doc = before.0;
|
||||
s.state_mut()?.restore_drawing(before.0);
|
||||
return Err(bad("view.set", "the view is too large to show. Nothing was changed"));
|
||||
}
|
||||
if let Some(dview::Target::Viewport(h)) = target {
|
||||
|
||||
@@ -237,7 +237,7 @@ impl DviewM {
|
||||
set_twist(s, t, twist)?;
|
||||
}
|
||||
if !s.state_mut()?.set_view(View { twist, ..v }) {
|
||||
s.state_mut()?.doc = before;
|
||||
s.state_mut()?.restore_drawing(before);
|
||||
return Err(EngineError::Other("The view is too large to show.".into()));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -28,6 +28,13 @@ pub struct DocState {
|
||||
pub title: String,
|
||||
pub saved: Arc<Drawing>,
|
||||
pub revision: u64,
|
||||
/// How many times the names AutoLISP gave this drawing's INSERTs' ATTRIBs and SEQENDs ended all
|
||||
/// at once (#1660): another state of the drawing was shown (Undo, Redo, opening or closing the
|
||||
/// Block Editor, a change taken back, or a command putting an earlier drawing back through
|
||||
/// [`DocState::restore_drawing`]), or attribute sets were rebuilt in place (ATTSYNC,
|
||||
/// -BLOCKREPLACE). A name given before names nothing after one of these, never another
|
||||
/// record.
|
||||
pub(crate) names_epoch: u64,
|
||||
pub space: Space,
|
||||
/// Tiled model viewports (VPORTS).
|
||||
pub tiles: ModelTiles,
|
||||
@@ -71,6 +78,7 @@ impl DocState {
|
||||
path,
|
||||
title: title.into(),
|
||||
revision: 1,
|
||||
names_epoch: 0,
|
||||
space: Space::Model,
|
||||
tiles: ModelTiles::default(),
|
||||
mspace: None,
|
||||
@@ -97,8 +105,26 @@ impl DocState {
|
||||
self.follow_layout(&cur.doc);
|
||||
self.reconcile_untiled_twist();
|
||||
self.revision += 1;
|
||||
self.expire_names();
|
||||
cur
|
||||
}
|
||||
/// Names given to records without handles (an INSERT's ATTRIBs and SEQEND) stop holding: the
|
||||
/// records of the drawing they were given for may be gone or replaced. They are never given
|
||||
/// to another record, so a routine's stale name names nothing (`nil`) rather than something
|
||||
/// else.
|
||||
pub(crate) fn expire_names(&mut self) {
|
||||
self.names_epoch = self.names_epoch.wrapping_add(1);
|
||||
}
|
||||
/// Show `doc` again. It is a drawing this document already showed, so its handle seed can
|
||||
/// give the next object a handle a removed one had. Names of INSERT records end, as they do
|
||||
/// for Undo. The same drawing already on show is left as it is: nothing was given out again.
|
||||
pub(crate) fn restore_drawing(&mut self, doc: Arc<Drawing>) {
|
||||
if Arc::ptr_eq(&self.doc, &doc) {
|
||||
return;
|
||||
}
|
||||
self.doc = doc;
|
||||
self.expire_names();
|
||||
}
|
||||
/// After undo/redo replaced the drawing (`before` is the one shown until then): if the current
|
||||
/// layout no longer exists, follow it to its other name when it was renamed (same tab order,
|
||||
/// a name `before` did not have), else go to the Model tab.
|
||||
|
||||
@@ -26,7 +26,7 @@ impl Session {
|
||||
};
|
||||
let Some(st) = st.filter(|st| !Arc::ptr_eq(before, &st.doc)) else { return Ok(()) };
|
||||
let Some(h) = first_non_finite(before, &st.doc) else { return Ok(()) };
|
||||
st.doc = before.clone();
|
||||
st.restore_drawing(before.clone());
|
||||
st.selection = selection.to_vec();
|
||||
Err(EngineError::BadParams {
|
||||
cmd: cmd.into(),
|
||||
|
||||
@@ -75,6 +75,10 @@ pub struct Env {
|
||||
/// The command history's length after LISP last printed a line: when something else wrote since
|
||||
/// (a prompt, a command's echo), a leading newline only ends that line.
|
||||
pub printed_at: Option<usize>,
|
||||
/// Application names `regapp` registered (upper case). A drawing's APPID table is written
|
||||
/// from the xdata its objects carry, so this only makes `regapp` answer like AutoCAD's and
|
||||
/// shows the names in the APPID table `tblsearch` lists.
|
||||
pub regapps: std::collections::BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Default for Env {
|
||||
@@ -93,6 +97,7 @@ impl Default for Env {
|
||||
pending_block: None,
|
||||
objects: objects::Names::default(),
|
||||
printed_at: None,
|
||||
regapps: std::collections::BTreeSet::new(),
|
||||
};
|
||||
builtins::install(&mut e);
|
||||
e
|
||||
@@ -121,6 +126,11 @@ impl Env {
|
||||
#[derive(Default)]
|
||||
pub struct LispState {
|
||||
envs: HashMap<u64, Env>,
|
||||
/// The names given to records without a handle of their own (an INSERT's ATTRIBs and SEQEND,
|
||||
/// #1660), by drawing. They are the session's, not a snapshot's, so the drawing's undo states
|
||||
/// and the Block Editor's drawing share them; each use checks what a name stands for against
|
||||
/// the drawing.
|
||||
pub(crate) records: HashMap<u64, drawing::RecordNames>,
|
||||
run: Option<Box<Run>>,
|
||||
/// A routine runs, from its start to its end (also while its machine is out of `run`).
|
||||
active: bool,
|
||||
@@ -246,6 +256,13 @@ impl Session {
|
||||
pub(crate) fn lisp_forget_closed(&mut self) {
|
||||
let docs = &self.docs;
|
||||
self.lisp.envs.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid));
|
||||
self.lisp.records.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid));
|
||||
}
|
||||
|
||||
/// The active drawing's names of an INSERT's records (#1660), made on first use.
|
||||
pub(crate) fn record_names(&mut self) -> Option<&mut drawing::RecordNames> {
|
||||
let uid = self.state().ok()?.uid;
|
||||
Some(self.lisp.records.entry(uid).or_default())
|
||||
}
|
||||
|
||||
/// A routine is running (possibly waiting for input).
|
||||
@@ -427,7 +444,7 @@ impl Session {
|
||||
if let Some((doc, sel)) = self.lisp.steps.base.as_ref().or(run.before.as_ref())
|
||||
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == run.uid)
|
||||
{
|
||||
st.doc = doc.clone();
|
||||
st.restore_drawing(doc.clone());
|
||||
st.selection = sel.clone();
|
||||
}
|
||||
run.handler = true;
|
||||
|
||||
@@ -252,6 +252,7 @@ static BUILTINS: &[Builtin] = &[
|
||||
ctx!("ENTNEXT", drawing::entnext),
|
||||
ctx!("ENTUPD", drawing::entupd),
|
||||
ctx!("HANDENT", drawing::handent),
|
||||
ctx!("REGAPP", drawing::regapp),
|
||||
ctx!("SSGET", drawing::ssget),
|
||||
ctx!("SSADD", drawing::ssadd),
|
||||
ctx!("SSDEL", drawing::ssdel),
|
||||
|
||||
@@ -6,19 +6,22 @@
|
||||
//!
|
||||
//! Entity lists use the DXF groups the file reader and writer use (through
|
||||
//! [`crate::cmd::file::entity_codec`]), so what `entget` shows is what a DXF file holds, except
|
||||
//! for angles, which are radians in a list and degrees in a file.
|
||||
//! for angles, which are radians in a list and degrees in a file. Extended data (xdata) is the
|
||||
//! `-3` group, as in AutoCAD: `(entget ename '("APP" …))` adds `(-3 ("APP" (1000 . "…") …))` for
|
||||
//! the applications named (wildcards allowed), `entmake` and `entmod` take it, and `regapp`
|
||||
//! registers an application name.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use cadcraft_doc::{Entity, Handle, Space};
|
||||
use cadcraft_doc::{Entity, Handle, RawTag, Space};
|
||||
use cadcraft_geom::Vec2;
|
||||
use craft_dxf::Tag;
|
||||
|
||||
use super::builtins::args_err;
|
||||
use super::eval::{Ctx, Flow, Need};
|
||||
use super::value::{PickSet, Value, to_text};
|
||||
use super::value::{PickSet, RecordName, Value, equal, to_text};
|
||||
use super::{BlockSlots, LispError};
|
||||
use crate::{Input, Session};
|
||||
|
||||
@@ -116,6 +119,8 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
}
|
||||
}
|
||||
Value::Ename(h) => named(ctx.s, *h, None),
|
||||
// An INSERT's record (#1660) is no object of the drawing: it picks nothing.
|
||||
Value::Record(_) => feed(ctx.s, Input::Pick(Vec::new())),
|
||||
Value::PickSet(p) => feed(ctx.s, Input::Pick(items(p))),
|
||||
Value::Cons(_) => {
|
||||
if let Some(p) = arg.as_point() {
|
||||
@@ -323,8 +328,8 @@ pub(super) fn groups_to_list(tags: &[Tag]) -> Vec<Value> {
|
||||
const MAX_GROUP_TEXT: usize = 32 << 20;
|
||||
|
||||
/// An association list back to DXF groups (points split into x, y, z groups). The type
|
||||
/// (`0`), the entity name (`-1`), the handle (`5`), the owner (`330`) and the layout (`410`) are
|
||||
/// left out: they aren't the entity's to set.
|
||||
/// (`0`), the entity name (`-1`), the owner of a record (`-2`) and of the entity (`330`), the
|
||||
/// handle (`5`) and the layout (`410`) are left out: they aren't the entity's to set.
|
||||
fn list_to_groups(list: &Value) -> Result<(String, Vec<Tag>), LispError> {
|
||||
let mut kind = None;
|
||||
let mut tags = Vec::new();
|
||||
@@ -340,7 +345,7 @@ fn list_to_groups(list: &Value) -> Result<(String, Vec<Tag>), LispError> {
|
||||
other => return Err(LispError::bad_arg("stringp", other)),
|
||||
})
|
||||
}
|
||||
-1 | 5 | 330 | 360 | 410 | 102 => {}
|
||||
-1 | -2 | -3 | 5 | 330 | 360 | 410 | 102 => {}
|
||||
_ if point_group(code) && matches!(v, Value::Cons(_)) => {
|
||||
let p = v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &v))?;
|
||||
tags.push(Tag::f(code, p[0]));
|
||||
@@ -371,9 +376,317 @@ fn space_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option<Space> {
|
||||
d.space_of(h)
|
||||
}
|
||||
|
||||
// ---------------- an INSERT's ATTRIBs and SEQEND ----------------
|
||||
|
||||
/// The most names one drawing's LISP holds for an INSERT's records at once: a routine can't fill
|
||||
/// memory by walking. At the limit `entnext` gives no *new* name (`nil`) until names end (an
|
||||
/// erased reference, Undo, ATTSYNC) and make room; the names already given still hold.
|
||||
const MAX_RECORD_NAMES: usize = 65_536;
|
||||
|
||||
/// What a name given to an INSERT's ATTRIB or SEQEND stands for, while it holds.
|
||||
struct Record {
|
||||
owner: Handle,
|
||||
/// The record's place after the INSERT's own: an ATTRIB's index, or `attribs.len()` for the
|
||||
/// SEQEND.
|
||||
slot: usize,
|
||||
/// The ATTRIB's tag, which can be empty. A SEQEND has no tag.
|
||||
tag: Option<String>,
|
||||
}
|
||||
|
||||
impl Record {
|
||||
/// Whether the reference still has the same kind of record in this slot, with the same tag.
|
||||
fn holds(&self, attribs: &[cadcraft_doc::Attrib]) -> bool {
|
||||
match (attribs.get(self.slot), self.tag.as_deref()) {
|
||||
(Some(a), Some(tag)) => a.tag.eq_ignore_ascii_case(tag),
|
||||
(None, None) => self.slot == attribs.len(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The names a drawing's LISP gave to INSERTs' ATTRIBs and SEQENDs (#1660). These records have no
|
||||
/// handle of their own in the drawing, and their names are not handles ([`RecordName`]): nothing
|
||||
/// a drawing, a copy of it or another session gives out can ever be one. A name holds while its
|
||||
/// reference keeps the record in that place with that tag, in the drawing's name epoch it was
|
||||
/// given in (`DocState::expire_names`); otherwise it names nothing (`nil`), never another record.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RecordNames {
|
||||
/// Names by INSERT and then by slot. Removing an INSERT ends all its names, even after a
|
||||
/// change to the length of its attribute run.
|
||||
by_owner: HashMap<Handle, HashMap<usize, RecordName>>,
|
||||
/// What each name that still holds stands for, by its number.
|
||||
by_name: HashMap<u64, Record>,
|
||||
/// The drawing's name epoch the names were given in.
|
||||
epoch: u64,
|
||||
}
|
||||
|
||||
impl RecordNames {
|
||||
/// Forget every name once the drawing's name epoch moved on: the records they named may be
|
||||
/// gone or rebuilt.
|
||||
fn expire(&mut self, epoch: u64) {
|
||||
if self.epoch != epoch {
|
||||
self.by_owner.clear();
|
||||
self.by_name.clear();
|
||||
self.epoch = epoch;
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop the name numbered `id`: it names nothing from now on.
|
||||
fn retire(&mut self, id: u64) {
|
||||
if let Some(r) = self.by_name.remove(&id)
|
||||
&& let Some(slots) = self.by_owner.get_mut(&r.owner)
|
||||
&& slots.get(&r.slot).is_some_and(|n| n.id == id)
|
||||
{
|
||||
slots.remove(&r.slot);
|
||||
if slots.is_empty() {
|
||||
self.by_owner.remove(&r.owner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// End the names of the removed reference. Restoring it does not revive any of its names.
|
||||
pub(crate) fn erased(&mut self, e: &Entity) {
|
||||
if let Some(slots) = self.by_owner.remove(&e.handle) {
|
||||
for n in slots.into_values() {
|
||||
self.by_name.remove(&n.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many names hold now (tests).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn count(&self) -> usize {
|
||||
self.by_name.len()
|
||||
}
|
||||
|
||||
/// The INSERT and place `name` stands for in `d` now. A name that no longer holds is dropped:
|
||||
/// it names nothing from then on, also if its record comes back.
|
||||
fn lookup(&mut self, epoch: u64, d: &cadcraft_doc::Drawing, name: RecordName) -> Option<(Handle, usize)> {
|
||||
self.expire(epoch);
|
||||
let r = self.by_name.get(&name.id)?;
|
||||
let at = insert_attribs(d, r.owner).filter(|attribs| r.holds(attribs)).map(|_| (r.owner, r.slot));
|
||||
if at.is_none() {
|
||||
self.retire(name.id);
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// The name of record `slot` after INSERT `owner`'s own (its attributes, then its SEQEND),
|
||||
/// given now if it has none that holds: the same one while the record holds, so a repeated
|
||||
/// walk is stable. None past the SEQEND, at the limit of names, or when the numbers run out.
|
||||
fn name(&mut self, epoch: u64, attribs: &[cadcraft_doc::Attrib], owner: Handle, slot: usize) -> Option<RecordName> {
|
||||
self.expire(epoch);
|
||||
if let Some(n) = self.by_owner.get(&owner).and_then(|slots| slots.get(&slot)).copied() {
|
||||
if self.by_name.get(&n.id).is_some_and(|r| r.holds(attribs)) {
|
||||
return Some(n);
|
||||
}
|
||||
self.retire(n.id);
|
||||
}
|
||||
let tag = match attribs.get(slot) {
|
||||
Some(a) => Some(a.tag.clone()),
|
||||
None if slot == attribs.len() => None,
|
||||
None => return None,
|
||||
};
|
||||
if self.by_name.len() >= MAX_RECORD_NAMES {
|
||||
return None;
|
||||
}
|
||||
let name = RecordName::fresh(owner)?;
|
||||
self.by_owner.entry(owner).or_default().insert(slot, name);
|
||||
self.by_name.insert(name.id, Record { owner, slot, tag });
|
||||
Some(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The attributes of the block reference `h` in `d` (none for anything else, and for a reference
|
||||
/// with no attributes: an empty run of records is not written).
|
||||
fn insert_attribs(d: &cadcraft_doc::Drawing, h: Handle) -> Option<&[cadcraft_doc::Attrib]> {
|
||||
match d.entity(h).map(|e| &e.kind) {
|
||||
Some(cadcraft_doc::EntityKind::Insert(i)) if !i.attribs.is_empty() => Some(&i.attribs),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawing and its name epoch, without holding a borrow of the session.
|
||||
fn doc_and_epoch(ctx: &Ctx<'_>) -> Option<(Arc<cadcraft_doc::Drawing>, u64)> {
|
||||
let st = ctx.s.state().ok()?;
|
||||
Some((st.doc.clone(), st.names_epoch))
|
||||
}
|
||||
|
||||
/// The INSERT and record the name `name` stands for now (none when it no longer holds).
|
||||
fn record_of(ctx: &mut Ctx<'_>, name: RecordName) -> Option<(Handle, usize)> {
|
||||
let (d, epoch) = doc_and_epoch(ctx)?;
|
||||
ctx.s.record_names()?.lookup(epoch, &d, name)
|
||||
}
|
||||
|
||||
/// The name of record `slot` after INSERT `owner`'s own (#1660): an ATTRIB, or its SEQEND (one
|
||||
/// past the last attribute). None when it has no such record, when the host has no record
|
||||
/// mapping, or when no name is left to give.
|
||||
fn name_record(ctx: &mut Ctx<'_>, owner: Handle, slot: usize) -> Option<RecordName> {
|
||||
crate::cmd::file::entity_sub_record()?;
|
||||
let (d, epoch) = doc_and_epoch(ctx)?;
|
||||
let attribs = insert_attribs(&d, owner)?;
|
||||
ctx.s.record_names()?.name(epoch, attribs, owner, slot)
|
||||
}
|
||||
|
||||
/// An entity list: `head` (its name, type and, for an INSERT's record, its owner), then the
|
||||
/// groups of its record with the layout name after the AcDbEntity marker, as AutoCAD lists it.
|
||||
/// The layout is the one object `at` is in; without a layout of its own (an entity of a block
|
||||
/// definition) it has none.
|
||||
fn entity_list(d: &cadcraft_doc::Drawing, mut items: Vec<Value>, at: Handle, tags: &[Tag], in_block: bool) -> Value {
|
||||
let layout = match space_of(d, at) {
|
||||
Some(Space::Paper(name)) => name,
|
||||
_ => "Model".into(),
|
||||
};
|
||||
let mut placed_layout = in_block;
|
||||
for v in groups_to_list(tags) {
|
||||
// The layout name follows the AcDbEntity marker, as AutoCAD lists it.
|
||||
let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity");
|
||||
items.push(v);
|
||||
if after_marker {
|
||||
items.push(Value::cons(Value::Int(410), Value::str(&layout)));
|
||||
placed_layout = true;
|
||||
}
|
||||
}
|
||||
Value::list(items)
|
||||
}
|
||||
|
||||
/// The list of record `slot` of the reference `owner` named `name`: the DXF writer's record,
|
||||
/// its name (`-1`), type (`0`) and reference (`-2`). None when the host has no record mapping.
|
||||
fn record_list(d: &cadcraft_doc::Drawing, name: RecordName, owner: Handle, slot: usize) -> Option<(Value, Vec<Tag>)> {
|
||||
let e = d.entity(owner)?;
|
||||
let (kind, mut tags) = (crate::cmd::file::entity_sub_record()?)(d, e, slot)?;
|
||||
convert_angles(&kind, &mut tags, f64::to_radians);
|
||||
let head = vec![
|
||||
Value::cons(Value::Int(-1), Value::Record(name)),
|
||||
Value::cons(Value::Int(0), Value::str(&kind)),
|
||||
Value::cons(Value::Int(-2), Value::Ename(owner)),
|
||||
];
|
||||
Some((entity_list(d, head, owner, &tags, false), tags))
|
||||
}
|
||||
|
||||
/// `entget` of an INSERT's ATTRIB or SEQEND (#1660), while `name` names one.
|
||||
fn record_entget(ctx: &mut Ctx<'_>, name: RecordName) -> Option<Value> {
|
||||
let (owner, slot) = record_of(ctx, name)?;
|
||||
let d = ctx.s.doc().ok()?;
|
||||
record_list(d, name, owner, slot).map(|(list, _)| list)
|
||||
}
|
||||
|
||||
/// What an ATTRIB's submitted list asks to change: `Some(None)` when it asks for nothing, and
|
||||
/// `Some(Some(value))` for its value (group 1). `None` when it asks for any other edit: a group
|
||||
/// added, dropped, moved or changed other than the attribute's own value.
|
||||
fn value_edit(now: &[Tag], asked: &[Tag]) -> Option<Option<String>> {
|
||||
if now.len() != asked.len() {
|
||||
return None;
|
||||
}
|
||||
let mut value = None;
|
||||
let mut seen = false;
|
||||
for (n, a) in now.iter().zip(asked) {
|
||||
if n.code != a.code {
|
||||
return None;
|
||||
}
|
||||
if n.code == 1 {
|
||||
// A multiline attribute's embedded text has a group 1 of its own, after its marker
|
||||
// (101): only the attribute's value, before it, may differ.
|
||||
match (&n.value, &a.value) {
|
||||
(craft_dxf::Value::Str(old), craft_dxf::Value::Str(new)) if !seen => {
|
||||
seen = true;
|
||||
if old != new {
|
||||
value = Some(new.clone());
|
||||
}
|
||||
}
|
||||
_ if n == a => {}
|
||||
_ => return None,
|
||||
}
|
||||
} else if n != a {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(value)
|
||||
}
|
||||
|
||||
/// The submitted list has the items `entget` would return, in order, except at group 1 (the
|
||||
/// value): `value_edit` checks which group 1 may differ. Every other group, including the ones
|
||||
/// an entity cannot set (`-2`, `5`, `330`, `360`, `410`, `102`), must be the same.
|
||||
fn only_value_diff(expected: &Value, asked: &Value) -> bool {
|
||||
let (mut expected, mut asked) = (expected.iter(), asked.iter());
|
||||
loop {
|
||||
match (expected.next(), asked.next()) {
|
||||
(None, None) => return true,
|
||||
(Some(x), Some(y)) => {
|
||||
let code = x.car().as_number();
|
||||
if code != y.car().as_number() {
|
||||
return false;
|
||||
}
|
||||
if code != Some(1.0) && !equal(&x, &y, 0.0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `entmod` of the INSERT's record `name` stands for (#1660): only an ATTRIB's value may change,
|
||||
/// the group 1 value; its tag, place, flags and properties are the reference's. A SEQEND holds
|
||||
/// nothing to change, and a name that no longer holds names nothing: both give `nil`, the drawing
|
||||
/// as it is.
|
||||
fn entmod_attrib(ctx: &mut Ctx<'_>, list: &Value, name: RecordName) -> Value {
|
||||
let Some((owner, slot)) = record_of(ctx, name) else { return Value::Nil };
|
||||
// An outer list with an atom tail is not the list `entget` returned: iterating it would drop
|
||||
// the tail and accept the malformed list. The group pairs inside are dotted, as DXF has them.
|
||||
if !list.is_list() {
|
||||
return Value::Nil;
|
||||
}
|
||||
let Ok((kind, asked)) = list_to_groups(list) else { return Value::Nil };
|
||||
if !kind.eq_ignore_ascii_case("ATTRIB") {
|
||||
return Value::Nil;
|
||||
}
|
||||
let Ok(d) = ctx.s.doc() else { return Value::Nil };
|
||||
if crate::cmd::blocks::refedit::locked(d, owner) {
|
||||
return Value::Nil;
|
||||
}
|
||||
let Some((expected, now)) = record_list(d, name, owner, slot) else { return Value::Nil };
|
||||
// The type, layout, owner, handle and any other group are not the attribute's to change: a
|
||||
// list that differs from `entget` anywhere but its group 1 value is refused (a SEQEND's
|
||||
// list too), the drawing untouched.
|
||||
if !only_value_diff(&expected, list) {
|
||||
return Value::Nil;
|
||||
}
|
||||
match value_edit(&now, &asked) {
|
||||
None => Value::Nil,
|
||||
Some(None) => list.clone(),
|
||||
Some(Some(value)) => {
|
||||
let ok = ctx.s.doc_mut().is_ok_and(|d| {
|
||||
d.modify_entity(owner, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind
|
||||
&& let Some(a) = i.attribs.get_mut(slot)
|
||||
{
|
||||
a.text.value = value.clone();
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
});
|
||||
if ok {
|
||||
ctx.s.touch();
|
||||
}
|
||||
if ok { list.clone() } else { Value::Nil }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 2)?;
|
||||
// An INSERT's ATTRIB or SEQEND (#1660) is not an entity of the drawing: its name reaches it.
|
||||
if let Value::Record(r) = &a[0] {
|
||||
return Ok(Flow::Value(record_entget(ctx, *r).unwrap_or_default()));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
// The applications whose xdata to list: names or wildcard patterns ("*": every application).
|
||||
let apps: Option<Vec<String>> = match a.get(1) {
|
||||
None | Some(Value::Nil) => None,
|
||||
Some(v) if v.is_list() => Some(v.iter().map(|x| string(&x)).collect::<Result<_, _>>()?),
|
||||
Some(other) => return Err(LispError::bad_arg("listp", other)),
|
||||
};
|
||||
let drawn = ctx.s.doc().is_ok_and(|d| d.entity(h).is_some());
|
||||
let from_block = if drawn { None } else { block_entity(ctx, h) };
|
||||
let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
@@ -385,28 +698,161 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
(None, None) => return Ok(Flow::Value(super::objects::entget(ctx, h))),
|
||||
};
|
||||
let (kind, mut tags) = (codec()?.groups)(d, e);
|
||||
let xdata = apps.map(|apps| xdata_to_list(&e.common.xdata, &apps)).filter(|v| !v.is_nil());
|
||||
convert_angles(&kind, &mut tags, f64::to_radians);
|
||||
let layout = match space_of(d, h) {
|
||||
Some(Space::Paper(name)) => name,
|
||||
_ => "Model".into(),
|
||||
};
|
||||
let mut items = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))];
|
||||
let mut placed_layout = in_block;
|
||||
for v in groups_to_list(&tags) {
|
||||
// The layout name follows the AcDbEntity marker, as AutoCAD lists it.
|
||||
let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity");
|
||||
items.push(v);
|
||||
if after_marker {
|
||||
items.push(Value::cons(Value::Int(410), Value::str(&layout)));
|
||||
placed_layout = true;
|
||||
}
|
||||
let head = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))];
|
||||
let mut items = entity_list(d, head, h, &tags, in_block).to_vec();
|
||||
if let Some(x) = xdata {
|
||||
items.push(Value::cons(Value::Int(-3), x));
|
||||
}
|
||||
Ok(Flow::Value(Value::list(items)))
|
||||
}
|
||||
|
||||
/// The entity a list describes, as the reader makes it; a missing layer (8) is the current one.
|
||||
fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<(String, cadcraft_doc::Common, cadcraft_doc::EntityKind), LispError> {
|
||||
/// A group kept raw, typed by its code (so a 1070 lists as an integer, a 1040 as a real, and a
|
||||
/// 1071 as a real per AutoLISP's `entget`, though the file holds a 32-bit integer).
|
||||
fn typed_tag(r: &RawTag) -> Tag {
|
||||
use craft_dxf::{Kind, Value as V, kind_of};
|
||||
let v = r.value.trim();
|
||||
let value = if r.code == 1071 {
|
||||
v.parse::<i64>().ok().map(|n| V::Real(n as f64))
|
||||
} else {
|
||||
match kind_of(r.code) {
|
||||
Kind::Real => v.parse::<f64>().ok().filter(|x| x.is_finite()).map(V::Real),
|
||||
Kind::Int16 | Kind::Int32 | Kind::Int64 => v.parse::<i64>().ok().map(V::Int),
|
||||
Kind::Bool => v.parse::<i64>().ok().map(|x| V::Bool(x != 0)),
|
||||
Kind::Hex => Some(V::Hex(v.to_string())),
|
||||
Kind::Str => None,
|
||||
}
|
||||
};
|
||||
Tag::new(r.code, value.unwrap_or_else(|| V::Str(r.value.clone())))
|
||||
}
|
||||
|
||||
/// The `-3` group's value: `(("APP" (1000 . "…") (1070 . 3) (1010 x y z) …) …)` for the
|
||||
/// applications of `xdata` matching one of `patterns` (any case; `wcmatch` wildcards).
|
||||
fn xdata_to_list(xdata: &[RawTag], patterns: &[String]) -> Value {
|
||||
let patterns: Vec<String> = patterns.iter().map(|p| p.trim().to_ascii_uppercase()).collect();
|
||||
// A file may hold several runs of one application, `ACME` and `acme` among them; they are
|
||||
// one application to `set_xdata_app`, so they are one list here (first spelling, all the
|
||||
// groups), or `(entmod (entget e '("*")))` would keep only the last run.
|
||||
let mut apps: Vec<(&str, Vec<RawTag>)> = Vec::new();
|
||||
for (name, groups) in cadcraft_doc::xdata_apps(xdata) {
|
||||
let up = name.to_ascii_uppercase();
|
||||
if !patterns.iter().any(|p| super::builtins::wild_match(&up, p)) {
|
||||
continue;
|
||||
}
|
||||
match apps.iter_mut().find(|(app, _)| app.eq_ignore_ascii_case(name)) {
|
||||
Some((_, all)) => all.extend_from_slice(groups),
|
||||
None => apps.push((name, groups.to_vec())),
|
||||
}
|
||||
}
|
||||
let lists: Vec<Value> = apps
|
||||
.into_iter()
|
||||
.map(|(name, groups)| {
|
||||
let tags: Vec<Tag> = groups.iter().map(typed_tag).collect();
|
||||
Value::list_with_tail(vec![Value::str(name)], Value::list(groups_to_list(&tags)))
|
||||
})
|
||||
.collect();
|
||||
Value::list(lists)
|
||||
}
|
||||
|
||||
/// The applications of a list's `-3` group, each with its groups (checked as xdata): `None`
|
||||
/// when the list has no `-3`. An application with no groups removes its data in `entmod`.
|
||||
fn xdata_from_list(list: &Value) -> Result<Option<Vec<(String, Vec<RawTag>)>>, LispError> {
|
||||
let Some(x) = list.iter().find(|v| v.car().as_number() == Some(-3.0)).map(|v| v.cdr()) else { return Ok(None) };
|
||||
// `(-3 . 7)` is not a list of applications: refused, not read as "no applications".
|
||||
if !x.is_list() {
|
||||
return Err(LispError::bad_arg("listp", &x));
|
||||
}
|
||||
let bad = |what: &str| LispError::new(format!("bad DXF group: {what}"));
|
||||
let mut out = Vec::new();
|
||||
for app in x.iter() {
|
||||
let name = match app.car() {
|
||||
Value::Str(s) => s.to_string(),
|
||||
other => return Err(LispError::bad_arg("stringp", &other)),
|
||||
};
|
||||
cadcraft_doc::check_xdata_app_name(&name).map_err(|e| bad(&e.to_string()))?;
|
||||
if cadcraft_doc::is_reserved_xdata_app(&name) {
|
||||
return Err(bad(&format!("xdata application {name} is reserved")));
|
||||
}
|
||||
// The application's groups must be a proper list too: `("ACME" . 7)` would otherwise
|
||||
// read as "no groups" and remove the data in `entmod`, and a dotted tail after real
|
||||
// groups would be dropped.
|
||||
let tail = app.cdr();
|
||||
if !tail.is_list() {
|
||||
return Err(LispError::bad_arg("listp", &tail));
|
||||
}
|
||||
let mut groups: Vec<RawTag> = Vec::new();
|
||||
for g in tail.iter() {
|
||||
if groups.len() >= cadcraft_doc::MAX_XDATA_GROUPS {
|
||||
return Err(bad("too many xdata groups"));
|
||||
}
|
||||
let Value::Cons(c) = &g else { return Err(LispError::bad_arg("consp", &g)) };
|
||||
let Value::Int(code) = c.car else { return Err(LispError::bad_arg("fixnump", &c.car)) };
|
||||
match &c.cdr {
|
||||
Value::Cons(_) if (1010..=1013).contains(&code) => {
|
||||
let p = c.cdr.as_point().ok_or_else(|| LispError::bad_arg("3D point", &c.cdr))?;
|
||||
if p.iter().any(|v| !v.is_finite()) {
|
||||
return Err(bad("xdata point must be finite"));
|
||||
}
|
||||
groups.push(RawTag { code, value: craft_dxf::format_real(p[0]) });
|
||||
groups.push(RawTag { code: code + 10, value: craft_dxf::format_real(p[1]) });
|
||||
groups.push(RawTag { code: code + 20, value: craft_dxf::format_real(p[2]) });
|
||||
}
|
||||
Value::Int(i) => groups.push(RawTag { code, value: i.to_string() }),
|
||||
Value::Real(r) if code == 1071 => {
|
||||
if r.is_finite() && r.fract() == 0.0 && *r >= f64::from(i32::MIN) && *r <= f64::from(i32::MAX) {
|
||||
groups.push(RawTag { code, value: (*r as i32).to_string() });
|
||||
} else {
|
||||
return Err(bad("group 1071 must be a 32-bit integer"));
|
||||
}
|
||||
}
|
||||
Value::Real(r) => groups.push(RawTag { code, value: craft_dxf::format_real(*r) }),
|
||||
Value::Str(s) => groups.push(RawTag { code, value: s.to_string() }),
|
||||
Value::Ename(h) => groups.push(RawTag { code, value: h.hex() }),
|
||||
other => return Err(LispError::bad_arg("DXF group value", other)),
|
||||
}
|
||||
}
|
||||
cadcraft_doc::check_xdata_groups(&groups).map_err(|e| bad(&e.to_string()))?;
|
||||
out.push((name, groups));
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// `(regapp "name")`: register an application for xdata. The name when it is new, nil when it
|
||||
/// is already registered (by `regapp` or by xdata an object carries) or invalid. Saving writes
|
||||
/// an APPID record for every application with xdata, so nothing else is needed.
|
||||
pub fn regapp(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
let name = string(&a[0])?;
|
||||
if cadcraft_doc::check_xdata_app_name(&name).is_err() {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let up = name.trim().to_ascii_uppercase();
|
||||
let known = ctx.env.regapps.contains(&up) || ctx.s.doc().is_ok_and(|d| xdata_app_names(d).contains(&up));
|
||||
if known {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
ctx.env.regapps.insert(up);
|
||||
Ok(Flow::Value(Value::str(name.trim())))
|
||||
}
|
||||
|
||||
/// The upper-case names of every application registered in the drawing or carrying xdata on an object.
|
||||
fn xdata_app_names(d: &cadcraft_doc::Drawing) -> std::collections::BTreeSet<String> {
|
||||
std::iter::once(&d.model)
|
||||
.chain(d.layouts.iter().map(|l| &l.entities))
|
||||
.chain(d.blocks.values().map(|b| &b.entities))
|
||||
.flat_map(|s| s.iter())
|
||||
.flat_map(|e| cadcraft_doc::xdata_apps(&e.common.xdata).into_iter().map(|(n, _)| n.to_ascii_uppercase()).collect::<Vec<_>>())
|
||||
.chain(d.foreign.appids.iter().map(|n| n.to_ascii_uppercase()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The entity a list describes, as the reader makes it, with the applications of its `-3`
|
||||
/// group (their xdata is on the entity); a missing layer (8) is the current one.
|
||||
type ListedEntity = (String, cadcraft_doc::Common, cadcraft_doc::EntityKind, Option<Vec<(String, Vec<RawTag>)>>);
|
||||
fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<ListedEntity, LispError> {
|
||||
let (kind, mut tags) = list_to_groups(list)?;
|
||||
let xdata = xdata_from_list(list)?;
|
||||
convert_angles(&kind, &mut tags, f64::to_degrees);
|
||||
if !tags.iter().any(|t| t.code == 8) {
|
||||
let layer = crate::sysvars::get(ctx.s, "CLAYER").and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "0".into());
|
||||
@@ -415,7 +861,23 @@ fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<(String, cadcraft_doc
|
||||
match (codec()?.entity)(&kind, &tags) {
|
||||
// A type the reader only carries through (an unknown or invalid name) isn't made.
|
||||
Some((_, cadcraft_doc::EntityKind::Unknown(_))) | None => Err(LispError::new(format!("bad DXF group: {kind} can't be made from this list"))),
|
||||
Some((common, k)) => Ok((kind, common, k)),
|
||||
Some((mut common, k)) => {
|
||||
if let Some(apps) = &xdata {
|
||||
for (app, groups) in apps {
|
||||
// `ACAD` on a dimension holds its overrides (DSTYLE), written from the model.
|
||||
if cadcraft_doc::is_model_xdata_app(app, &k) {
|
||||
return Err(LispError::new(format!("bad DXF group: xdata application {app} of a {kind} is written from its own properties")));
|
||||
}
|
||||
cadcraft_doc::set_xdata_app(&mut common.xdata, app, Some(groups));
|
||||
}
|
||||
// Each application's groups are checked one by one above; together they must
|
||||
// still fit what a file holds for one object.
|
||||
if common.xdata.len() > cadcraft_doc::MAX_XDATA_GROUPS {
|
||||
return Err(LispError::new("bad DXF group: too many xdata groups"));
|
||||
}
|
||||
}
|
||||
Ok((kind, common, k, xdata))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -428,7 +890,7 @@ pub fn entmake(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
Ok((k, _)) if k == "ENDBLK" => return Ok(Flow::Value(end_block(ctx))),
|
||||
_ => {}
|
||||
}
|
||||
let (_, common, kind) = match entity_from_list(ctx, list) {
|
||||
let (_, common, kind, _) = match entity_from_list(ctx, list) {
|
||||
Ok(x) => x,
|
||||
Err(_) => return Ok(Flow::Value(Value::Nil)),
|
||||
};
|
||||
@@ -527,11 +989,16 @@ fn end_block(ctx: &mut Ctx<'_>) -> Value {
|
||||
pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
let list = &a[0];
|
||||
let Some(Value::Ename(h)) = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr()) else {
|
||||
let name = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr());
|
||||
// An INSERT's record takes a value edit only (#1660); any other edit of one is refused.
|
||||
if let Some(Value::Record(r)) = name {
|
||||
return Ok(Flow::Value(entmod_attrib(ctx, list, r)));
|
||||
}
|
||||
let Some(Value::Ename(h)) = name else {
|
||||
return Err(LispError::bad_arg("lentityp", &Value::Nil));
|
||||
};
|
||||
let Some(old) = ctx.s.doc().ok().and_then(|d| d.entity(h)).cloned() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let (kind_name, common, mut kind) = match entity_from_list(ctx, list) {
|
||||
let (kind_name, mut common, mut kind, xdata) = match entity_from_list(ctx, list) {
|
||||
Ok(x) => x,
|
||||
Err(_) => return Ok(Flow::Value(Value::Nil)),
|
||||
};
|
||||
@@ -539,6 +1006,17 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
if !kind_name.eq_ignore_ascii_case(old.kind.dxf_name()) {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
// Xdata stays unless the list has a -3 group, which replaces the data of the applications it
|
||||
// names (one with no groups removes it) and leaves the others alone, as in AutoCAD.
|
||||
common.xdata = old.common.xdata.clone();
|
||||
if let Some(apps) = &xdata {
|
||||
for (app, groups) in apps {
|
||||
cadcraft_doc::set_xdata_app(&mut common.xdata, app, Some(groups));
|
||||
}
|
||||
if common.xdata.len() > cadcraft_doc::MAX_XDATA_GROUPS {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
}
|
||||
// A block reference's attributes are entities of their own in AutoCAD, which entmod of the
|
||||
// INSERT leaves alone; its list doesn't hold them, so they are kept from the reference.
|
||||
if let (cadcraft_doc::EntityKind::Insert(new), cadcraft_doc::EntityKind::Insert(was)) = (&mut kind, &old.kind)
|
||||
@@ -560,9 +1038,15 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
Ok(Flow::Value(if ok { list.clone() } else { Value::Nil }))
|
||||
}
|
||||
|
||||
/// `(entupd ename)`: redraw an entity (the canvas redraws on its own).
|
||||
/// `(entupd ename)`: redraw an entity (the canvas redraws on its own). For an INSERT's record
|
||||
/// (#1660) its reference: the record's name while it holds.
|
||||
pub fn entupd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
if let Value::Record(r) = &a[0] {
|
||||
let holds = record_of(ctx, *r).is_some();
|
||||
ctx.s.touch();
|
||||
return Ok(Flow::Value(if holds { a[0].clone() } else { Value::Nil }));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
ctx.s.touch();
|
||||
Ok(Flow::Value(if ctx.s.doc().is_ok_and(|d| d.entity(h).is_some()) { Value::Ename(h) } else { Value::Nil }))
|
||||
@@ -571,10 +1055,18 @@ pub fn entupd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
/// `(entdel ename)`: delete an entity, or bring back one this routine's drawing deleted.
|
||||
pub fn entdel(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
// An INSERT's ATTRIB or SEQEND is the reference's: it is not deleted on its own (#1660).
|
||||
if matches!(a[0], Value::Record(_)) {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
let Ok(d) = ctx.s.doc_mut() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
if let Some(space) = d.space_of(h) {
|
||||
if let Some(e) = d.remove_entity(h) {
|
||||
// The names of its records went with it: `entdel` bringing it back brings none back.
|
||||
if let Some(names) = ctx.s.record_names() {
|
||||
names.erased(&e);
|
||||
}
|
||||
ctx.env.deleted.insert(h, (space, e));
|
||||
ctx.s.touch();
|
||||
return Ok(Flow::Value(Value::Ename(h)));
|
||||
@@ -670,24 +1162,41 @@ pub fn entlast(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
|
||||
pub fn entnext(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 0, 1)?;
|
||||
// From an entity of a block definition: the next one in that block, nil after the last (#1700).
|
||||
if let Some(v) = a.first().filter(|v| !v.is_nil()) {
|
||||
let h = ename(v)?;
|
||||
if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none())
|
||||
&& let Some((_, next)) = block_slots(ctx).get(&h)
|
||||
{
|
||||
return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()));
|
||||
let after = match a.first() {
|
||||
None | Some(Value::Nil) => None,
|
||||
// From a record of an INSERT (#1660): the next record of its run, and after its SEQEND the
|
||||
// next main entity after the INSERT. A name that no longer holds names nothing.
|
||||
Some(Value::Record(r)) => {
|
||||
let Some((owner, slot)) = record_of(ctx, *r) else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let attribs = ctx.s.doc().ok().and_then(|d| insert_attribs(d, owner)).map_or(0, <[cadcraft_doc::Attrib]>::len);
|
||||
if slot < attribs {
|
||||
return Ok(Flow::Value(name_record(ctx, owner, slot.saturating_add(1)).map(Value::Record).unwrap_or_default()));
|
||||
}
|
||||
Some(owner)
|
||||
}
|
||||
}
|
||||
let order = handles_in_order(ctx);
|
||||
let next = match a.first() {
|
||||
None | Some(Value::Nil) => order.first().copied(),
|
||||
Some(v) => {
|
||||
let h = ename(v)?;
|
||||
let i = order.partition_point(|x| *x <= h);
|
||||
order.get(i).copied()
|
||||
// From an entity of a block definition: the next one in that block, nil after the last (#1700).
|
||||
if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none())
|
||||
&& let Some((_, next)) = block_slots(ctx).get(&h)
|
||||
{
|
||||
return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()));
|
||||
}
|
||||
// An INSERT with attributes is followed by its ATTRIBs and its SEQEND (#1660): its
|
||||
// first ATTRIB, or nil when no name is left to give (the walk stops rather than skip
|
||||
// records it can't name). A host without the optional record mapping has no such
|
||||
// records: the walk goes on to the next entity, as it always did.
|
||||
if crate::cmd::file::entity_sub_record().is_some() && ctx.s.doc().is_ok_and(|d| insert_attribs(d, h).is_some()) {
|
||||
return Ok(Flow::Value(name_record(ctx, h, 0).map(Value::Record).unwrap_or_default()));
|
||||
}
|
||||
Some(h)
|
||||
}
|
||||
};
|
||||
let order = handles_in_order(ctx);
|
||||
let next = match after {
|
||||
Some(h) => order.get(order.partition_point(|x| *x <= h)).copied(),
|
||||
None => order.first().copied(),
|
||||
};
|
||||
Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()))
|
||||
}
|
||||
|
||||
@@ -969,6 +1478,13 @@ fn compare(h: f64, w: f64, op: &str) -> bool {
|
||||
|
||||
pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 0, 2)?;
|
||||
// A selection set holds objects of the drawing; an INSERT's record (#1660) is not one.
|
||||
if matches!(a.first(), Some(Value::Record(_))) {
|
||||
if let Some(ss) = a.get(1) {
|
||||
pickset(ss)?;
|
||||
}
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
match (a.first(), a.get(1)) {
|
||||
(None, _) => Ok(Flow::Value(new_pickset(ctx, Vec::new()))),
|
||||
(Some(e), None) => {
|
||||
@@ -990,6 +1506,11 @@ pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
|
||||
pub fn ssdel(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
// Never in a selection set (#1660).
|
||||
if matches!(a[0], Value::Record(_)) {
|
||||
pickset(&a[1])?;
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
let p = pickset(&a[1])?;
|
||||
let removed = p.items.lock().map(|mut v| {
|
||||
@@ -1017,6 +1538,11 @@ pub fn ssname(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
|
||||
pub fn ssmemb(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
// Never in a selection set (#1660).
|
||||
if matches!(a[0], Value::Record(_)) {
|
||||
pickset(&a[1])?;
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
Ok(Flow::Value(if items(&pickset(&a[1])?).contains(&h) { Value::Ename(h) } else { Value::Nil }))
|
||||
}
|
||||
@@ -1116,11 +1642,27 @@ fn table_records(d: &cadcraft_doc::Drawing, table: &str) -> Vec<Value> {
|
||||
.iter()
|
||||
.map(|s| Value::list(vec![pair(0, Value::str("DIMSTYLE")), pair(2, Value::str(&s.name)), pair(70, Value::Int(0))]))
|
||||
.collect(),
|
||||
"APPID" => vec![Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str("ACAD")), pair(70, Value::Int(0))])],
|
||||
"APPID" => std::iter::once("ACAD".to_string())
|
||||
.chain(xdata_app_names(d).into_iter().filter(|n| n != "ACAD"))
|
||||
.map(|n| Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str(&n)), pair(70, Value::Int(0))]))
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`table_records`] plus, for APPID, the applications `regapp` registered in this session.
|
||||
fn table_records_with(ctx: &Ctx<'_>, d: &cadcraft_doc::Drawing, table: &str) -> Vec<Value> {
|
||||
let mut records = table_records(d, table);
|
||||
if table == "APPID" {
|
||||
let have: Vec<String> = records.iter().map(record_name).map(|n| n.to_ascii_uppercase()).collect();
|
||||
for app in ctx.env.regapps.iter().filter(|a| !have.contains(a)) {
|
||||
let pair = |c: i32, v: Value| Value::cons(Value::Int(c), v);
|
||||
records.push(Value::list(vec![pair(0, Value::str("APPID")), pair(2, Value::str(app)), pair(70, Value::Int(0))]));
|
||||
}
|
||||
}
|
||||
records
|
||||
}
|
||||
|
||||
fn record_name(r: &Value) -> String {
|
||||
r.iter().find(|p| p.car().as_number() == Some(2.0)).map(|p| to_text(&p.cdr(), false)).unwrap_or_default()
|
||||
}
|
||||
@@ -1130,7 +1672,7 @@ pub fn tblsearch(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
let table = string(&a[0])?.to_ascii_uppercase();
|
||||
let name = string(&a[1])?;
|
||||
let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let records = table_records(d, &table);
|
||||
let records = table_records_with(ctx, d, &table);
|
||||
let found = records.iter().position(|r| record_name(r).eq_ignore_ascii_case(&name));
|
||||
if let Some(i) = found
|
||||
&& a.get(2).is_some_and(|v| !v.is_nil())
|
||||
@@ -1145,7 +1687,7 @@ pub fn tblnext(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
let table = string(&a[0])?.to_ascii_uppercase();
|
||||
let rewind = a.get(1).is_some_and(|v| !v.is_nil());
|
||||
let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let records = table_records(d, &table);
|
||||
let records = table_records_with(ctx, d, &table);
|
||||
let i = if rewind { 0 } else { ctx.env.tblnext.get(&table).copied().unwrap_or(0) };
|
||||
ctx.env.tblnext.insert(table, i + 1);
|
||||
Ok(Flow::Value(records.get(i).cloned().unwrap_or_default()))
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use cadcraft_doc::Handle;
|
||||
use serde_json::json;
|
||||
|
||||
use super::value::{Value, to_text};
|
||||
use crate::Session;
|
||||
use crate::cmd::file::{EntityCodec, set_entity_codec, set_object_records};
|
||||
use crate::cmd::file::{EntityCodec, set_entity_codec, set_entity_sub_record, set_object_records};
|
||||
|
||||
pub(super) fn session() -> Session {
|
||||
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
set_object_records(cadcraft_io::object_records);
|
||||
Session::new()
|
||||
@@ -666,6 +671,154 @@ fn handseed_follows_new_objects() {
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 5 (entget (entlast))))"), format!("\"{:X}\"", held + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entity_lists_carry_xdata_in_group_minus_3() {
|
||||
let mut s = session();
|
||||
// entmake with a -3 group puts the xdata on the new entity; entget shows it only when asked.
|
||||
let made = ok(
|
||||
&mut s,
|
||||
"(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACME\" (1000 . \"D-07\") (1070 . 3) (1040 . 2.5) (1010 1.0 2.0 0.0) (1005 . \"2A\") (1071 . 100000)) (\"PE_URL\" (1000 . \"https://example.com\")))))",
|
||||
);
|
||||
assert!(made.contains("LINE"));
|
||||
assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast)))"), "nil");
|
||||
assert_eq!(
|
||||
ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"acme\"))))"),
|
||||
"((\"ACME\" (1000 . \"D-07\") (1070 . 3) (1040 . 2.5) (1010 1.0 2.0 0.0) (1005 . \"2A\") (1071 . 100000.0)))"
|
||||
);
|
||||
// Group 1070 is INT, whereas group 1071 is REAL in AutoLISP's entget while remaining a 32-bit
|
||||
// integer in the drawing/API and when written back with entmod.
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
"(setq g (cdr (car (cdr (assoc -3 (entget (entlast) '(\"ACME\"))))))) (list (type (cdr (assoc 1070 g))) (type (cdr (assoc 1071 g))))"
|
||||
),
|
||||
"(INT REAL)"
|
||||
);
|
||||
assert!(ok(&mut s, "(entmod (entget (entlast) '(\"ACME\")))").contains("LINE"));
|
||||
assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2");
|
||||
assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"PE_*\" \"nope\")))))"), "1");
|
||||
assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast) '(\"nope\")))"), "nil");
|
||||
// The xdata is what the drawing holds (the API sees 1070 and 1071 as integers too).
|
||||
let x = s.execute("entities", &serde_json::json!({"xdata": "ACME"})).unwrap();
|
||||
assert_eq!(x["entities"][0]["xdata"]["ACME"][1], serde_json::json!([1070, 3]));
|
||||
assert_eq!(x["entities"][0]["xdata"]["ACME"][5], serde_json::json!([1071, 100000]));
|
||||
// entmod without -3 keeps the xdata; with -3 it replaces the named applications' data and
|
||||
// removes one listed without groups; the others stay.
|
||||
ok(&mut s, "(setq d (entget (entlast))) (entmod (subst (cons 8 \"WALLS\") (assoc 8 d) d))");
|
||||
assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2");
|
||||
ok(&mut s, "(entmod (append (entget (entlast)) (list (list -3 (list \"ACME\" (cons 1070 9))))))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACME\"))))"), "((\"ACME\" (1070 . 9)))");
|
||||
assert_eq!(ok(&mut s, "(length (cdr (assoc -3 (entget (entlast) '(\"*\")))))"), "2");
|
||||
ok(&mut s, "(entmod (append (entget (entlast)) '((-3 (\"PE_URL\")))))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))");
|
||||
// Bad xdata is refused as a bad list (nil), and nothing changes.
|
||||
for bad in [
|
||||
"(-3 (\"ACME\" (1002 . \"{\")))",
|
||||
"(-3 (\"ACME\" (8 . \"0\")))",
|
||||
"(-3 (\"ACME\" (1070 . 70000)))",
|
||||
"(-3 (\"ACME\" (1071 . 1.5)))",
|
||||
"(-3 (\"ACME\" (1071 . 2147483648.0)))",
|
||||
"(-3 (\"ACME\" (1071 . -2147483649.0)))",
|
||||
"(-3 (\"ACME\" (1010 1.0)))",
|
||||
"(-3 (\"CADCRAFT\" (1000 . \"x\")))",
|
||||
"(-3 (\"\" (1000 . \"x\")))",
|
||||
"(-3 (7 (1000 . \"x\")))",
|
||||
"(-3 (\"ACME\" 5))",
|
||||
] {
|
||||
assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '({bad})))")), "nil", "{bad}");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))", "{bad}");
|
||||
}
|
||||
assert!(eval(&mut s, "(entget (entlast) \"ACME\")").is_err(), "the second argument is a list");
|
||||
// regapp: the name when new, nil once registered (by regapp or by xdata an object carries);
|
||||
// the APPID table lists both.
|
||||
assert_eq!(ok(&mut s, "(regapp \"ACME\")"), "nil");
|
||||
assert_eq!(ok(&mut s, "(regapp \"MYAPP\")"), "\"MYAPP\"");
|
||||
assert_eq!(ok(&mut s, "(regapp \"myapp\")"), "nil");
|
||||
assert_eq!(ok(&mut s, "(regapp \"bad*name\")"), "nil");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (tblsearch \"APPID\" \"acme\")))"), "\"ACME\"");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (tblsearch \"APPID\" \"MYAPP\")))"), "\"MYAPP\"");
|
||||
assert_eq!(ok(&mut s, "(tblsearch \"APPID\" \"PE_URL\")"), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_1071_boundary_reals_round_trip_as_32bit_integers() {
|
||||
let mut s = session();
|
||||
let made =
|
||||
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"LIMITS\" (1071 . 2147483647.0) (1071 . -2147483648.0) (1071 . -0.0)))))");
|
||||
assert!(made.contains("LINE"));
|
||||
assert_eq!(ok(&mut s, "(type (cdr (assoc 1071 (cdr (car (cdr (assoc -3 (entget (entlast) '(\"LIMITS\")))))))))"), "REAL");
|
||||
assert!(ok(&mut s, "(entmod (entget (entlast) '(\"LIMITS\")))").contains("LINE"));
|
||||
let lim = s.execute("entities", &serde_json::json!({"xdata": "LIMITS"})).unwrap();
|
||||
assert_eq!(lim["entities"][0]["xdata"]["LIMITS"], serde_json::json!([[1071, 2147483647], [1071, -2147483648], [1071, 0]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entmake_refuses_xdata_over_the_object_limit_across_applications() {
|
||||
// Each application's groups fit the per-application cap; together they exceed what an object
|
||||
// may hold, so the list is refused (nil) and nothing is made.
|
||||
let mut s = session();
|
||||
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0)))");
|
||||
let last = ok(&mut s, "(entlast)");
|
||||
let groups = "(1000 . \"x\") ".repeat(cadcraft_doc::MAX_XDATA_GROUPS / 2 + 8);
|
||||
let code = format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 (\"A1\" {groups}) (\"A2\" {groups}))))");
|
||||
assert_eq!(ok(&mut s, &code), "nil");
|
||||
assert_eq!(ok(&mut s, "(entlast)"), last, "nothing was made");
|
||||
// Half of that on one application is within the limit and is made.
|
||||
let code = format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 (\"A1\" {groups}))))");
|
||||
assert!(ok(&mut s, &code).contains("LINE"));
|
||||
assert_ne!(ok(&mut s, "(entlast)"), last);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dotted_minus_3_group_is_refused() {
|
||||
// `(-3 . 7)` names no applications; it is a bad list (nil), not an empty one.
|
||||
let mut s = session();
|
||||
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACME\" (1070 . 9)))))");
|
||||
let last = ok(&mut s, "(entlast)");
|
||||
assert_eq!(ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 . 7)))"), "nil");
|
||||
assert_eq!(ok(&mut s, "(entlast)"), last, "nothing was made");
|
||||
assert_eq!(ok(&mut s, "(entmod (append (entget (entlast)) '((-3 . 7))))"), "nil");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))");
|
||||
// The same one level down: an application whose groups are not a proper list is refused,
|
||||
// not read as "no groups" (which would remove its data), and a dotted tail after real
|
||||
// groups is not dropped.
|
||||
for bad in ["(\"ACME\" . 7)", "(\"ACME\" (1070 . 1) . 5)", "(\"NEW\" . \"x\")"] {
|
||||
assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '((-3 {bad}))))")), "nil", "{bad}");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), "((\"ACME\" (1070 . 9)))", "{bad}");
|
||||
assert_eq!(ok(&mut s, &format!("(entmake '((0 . \"LINE\") (10 0 0 0) (11 9 0 0) (-3 {bad})))")), "nil", "{bad}");
|
||||
assert_eq!(ok(&mut s, "(entlast)"), last, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_of_one_application_in_any_case_are_one_list() {
|
||||
// A file with `ACME` and `acme` runs on one entity: entget shows one application with every
|
||||
// group, and writing that list back with entmod keeps them all.
|
||||
let dxf = "0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n2A\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\
|
||||
1001\nACME\n1070\n1\n1001\nacme\n1070\n2\n1001\nOTHER\n1000\nx\n0\nENDSEC\n0\nEOF\n";
|
||||
let mut s = session();
|
||||
s.open_drawing(cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(), "runs", None);
|
||||
let want = "((\"ACME\" (1070 . 1) (1070 . 2)) (\"OTHER\" (1000 . \"x\")))";
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), want);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"acme\"))))"), "((\"ACME\" (1070 . 1) (1070 . 2)))");
|
||||
assert!(ok(&mut s, "(entmod (entget (entlast) '(\"*\")))").contains("LINE"));
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"*\"))))"), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acad_xdata_of_a_dimension_is_refused_but_kept_on_other_entities() {
|
||||
// A dimension's ACAD run is its DSTYLE overrides, written from the model: raw ACAD groups
|
||||
// on it are refused (nil, nothing changes). On a line, ACAD is foreign data and stays.
|
||||
let mut s = session();
|
||||
s.script("dimlinear 0,0 10,0 5,-3\n").unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entlast))))"), "\"DIMENSION\"");
|
||||
assert_eq!(ok(&mut s, "(entmod (append (entget (entlast)) '((-3 (\"ACAD\" (1070 . 1))))))"), "nil");
|
||||
assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast) '(\"*\")))"), "nil");
|
||||
let made = ok(&mut s, "(entmake '((0 . \"LINE\") (10 0 0 0) (11 5 0 0) (-3 (\"ACAD\" (1000 . \"MINE\") (1070 . 42)))))");
|
||||
assert!(made.contains("LINE"));
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACAD\"))))"), "((\"ACAD\" (1000 . \"MINE\") (1070 . 42)))");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entity_lists_hold_angles_in_radians() {
|
||||
let mut s = session();
|
||||
@@ -1818,3 +1971,704 @@ fn append_checks_the_cell_cap_before_building_its_result() {
|
||||
assert!(super::value::live_cells() < before + 50_000, "no oversized result was built");
|
||||
assert_eq!(ok(&mut s, "(setq l nil m nil) (length (append '(1) '(2 3)))"), "3");
|
||||
}
|
||||
|
||||
// ---------------- an INSERT's ATTRIBs and SEQEND (#1660) ----------------
|
||||
|
||||
/// A session with block K: a circle and attributes (tag, DXF flags, default value). `entmake`
|
||||
/// goes through the DXF codec, as in the app.
|
||||
fn with_attributes(defs: &[(&str, i32, &str)]) -> Session {
|
||||
let mut s = session();
|
||||
let mut code =
|
||||
String::from("(entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 3.0)))");
|
||||
for (i, (tag, flags, default)) in defs.iter().enumerate() {
|
||||
let y = 5.0 + 3.0 * i as f64;
|
||||
code += &format!(
|
||||
" (entmake '((0 . \"ATTDEF\") (10 0.0 {y:.1} 0.0) (40 . 2.5) (1 . \"{default}\") (3 . \"P{tag}\") (2 . \"{tag}\") (70 . {flags})))"
|
||||
);
|
||||
}
|
||||
code += " (entmake '((0 . \"ENDBLK\")))";
|
||||
s.cmdline(&format!("(progn {code})")).unwrap();
|
||||
s.log.clear();
|
||||
s
|
||||
}
|
||||
|
||||
/// `s` with one reference of K at (10,10), its values `attribs`, and the reference's handle; the
|
||||
/// LISP global `i` names it.
|
||||
fn inserted(s: &mut Session, attribs: serde_json::Value) -> Handle {
|
||||
s.execute("insert", &json!({ "name": "K", "at": [10, 10], "attribs": attribs })).unwrap();
|
||||
let h = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
ok(s, &format!("(setq i (handent \"{}\")) i", h.hex()));
|
||||
h
|
||||
}
|
||||
|
||||
/// Every reference's attributes (tag, value) from the model, in order.
|
||||
fn attribute_values(s: &Session) -> Vec<(String, String)> {
|
||||
let d = s.doc().unwrap();
|
||||
d.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect::<Vec<_>>()),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The records from `i` in order: (type, tag, value) and the SEQEND's owner.
|
||||
const WALK: &str = r#"(progn
|
||||
(setq e (entnext i) out nil)
|
||||
(while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e))))))
|
||||
(setq out (append out (list (list (cdr (assoc 0 ed)) (cdr (assoc 2 ed)) (cdr (assoc 1 ed))
|
||||
(if (equal (cdr (assoc -2 ed)) i) T nil))))
|
||||
e (entnext e)))
|
||||
(list out (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i)))"#;
|
||||
|
||||
#[test]
|
||||
fn entnext_walks_an_inserts_attribs_then_the_seqend_then_the_next_entity() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2"), ("T3", 0, "D3")]);
|
||||
inserted(&mut s, json!({ "T1": "A1", "T3": "A3" }));
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget i)))"), "\"INSERT\"");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 66 (entget i)))"), "1");
|
||||
assert_eq!(ok(&mut s, WALK), "(((\"ATTRIB\" \"T1\" \"A1\" T) (\"ATTRIB\" \"T2\" \"P2\" T) (\"ATTRIB\" \"T3\" \"A3\" T)) \"SEQEND\" T)");
|
||||
// After the SEQEND the main order goes on: a line made later is next, then nil.
|
||||
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entnext (entnext (entnext (entnext (entnext i))))))))"), "\"LINE\"");
|
||||
assert_eq!(ok(&mut s, "(entnext (entlast))"), "nil");
|
||||
// A reference of a block without attributes is followed by the next main entity, no SEQEND.
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
s.cmdline("(progn (entmake '((0 . \"BLOCK\") (2 . \"E\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (entmake '((0 . \"ENDBLK\"))))").unwrap();
|
||||
s.execute("insert", &json!({ "name": "E", "at": [0, 0] })).unwrap();
|
||||
let plain = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap();
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 0 (entget (entnext (handent \"{}\")))))", plain.hex())), "\"LINE\"");
|
||||
// The owner is group -2 in a record's list and not 330, and the reference's own list has
|
||||
// neither (as `entity_groups` keeps it).
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
assert_eq!(ok(&mut s, "(assoc 330 (entget (entnext i)))"), "nil");
|
||||
assert!(attribute_values(&s).iter().any(|(t, v)| t == "T1" && v == "A1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entmod_of_an_attrib_changes_only_its_value() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a) seq (entnext (entnext a)))");
|
||||
// The value (group 1) is the one edit an ATTRIB's list takes.
|
||||
let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
|
||||
assert!(r.contains("(1 . \"A2\")"), "{r}");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\"");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]);
|
||||
// A list asking for anything else, and any edit of the SEQEND, is refused and changes nothing.
|
||||
for code in [
|
||||
"(entmod (subst (cons 2 \"X\") (assoc 2 d) d))",
|
||||
"(entmod (subst (cons 40 9.0) (assoc 40 d) d))",
|
||||
"(entmod (subst (cons 8 \"L\") (assoc 8 d) d))",
|
||||
"(entmod (subst (cons 0 \"SEQEND\") (assoc 0 d) d))",
|
||||
"(entmod (entget seq))",
|
||||
// Groups `list_to_groups` does not keep are still the reference's: an edit (or an added
|
||||
// group) is refused, also when the same list changes group 1.
|
||||
"(entmod (subst (cons 410 \"Layout2\") (assoc 410 d) d))",
|
||||
"(entmod (subst (cons -2 a) (assoc -2 d) d))",
|
||||
"(entmod (append d (list (cons 5 \"FF\"))))",
|
||||
"(entmod (append d (list (cons 330 a))))",
|
||||
"(entmod (append d (list (cons 360 \"FF\"))))",
|
||||
"(entmod (append d (list (cons 102 \"{X\"))))",
|
||||
"(entmod (subst (cons 1 \"A2\") (assoc 1 d) (subst (cons 410 \"Layout2\") (assoc 410 d) d)))",
|
||||
// The same items, but the outer list ends in an atom: iterating it would drop the tail
|
||||
// and accept a list `entget` never returned.
|
||||
"(progn (setq r \"X\" p (reverse d)) (while p (setq r (cons (car p) r) p (cdr p))) (entmod r))",
|
||||
] {
|
||||
assert_eq!(ok(&mut s, code), "nil", "{code}");
|
||||
}
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "no refused edit changed the value");
|
||||
// `entdel` of a record, and `entdel` of the SEQEND, do nothing either.
|
||||
assert_eq!(ok(&mut s, "(progn (entdel a) (entdel seq))"), "nil");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "the name still holds: nothing changed");
|
||||
// The edit is one undo step: the value goes back with it.
|
||||
s.undo().unwrap();
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subentity_name_expires_when_its_record_is_rebuilt() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// Erased: the records go with the reference.
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(list (entget a) (entnext a))"), "(nil nil)");
|
||||
// Undone: the reference is back, the name given before the Undo is not.
|
||||
s.undo().unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", h.hex())), "\"A1\"");
|
||||
// ATTSYNC rebuilds the attributes in place: the old name names nothing, the values stay.
|
||||
ok(&mut s, "(setq b (entnext i))");
|
||||
s.execute("attsync", &json!({ "name": "K" })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget b)"), "nil");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
// A name never resolves to another attribute: when the record at its place has another tag
|
||||
// now, it names nothing (the change makes no new epoch), and a new walk reaches the new tag.
|
||||
ok(&mut s, "(setq c (entnext i))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget c)))"), "\"T1\"");
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind
|
||||
&& let Some(a) = i.attribs.first_mut()
|
||||
{
|
||||
a.tag = "T9".into();
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget c)"), "nil", "the record at that place has another tag now");
|
||||
assert_eq!(ok(&mut s, "(list (cdr (assoc 0 (entget (entnext i)))) (cdr (assoc 2 (entget (entnext i)))))"), "(\"ATTRIB\" \"T9\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_attrib_and_a_seqend_have_distinct_names() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) end (entnext a))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget end)))"), "\"SEQEND\"");
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
let mut blank = i.attribs[0].clone();
|
||||
blank.tag.clear();
|
||||
i.attribs.push(blank);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget end)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(setq b (entnext a)) (list (cdr (assoc 0 (entget b))) (eq b (entnext a)))"), "(\"ATTRIB\" T)");
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
i.attribs.truncate(1);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(ok(&mut s, "(list (entget b) (cdr (assoc 0 (entget (entnext a)))))"), "(nil \"SEQEND\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explode_and_burst_retire_the_removed_inserts_record_names() {
|
||||
for command in ["explode", "burst"] {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) end (entnext (entnext a)))");
|
||||
let original = s.doc().unwrap().entity(h).unwrap().as_ref().clone();
|
||||
inserted(&mut s, json!({ "T1": "B1" }));
|
||||
ok(&mut s, "(setq b (entnext i))");
|
||||
// A host can shorten the run before removal and later reuse the handle.
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
i.attribs.truncate(1);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let result = s.execute(command, &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert!(!result["handles"].as_array().unwrap().is_empty(), "{command} creates pieces");
|
||||
assert!(s.doc().unwrap().entity(h).is_none(), "{command} removes the reference");
|
||||
s.doc_mut().unwrap().model.push(original);
|
||||
assert_eq!(ok(&mut s, "(list (entget a) (entget end) (cdr (assoc 1 (entget b))))"), "(nil nil \"B1\")", "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entmod_obeys_the_refedit_working_set_for_attrib_owners() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let editing = inserted(&mut s, json!({ "T1": "E1" }));
|
||||
let outside = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.execute("refedit", &json!({ "handle": editing.hex() })).unwrap();
|
||||
let read = "(cdr (assoc 1 (entget (entnext i))))";
|
||||
let edit = r#"(progn (setq d (entget (entnext i))) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#;
|
||||
assert_eq!(ok(&mut s, read), "\"A1\"");
|
||||
assert_eq!(ok(&mut s, edit), "nil");
|
||||
assert_eq!(ok(&mut s, read), "\"A1\"");
|
||||
s.execute("refset", &json!({ "add": [outside.hex()] })).unwrap();
|
||||
assert_ne!(ok(&mut s, edit), "nil");
|
||||
assert_eq!(ok(&mut s, read), "\"A2\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_reference_does_not_revive_an_old_name() {
|
||||
// entdel of the reference, then entdel again to bring it back: the name given before the
|
||||
// first entdel names nothing, also after the reference returns.
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil");
|
||||
assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil", "the name must not come back");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
// ERASE, then OOPS: the same. Erasing expires the names it took with it.
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.execute("oops", &json!({})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "OOPS must not revive the name");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erasing_another_object_keeps_an_attrib_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a))");
|
||||
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
|
||||
let line = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
// Erasing another object leaves the reference and its records as they were: the name holds
|
||||
// and takes the value edit it always took.
|
||||
s.execute("erase", &json!({ "handles": [line.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\"");
|
||||
let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
|
||||
assert!(r.contains("(1 . \"A2\")"), "{r}");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into())]);
|
||||
// Erasing the reference itself ends its names, and OOPS bringing it back revives none.
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.execute("oops", &json!({})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "the name of an erased reference stays dead");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entdel_of_another_object_keeps_an_attrib_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
|
||||
ok(&mut s, "(setq line (entlast))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget line)))"), "\"LINE\"");
|
||||
ok(&mut s, "(entdel line)");
|
||||
assert_eq!(ok(&mut s, "(entget line)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_given_in_the_block_editor_never_resolves_in_the_host() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.execute("bedit", &json!({ "name": "K" })).unwrap();
|
||||
// A reference made in the editor's drawing, named there. The editor starts from the host's
|
||||
// drawing, so its handle is the one the host gives its next new object.
|
||||
s.execute("insert", &json!({ "name": "K", "at": [40, 40], "attribs": { "T1": "E1" } })).unwrap();
|
||||
let editor = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
ok(&mut s, &format!("(setq a (entnext (handent \"{}\")))", editor.hex()));
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"E1\"");
|
||||
s.execute("bclose", &json!({ "save": false })).unwrap();
|
||||
// The host's next reference takes the handle the editor's reference had: the name given in
|
||||
// the editor must not reach its ATTRIB, or `entmod` through it would edit the wrong one.
|
||||
s.execute("insert", &json!({ "name": "K", "at": [80, 80], "attribs": { "T1": "H1" } })).unwrap();
|
||||
let host = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
assert_eq!(host, editor, "the host takes the handle the editor's reference had");
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(entdel a)"), "nil");
|
||||
assert_eq!(
|
||||
ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", host.hex())),
|
||||
"\"H1\"",
|
||||
"the host's own attribute is untouched"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_record_provider_entnext_walks_the_next_entity() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap();
|
||||
// A host that installed no provider has no records to name: the walk goes on to the next
|
||||
// main entity as it always did, rather than answering nil at the reference.
|
||||
let next = crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(entnext i)"));
|
||||
assert_ne!(next, "nil");
|
||||
assert_eq!(crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(cdr (assoc 0 (entget (entnext i))))")), "\"LINE\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_redo_does_not_revive_an_old_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a))");
|
||||
ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
|
||||
s.undo().unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.redo().unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "Redo must not revive the name");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_replace_expires_an_old_attrib_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
// A replacement block with the same tag as K's first attribute: without the expiry, the old
|
||||
// name would keep naming that place and return the new record.
|
||||
s.cmdline(
|
||||
"(progn (entmake '((0 . \"BLOCK\") (2 . \"L\") (70 . 2) (10 0.0 0.0 0.0))) \
|
||||
(entmake '((0 . \"ATTDEF\") (10 0.0 0.0 0.0) (40 . 2.5) (1 . \"Z1\") (3 . \"P\") (2 . \"T1\") (70 . 0))) \
|
||||
(entmake '((0 . \"ENDBLK\"))))",
|
||||
)
|
||||
.unwrap();
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
s.execute("blockreplace", &json!({ "block": "K", "with": "L" })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "-BLOCKREPLACE rebuilt the record");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reinsert_after_undo_takes_the_handle_and_no_old_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// U takes the reference back; INSERT then gives a new one the handle it had.
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc().unwrap().entity(h).is_none());
|
||||
let again = inserted(&mut s, json!({ "T1": "B1" }));
|
||||
assert_eq!(again, h, "the same handle");
|
||||
assert_eq!(ok(&mut s, "(list (entget a) (cdr (assoc 1 (entget (entnext i)))))"), "(nil \"B1\")");
|
||||
}
|
||||
|
||||
/// A drawing with one reference of `attribs` attributes (all value V), for the bounds.
|
||||
fn drawing_with_attributes(attribs: usize) -> (Session, Handle) {
|
||||
let text = |v: &str| cadcraft_doc::Text {
|
||||
insert: cadcraft_geom::Vec3::ZERO,
|
||||
align_pt: None,
|
||||
height: 1.0,
|
||||
value: v.into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: cadcraft_doc::HAlign::Left,
|
||||
valign: cadcraft_doc::VAlign::Baseline,
|
||||
backwards: false,
|
||||
upside_down: false,
|
||||
};
|
||||
let mut d = cadcraft_doc::Drawing::new_metric();
|
||||
let list = (0..attribs)
|
||||
.map(|i| cadcraft_doc::Attrib {
|
||||
tag: format!("T{i}"),
|
||||
text: text("V"),
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: cadcraft_doc::AttribProps::default(),
|
||||
multiline: None,
|
||||
modes: cadcraft_doc::AttribModes::default(),
|
||||
})
|
||||
.collect();
|
||||
let insert = cadcraft_doc::Insert { block: "B".into(), attribs: list, ..cadcraft_doc::Insert::default() };
|
||||
let h = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Insert(insert)).expect("add");
|
||||
let mut s = session();
|
||||
s.open_drawing(d, "attributes", None);
|
||||
ok(&mut s, &format!("(setq i (handent \"{}\"))", h.hex()));
|
||||
(s, h)
|
||||
}
|
||||
|
||||
/// The number of records a walk from `i` names.
|
||||
const COUNT: &str = "(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)";
|
||||
|
||||
#[test]
|
||||
fn a_session_names_at_most_65536_records_and_nothing_changes() {
|
||||
let (mut s, h) = drawing_with_attributes(65_537);
|
||||
assert_eq!(ok(&mut s, COUNT), "65536");
|
||||
// The names given hold: a second walk is the same, and the drawing kept every attribute.
|
||||
assert_eq!(ok(&mut s, COUNT), "65536");
|
||||
// Erasing and bringing the reference back frees the 65,536 names it held: the old name names
|
||||
// nothing, and a new walk can name the records again.
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
ok(&mut s, "(progn (entdel i) (entdel i))");
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, COUNT), "65536");
|
||||
let d = s.doc().unwrap();
|
||||
let kept = d.entity(h).and_then(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.len()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(kept, Some(65_537));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_object_at_any_handle_is_never_a_record() {
|
||||
// A hostile $HANDSEED at the top of the range: the line made after the walk takes that
|
||||
// handle, and the record keeps its own name, which is no handle.
|
||||
let (mut s, _) = drawing_with_attributes(1);
|
||||
s.doc_mut().unwrap().handseed = u64::MAX - 1;
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
assert_eq!(
|
||||
ok(&mut s, r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#),
|
||||
"\"FFFFFFFFFFFFFFFE\""
|
||||
);
|
||||
assert_eq!(
|
||||
ok(&mut s, "(list (cdr (assoc 0 (entget a))) (eq a (entlast)) (entdel a) (cdr (assoc 0 (entget (entlast)))))"),
|
||||
"(\"ATTRIB\" nil nil \"LINE\")"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_at_the_top_of_the_handle_range_walk_as_objects() {
|
||||
let (mut s, _) = drawing_with_attributes(1);
|
||||
{
|
||||
let d = s.doc_mut().unwrap();
|
||||
d.handseed = u64::MAX;
|
||||
for handle in [Handle(u64::MAX - 1), Handle(u64::MAX)] {
|
||||
let line =
|
||||
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(1.0, 0.0, 0.0) });
|
||||
d.model.push(cadcraft_doc::Entity { handle, common: cadcraft_doc::Common::default(), kind: line });
|
||||
}
|
||||
}
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// The lines' handles are theirs: `entnext` of the first finds the second, then the end.
|
||||
assert_eq!(ok(&mut s, "(equal (entnext (handent \"FFFFFFFFFFFFFFFE\")) (handent \"FFFFFFFFFFFFFFFF\"))"), "T");
|
||||
assert_eq!(ok(&mut s, "(entnext (handent \"FFFFFFFFFFFFFFFF\"))"), "nil");
|
||||
// The record, a table record and the lines each keep their own name.
|
||||
assert_eq!(
|
||||
ok(&mut s, "(list (cdr (assoc 0 (entget a))) (equal a (tblobjname \"LAYER\" \"0\")) (equal a (handent \"FFFFFFFFFFFFFFFE\")))"),
|
||||
"(\"ATTRIB\" nil nil)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_name_is_an_entity_name_but_no_handle() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) b (entnext a))");
|
||||
assert_eq!(ok(&mut s, "(type a)"), "ENAME");
|
||||
// The same record has the same name on every walk; another record and the reference have
|
||||
// their own.
|
||||
assert_eq!(ok(&mut s, "(list (eq a (entnext i)) (equal a (entnext i)) (eq a b) (eq a i) (equal a i))"), "(T T nil nil nil)");
|
||||
// It prints as the reference's handle, a dot and its number: never a handle's text.
|
||||
let printed = ok(&mut s, "a");
|
||||
assert!(printed.starts_with(&format!("<Entity name: {:x}.", h.0)) && printed.ends_with('>'), "{printed}");
|
||||
// No handle reaches it: its list has no group 5, and `handent` of the reference's handle is
|
||||
// the reference.
|
||||
assert_eq!(ok(&mut s, "(list (assoc 5 (entget a)) (eq a (handent (cdr (assoc 5 (entget i))))))"), "(nil nil)");
|
||||
// A DXF group cannot point at it: `entmake` of a list that does is refused.
|
||||
assert_eq!(ok(&mut s, "(entmake (list '(0 . \"LINE\") '(10 0.0 0.0 0.0) '(11 1.0 0.0 0.0) (cons 340 a)))"), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_sets_and_commands_take_no_record() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) ss (ssadd i))");
|
||||
// A selection set holds objects of the drawing; a record is not one on its own.
|
||||
assert_eq!(ok(&mut s, "(list (ssadd a) (ssadd a ss) (sslength ss) (ssmemb a ss) (ssdel a ss) (sslength ss))"), "(nil nil 1 nil nil 1)");
|
||||
// A command given the name picks nothing: the reference stays, and the name holds.
|
||||
ok(&mut s, "(command \"_.ERASE\" a \"\")");
|
||||
assert!(s.doc().unwrap().entity(h).is_some());
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entupd_of_a_record_answers_its_name_while_it_holds() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a))");
|
||||
assert_eq!(ok(&mut s, "(progn (entmod (subst (cons 1 \"A2\") (assoc 1 d) d)) (eq (entupd a) a))"), "T");
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entupd a)"), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_name_holds_while_commands_keep_its_record() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// Moving the reference, or changing its colour, keeps its records in their places.
|
||||
s.execute("move", &json!({ "handles": [h.hex()], "delta": [5, 5] })).unwrap();
|
||||
s.execute("chprop", &json!({ "handles": [h.hex()], "color": 1 })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(list (cdr (assoc 1 (entget a))) (eq a (entnext i)))"), "(\"A1\" T)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_record_name_is_one_entry_and_walking_again_adds_none() {
|
||||
const N: usize = 64;
|
||||
let (mut s, _) = drawing_with_attributes(N);
|
||||
let before = s.state().unwrap().doc.clone();
|
||||
ok(&mut s, "(setq e nil)");
|
||||
// The R3 pattern: each new name, then state access. Nothing is copied or replayed.
|
||||
for _ in 0..=N {
|
||||
ok(&mut s, "(setq e (if e (entnext e) (entnext i)))");
|
||||
let _ = s.state_mut().unwrap();
|
||||
}
|
||||
let uid = s.state().unwrap().uid;
|
||||
let held = |s: &Session| s.lisp.records.get(&uid).map_or(0, super::drawing::RecordNames::count);
|
||||
assert_eq!(held(&s), N + 1, "the attributes and the SEQEND, one entry each");
|
||||
assert_eq!(ok(&mut s, COUNT), (N + 1).to_string());
|
||||
assert_eq!(held(&s), N + 1, "a walk again gives the same names");
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.state().unwrap().doc), "naming changes nothing in the drawing");
|
||||
// Undo or redo ends them: the next walk starts over with as many.
|
||||
s.execute("line", &json!({ "points": [[0, -4], [1, -4]] })).unwrap();
|
||||
s.undo().unwrap();
|
||||
assert_eq!(ok(&mut s, COUNT), (N + 1).to_string());
|
||||
assert_eq!(held(&s), N + 1);
|
||||
}
|
||||
|
||||
/// A saved drawing with one named attribute. The name comes from the command line, which does
|
||||
/// not run the after-command pass.
|
||||
fn clean_named() -> Session {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
{
|
||||
let st = s.state_mut().unwrap();
|
||||
st.saved = st.doc.clone();
|
||||
st.undo.clear();
|
||||
st.redo.clear();
|
||||
}
|
||||
s.cmdline("(setq a (entnext i))").unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget a)))"), "\"ATTRIB\"");
|
||||
assert!(!s.state().unwrap().is_dirty(), "naming from the command line saves nothing");
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issued_name_reads_keep_the_drawing_clean() {
|
||||
let mut s = clean_named();
|
||||
s.cmdline("(getvar \"DBMOD\")").unwrap();
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved));
|
||||
// A programmatic read runs the after-command pass. That pass must not make a saved drawing dirty.
|
||||
s.execute("lisp", &json!({ "code": "(entget a)" })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved));
|
||||
assert_eq!(s.state().unwrap().undo.len(), 0, "a read is not an undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issued_name_selection_keeps_the_drawing_clean() {
|
||||
let mut s = clean_named();
|
||||
let saved = s.state().unwrap().saved.clone();
|
||||
s.execute("select", &json!({ "clear": true })).unwrap();
|
||||
assert!(s.state().unwrap().selection.is_empty());
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved));
|
||||
assert!(!s.state().unwrap().is_dirty());
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
assert_eq!(s.state().unwrap().undo.len(), 0, "clearing an empty selection is not an undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issued_name_undo_restores_the_saved_drawing() {
|
||||
let mut s = clean_named();
|
||||
let saved = s.state().unwrap().saved.clone();
|
||||
// A selection change writes no undo step. If it also changes the drawing, the next command
|
||||
// records that copy, and undo cannot return to the saved drawing.
|
||||
s.execute("select", &json!({ "clear": true })).unwrap();
|
||||
assert_eq!(s.state().unwrap().undo.len(), 0);
|
||||
s.execute("line", &json!({ "points": [[0, -3], [1, -3]] })).unwrap();
|
||||
assert!(s.undo().unwrap().is_some());
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved), "undo returns the saved drawing, not a reservation copy");
|
||||
assert!(!s.state().unwrap().is_dirty());
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_given_in_the_host_never_resolves_in_the_block_editor() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
let mut same = cadcraft_doc::Entity::clone(s.doc().unwrap().entity(h).unwrap());
|
||||
if let cadcraft_doc::EntityKind::Insert(ins) = &mut same.kind
|
||||
&& let Some(at) = ins.attribs.first_mut()
|
||||
{
|
||||
at.text.value = "E1".into();
|
||||
}
|
||||
s.execute("bedit", &json!({ "name": "K" })).unwrap();
|
||||
// An object of the editor's drawing with the handle the host's reference has: the host's
|
||||
// name must not reach its ATTRIB.
|
||||
s.doc_mut().unwrap().model.push(same);
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.execute("bclose", &json!({ "save": false })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drawing_put_back_after_a_refused_change_ends_its_names() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let before = s.state().unwrap().doc.clone();
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// A change with a number that is not finite: the drawing goes back as it was, without the
|
||||
// reference the name was given for.
|
||||
let bad = cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(f64::NAN, 0.0, 0.0), b: cadcraft_geom::Vec3::ZERO });
|
||||
s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), bad).unwrap();
|
||||
assert!(s.refuse_non_finite(None, &before, &[], "line").is_err());
|
||||
assert!(s.doc().unwrap().entity(h).is_none());
|
||||
// The next reference takes the handle back: the old name names nothing in it.
|
||||
assert_eq!(inserted(&mut s, json!({ "T1": "B1" })), h);
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"B1\"");
|
||||
}
|
||||
|
||||
/// MOCORO's own Undo puts the drawing from before the Copy back, handle seed included.
|
||||
/// The next Copy is given that handle again. The name of the removed copy's attribute
|
||||
/// must not read it, walk from it, or change it.
|
||||
#[test]
|
||||
fn mocoro_undo_does_not_let_an_old_record_name_reach_the_next_copy() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(sssetfirst nil nil)
|
||||
(command "_.MOCORO" i "" '(0 0) "_Copy" '(10 0))
|
||||
(setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c) v (cdr (assoc 1 (entget a))))
|
||||
(command "_Undo" "_Copy" '(20 0) "_eXit"))"#,
|
||||
);
|
||||
// The name was given for a copy with a handle of its own, and it read that copy's attribute.
|
||||
// The copy made after the Undo has the removed copy's handle.
|
||||
assert_eq!(ok(&mut s, "(list (= ch (cdr (assoc 5 (entget i)))) v (= ch (cdr (assoc 5 (entget (entlast))))))"), "(nil \"A1\" T)");
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(setq d (entget a) w (entnext a))
|
||||
(if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d)))
|
||||
(list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"#
|
||||
),
|
||||
"(T T \"A1\")"
|
||||
);
|
||||
}
|
||||
|
||||
/// A grip Copy's Undo is the same kind of restore: the next copy reuses the handle.
|
||||
#[test]
|
||||
fn grip_copy_undo_does_not_let_an_old_record_name_reach_the_next_copy() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.start_grip_edit(&[(h, 0)]).unwrap();
|
||||
// Enter leaves STRETCH for MOVE, which copies the reference whole.
|
||||
s.input(crate::Input::Enter).unwrap();
|
||||
s.input(crate::Input::Keyword("Copy".into())).unwrap();
|
||||
s.input(crate::Input::Point(cadcraft_geom::Vec2::new(20.0, 10.0))).unwrap();
|
||||
// The name is given for a copy with a handle of its own, and it reads that copy's attribute.
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c))
|
||||
(list (= ch (cdr (assoc 5 (entget i)))) (cdr (assoc 1 (entget a)))))"#
|
||||
),
|
||||
"(nil \"A1\")"
|
||||
);
|
||||
s.input(crate::Input::Keyword("Undo".into())).unwrap();
|
||||
s.input(crate::Input::Point(cadcraft_geom::Vec2::new(30.0, 10.0))).unwrap();
|
||||
assert_eq!(ok(&mut s, "(= ch (cdr (assoc 5 (entget (entlast)))))"), "T", "the next copy takes the removed copy's handle");
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(setq d (entget a) w (entnext a))
|
||||
(if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d)))
|
||||
(list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"#
|
||||
),
|
||||
"(T T \"A1\")"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//! ([`charge_bytes`]).
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use cadcraft_doc::Handle;
|
||||
@@ -207,6 +207,26 @@ pub enum BuiltinKind {
|
||||
Special(super::eval::Special),
|
||||
}
|
||||
|
||||
/// The name AutoLISP gives an INSERT's ATTRIB or SEQEND (#1660). Those records have no handle of
|
||||
/// their own in the drawing, so their names are not handles: `id` comes from one count for the
|
||||
/// whole process and is never given again, so no object of any drawing, and no other record,
|
||||
/// ever has it. `owner` is the reference's handle, for printing. What a name stands for is kept
|
||||
/// by the session; a name that no longer holds names nothing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RecordName {
|
||||
pub(crate) owner: Handle,
|
||||
pub(crate) id: u64,
|
||||
}
|
||||
|
||||
impl RecordName {
|
||||
/// A name never given before, for a record of `owner`; `None` once the count runs out.
|
||||
pub(crate) fn fresh(owner: Handle) -> Option<RecordName> {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
let id = NEXT.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)).ok()?;
|
||||
Some(RecordName { owner, id })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub enum Value {
|
||||
#[default]
|
||||
@@ -217,6 +237,8 @@ pub enum Value {
|
||||
Sym(Sym),
|
||||
Cons(Arc<Cons>),
|
||||
Ename(Handle),
|
||||
/// An INSERT's ATTRIB or SEQEND (#1660): an entity name that is no handle.
|
||||
Record(RecordName),
|
||||
PickSet(PickSet),
|
||||
File(u32),
|
||||
Subr(&'static Builtin),
|
||||
@@ -310,7 +332,7 @@ impl Value {
|
||||
Value::Str(_) => "STR",
|
||||
Value::Sym(_) => "SYM",
|
||||
Value::Cons(_) => "LIST",
|
||||
Value::Ename(_) => "ENAME",
|
||||
Value::Ename(_) | Value::Record(_) => "ENAME",
|
||||
Value::PickSet(_) => "PICKSET",
|
||||
Value::File(_) => "FILE",
|
||||
Value::Subr(_) => "SUBR",
|
||||
@@ -423,6 +445,7 @@ fn atom_equal(a: &Value, b: &Value, fuzz: f64) -> bool {
|
||||
(Value::Str(x), Value::Str(y)) => x == y,
|
||||
(Value::Sym(x), Value::Sym(y)) => x == y,
|
||||
(Value::Ename(x), Value::Ename(y)) => x == y,
|
||||
(Value::Record(x), Value::Record(y)) => x == y,
|
||||
(Value::File(x), Value::File(y)) => x == y,
|
||||
(Value::PickSet(x), Value::PickSet(y)) => x.id == y.id,
|
||||
(Value::Subr(x), Value::Subr(y)) => std::ptr::eq(*x, *y),
|
||||
@@ -567,6 +590,8 @@ fn write_value(out: &mut String, v: &Value, escape: bool, depth: usize) {
|
||||
out.push(')');
|
||||
}
|
||||
Value::Ename(h) => out.push_str(&format!("<Entity name: {:x}>", h.0)),
|
||||
// The reference's handle, a dot and the record's number: never a handle's text.
|
||||
Value::Record(r) => out.push_str(&format!("<Entity name: {:x}.{:x}>", r.owner.0, r.id)),
|
||||
Value::PickSet(p) => out.push_str(&format!("<Selection set: {:x}>", p.id)),
|
||||
Value::File(f) => out.push_str(&format!("#<FILE {f:x}>")),
|
||||
Value::Subr(b) => out.push_str(&format!("#<SUBR @{} {}>", "0", b.name)),
|
||||
|
||||
@@ -216,7 +216,7 @@ pub fn bracket() -> Drawing {
|
||||
add(on("Notes"), text(Vec2::new(4.1, -0.3), 0.16, "FRONT VIEW"));
|
||||
add(
|
||||
on("Notes"),
|
||||
EntityKind::MText(MText { insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None }),
|
||||
EntityKind::MText(MText { insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None, background: None }),
|
||||
);
|
||||
let tb0 = Vec2::new(14.0, -0.5);
|
||||
add(on("Title"), lwpoly(rect_vertices(tb0, tb0 + Vec2::new(4.0, 2.0)), true));
|
||||
|
||||
@@ -962,6 +962,7 @@ mod tests {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ impl Session {
|
||||
if let Some((doc, sel, uid)) = before
|
||||
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid)
|
||||
{
|
||||
st.doc = doc;
|
||||
st.restore_drawing(doc);
|
||||
st.selection = sel;
|
||||
}
|
||||
Err(EngineError::Internal(id.into(), crate::guard::message(&*p)))
|
||||
@@ -50,7 +50,7 @@ impl Session {
|
||||
if let Some((doc, sel, uid)) = &before
|
||||
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == *uid)
|
||||
{
|
||||
st.doc = doc.clone();
|
||||
st.restore_drawing(doc.clone());
|
||||
st.selection = sel.clone();
|
||||
}
|
||||
return Err(EngineError::Internal(id.into(), msg));
|
||||
|
||||
@@ -479,7 +479,7 @@ impl Session {
|
||||
Err(EngineError::Internal(id, m)) => {
|
||||
// Restore and end the command.
|
||||
if let Ok(st) = self.state_mut() {
|
||||
st.doc = run.before.clone();
|
||||
st.restore_drawing(run.before.clone());
|
||||
}
|
||||
self.echo(format!("Internal error in {id}: {m}"));
|
||||
self.resume_suspended();
|
||||
@@ -501,7 +501,7 @@ impl Session {
|
||||
let (id, before, selection) = (run.id.clone(), run.before.clone(), run.selection_before.clone());
|
||||
if let Err(p) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.finish_guarded(run, cancelled))) {
|
||||
if let Ok(st) = self.state_mut() {
|
||||
st.doc = before;
|
||||
st.restore_drawing(before);
|
||||
st.selection = selection;
|
||||
}
|
||||
self.echo(format!("Internal error in {id}: {}", crate::guard::message(&*p)));
|
||||
|
||||
@@ -1374,6 +1374,7 @@ mod tests {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
|
||||
}
|
||||
@@ -1405,6 +1406,7 @@ mod tests {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
|
||||
}
|
||||
@@ -1488,6 +1490,7 @@ mod tests {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
|
||||
}
|
||||
|
||||
@@ -428,6 +428,7 @@ mod tests {
|
||||
xref_path: None,
|
||||
explodable: true,
|
||||
units: 0,
|
||||
scale_uniformly: false,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
};
|
||||
|
||||
@@ -304,6 +304,7 @@ fn dash_attedit_edits_a_multiline_attributes_text() {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
set_t(&mut s, h, |a| a.multiline = Some(MultilineAttrib { mtext: mtext.clone(), read_as: "abc".into() }));
|
||||
let before = attrib_t(&s, h).text.insert;
|
||||
@@ -337,6 +338,7 @@ fn dash_attedit_defaults_of_a_multiline_attribute_come_from_its_multiline_text()
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
set_t(&mut s, h, |a| {
|
||||
a.text.height = 1.25;
|
||||
|
||||
@@ -76,6 +76,7 @@ fn definition(tag: &str, x: f64, modes: AttribModes, invisible: bool, multiline:
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
MultilineAttrib { mtext, read_as: format!("{tag}\nTWO") }
|
||||
});
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
//! AutoLISP's name of an INSERT's ATTRIB keeps naming that attribute when a command, another
|
||||
//! session, another document or another thread gives out handles in the drawing or in a copy of
|
||||
//! it, and installs the result (#1660).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{EntityCodec, IoHooks, set_entity_codec, set_entity_sub_record, set_io, set_object_records};
|
||||
use cadcraft_engine::doc::geom::Vec3;
|
||||
use cadcraft_engine::doc::{Block, Common, Drawing, Entity, EntityKind, Handle, Line, Space};
|
||||
use cadcraft_engine::lisp::value::to_text;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::temp_dir::TempDir;
|
||||
|
||||
fn session() -> Session {
|
||||
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
|
||||
set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
set_object_records(cadcraft_io::object_records);
|
||||
set_io(IoHooks {
|
||||
read: |bytes, name| cadcraft_io::read(bytes, name).map_err(|e| e.to_string()),
|
||||
write: |drawing, name| cadcraft_io::write(drawing, name).map_err(|e| e.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
Session::new()
|
||||
}
|
||||
|
||||
fn eval(s: &mut Session, code: &str) -> String {
|
||||
match s.lisp_eval(code, false, true, Vec::new()) {
|
||||
Ok(Some(Ok(v))) => to_text(&v, true),
|
||||
Ok(Some(Err(e))) => panic!("{code}: {e}"),
|
||||
Ok(None) => panic!("{code}: did not finish"),
|
||||
Err(e) => panic!("{code}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Block K with one attribute, one reference, and `i` naming that reference.
|
||||
fn attributed() -> Session {
|
||||
let mut s = session();
|
||||
s.cmdline(
|
||||
"(progn (entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) \
|
||||
(entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 1.0))) \
|
||||
(entmake '((0 . \"ATTDEF\") (10 0.0 5.0 0.0) (40 . 2.5) (1 . \"D1\") (3 . \"P\") (2 . \"T1\") (70 . 0))) \
|
||||
(entmake '((0 . \"ENDBLK\"))))",
|
||||
)
|
||||
.unwrap();
|
||||
let ins = s.execute("insert", &json!({ "name": "K", "at": [10, 10], "attribs": { "T1": "A1" } })).unwrap();
|
||||
let href = ins["handle"].as_str().unwrap();
|
||||
eval(&mut s, &format!("(setq i (handent \"{href}\"))"));
|
||||
s
|
||||
}
|
||||
|
||||
/// The command line names the reference's first ATTRIB `a`, with `$HANDSEED` one below the top:
|
||||
/// the next handle the drawing, or a copy of it, gives out. The command line does not run the
|
||||
/// after-command pass.
|
||||
fn name_at_top(s: &mut Session) {
|
||||
s.doc_mut().unwrap().handseed = u64::MAX - 1;
|
||||
s.cmdline("(setq a (entnext i))").unwrap();
|
||||
assert_eq!(eval(s, "(cdr (assoc 0 (entget a)))"), "\"ATTRIB\"");
|
||||
}
|
||||
|
||||
/// Every object's handle: model space, layouts and block definitions.
|
||||
fn every_handle(d: &Drawing) -> Vec<Handle> {
|
||||
let mut v = d.model.handles();
|
||||
for l in &d.layouts {
|
||||
v.extend(l.entities.handles());
|
||||
}
|
||||
for b in d.blocks.values() {
|
||||
v.extend(b.entities.handles());
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// `a` still names the attribute, and no object of the drawing is `a`: whatever handles were
|
||||
/// given out, each object keeps its own name.
|
||||
fn assert_kept(s: &mut Session) {
|
||||
assert_eq!(
|
||||
eval(s, "(list (cdr (assoc 0 (entget a))) (cdr (assoc 1 (entget a))))"),
|
||||
"(\"ATTRIB\" \"A1\")",
|
||||
"the old name still means the attribute"
|
||||
);
|
||||
let handles = every_handle(s.doc().unwrap());
|
||||
for h in handles {
|
||||
let hex = h.hex();
|
||||
assert_eq!(eval(s, &format!("(eq a (handent \"{hex}\"))")), "nil", "object {hex} is not the attribute");
|
||||
}
|
||||
}
|
||||
|
||||
/// A line added to `d` with the drawing's next handle.
|
||||
fn add_line(d: &mut Drawing) -> Handle {
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).unwrap()
|
||||
}
|
||||
|
||||
/// After a copy of the drawing took `line`, the name still means the attribute and the line is
|
||||
/// the line.
|
||||
fn assert_line_and_name(s: &mut Session, line: Handle) {
|
||||
assert_kept(s);
|
||||
let hex = line.hex();
|
||||
assert_eq!(eval(s, &format!("(cdr (assoc 0 (entget (handent \"{hex}\"))))")), "\"LINE\"");
|
||||
}
|
||||
|
||||
fn one_line(dir: &TempDir) -> String {
|
||||
let mut d = Drawing::new_metric();
|
||||
add_line(&mut d);
|
||||
dir.file("one-line.dxf", cadcraft_io::write_dxf(&d))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_sessions_read_leaves_a_record_name_alone() {
|
||||
// Session A names an attribute and keeps a copy of its drawing; session B, which named
|
||||
// nothing, is read; then A's copy gives out a handle and A installs it.
|
||||
let mut a = attributed();
|
||||
let b = attributed();
|
||||
name_at_top(&mut a);
|
||||
let mut copy = a.doc().unwrap().clone();
|
||||
let _ = b.doc().unwrap();
|
||||
let line = add_line(&mut copy);
|
||||
*a.doc_mut().unwrap() = copy;
|
||||
assert_line_and_name(&mut a, line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_edited_on_another_thread_leaves_a_record_name_alone() {
|
||||
let mut a = attributed();
|
||||
name_at_top(&mut a);
|
||||
let copy = a.doc().unwrap().clone();
|
||||
let (copy, line) = std::thread::spawn(move || {
|
||||
let mut copy = copy;
|
||||
let line = add_line(&mut copy);
|
||||
(copy, line)
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
*a.doc_mut().unwrap() = copy;
|
||||
assert_line_and_name(&mut a, line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_made_while_another_document_is_current_leaves_a_record_name_alone() {
|
||||
let mut s = attributed();
|
||||
name_at_top(&mut s);
|
||||
let first = s.active;
|
||||
let mut copy = s.doc().unwrap().clone();
|
||||
s.open_drawing(Drawing::new_metric(), "other", None);
|
||||
let _ = s.doc().unwrap();
|
||||
let line = add_line(&mut copy);
|
||||
s.active = first;
|
||||
*s.doc_mut().unwrap() = copy;
|
||||
assert_line_and_name(&mut s, line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_from_file_keeps_an_attrib_name() {
|
||||
let mut s = attributed();
|
||||
name_at_top(&mut s);
|
||||
let dir = TempDir::new("attrib-insert");
|
||||
let path = one_line(&dir);
|
||||
s.execute("insert", &json!({ "file": path, "name": "SRC", "at": [4.0, 4.0] })).unwrap();
|
||||
assert_kept(&mut s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xattach_keeps_an_attrib_name() {
|
||||
let mut s = attributed();
|
||||
name_at_top(&mut s);
|
||||
let dir = TempDir::new("attrib-xref");
|
||||
let path = one_line(&dir);
|
||||
s.execute("xattach", &json!({ "path": path, "name": "XR", "at": [8.0, 8.0] })).unwrap();
|
||||
assert_kept(&mut s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audit_fix_keeps_an_attrib_name() {
|
||||
let mut s = attributed();
|
||||
{
|
||||
let d = s.doc_mut().unwrap();
|
||||
let line = Entity::new(Handle(0xABC), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) }));
|
||||
d.model.push(line.clone());
|
||||
let mut b = Block::new("DUP");
|
||||
b.entities.push(line);
|
||||
d.blocks.insert("DUP".into(), Arc::new(b));
|
||||
}
|
||||
name_at_top(&mut s);
|
||||
s.execute("audit", &json!({ "fix": true })).unwrap();
|
||||
assert_kept(&mut s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refclose_keeps_an_attrib_name() {
|
||||
let mut s = attributed();
|
||||
s.cmdline(
|
||||
"(progn (entmake '((0 . \"BLOCK\") (2 . \"R\") (70 . 0) (10 0.0 0.0 0.0))) \
|
||||
(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 2.0 0.0 0.0))) \
|
||||
(entmake '((0 . \"ENDBLK\"))))",
|
||||
)
|
||||
.unwrap();
|
||||
let r = s.execute("insert", &json!({ "name": "R", "at": [0, 0] })).unwrap();
|
||||
s.execute("refedit", &json!({ "handle": r["handle"] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, 1], [3, 1]] })).unwrap();
|
||||
name_at_top(&mut s);
|
||||
s.execute("refclose", &json!({ "save": true })).unwrap();
|
||||
assert_kept(&mut s);
|
||||
}
|
||||
@@ -65,9 +65,9 @@ fn burst_matches_many_attributes_without_comparing_every_pair() {
|
||||
#[test]
|
||||
fn attsync_matches_many_definitions_without_comparing_every_pair() {
|
||||
let (mut s, h) = reference(N);
|
||||
let t = std::time::Instant::now();
|
||||
// The adjacent engine unit test checks exact indexed lookup work; this keeps
|
||||
// the same end-to-end ATTSYNC fixture and its result checks.
|
||||
s.execute("attsync", &json!({"name": "B"})).unwrap();
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
|
||||
// An attribute for each definition (T and the N others), with its default value: the
|
||||
// reference carried none of their tags.
|
||||
let a = attribs(&s, h);
|
||||
|
||||
@@ -4,10 +4,7 @@
|
||||
use cadcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
#[path = "../support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
use crate::temp_dir::TempDir;
|
||||
|
||||
/// `(findfile name)` as LISP prints it.
|
||||
fn findfile(name: &str) -> String {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
#[path = "../support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
mod angle_prompts;
|
||||
mod angle_settings;
|
||||
mod annotate_options;
|
||||
@@ -12,6 +15,7 @@ mod attdef_command;
|
||||
mod attdisp_attsync;
|
||||
mod attedit_prompts;
|
||||
mod attrib_modes;
|
||||
mod attrib_names;
|
||||
mod attrib_props;
|
||||
mod attribute_tag_matching;
|
||||
mod attribute_tools;
|
||||
@@ -209,10 +213,12 @@ mod undo_layout_tab;
|
||||
mod viewport_clip;
|
||||
mod viewport_frozen_block_parts;
|
||||
mod viewport_frozen_selection;
|
||||
mod viewport_ucs_copy;
|
||||
mod vplayer_prompts;
|
||||
mod vports;
|
||||
mod wipeout_grips;
|
||||
mod xclip;
|
||||
mod xdata_api;
|
||||
mod xdata_follows_entity;
|
||||
mod zoom_keywords;
|
||||
mod zoom_viewport;
|
||||
|
||||
@@ -27,6 +27,9 @@ fn drawing() -> (Drawing, Space) {
|
||||
layer_colors: Vec::new(),
|
||||
clip: None,
|
||||
on: true,
|
||||
ucs: None,
|
||||
ucs_per_viewport: false,
|
||||
extra: Vec::new(),
|
||||
twist: 0.0,
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -103,6 +103,7 @@ fn scale_scales_multileader_text_width_and_columns() {
|
||||
heights: vec![3.0, 4.0],
|
||||
flow_reversed: false,
|
||||
}),
|
||||
background: None,
|
||||
};
|
||||
let mut s = Session::new();
|
||||
let ml = MLeader {
|
||||
|
||||
@@ -36,6 +36,7 @@ fn session() -> Session {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
let def = Attrib {
|
||||
tag: "LABEL".into(),
|
||||
|
||||
@@ -103,6 +103,7 @@ fn a_dimension_drawn_from_its_block_is_picked_on_the_block_text() {
|
||||
xref_path: None,
|
||||
explodable: true,
|
||||
units: 0,
|
||||
scale_uniformly: false,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
};
|
||||
|
||||
@@ -1287,6 +1287,7 @@ fn dimension_with_its_text_on_hidden() -> (cadcraft_engine::doc::Drawing, Handle
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
let mut text = Entity::new(Handle(5), EntityKind::MText(words));
|
||||
text.common.layer = "Hidden".into();
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
//! COPY and MIRROR of a layout viewport keep its own UCS and its unmodelled settings (#1316): they
|
||||
//! belong to the viewport, like its view.
|
||||
|
||||
use cadcraft_doc::{EntityKind, Handle, RawTag, Space, Viewport, ViewportUcs};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_geom::Vec3;
|
||||
use serde_json::json;
|
||||
|
||||
fn viewports(s: &Session) -> Vec<(Handle, Viewport)> {
|
||||
let d = s.doc().unwrap();
|
||||
d.layout("Layout1")
|
||||
.unwrap()
|
||||
.entities
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::Viewport(v) if v.id != 1 => Some((e.handle, v.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn ucs() -> ViewportUcs {
|
||||
ViewportUcs {
|
||||
origin: Vec3::new(100.0, 50.0, 0.0),
|
||||
x_axis: Vec3::new(0.0, 1.0, 0.0),
|
||||
y_axis: Vec3::new(-1.0, 0.0, 0.0),
|
||||
elevation: 2.5,
|
||||
ortho: 0,
|
||||
named: Some("SITE".into()),
|
||||
base: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn extra() -> Vec<RawTag> {
|
||||
vec![RawTag { code: 1, value: "monochrome.ctb".into() }, RawTag { code: 15, value: "10.0".into() }, RawTag { code: 170, value: "2".into() }]
|
||||
}
|
||||
|
||||
/// Layout1 with one viewport that has its own UCS and settings.
|
||||
fn session() -> (Session, Handle) {
|
||||
let mut s = Session::new();
|
||||
s.new_drawing(true);
|
||||
s.execute("line", &json!({"points": [[0, 0], [100, 100]]})).unwrap();
|
||||
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
|
||||
let old: Vec<String> = viewports(&s).iter().map(|(h, _)| h.hex()).collect();
|
||||
if !old.is_empty() {
|
||||
s.execute("erase", &json!({"handles": old})).unwrap();
|
||||
}
|
||||
s.execute("mview", &json!({"p1": [10, 10], "p2": [110, 80]})).unwrap();
|
||||
let (h, _) = viewports(&s).into_iter().next().unwrap();
|
||||
let d = s.doc_mut().unwrap();
|
||||
let store = d.space_mut(&Space::Paper("Layout1".into())).unwrap();
|
||||
let mut e = (**store.get(h).unwrap()).clone();
|
||||
if let EntityKind::Viewport(v) = &mut e.kind {
|
||||
v.ucs = Some(ucs());
|
||||
v.ucs_per_viewport = true;
|
||||
v.extra = extra();
|
||||
}
|
||||
assert!(store.replace(e));
|
||||
(s, h)
|
||||
}
|
||||
|
||||
fn assert_kept(v: &Viewport) {
|
||||
assert_eq!(v.ucs, Some(ucs()));
|
||||
assert!(v.ucs_per_viewport);
|
||||
assert_eq!(v.extra, extra());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_keeps_a_viewport_s_ucs_and_settings() {
|
||||
let (mut s, h) = session();
|
||||
s.execute("copy", &json!({"handles": [h.hex()], "delta": [150, 0]})).unwrap();
|
||||
let vps = viewports(&s);
|
||||
assert_eq!(vps.len(), 2);
|
||||
for (_, v) in &vps {
|
||||
assert_kept(v);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_keeps_a_viewport_s_ucs_and_settings() {
|
||||
let (mut s, h) = session();
|
||||
s.execute("mirror", &json!({"handles": [h.hex()], "p1": [0, 100], "p2": [10, 100]})).unwrap();
|
||||
for (_, v) in &viewports(&s) {
|
||||
assert_kept(v);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Extended data (xdata) through the API: `entities` shows it when asked (`xdata: true`, or an
|
||||
//! application name that also filters), `properties` lists it, and `properties.set` replaces or
|
||||
//! removes one application's data, checked as hostile input; what is set is written to DXF with
|
||||
//! its APPID record and read back the same.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A LINE with a hyperlink and another application's data, a circle without any, and an
|
||||
/// LWPOLYLINE with the second application's data.
|
||||
const DXF: &str = "0\nSECTION\n2\nENTITIES\n\
|
||||
0\nLINE\n5\n2A\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\
|
||||
1001\nPE_URL\n1000\nhttps://example.com/door-7\n1002\n{\n1000\nDoor 7\n1002\n}\n\
|
||||
1001\nACME_TAGS\n1000\nD-07\n1070\n3\n1040\n2.5\n1071\n70000\n1010\n1.5\n1020\n2.5\n1030\n0\n1005\n2B\n1004\n0AFF\n\
|
||||
0\nCIRCLE\n5\n2C\n8\n0\n10\n50\n20\n50\n30\n0\n40\n5\n\
|
||||
0\nLWPOLYLINE\n5\n2B\n8\n0\n90\n3\n70\n0\n10\n0\n20\n5\n10\n5\n20\n5\n10\n5\n20\n10\n\
|
||||
1001\nACME_TAGS\n1000\nP-01\n\
|
||||
0\nENDSEC\n0\nEOF\n";
|
||||
|
||||
fn session_from(dxf: &str) -> Session {
|
||||
let d = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "xdata", None);
|
||||
s
|
||||
}
|
||||
|
||||
fn entities(s: &mut Session, p: Value) -> Vec<Value> {
|
||||
s.execute("entities", &p).unwrap()["entities"].as_array().unwrap().clone()
|
||||
}
|
||||
|
||||
fn handle_of(s: &Session, line: bool) -> String {
|
||||
s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Line(_)) == line).map(|e| e.handle.hex()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entities_show_xdata_only_when_asked() {
|
||||
let mut s = session_from(DXF);
|
||||
let plain = entities(&mut s, json!({}));
|
||||
assert_eq!(plain.len(), 3);
|
||||
assert!(plain.iter().all(|e| e.get("xdata").is_none()), "{plain:?}");
|
||||
|
||||
let all = entities(&mut s, json!({"xdata": true}));
|
||||
let line = all.iter().find(|e| e["type"] == "Line").unwrap();
|
||||
assert_eq!(line["xdata"]["PE_URL"], json!([[1000, "https://example.com/door-7"], [1002, "{"], [1000, "Door 7"], [1002, "}"]]));
|
||||
assert_eq!(
|
||||
line["xdata"]["ACME_TAGS"],
|
||||
json!([[1000, "D-07"], [1070, 3], [1040, 2.5], [1071, 70000], [1010, [1.5, 2.5, 0.0]], [1005, "2B"], [1004, "0AFF"]])
|
||||
);
|
||||
assert!(all.iter().find(|e| e["type"] == "Circle").unwrap().get("xdata").is_none(), "no xdata, no key");
|
||||
assert_eq!(s.execute("entities", &json!({"xdata": false})).unwrap()["entities"], json!(plain));
|
||||
|
||||
// An application name keeps only the entities carrying its data and shows just that.
|
||||
let acme = entities(&mut s, json!({"xdata": "acme_tags"}));
|
||||
assert_eq!(acme.len(), 2);
|
||||
assert!(acme.iter().all(|e| e["xdata"].as_object().unwrap().keys().eq(["ACME_TAGS"])), "{acme:?}");
|
||||
let r = s.execute("entities", &json!({"xdata": ["PE_URL"], "type": "Line"})).unwrap();
|
||||
assert_eq!((r["count"].as_u64(), r["returned"].as_u64()), (Some(1), Some(1)));
|
||||
assert_eq!(s.execute("entities", &json!({"xdata": ["NOPE"]})).unwrap()["count"], 0);
|
||||
for bad in [json!({"xdata": 1}), json!({"xdata": []}), json!({"xdata": [1]}), json!({"xdata": {"app": true}})] {
|
||||
assert!(s.execute("entities", &bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn properties_set_replaces_removes_and_round_trips_through_dxf() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
let h = handle_of(&s, true);
|
||||
// A 1005 handle refers to an object of the drawing (here the line itself): saving remaps it
|
||||
// with the other references, so one that refers to nothing would come back as 0.
|
||||
let acme = json!([
|
||||
[1000, "D-07"],
|
||||
[1002, "{"],
|
||||
[1003, "0"],
|
||||
[1004, "0aff"],
|
||||
[1005, h.to_ascii_lowercase()],
|
||||
[1010, [1.5, 2.5]],
|
||||
[1011, [1, 2, 3]],
|
||||
[1040, 2.5],
|
||||
[1041, -1.0],
|
||||
[1042, 1e3],
|
||||
[1070, -3],
|
||||
[1071, 70000],
|
||||
[1002, "}"]
|
||||
]);
|
||||
let want = json!([
|
||||
[1000, "D-07"],
|
||||
[1002, "{"],
|
||||
[1003, "0"],
|
||||
[1004, "0AFF"],
|
||||
[1005, h],
|
||||
[1010, [1.5, 2.5, 0.0]],
|
||||
[1011, [1.0, 2.0, 3.0]],
|
||||
[1040, 2.5],
|
||||
[1041, -1.0],
|
||||
[1042, 1000.0],
|
||||
[1070, -3],
|
||||
[1071, 70000],
|
||||
[1002, "}"]
|
||||
]);
|
||||
let r = s.execute("properties.set", &json!({"handles": [h], "xdata": {"ACME": acme, "PE_URL": [[1000, "https://example.com"]]}})).unwrap();
|
||||
assert_eq!(r["changed"], 1);
|
||||
let got = &entities(&mut s, json!({"xdata": true}))[0]["xdata"];
|
||||
assert_eq!(got["ACME"], want);
|
||||
assert_eq!(got["PE_URL"], json!([[1000, "https://example.com"]]));
|
||||
// `properties` lists it too.
|
||||
let props = s.execute("properties", &json!({"handles": [h]})).unwrap();
|
||||
assert_eq!(props["objects"][0]["xdata"]["ACME"], want);
|
||||
|
||||
// Saved and read back the same, with an APPID record for each application.
|
||||
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
let tags = craft_dxf::parse_ascii(&text).unwrap();
|
||||
let appids: Vec<String> =
|
||||
craft_dxf::records(&tags).iter().filter(|(k, _)| k == "APPID").filter_map(|(_, t)| t.iter().find(|t| t.code == 2).map(|t| t.str())).collect();
|
||||
assert!(appids.contains(&"ACME".to_string()) && appids.contains(&"PE_URL".to_string()), "{appids:?}");
|
||||
let mut back = session_from(&text);
|
||||
assert_eq!(handle_of(&back, true), h, "the line keeps its handle");
|
||||
let again = &entities(&mut back, json!({"xdata": true}))[0]["xdata"];
|
||||
assert_eq!(again, got, "{text}");
|
||||
|
||||
// Replacing one application leaves the other; null removes; undo brings it back.
|
||||
s.execute("properties.set", &json!({"handles": [h], "xdata": {"ACME": [[1070, 9]]}})).unwrap();
|
||||
let got = &entities(&mut s, json!({"xdata": true}))[0]["xdata"];
|
||||
assert_eq!(got, &json!({"ACME": [[1070, 9]], "PE_URL": [[1000, "https://example.com"]]}));
|
||||
s.execute("properties.set", &json!({"handles": [h], "xdata": {"PE_URL": null, "ACME": []}})).unwrap();
|
||||
assert!(entities(&mut s, json!({"xdata": true}))[0].get("xdata").is_none());
|
||||
s.undo().unwrap();
|
||||
assert_eq!(entities(&mut s, json!({"xdata": true}))[0]["xdata"]["ACME"], json!([[1070, 9]]));
|
||||
// The xdata of a drawing's own file comes with it and can be edited too.
|
||||
let mut s = session_from(DXF);
|
||||
let h = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_))).map(|e| e.handle.hex()).unwrap();
|
||||
s.execute("properties.set", &json!({"handles": [h], "xdata": {"acme_tags": [[1000, "P-02"]]}})).unwrap();
|
||||
assert_eq!(entities(&mut s, json!({"xdata": "ACME_TAGS", "type": "LwPolyline"}))[0]["xdata"], json!({"acme_tags": [[1000, "P-02"]]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_xdata_is_refused_and_changes_nothing() {
|
||||
let mut s = session_from(DXF);
|
||||
let h = handle_of(&s, true);
|
||||
let before = entities(&mut s, json!({"xdata": true}));
|
||||
let huge: Vec<Value> = std::iter::repeat_n(json!([1000, "x"]), cadcraft_engine::doc::MAX_XDATA_GROUPS + 1).collect();
|
||||
for bad in [
|
||||
json!([]),
|
||||
json!("ACME"),
|
||||
json!({"": [[1000, "x"]]}),
|
||||
json!({"CADCRAFT": [[1000, "x"]]}),
|
||||
json!({"bad*name": [[1000, "x"]]}),
|
||||
json!({"ACME": "x"}),
|
||||
json!({"ACME": [1000, "x"]}),
|
||||
json!({"ACME": [[1000]]}),
|
||||
json!({"ACME": [[1000, 5]]}),
|
||||
json!({"ACME": [[1001, "B"]]}),
|
||||
json!({"ACME": [[8, "0"]]}),
|
||||
json!({"ACME": [[999, "x"]]}),
|
||||
json!({"ACME": [[1072, 1]]}),
|
||||
json!({"ACME": [["1000", "x"]]}),
|
||||
json!({"ACME": [[1e300, "x"]]}),
|
||||
json!({"ACME": [[1002, "("]]}),
|
||||
json!({"ACME": [[1002, "}"]]}),
|
||||
json!({"ACME": [[1002, "{"], [1000, "x"]]}),
|
||||
json!({"ACME": [[1010, 1]]}),
|
||||
json!({"ACME": [[1010, [1]]]}),
|
||||
json!({"ACME": [[1010, [1, 2, 3, 4]]]}),
|
||||
json!({"ACME": [[1010, [1, "y"]]]}),
|
||||
json!({"ACME": [[1020, 1]]}),
|
||||
json!({"ACME": [[1040, "1"]]}),
|
||||
json!({"ACME": [[1040, null]]}),
|
||||
json!({"ACME": [[1070, 1.5]]}),
|
||||
json!({"ACME": [[1070, 40000]]}),
|
||||
json!({"ACME": [[1071, 3000000000i64]]}),
|
||||
json!({"ACME": [[1004, "ABC"]]}),
|
||||
json!({"ACME": [[1004, "zz"]]}),
|
||||
json!({"ACME": [[1005, ""]]}),
|
||||
json!({"ACME": [[1005, "nothex"]]}),
|
||||
json!({"ACME": [[1000, "x".repeat(256)]]}),
|
||||
json!({"ACME": [[1000, "a\nb"]]}),
|
||||
json!({"ACME": huge}),
|
||||
] {
|
||||
let err = s.execute("properties.set", &json!({"handles": [h], "xdata": bad})).expect_err(&format!("{bad} must be refused"));
|
||||
assert!(!err.to_string().is_empty());
|
||||
assert_eq!(entities(&mut s, json!({"xdata": true})), before, "{bad} changed something");
|
||||
}
|
||||
// Together, two applications may not exceed what one object holds.
|
||||
let full: Vec<Value> = std::iter::repeat_n(json!([1070, 1]), cadcraft_engine::doc::MAX_XDATA_GROUPS - 1).collect();
|
||||
s.execute("properties.set", &json!({"handles": [h], "xdata": {"PE_URL": null, "ACME_TAGS": null, "FULL": full}})).unwrap();
|
||||
let err = s.execute("properties.set", &json!({"handles": [h], "xdata": {"MORE": [[1070, 1]]}})).unwrap_err();
|
||||
assert!(err.to_string().contains("exceed"), "{err}");
|
||||
assert!(entities(&mut s, json!({"xdata": true}))[0]["xdata"].get("MORE").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_handle_changes_nothing() {
|
||||
// One handle that names no object fails the whole call before any object or the layer
|
||||
// table changes: the other object keeps its data and the new layer is not created.
|
||||
let mut s = session_from(DXF);
|
||||
let h = handle_of(&s, true);
|
||||
let before = entities(&mut s, json!({"xdata": true}));
|
||||
let r = s.execute("properties.set", &json!({"handles": [h, "FFFF"], "layer": "NEWLAYER", "xdata": {"ACME": [[1000, "x"]]}}));
|
||||
assert!(r.is_err(), "a missing handle is refused");
|
||||
assert_eq!(entities(&mut s, json!({"xdata": true})), before);
|
||||
assert!(s.doc().unwrap().layer("NEWLAYER").is_none(), "no layer is left behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_of_one_application_in_any_case_are_one_entry() {
|
||||
// `ACME` and `acme` runs on one entity are one application (as `set_xdata_app` treats
|
||||
// them): one JSON key with every group, and `properties.set` with that entry keeps them all.
|
||||
let dxf = "0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n2A\n8\n0\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n\
|
||||
1001\nACME\n1070\n1\n1001\nacme\n1070\n2\n1001\nOTHER\n1000\nx\n0\nENDSEC\n0\nEOF\n";
|
||||
let mut s = session_from(dxf);
|
||||
let h = handle_of(&s, true);
|
||||
let shown = entities(&mut s, json!({"xdata": true}));
|
||||
assert_eq!(shown[0]["xdata"], json!({"ACME": [[1070, 1], [1070, 2]], "OTHER": [[1000, "x"]]}));
|
||||
assert_eq!(entities(&mut s, json!({"xdata": "acme"}))[0]["xdata"], json!({"ACME": [[1070, 1], [1070, 2]]}));
|
||||
s.execute("properties.set", &json!({"handles": [h], "xdata": shown[0]["xdata"]})).unwrap();
|
||||
assert_eq!(entities(&mut s, json!({"xdata": true}))[0]["xdata"], shown[0]["xdata"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acad_xdata_of_a_dimension_is_refused_and_kept_elsewhere() {
|
||||
// A dimension's `ACAD` run is its DSTYLE overrides, written from the model and read back
|
||||
// into them: raw `ACAD` groups on a dimension would be lost on save, so they are refused
|
||||
// (nothing changes). On any other object `ACAD` is foreign data and survives a save.
|
||||
let mut s = Session::new();
|
||||
s.script("dimlinear 0,0 10,0 5,-3\n").unwrap();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
let dim = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).map(|e| e.handle.hex()).unwrap();
|
||||
let line = handle_of(&s, true);
|
||||
s.execute("properties.set", &json!({"handles": [&dim], "textHeight": 5})).unwrap();
|
||||
let before = entities(&mut s, json!({"xdata": true}));
|
||||
let r = s.execute("properties.set", &json!({"handles": [&dim], "xdata": {"ACAD": [[1000, "MINE"], [1070, 42]]}}));
|
||||
assert!(r.is_err(), "ACAD on a dimension is refused");
|
||||
assert_eq!(entities(&mut s, json!({"xdata": true})), before);
|
||||
s.execute("properties.set", &json!({"handles": [&line], "xdata": {"ACAD": [[1000, "MINE"], [1070, 42]]}})).unwrap();
|
||||
let bytes = cadcraft_io::write(s.doc().unwrap(), "acad.dxf").unwrap();
|
||||
let mut back = Session::empty();
|
||||
back.open_drawing(cadcraft_io::read_dxf(&bytes).unwrap(), "acad", None);
|
||||
let kept = entities(&mut back, json!({"xdata": "ACAD"}));
|
||||
assert_eq!(kept.len(), 1, "only the line carries raw ACAD data");
|
||||
assert_eq!(kept[0]["type"], "Line");
|
||||
assert_eq!(kept[0]["xdata"], json!({"ACAD": [[1000, "MINE"], [1070, 42]]}));
|
||||
// The dimension's own override is still there after the round trip.
|
||||
let dm = back.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap();
|
||||
assert!(matches!(&dm.kind, EntityKind::Dimension(d) if !d.overrides.is_empty()), "the DSTYLE overrides survive");
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
//! Annotative text, MText, dimensions and multileaders in DXF, as AutoCAD keeps them. An annotative object
|
||||
//! carries `AcadAnnotative` xdata and, in its extension dictionary under
|
||||
//! `AcDbContextDataManager`, a dictionary `ACDB_ANNOTATIONSCALES` with one "object context data"
|
||||
//! object per annotation scale it supports (`*A1`, `*A2`…). Each context names its SCALE object
|
||||
//! (340), says whether it is the default one (290 = 1, the scale the object's own groups are
|
||||
//! written at) and holds what changes with the scale: a text's insertion and alignment points, an
|
||||
//! MText's insertion point, width and columns, a dimension's text position and the anonymous `*D`
|
||||
//! block with its geometry at that scale, a multileader's whole `CONTEXT_DATA{` body at that
|
||||
//! scale.
|
||||
//!
|
||||
//! CADCraft keeps an annotative object at paper size with the list of scales it supports
|
||||
//! ([`cadcraft_doc::Common::anno_scales`]). It writes the object at its default scale with a
|
||||
//! context per scale ([`plan`], [`objects`]), and reads the scales and paper size back from the
|
||||
//! contexts ([`resolve`]). An object's position at each scale is the one the scale gives it:
|
||||
//! AutoCAD lets a context move an object at one scale only, which CADCraft doesn't model.
|
||||
//!
|
||||
//! Objects inside block definitions are left alone, and files older than AutoCAD 2007's format
|
||||
//! (before annotation scaling) don't get contexts.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use cadcraft_doc::{AnnoScale, DimKind, Drawing, Entity, EntityKind, HAlign, Handle, MLeader, MTextColumnType, Text, VAlign};
|
||||
use cadcraft_geom::Vec3;
|
||||
use craft_dxf::{SectionRef, Tag};
|
||||
|
||||
/// The context classes: (DXF record name, C++ class name).
|
||||
const TEXT: (&str, &str) = ("ACDB_TEXTOBJECTCONTEXTDATA_CLASS", "AcDbTextObjectContextData");
|
||||
const MTEXT: (&str, &str) = ("ACDB_MTEXTOBJECTCONTEXTDATA_CLASS", "AcDbMTextObjectContextData");
|
||||
const ALDIM: (&str, &str) = ("ACDB_ALDIMOBJECTCONTEXTDATA_CLASS", "AcDbAlignedDimensionObjectContextData");
|
||||
const ANGDIM: (&str, &str) = ("ACDB_ANGDIMOBJECTCONTEXTDATA_CLASS", "AcDbAngularDimensionObjectContextData");
|
||||
const RADIM: (&str, &str) = ("ACDB_RADIMOBJECTCONTEXTDATA_CLASS", "AcDbRadialDimensionObjectContextData");
|
||||
const DMDIM: (&str, &str) = ("ACDB_DMDIMOBJECTCONTEXTDATA_CLASS", "AcDbDiametricDimensionObjectContextData");
|
||||
const ORDDIM: (&str, &str) = ("ACDB_ORDDIMOBJECTCONTEXTDATA_CLASS", "AcDbOrdinateDimensionObjectContextData");
|
||||
const MLEADER: (&str, &str) = ("ACDB_MLEADEROBJECTCONTEXTDATA_CLASS", "AcDbMLeaderObjectContextData");
|
||||
|
||||
/// The extension dictionary entry and the dictionary of contexts.
|
||||
const MANAGER_KEY: &str = "AcDbContextDataManager";
|
||||
const SCALES_KEY: &str = "ACDB_ANNOTATIONSCALES";
|
||||
|
||||
/// Most contexts read per object (hostile files).
|
||||
const MAX_CONTEXTS: usize = cadcraft_doc::MAX_SCALES;
|
||||
|
||||
/// Whether `e` (in model space or a layout) is written with annotation scale contexts: annotative
|
||||
/// text, MText, dimensions and multileaders.
|
||||
pub(crate) fn has_contexts(e: &Entity) -> bool {
|
||||
cadcraft_doc::is_annotative(e) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_))
|
||||
}
|
||||
|
||||
/// The scales `e` is written at (valid, each name once) and which of them is the default: the
|
||||
/// current annotation scale when `e` supports it, else its first.
|
||||
pub(crate) fn scales(d: &Drawing, e: &Entity) -> (Vec<AnnoScale>, usize) {
|
||||
let mut out: Vec<AnnoScale> = Vec::new();
|
||||
for s in e.common.anno_scales.iter().filter(|s| s.is_valid() && !s.name.trim().is_empty()) {
|
||||
if !out.iter().any(|x| x.name.eq_ignore_ascii_case(&s.name)) {
|
||||
out.push(s.clone());
|
||||
}
|
||||
}
|
||||
let current = d.current_anno_scale();
|
||||
let default = out.iter().position(|s| s.name.eq_ignore_ascii_case(¤t.name)).unwrap_or(0);
|
||||
(out, default)
|
||||
}
|
||||
|
||||
/// Whether text placed by its alignment point (group 11) rather than its start point (10).
|
||||
fn by_alignment(t: &Text) -> bool {
|
||||
t.align_pt.is_some() && !matches!((t.halign, t.valign), (HAlign::Left, VAlign::Baseline) | (HAlign::Aligned | HAlign::Fit, _))
|
||||
}
|
||||
|
||||
/// `e` at annotation scale `f`, as its groups are written there: sizes scaled (see
|
||||
/// [`cadcraft_doc::anno_scaled`]) and justified text's start point moved with its size about its
|
||||
/// alignment point. A dimension's definition gets that scale (DIMSCALE).
|
||||
pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity {
|
||||
let mut out = cadcraft_doc::anno_scaled(e, f);
|
||||
if let (EntityKind::Text(t), EntityKind::Text(paper)) = (&mut out.kind, &e.kind)
|
||||
&& by_alignment(paper)
|
||||
&& let Some(a) = paper.align_pt
|
||||
{
|
||||
t.insert = a + (paper.insert - a) * f;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One context: its handle, the SCALE object's handle and the scale.
|
||||
pub(crate) struct Context {
|
||||
handle: String,
|
||||
scale: String,
|
||||
factor: f64,
|
||||
default: bool,
|
||||
/// A dimension's `*D` block at this scale.
|
||||
block: Option<String>,
|
||||
}
|
||||
|
||||
/// The objects written for one annotative object.
|
||||
pub(crate) struct Obj {
|
||||
/// Its extension dictionary (shared with a dimension's DIMASSOC).
|
||||
pub xdict: String,
|
||||
/// Whether the extension dictionary is written here (not with the DIMASSOC).
|
||||
pub own_xdict: bool,
|
||||
pub manager: String,
|
||||
dict: String,
|
||||
contexts: Vec<Context>,
|
||||
}
|
||||
|
||||
/// The annotative objects of a file being written, by entity handle.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Plan {
|
||||
pub objs: HashMap<Handle, Obj>,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
/// The context classes the file uses (for its CLASSES section).
|
||||
pub fn classes(&self, d: &Drawing) -> Vec<(&'static str, &'static str)> {
|
||||
let mut out = BTreeSet::new();
|
||||
for h in self.objs.keys() {
|
||||
if let Some(e) = d.entity(*h) {
|
||||
out.insert(class_of(e));
|
||||
}
|
||||
}
|
||||
out.into_iter().flatten().collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn class_of(e: &Entity) -> Option<(&'static str, &'static str)> {
|
||||
Some(match &e.kind {
|
||||
EntityKind::Text(_) => TEXT,
|
||||
EntityKind::MText(_) => MTEXT,
|
||||
EntityKind::MLeader(_) => MLEADER,
|
||||
EntityKind::Dimension(dm) => match dm.kind {
|
||||
DimKind::Linear { .. } | DimKind::Aligned | DimKind::ArcLength => ALDIM,
|
||||
DimKind::Angular | DimKind::Angular3P => ANGDIM,
|
||||
DimKind::Radius => RADIM,
|
||||
DimKind::Diameter => DMDIM,
|
||||
DimKind::Ordinate { .. } => ORDDIM,
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Plan the objects of `e` (annotative, see [`has_contexts`]): `scale_handle` gives each scale's
|
||||
/// SCALE object, `xdict` the extension dictionary it already has (a dimension's DIMASSOC),
|
||||
/// `blocks` a dimension's `*D` block at each of [`scales`], and `next` new handles. `None` when
|
||||
/// no scale has a SCALE object.
|
||||
pub(crate) fn plan_one(
|
||||
d: &Drawing,
|
||||
e: &Entity,
|
||||
scale_handle: impl Fn(&str) -> Option<String>,
|
||||
xdict: Option<String>,
|
||||
blocks: Option<&[String]>,
|
||||
mut next: impl FnMut() -> String,
|
||||
) -> Option<Obj> {
|
||||
let (scales, default) = scales(d, e);
|
||||
let mut contexts = Vec::new();
|
||||
for (i, s) in scales.iter().enumerate() {
|
||||
let Some(scale) = scale_handle(&s.name) else { continue };
|
||||
let block = blocks.and_then(|b| b.get(i)).cloned();
|
||||
contexts.push(Context { handle: String::new(), scale, factor: s.factor(), default: i == default, block });
|
||||
}
|
||||
if contexts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if !contexts.iter().any(|c| c.default)
|
||||
&& let Some(c) = contexts.first_mut()
|
||||
{
|
||||
c.default = true;
|
||||
}
|
||||
let own_xdict = xdict.is_none();
|
||||
let xdict = xdict.unwrap_or_else(&mut next);
|
||||
let (manager, dict) = (next(), next());
|
||||
for c in &mut contexts {
|
||||
c.handle = next();
|
||||
}
|
||||
Some(Obj { xdict, own_xdict, manager, dict, contexts })
|
||||
}
|
||||
|
||||
/// The factor `e` is written at (its default context's).
|
||||
pub(crate) fn default_factor(o: &Obj) -> f64 {
|
||||
o.contexts.iter().find(|c| c.default).map_or(1.0, |c| c.factor)
|
||||
}
|
||||
|
||||
/// `AcadAnnotative` xdata marking an annotative object.
|
||||
pub(crate) fn xdata() -> Vec<Tag> {
|
||||
vec![Tag::s(1001, "AcadAnnotative"), Tag::s(1000, "AnnotativeData"), Tag::s(1002, "{"), Tag::i(1070, 1), Tag::i(1070, 1), Tag::s(1002, "}")]
|
||||
}
|
||||
|
||||
/// The extension dictionary entry of `o`'s context manager (key and handle groups).
|
||||
pub(crate) fn xdict_entry(o: &Obj) -> Vec<Tag> {
|
||||
vec![Tag::s(3, MANAGER_KEY), Tag::s(360, o.manager.clone())]
|
||||
}
|
||||
|
||||
fn p(out: &mut Vec<Tag>, c: i32, v: Vec3, z: bool) {
|
||||
out.push(Tag::f(c, v.x));
|
||||
out.push(Tag::f(c + 10, v.y));
|
||||
if z {
|
||||
out.push(Tag::f(c + 20, v.z));
|
||||
}
|
||||
}
|
||||
|
||||
/// A dictionary record: handle, reactor and owner `owner`, hard-owner flag 281 = 1, `entries`.
|
||||
fn dictionary(out: &mut Vec<Tag>, h: &str, owner: &str, cloning: bool, entries: &[(String, i32, String)]) {
|
||||
out.push(Tag::s(0, "DICTIONARY"));
|
||||
out.push(Tag::s(5, h));
|
||||
out.extend([Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, owner), Tag::s(102, "}")]);
|
||||
out.push(Tag::s(330, owner));
|
||||
out.push(Tag::s(100, "AcDbDictionary"));
|
||||
if cloning {
|
||||
out.push(Tag::i(280, 1));
|
||||
}
|
||||
out.push(Tag::i(281, 1));
|
||||
for (k, code, v) in entries {
|
||||
out.push(Tag::s(3, k.clone()));
|
||||
out.push(Tag::s(*code, v.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects of annotative object `e` planned as `o`: its extension dictionary (unless the
|
||||
/// DIMASSOC's holds the manager), the context manager, the dictionary of contexts and the
|
||||
/// contexts. `mleader` gives a multileader's groups as the entity writer writes them.
|
||||
pub(crate) fn objects(d: &Drawing, e: &Entity, o: &Obj, mleader: &dyn Fn(&MLeader) -> Vec<Tag>) -> Vec<Tag> {
|
||||
let mut out = Vec::new();
|
||||
let eh = e.handle.hex();
|
||||
if o.own_xdict {
|
||||
dictionary(&mut out, &o.xdict, &eh, true, &[(MANAGER_KEY.to_string(), 360, o.manager.clone())]);
|
||||
}
|
||||
dictionary(&mut out, &o.manager, &o.xdict, false, &[(SCALES_KEY.to_string(), 350, o.dict.clone())]);
|
||||
let keyed: Vec<(String, i32, String)> = o.contexts.iter().enumerate().map(|(i, c)| (format!("*A{}", i + 1), 350, c.handle.clone())).collect();
|
||||
dictionary(&mut out, &o.dict, &o.manager, false, &keyed);
|
||||
let Some((class, _)) = class_of(e) else { return out };
|
||||
for c in &o.contexts {
|
||||
out.push(Tag::s(0, class));
|
||||
out.push(Tag::s(5, c.handle.clone()));
|
||||
out.extend([Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, o.dict.clone()), Tag::s(102, "}")]);
|
||||
out.push(Tag::s(330, o.dict.clone()));
|
||||
out.push(Tag::s(100, "AcDbObjectContextData"));
|
||||
out.push(Tag::i(70, 4));
|
||||
out.push(Tag::i(290, i64::from(c.default)));
|
||||
out.push(Tag::s(100, "AcDbAnnotScaleObjectContextData"));
|
||||
out.push(Tag::s(340, c.scale.clone()));
|
||||
context_groups(&mut out, d, &at_scale(e, c.factor), c, mleader);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What a context holds of `e` (already at the context's scale).
|
||||
fn context_groups(out: &mut Vec<Tag>, d: &Drawing, e: &Entity, c: &Context, mleader: &dyn Fn(&MLeader) -> Vec<Tag>) {
|
||||
match &e.kind {
|
||||
// The multileader's `CONTEXT_DATA{` body, without its braces.
|
||||
EntityKind::MLeader(m) => {
|
||||
let mut tags = mleader(m);
|
||||
mleader_at(&mut tags, c.factor);
|
||||
let open = tags.iter().position(|t| t.code == 300 && t.str().trim_start().starts_with("CONTEXT_DATA"));
|
||||
let close = tags.iter().position(|t| t.code == 301);
|
||||
if let (Some(a), Some(b)) = (open, close)
|
||||
&& a < b
|
||||
{
|
||||
out.extend(tags.get(a + 1..b).unwrap_or(&[]).iter().cloned());
|
||||
}
|
||||
}
|
||||
EntityKind::Text(t) => {
|
||||
let h = match t.halign {
|
||||
HAlign::Left => 0,
|
||||
HAlign::Center => 1,
|
||||
HAlign::Right => 2,
|
||||
HAlign::Aligned => 3,
|
||||
HAlign::Middle => 4,
|
||||
HAlign::Fit => 5,
|
||||
};
|
||||
out.push(Tag::i(70, h));
|
||||
out.push(Tag::f(50, t.rotation.to_degrees()));
|
||||
p(out, 10, t.insert, false);
|
||||
p(out, 11, t.align_pt.unwrap_or(Vec3::ZERO), false);
|
||||
}
|
||||
EntityKind::MText(t) => {
|
||||
out.push(Tag::i(70, i64::from(t.attach)));
|
||||
p(out, 10, Vec3::new(t.rotation.cos(), t.rotation.sin(), 0.0), true);
|
||||
p(out, 11, t.insert, true);
|
||||
// Reference rectangle (40, 41) and an estimate of the text's extents (42, 43): AutoCAD
|
||||
// lays the text out again.
|
||||
let lines = t.contents.split("\\P").count().max(1) as f64;
|
||||
let longest = t.contents.split("\\P").map(|l| l.chars().count()).max().unwrap_or(1) as f64;
|
||||
out.push(Tag::f(40, t.width));
|
||||
out.push(Tag::f(41, 0.0));
|
||||
out.push(Tag::f(42, if t.width > 0.0 { t.width } else { t.height * 0.8 * longest }));
|
||||
out.push(Tag::f(43, t.height * 1.66 * lines));
|
||||
match &t.columns {
|
||||
None => out.push(Tag::i(71, 0)),
|
||||
Some(cols) => {
|
||||
let dynamic = cols.kind == MTextColumnType::Dynamic;
|
||||
let manual = dynamic && !cols.auto_height;
|
||||
out.push(Tag::i(71, if dynamic { 2 } else { 1 }));
|
||||
out.push(Tag::i(72, if manual { cols.heights.len() as i64 } else { i64::from(cols.count.max(1)) }));
|
||||
out.push(Tag::f(44, t.width));
|
||||
out.push(Tag::f(45, cols.gutter));
|
||||
out.push(Tag::i(73, i64::from(cols.auto_height)));
|
||||
out.push(Tag::i(74, i64::from(cols.flow_reversed)));
|
||||
if manual {
|
||||
out.extend(cols.heights.iter().map(|h| Tag::f(46, *h)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::Dimension(dm) => {
|
||||
out.push(Tag::s(100, "AcDbDimensionObjectContextData"));
|
||||
out.push(Tag::s(2, c.block.clone().unwrap_or_default()));
|
||||
out.push(Tag::i(293, 0));
|
||||
let text = if dm.user_text_pos { dm.text_mid } else { cadcraft_render::dimension_in(d, dm).text_pos.to3(0.0) };
|
||||
p(out, 10, text, false);
|
||||
out.push(Tag::i(294, i64::from(!dm.user_text_pos)));
|
||||
out.push(Tag::f(140, dm.text_rotation));
|
||||
for code in [298, 291, 70, 292, 71, 280, 295, 296, 297] {
|
||||
out.push(Tag::i(code, 0));
|
||||
}
|
||||
let Some((_, sub)) = class_of(e) else { return };
|
||||
out.push(Tag::s(100, sub));
|
||||
let pts: &[(i32, Vec3)] = match dm.kind {
|
||||
DimKind::Linear { .. } | DimKind::Aligned | DimKind::ArcLength | DimKind::Angular3P => &[(11, dm.defpt)],
|
||||
DimKind::Angular => &[(11, dm.p16)],
|
||||
DimKind::Radius => &[(11, dm.p15)],
|
||||
DimKind::Diameter => &[(11, dm.p15), (12, dm.defpt)],
|
||||
DimKind::Ordinate { .. } => &[(11, dm.defpt), (12, dm.p14)],
|
||||
};
|
||||
for (code, v) in pts {
|
||||
p(out, *code, *v, true);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A multileader's groups (as [`crate::dxf_mleader::entity_tags`] writes them) at annotation
|
||||
/// scale `f`: its context's overall scale (40) is `f` and its landing gap (145) is at that scale.
|
||||
pub(crate) fn mleader_at(tags: &mut [Tag], f: f64) {
|
||||
let Some(open) = tags.iter().position(|t| t.code == 300 && t.str().trim_start().starts_with("CONTEXT_DATA")) else { return };
|
||||
let (mut scale, mut gap) = (false, false);
|
||||
for t in tags.iter_mut().skip(open + 1) {
|
||||
match t.code {
|
||||
// The context's own groups end where its leaders start.
|
||||
302 | 301 => break,
|
||||
40 if !scale => {
|
||||
*t = Tag::f(40, f);
|
||||
scale = true;
|
||||
}
|
||||
145 if !gap => {
|
||||
*t = Tag::f(145, t.f64() * f);
|
||||
gap = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Reading
|
||||
|
||||
/// A record's groups before its xdata.
|
||||
fn own(tags: &[Tag]) -> &[Tag] {
|
||||
tags.get(..tags.iter().position(|t| t.code >= 1000).unwrap_or(tags.len())).unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// A handle as the key of the maps below.
|
||||
fn key(s: &str) -> Option<Handle> {
|
||||
Handle::parse_hex(s.trim()).filter(|h| h.0 != 0)
|
||||
}
|
||||
|
||||
/// The extension dictionary of a record (`{ACAD_XDICTIONARY` group).
|
||||
fn xdict_of(tags: &[Tag]) -> Option<Handle> {
|
||||
let i = own(tags).iter().position(|t| t.code == 102 && t.str().trim() == "{ACAD_XDICTIONARY")?;
|
||||
tags.get(i + 1).filter(|t| t.code == 360).and_then(|t| key(&t.str()))
|
||||
}
|
||||
|
||||
/// A dictionary's entry `name` (case-insensitive).
|
||||
fn entry(tags: &[Tag], name: &str) -> Option<Handle> {
|
||||
let g = own(tags);
|
||||
let i = g.iter().position(|t| t.code == 3 && t.str().trim().eq_ignore_ascii_case(name))?;
|
||||
g.get(i + 1).filter(|t| matches!(t.code, 350 | 360)).and_then(|t| key(&t.str()))
|
||||
}
|
||||
|
||||
/// Every entry of a dictionary.
|
||||
fn all_entries(tags: &[Tag]) -> Vec<Handle> {
|
||||
own(tags).iter().filter(|t| matches!(t.code, 350 | 360)).filter_map(|t| key(&t.str())).take(MAX_CONTEXTS).collect()
|
||||
}
|
||||
|
||||
/// Read the annotation scale contexts of the text, MText and dimensions of model space and the
|
||||
/// layouts: each becomes annotative with the scales of its contexts (in their order), and
|
||||
/// its sizes are taken back to paper size from the default scale. Contexts of other objects, and
|
||||
/// contexts whose scale is unknown, are passed over.
|
||||
pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
let Some(objects) = secs.iter().find(|s| s.name == "OBJECTS") else { return };
|
||||
let mut objs: HashMap<Handle, (String, &[Tag])> = HashMap::new();
|
||||
each_record(objects.tags, |kind, tags| {
|
||||
if let Some(h) = own(tags).iter().find(|t| t.code == 5).and_then(|t| key(&t.str())) {
|
||||
objs.entry(h).or_insert((kind.to_ascii_uppercase(), tags));
|
||||
}
|
||||
});
|
||||
current_scale(&objs, d);
|
||||
if !objs.values().any(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) {
|
||||
return;
|
||||
}
|
||||
let scales: HashMap<Handle, AnnoScale> =
|
||||
objs.iter().filter(|(_, (k, _))| k == "SCALE").filter_map(|(h, (_, t))| Some((*h, crate::dxf_ext::read_scale(own(t))?))).collect();
|
||||
// The entities that may have contexts: their extension dictionaries.
|
||||
let mut found: Vec<(Handle, Handle)> = Vec::new();
|
||||
for s in secs.iter().filter(|s| s.name == "ENTITIES" || s.name == "BLOCKS") {
|
||||
each_record(s.tags, |kind, tags| {
|
||||
if !matches!(kind, "TEXT" | "MTEXT" | "DIMENSION" | "ARC_DIMENSION" | "LARGE_RADIAL_DIMENSION" | "MULTILEADER") {
|
||||
return;
|
||||
}
|
||||
let h = own(tags).iter().find(|t| t.code == 5).and_then(|t| key(&t.str()));
|
||||
if let (Some(h), Some(x)) = (h, xdict_of(tags)) {
|
||||
found.push((h, x));
|
||||
}
|
||||
});
|
||||
}
|
||||
for (h, xdict) in found {
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
if !matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_)) {
|
||||
continue;
|
||||
}
|
||||
let dict = objs
|
||||
.get(&xdict)
|
||||
.and_then(|(_, t)| entry(t, MANAGER_KEY))
|
||||
.and_then(|m| objs.get(&m))
|
||||
.and_then(|(_, t)| entry(t, SCALES_KEY))
|
||||
.and_then(|s| objs.get(&s));
|
||||
let Some((_, dict)) = dict else { continue };
|
||||
let mut list: Vec<(AnnoScale, bool)> = Vec::new();
|
||||
for c in all_entries(dict) {
|
||||
let Some((_, t)) = objs.get(&c).filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) else { continue };
|
||||
let g = own(t);
|
||||
let scale = g.iter().find(|t| t.code == 340).and_then(|t| key(&t.str())).and_then(|s| scales.get(&s));
|
||||
let default = g.iter().find(|t| t.code == 290).is_some_and(|t| t.i64() != 0);
|
||||
if let Some(s) = scale
|
||||
&& !list.iter().any(|(x, _)| x.name.eq_ignore_ascii_case(&s.name))
|
||||
{
|
||||
list.push((s.clone(), default));
|
||||
}
|
||||
}
|
||||
if list.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// The object's groups were written at the default context's scale.
|
||||
let f = list.iter().find(|(_, default)| *default).or(list.first()).map_or(1.0, |(s, _)| s.factor());
|
||||
let list: Vec<AnnoScale> = list.into_iter().map(|(s, _)| s).collect();
|
||||
let _ = d.modify_entity(h, |e| {
|
||||
e.common.anno_scales = list;
|
||||
to_paper(e, f);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The current annotation scale as AutoCAD keeps it: in the named object dictionary's
|
||||
/// `AcDbVariableDictionary`, a DICTIONARYVAR `CANNOSCALE` with the scale's name (group 1). It is
|
||||
/// newer than CADCraft's own record when AutoCAD saved the file last (AutoCAD keeps that record as
|
||||
/// it was), and CADCraft writes the two alike. A name the scale list lacks is passed over.
|
||||
fn current_scale(objs: &HashMap<Handle, (String, &[Tag])>, d: &mut Drawing) {
|
||||
let root = objs.iter().filter(|(_, (k, t))| k == "DICTIONARY" && own(t).iter().find(|t| t.code == 330).is_some_and(|o| o.str().trim() == "0"));
|
||||
let Some((_, (_, root))) = root.min_by_key(|(h, _)| h.0) else { return };
|
||||
let var = entry(root, "AcDbVariableDictionary").and_then(|v| objs.get(&v)).and_then(|(_, t)| entry(t, "CANNOSCALE")).and_then(|c| objs.get(&c));
|
||||
let Some(name) = var.and_then(|(_, t)| own(t).iter().find(|t| t.code == 1).map(Tag::str)) else { return };
|
||||
let name = name.trim();
|
||||
if d.anno_scale(name).is_some_and(AnnoScale::is_valid) {
|
||||
d.header.set_str("CANNOSCALE", name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Take an object written at annotation scale `f` back to paper size (the inverse of
|
||||
/// [`at_scale`]).
|
||||
fn to_paper(e: &mut Entity, f: f64) {
|
||||
if !(f.is_finite() && f > 0.0) || (f - 1.0).abs() < 1e-12 {
|
||||
return;
|
||||
}
|
||||
let inv = 1.0 / f;
|
||||
match &mut e.kind {
|
||||
EntityKind::Text(t) => {
|
||||
if by_alignment(t)
|
||||
&& let Some(a) = t.align_pt
|
||||
{
|
||||
t.insert = a + (t.insert - a) * inv;
|
||||
}
|
||||
t.height *= inv;
|
||||
}
|
||||
EntityKind::MText(t) => {
|
||||
t.height *= inv;
|
||||
t.width *= inv;
|
||||
if let Some(c) = &mut t.columns {
|
||||
c.scale(inv);
|
||||
}
|
||||
}
|
||||
// Its sizes, and its content's place about the landing, scale linearly.
|
||||
EntityKind::MLeader(_) => e.kind = cadcraft_doc::anno_scaled(e, inv).kind,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Call `f` with each record (type, groups after its `0` group) of a section.
|
||||
fn each_record<'a>(tags: &'a [Tag], mut f: impl FnMut(&str, &'a [Tag])) {
|
||||
let mut open: Option<(String, usize)> = None;
|
||||
for (i, t) in tags.iter().enumerate() {
|
||||
if t.code == 0 {
|
||||
if let Some((k, s)) = open.take() {
|
||||
f(&k, tags.get(s..i).unwrap_or(&[]));
|
||||
}
|
||||
open = Some((t.str(), i + 1));
|
||||
}
|
||||
}
|
||||
if let Some((k, s)) = open {
|
||||
f(&k, tags.get(s..).unwrap_or(&[]));
|
||||
}
|
||||
}
|
||||
+295
-21
@@ -3,7 +3,8 @@
|
||||
//! The filter holds the boundary vertices in the reference's coordinates (group 70 the count,
|
||||
//! 10/20 the vertices), whether clipping is on (71), the front and back clip (72/73, 40/41) and
|
||||
//! two 3×4 matrices (group 40, row by row): the inverse of the reference's transform, which takes
|
||||
//! the boundary into the block's coordinates, and the boundary's own transform (identity here).
|
||||
//! the boundary into the block's coordinates, and the boundary's own transform (composed with
|
||||
//! the inverse transform when non-identity, e.g. on clipboard-pasted block references).
|
||||
//!
|
||||
//! An inverted clip ("Invert clip") is marked as the reference app writes it in a file: the
|
||||
//! filter has an extension dictionary whose `ACAD_XREC_ROUNDTRIP` entry is an XRECORD holding
|
||||
@@ -15,7 +16,7 @@
|
||||
//! written. The record goes through DWG as it is.
|
||||
//!
|
||||
//! Reading takes the planar filters the model can hold out of the kept foreign data and puts them
|
||||
//! on the references ([`read`]); others (front/back clipping, a skewed boundary transform) stay
|
||||
//! on the references ([`read`]); others (front/back clipping, non-planar extrusion, sheared boundary transform) stay
|
||||
//! foreign and are written back untouched. Writing adds the dictionaries and the filter of every
|
||||
//! clipped reference to a copy of the drawing's foreign data ([`prepare`]), which the raw-data
|
||||
//! writer (#528) then places on the reference.
|
||||
@@ -164,9 +165,22 @@ fn roundtrip(f: &Foreign, idx: &Index, filter: &ForeignObject) -> Option<Vec<Vec
|
||||
(same && boundary.len() >= 2).then_some(boundary)
|
||||
}
|
||||
|
||||
/// The boundary a planar SPATIAL_FILTER holds, in the block's coordinates; with `boundary`, the
|
||||
/// clip is inverted and that is its outline (in the filter's coordinates). `None` for anything
|
||||
/// the model can't hold as it is (it then stays foreign).
|
||||
/// The boundary a planar SPATIAL_FILTER holds, in the block's coordinates.
|
||||
///
|
||||
/// Per the Autodesk DXF Reference for `SPATIAL_FILTER`:
|
||||
/// - Group 40 (first 12 values): 3×4 matrix representing the inverse of the block reference
|
||||
/// transformation (maps coordinates from WCS to block local space).
|
||||
/// - Group 40 (second 12 values): 3×4 matrix representing the transformation into the coordinate
|
||||
/// system of the clip boundary ($WCS \to \text{Boundary}$).
|
||||
///
|
||||
/// Since boundary vertices (group 10/20) are stored in the clip boundary's coordinate system,
|
||||
/// transforming them into the block's local coordinates requires inverting the boundary transform
|
||||
/// ($\text{Boundary} \to WCS$) and then applying the inverse block transform ($WCS \to \text{Block}$):
|
||||
/// $P_{\text{block}} = M_{\text{inverse}} \times (M_{\text{boundary\_xf}})^{-1} \times P_{\text{boundary}}$.
|
||||
/// In code: `boundary_xf.inverse()?.then(inverse)`.
|
||||
///
|
||||
/// With `boundary`, the clip is inverted and that is its outline (in the filter's coordinates).
|
||||
/// Returns `None` for unsupported configurations (e.g. non-planar extrusion, front/back clipping depth).
|
||||
fn parse_filter(o: &ForeignObject, boundary: Option<&[Vec2]>) -> Option<ClipBoundary> {
|
||||
let count = usize::try_from(number(&o.tags, 70)? as i64).ok()?;
|
||||
if !(2..=MAX_CLIP_VERTICES).contains(&count) {
|
||||
@@ -180,30 +194,47 @@ fn parse_filter(o: &ForeignObject, boundary: Option<&[Vec2]>) -> Option<ClipBoun
|
||||
return None;
|
||||
}
|
||||
let m: Vec<f64> = o.tags.iter().filter(|t| t.code == 40).map(|t| t.value.trim().parse::<f64>().unwrap_or(f64::NAN)).collect();
|
||||
let (inverse, own) = match m.len() {
|
||||
let (inverse, boundary_xf) = match m.len() {
|
||||
24 => (matrix_2d(m.get(..12)?)?, matrix_2d(m.get(12..)?)?),
|
||||
// Without matrices the vertices are taken as the block's own.
|
||||
0 => (Mat3::IDENTITY, Mat3::IDENTITY),
|
||||
_ => return None,
|
||||
};
|
||||
if (own.a - 1.0).abs() > 1e-9
|
||||
|| own.b.abs() > 1e-9
|
||||
|| own.c.abs() > 1e-9
|
||||
|| (own.d - 1.0).abs() > 1e-9
|
||||
|| own.e.abs() > 1e-9
|
||||
|| own.f.abs() > 1e-9
|
||||
{
|
||||
// Reject sheared/skewed boundary transforms that cannot be losslessly represented.
|
||||
// Scale-independent orthogonality check: |u . v| > 1e-4 * |u| * |v|
|
||||
let u_len = (boundary_xf.a * boundary_xf.a + boundary_xf.b * boundary_xf.b).sqrt();
|
||||
let v_len = (boundary_xf.c * boundary_xf.c + boundary_xf.d * boundary_xf.d).sqrt();
|
||||
if u_len <= 1e-9 || v_len <= 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let own = vertices(&o.tags, count)?;
|
||||
let outline = boundary.unwrap_or(&own);
|
||||
if !(2..=MAX_CLIP_VERTICES).contains(&outline.len()) {
|
||||
let dot = boundary_xf.a * boundary_xf.c + boundary_xf.b * boundary_xf.d;
|
||||
if dot.abs() > 1e-4 * u_len * v_len {
|
||||
return None;
|
||||
}
|
||||
let points: Vec<Vec2> = outline.iter().map(|p| inverse.apply(*p)).collect();
|
||||
let verts = vertices(&o.tags, count)?;
|
||||
let raw_outline = boundary.unwrap_or(&verts);
|
||||
if !(2..=MAX_CLIP_VERTICES).contains(&raw_outline.len()) {
|
||||
return None;
|
||||
}
|
||||
let net = boundary_xf.inverse()?.then(inverse);
|
||||
// Expand a 2-corner rectangle to 4 corners whenever the net transform from boundary space
|
||||
// to block space introduces rotation, preserving its rotated orientation in block space.
|
||||
let rotated_rect;
|
||||
let net_rotated = net.b.abs() > 1e-9 || net.c.abs() > 1e-9;
|
||||
let outline = match raw_outline {
|
||||
[a, b] if net_rotated => {
|
||||
rotated_rect = vec![*a, Vec2::new(b.x, a.y), *b, Vec2::new(a.x, b.y)];
|
||||
&rotated_rect[..]
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
let mut points: Vec<Vec2> = outline.iter().map(|p| net.apply(*p)).collect();
|
||||
if !points.iter().all(|p| p.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
if let [a, b] = points.as_slice() {
|
||||
points = vec![Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y))];
|
||||
}
|
||||
let inverted = boundary.is_some() || number(&o.tags, 290).is_some_and(|v| v != 0.0);
|
||||
let clip = ClipBoundary { points, enabled: number(&o.tags, 71).unwrap_or(1.0) != 0.0, inverted };
|
||||
cadcraft_render::clip::PolyClip::new(&clip.polygon()).is_some().then_some(clip)
|
||||
@@ -318,6 +349,25 @@ fn dictionary(h: Handle, owner: Handle) -> ForeignObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// The boundary transform (`boundary_xf`) and boundary-space vertices for `clip`.
|
||||
///
|
||||
/// A 2-vertex `SPATIAL_FILTER` defines an axis-aligned rectangle in `boundary_xf` space, with
|
||||
/// vertices ordered lower-left then upper-right per the DXF specification. When the reference is
|
||||
/// rotated, a 2-point block-space rectangle is axis-aligned in a frame rotated by
|
||||
/// `-to_world.rotation()` (orthogonal even under non-uniform or mirrored scale), and the two
|
||||
/// transformed corners are canonicalized to `(min_x, min_y)` then `(max_x, max_y)` in that
|
||||
/// boundary frame. Polyline boundaries (`len > 2`) keep their transformed vertex order.
|
||||
fn filter_geometry(clip: &ClipBoundary, to_world: &Mat3) -> (Mat3, Vec<Vec2>) {
|
||||
let block_space_rect = clip.points.len() == 2 && (to_world.b.abs() > 1e-9 || to_world.c.abs() > 1e-9);
|
||||
let boundary_xf = if block_space_rect { Mat3::rotate(-to_world.rotation()) } else { Mat3::IDENTITY };
|
||||
let pts_xf = to_world.then(boundary_xf);
|
||||
let mut points: Vec<Vec2> = clip.points.iter().map(|p| pts_xf.apply(*p)).collect();
|
||||
if let [a, b] = points.as_slice() {
|
||||
points = vec![Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y))];
|
||||
}
|
||||
(boundary_xf, points)
|
||||
}
|
||||
|
||||
/// The SPATIAL_FILTER of `clip`; `xdict` is its extension dictionary (an inverted clip's).
|
||||
/// No group 290: the reference app discards a file whose filter has one.
|
||||
fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3, inverse: &Mat3, xdict: Option<Handle>) -> ForeignObject {
|
||||
@@ -326,14 +376,14 @@ fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3
|
||||
tags.extend([raw(102, "{ACAD_XDICTIONARY"), raw(360, x.hex()), raw(102, "}")]);
|
||||
}
|
||||
tags.extend([raw(330, owner.hex()), raw(100, "AcDbFilter"), raw(100, "AcDbSpatialFilter"), raw(70, clip.points.len())]);
|
||||
for p in &clip.points {
|
||||
let q = to_world.apply(*p);
|
||||
let (boundary_xf, points) = filter_geometry(clip, to_world);
|
||||
for q in points {
|
||||
tags.push(raw(10, q.x));
|
||||
tags.push(raw(20, q.y));
|
||||
}
|
||||
tags.extend([raw(210, 0.0), raw(220, 0.0), raw(230, 1.0), raw(11, 0.0), raw(21, 0.0), raw(31, 0.0)]);
|
||||
tags.extend([raw(71, i32::from(clip.enabled)), raw(72, 0), raw(73, 0)]);
|
||||
for v in matrix_values(inverse).into_iter().chain(matrix_values(&Mat3::IDENTITY)) {
|
||||
for v in matrix_values(inverse).into_iter().chain(matrix_values(&boundary_xf)) {
|
||||
tags.push(raw(40, v));
|
||||
}
|
||||
ForeignObject { handle: h, kind: "SPATIAL_FILTER".into(), tags }
|
||||
@@ -417,7 +467,7 @@ pub(crate) fn prepare(d: &Drawing) -> Option<Drawing> {
|
||||
let mut own = dictionary(x, sf);
|
||||
own.tags.extend([raw(3, ROUNDTRIP_KEY), raw(360, r.hex())]);
|
||||
add(own);
|
||||
let world: Vec<Vec2> = clip.points.iter().map(|p| to_world.apply(*p)).collect();
|
||||
let (_, world) = filter_geometry(&clip, &to_world);
|
||||
add(roundtrip_record(r, x, &world));
|
||||
}
|
||||
}
|
||||
@@ -548,4 +598,228 @@ mod tests {
|
||||
assert!(parse_filter(&filter, None).is_none(), "{count}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a mock SPATIAL_FILTER [`ForeignObject`] with a 10×10 rectangle boundary:
|
||||
/// (0,0), (10,0), (10,10), (0,10).
|
||||
fn make_test_filter(inverse: &Mat3, own: &Mat3) -> ForeignObject {
|
||||
let mut tags = vec![
|
||||
raw(100, "AcDbFilter"),
|
||||
raw(100, "AcDbSpatialFilter"),
|
||||
raw(70, 4),
|
||||
raw(10, 0.0),
|
||||
raw(20, 0.0),
|
||||
raw(10, 10.0),
|
||||
raw(20, 0.0),
|
||||
raw(10, 10.0),
|
||||
raw(20, 10.0),
|
||||
raw(10, 0.0),
|
||||
raw(20, 10.0),
|
||||
raw(210, 0.0),
|
||||
raw(220, 0.0),
|
||||
raw(230, 1.0),
|
||||
raw(71, 1),
|
||||
raw(72, 0),
|
||||
raw(73, 0),
|
||||
];
|
||||
for v in matrix_values(inverse).into_iter().chain(matrix_values(own)) {
|
||||
tags.push(raw(40, v));
|
||||
}
|
||||
ForeignObject { handle: Handle(0x100), kind: "SPATIAL_FILTER".into(), tags }
|
||||
}
|
||||
|
||||
/// Baseline check: verifies `parse_filter` accepts filters where the boundary matrix is identity.
|
||||
#[test]
|
||||
fn parse_filter_accepts_identity_boundary_transform() {
|
||||
// Baseline: parse_filter accepts filters where the second matrix is Identity.
|
||||
let filter = make_test_filter(&Mat3::IDENTITY, &Mat3::IDENTITY);
|
||||
let parsed = parse_filter(&filter, None);
|
||||
assert!(parsed.is_some(), "Baseline filter with identity own matrix must be accepted");
|
||||
}
|
||||
|
||||
/// Regression test: verifies `parse_filter` preserves filters with a non-identity translation matrix.
|
||||
#[test]
|
||||
fn parse_filter_preserves_non_identity_boundary_transform() {
|
||||
// WHY:
|
||||
// SPATIAL_FILTER can contain two transformation matrices.
|
||||
// parse_filter previously rejected every non-identity `own` matrix,
|
||||
// causing an otherwise valid clipping definition to be discarded.
|
||||
//
|
||||
// Matrix 2 transforms WCS into boundary coordinates; its inverse transforms
|
||||
// boundary coordinates into WCS, mapping (0..10, 0..10) shifted by (-100, -50).
|
||||
|
||||
let inverse = Mat3::IDENTITY;
|
||||
let own = Mat3::translate(Vec2::new(100.0, 50.0));
|
||||
|
||||
let filter = make_test_filter(&inverse, &own);
|
||||
let parsed = parse_filter(&filter, None);
|
||||
|
||||
assert!(parsed.is_some(), "A valid non-identity boundary transform must not cause the filter to be discarded");
|
||||
let clip = parsed.unwrap();
|
||||
assert_eq!(clip.points.len(), 4);
|
||||
assert!(clip.points[0].near(Vec2::new(-100.0, -50.0), 1e-9));
|
||||
assert!(clip.points[1].near(Vec2::new(-90.0, -50.0), 1e-9));
|
||||
assert!(clip.points[2].near(Vec2::new(-90.0, -40.0), 1e-9));
|
||||
assert!(clip.points[3].near(Vec2::new(-100.0, -40.0), 1e-9));
|
||||
}
|
||||
|
||||
/// Verifies `boundary_xf.inverse()?.then(inverse)` correctly composes rotation, scaling, and translation.
|
||||
#[test]
|
||||
fn parse_filter_applies_rotation_and_scale_boundary_transform() {
|
||||
let boundary_xf = Mat3::scale(2.0, 2.0).then(Mat3::rotate(std::f64::consts::FRAC_PI_2)).then(Mat3::translate(Vec2::new(50.0, 20.0)));
|
||||
let inverse = Mat3::translate(Vec2::new(-10.0, -5.0));
|
||||
|
||||
let filter = make_test_filter(&inverse, &boundary_xf);
|
||||
let parsed = parse_filter(&filter, None);
|
||||
|
||||
assert!(parsed.is_some(), "Combined scale, rotation, and translation boundary transform must be parsed");
|
||||
let clip = parsed.unwrap();
|
||||
assert_eq!(clip.points.len(), 4);
|
||||
assert!(clip.points[0].near(Vec2::new(-20.0, 20.0), 1e-9));
|
||||
assert!(clip.points[1].near(Vec2::new(-20.0, 15.0), 1e-9));
|
||||
assert!(clip.points[2].near(Vec2::new(-15.0, 15.0), 1e-9));
|
||||
assert!(clip.points[3].near(Vec2::new(-15.0, 20.0), 1e-9));
|
||||
}
|
||||
/// Verifies `parse_filter` rejects sheared boundary matrices to preserve foreign data.
|
||||
#[test]
|
||||
fn parse_filter_rejects_sheared_boundary_transform() {
|
||||
let inverse = Mat3::IDENTITY;
|
||||
// Non-orthogonal shear matrix: (x' = x + 0.5y, y' = y)
|
||||
let shear = Mat3 { a: 1.0, b: 0.0, c: 0.5, d: 1.0, e: 0.0, f: 0.0 };
|
||||
let filter = make_test_filter(&inverse, &shear);
|
||||
assert!(parse_filter(&filter, None).is_none(), "Sheared transforms must be rejected to stay foreign");
|
||||
}
|
||||
|
||||
/// Verifies that an explicit boundary slice (e.g. inverted clip) is transformed correctly.
|
||||
#[test]
|
||||
fn parse_filter_applies_transform_to_inverted_boundary() {
|
||||
let inverse = Mat3::translate(Vec2::new(-10.0, 0.0));
|
||||
let boundary_xf = Mat3::translate(Vec2::new(50.0, 0.0));
|
||||
let filter = make_test_filter(&inverse, &boundary_xf);
|
||||
|
||||
let explicit_boundary = vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0)];
|
||||
let parsed = parse_filter(&filter, Some(&explicit_boundary));
|
||||
assert!(parsed.is_some());
|
||||
let clip = parsed.unwrap();
|
||||
assert!(clip.inverted);
|
||||
// Explicit boundary points transformed by net: (x - 50 - 10) = x - 60
|
||||
assert_eq!(clip.points.len(), 3);
|
||||
assert!(clip.points[0].near(Vec2::new(-60.0, 0.0), 1e-9));
|
||||
assert!(clip.points[1].near(Vec2::new(-50.0, 0.0), 1e-9));
|
||||
assert!(clip.points[2].near(Vec2::new(-50.0, 10.0), 1e-9));
|
||||
}
|
||||
/// Verifies that small-scale sheared transforms are rejected by the scale-independent guard.
|
||||
#[test]
|
||||
fn parse_filter_rejects_small_scale_sheared_boundary_transform() {
|
||||
// WHY:
|
||||
// A sheared transform with tiny scale factors (e.g. u = (0.001, 0), v = (0.0005, 0.001))
|
||||
// yields a small absolute dot product (5e-7), which would bypass a naive absolute tolerance.
|
||||
// The orthogonality guard is scale-independent (|u . v| > 1e-4 * |u| * |v|) so that
|
||||
// non-orthogonal shears are consistently rejected across all coordinate scales.
|
||||
let inverse = Mat3::IDENTITY;
|
||||
let small_shear = Mat3 { a: 0.001, b: 0.0, c: 0.0005, d: 0.001, e: 0.0, f: 0.0 };
|
||||
let filter = make_test_filter(&inverse, &small_shear);
|
||||
assert!(parse_filter(&filter, None).is_none(), "Small-scale sheared transform must be rejected");
|
||||
}
|
||||
|
||||
/// Verifies that a 2-corner rectangle rotated by 30°, 45°, 60°, or 90° (whether via
|
||||
/// `boundary_xf` or via `inverse` with an unrotated/translated `boundary_xf`) expands
|
||||
/// to an exact 4-corner orthogonal rectangle in block coordinates without collapsing or skewing.
|
||||
#[test]
|
||||
fn parse_filter_expands_rotated_two_corner_boundary() {
|
||||
for deg in [30.0_f64, 45.0, 60.0, 90.0] {
|
||||
let rot = Mat3::rotate(deg.to_radians());
|
||||
let trans = Mat3::translate(Vec2::new(15.0, -10.0));
|
||||
for (inverse, boundary_xf) in [(Mat3::IDENTITY, rot), (rot, Mat3::IDENTITY), (rot, trans)] {
|
||||
let mut tags = vec![
|
||||
raw(100, "AcDbFilter"),
|
||||
raw(100, "AcDbSpatialFilter"),
|
||||
raw(70, 2),
|
||||
raw(10, 0.0),
|
||||
raw(20, 0.0),
|
||||
raw(10, 10.0),
|
||||
raw(20, 20.0),
|
||||
raw(210, 0.0),
|
||||
raw(220, 0.0),
|
||||
raw(230, 1.0),
|
||||
raw(71, 1),
|
||||
raw(72, 0),
|
||||
raw(73, 0),
|
||||
];
|
||||
for v in matrix_values(&inverse).into_iter().chain(matrix_values(&boundary_xf)) {
|
||||
tags.push(raw(40, v));
|
||||
}
|
||||
let filter = ForeignObject { handle: Handle(0x102), kind: "SPATIAL_FILTER".into(), tags };
|
||||
let clip = parse_filter(&filter, None).expect("rotated 2-corner clip must not collapse");
|
||||
assert_eq!(clip.points.len(), 4, "angle {deg}°");
|
||||
let e01 = clip.points[1] - clip.points[0];
|
||||
let e12 = clip.points[2] - clip.points[1];
|
||||
assert!((e01.len() - 10.0).abs() < 1e-9, "width preserved at {deg}°");
|
||||
assert!((e12.len() - 20.0).abs() < 1e-9, "height preserved at {deg}°");
|
||||
assert!(e01.dot(e12).abs() < 1e-9, "right angle preserved at {deg}°");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spatial_filter_canonicalizes_mirrored_two_point_corners_in_boundary_space() {
|
||||
let clip = ClipBoundary::new(vec![Vec2::new(-1.0, 0.5), Vec2::new(3.0, 2.5)]);
|
||||
for (sx, sy, rot) in [(-2.0, 3.0, 0.0), (2.0, -3.0, 0.0), (-2.0, -3.0, 0.0), (-2.0, 3.0, 0.3)] {
|
||||
let to_world = Mat3::translate(Vec2::new(10.0, 20.0)).then_before(Mat3::rotate(rot)).then_before(Mat3::scale(sx, sy));
|
||||
let inverse = to_world.inverse().unwrap();
|
||||
let sf = spatial_filter(Handle(0x10), Handle(0x1), &clip, &to_world, &inverse, None);
|
||||
let verts = vertices(&sf.tags, 2).unwrap();
|
||||
assert_eq!(verts.len(), 2);
|
||||
assert!(verts[0].x < verts[1].x && verts[0].y < verts[1].y, "expected lower-left < upper-right for ({sx},{sy},{rot}): {verts:?}");
|
||||
}
|
||||
|
||||
// Polyline boundaries (> 2 vertices) must preserve their transformed vertex order.
|
||||
let poly = ClipBoundary::new(vec![Vec2::new(3.0, 2.5), Vec2::new(-1.0, 2.5), Vec2::new(1.0, -1.0)]);
|
||||
let to_world = Mat3::scale(-2.0, 3.0);
|
||||
let (_, pts) = filter_geometry(&poly, &to_world);
|
||||
assert_eq!(pts, vec![Vec2::new(-6.0, 7.5), Vec2::new(2.0, 7.5), Vec2::new(-2.0, -3.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_canonicalizes_inverted_mirrored_companion_record() {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.blocks.insert("B".into(), Arc::new(cadcraft_doc::Block::new("B")));
|
||||
let clip = ClipBoundary { inverted: true, ..ClipBoundary::new(vec![Vec2::new(-1.0, 0.5), Vec2::new(3.0, 2.5)]) };
|
||||
let ins = cadcraft_doc::Insert {
|
||||
block: "B".into(),
|
||||
insert: cadcraft_geom::Vec3::new(10.0, 20.0, 0.0),
|
||||
scale: cadcraft_geom::Vec3::new(-2.0, 3.0, 1.0),
|
||||
rotation: 0.3,
|
||||
clip: Some(clip),
|
||||
..Default::default()
|
||||
};
|
||||
d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
|
||||
let out = prepare(&d).unwrap();
|
||||
let sf = out.foreign.objects.iter().find(|o| o.kind == "SPATIAL_FILTER").unwrap();
|
||||
let sf_verts = vertices(&sf.tags, 2).unwrap();
|
||||
assert!(sf_verts[0].x < sf_verts[1].x && sf_verts[0].y < sf_verts[1].y);
|
||||
|
||||
let xr = out.foreign.objects.iter().find(|o| o.kind == "XRECORD").unwrap();
|
||||
let xrec_list = |marker: &str| -> Vec<Vec2> {
|
||||
let start = xr.tags.iter().position(|t| t.code == 102 && t.value == marker).unwrap() + 1;
|
||||
let end = xr.tags[start..].iter().position(|t| t.code == 102).map_or(xr.tags.len(), |n| start + n);
|
||||
let mut pts = Vec::new();
|
||||
let mut x = None;
|
||||
for t in &xr.tags[start..end] {
|
||||
if t.code == 10 {
|
||||
x = t.value.parse::<f64>().ok();
|
||||
} else if t.code == 20
|
||||
&& let (Some(px), Ok(py)) = (x.take(), t.value.parse::<f64>())
|
||||
{
|
||||
pts.push(Vec2::new(px, py));
|
||||
}
|
||||
}
|
||||
pts
|
||||
};
|
||||
let rt = xrec_list(ROUNDTRIP);
|
||||
let cmp = xrec_list(COMPARE);
|
||||
assert_eq!((rt.len(), cmp.len()), (2, 2));
|
||||
assert!(rt[0].near(sf_verts[0], 1e-9) && rt[1].near(sf_verts[1], 1e-9));
|
||||
assert!(cmp[0].near(sf_verts[0], 1e-9) && cmp[1].near(sf_verts[1], 1e-9));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -701,6 +701,41 @@ pub(crate) fn read_layer_colors(tags: &[Tag]) -> Vec<(String, Color)> {
|
||||
names.as_chunks::<2>().0.iter().filter_map(|[name, color]| Some((name.clone(), Color::parse(color)?))).collect()
|
||||
}
|
||||
|
||||
/// A viewport's named and base UCS as CADCraft xdata: `1000 VPUCS`, `1002 {`, `1000 named`,
|
||||
/// `1000 base` (empty for none), `1002 }`. Groups 345 and 346 say the same, but the DWG bridge
|
||||
/// drops them.
|
||||
pub(crate) fn ucs_xdata(named: Option<&str>, base: Option<&str>) -> Vec<Tag> {
|
||||
vec![Tag::s(1000, "VPUCS"), Tag::s(1002, "{"), Tag::s(1000, named.unwrap_or_default()), Tag::s(1000, base.unwrap_or_default()), Tag::s(1002, "}")]
|
||||
}
|
||||
|
||||
/// The named and base UCS written by [`ucs_xdata`]; `(None, None)` for files from other writers.
|
||||
pub(crate) fn read_ucs_names(tags: &[Tag]) -> (Option<String>, Option<String>) {
|
||||
let list = xdata_list(xdata(tags, APP), "VPUCS");
|
||||
let mut names = list.iter().filter(|t| t.code == 1000).map(Tag::str).map(|s| Some(s).filter(|s| !s.trim().is_empty()));
|
||||
(names.next().flatten(), names.next().flatten())
|
||||
}
|
||||
|
||||
/// A copy of a viewport's unmodelled groups ([`cadcraft_doc::Viewport::extra`]) that aren't
|
||||
/// references, as CADCraft xdata: `1000 VPEXTRA`, `1002 {`, then per group `1000 code` and
|
||||
/// `1000 value`, `1002 }`. The groups themselves are in the record; the DWG bridge drops some
|
||||
/// of them (the plot style sheet, shade plot and lighting), and this copy brings them back.
|
||||
pub(crate) fn extra_xdata(extra: &[cadcraft_doc::RawTag]) -> Vec<Tag> {
|
||||
let mut v = vec![Tag::s(1000, "VPEXTRA"), Tag::s(1002, "{")];
|
||||
for t in extra.iter().filter(|t| !crate::dxf_raw::is_pointer(t.code)) {
|
||||
v.push(Tag::s(1000, t.code.to_string()));
|
||||
v.push(Tag::s(1000, t.value.clone()));
|
||||
}
|
||||
v.push(Tag::s(1002, "}"));
|
||||
v
|
||||
}
|
||||
|
||||
/// The groups written by [`extra_xdata`]; empty for files from other writers, bad pairs skipped.
|
||||
pub(crate) fn read_extra(tags: &[Tag]) -> Vec<(i32, String)> {
|
||||
let list = xdata_list(xdata(tags, APP), "VPEXTRA");
|
||||
let items: Vec<String> = list.iter().take(MAX_XDATA_ITEMS * 2).filter(|t| t.code == 1000).map(Tag::str).collect();
|
||||
items.as_chunks::<2>().0.iter().filter_map(|[code, value]| Some((code.trim().parse::<i32>().ok()?, value.clone()))).collect()
|
||||
}
|
||||
|
||||
const POINT_NAMES: [&str; 5] = ["defpt", "p13", "p14", "p15", "p16"];
|
||||
|
||||
/// Associativity links from CADCraft xdata; malformed links are skipped.
|
||||
@@ -914,8 +949,9 @@ struct AnnoObject {
|
||||
const MAX_ANNO_OBJECTS: usize = 1_000_000;
|
||||
|
||||
/// JSON chunks for the annotative scaling XRECORD, or `None` when nothing differs from a new
|
||||
/// drawing (1:1, ANNOALLVISIBLE 1, no annotative objects or blocks).
|
||||
pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing) -> Option<Vec<String>> {
|
||||
/// drawing (1:1, ANNOALLVISIBLE 1, no annotative objects or blocks). With `contexts` the objects
|
||||
/// written with AutoCAD's annotation scale contexts (`dxf_anno`) are left to them.
|
||||
pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing, contexts: bool) -> Option<Vec<String>> {
|
||||
let cannoscale = d.header.str("CANNOSCALE", "1:1");
|
||||
let annoallvisible = d.header.i64("ANNOALLVISIBLE", 1);
|
||||
let blocks: Vec<String> = d.blocks.values().filter(|b| b.annotative).map(|b| b.name.clone()).collect();
|
||||
@@ -923,7 +959,7 @@ pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing) -> Option<Vec<String>> {
|
||||
.model
|
||||
.iter()
|
||||
.chain(d.layouts.iter().flat_map(|l| l.entities.iter()))
|
||||
.filter(|e| cadcraft_doc::is_annotative(e))
|
||||
.filter(|e| cadcraft_doc::is_annotative(e) && !(contexts && crate::dxf_anno::has_contexts(e)))
|
||||
.map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone() })
|
||||
.collect();
|
||||
if cannoscale == "1:1" && annoallvisible == 1 && blocks.is_empty() && objects.is_empty() {
|
||||
|
||||
@@ -310,6 +310,7 @@ pub(crate) fn read(tags: &[Tag]) -> MLeader {
|
||||
line_spacing: pos(p.line_spacing).unwrap_or(1.0),
|
||||
line_spacing_exact: p.line_spacing_style == Some(2),
|
||||
columns: None,
|
||||
background: None,
|
||||
}
|
||||
});
|
||||
let block = has_block.then(|| {
|
||||
|
||||
+721
-37
File diff suppressed because it is too large
Load Diff
@@ -7,7 +7,8 @@ use cadcraft_doc::{
|
||||
Arc, AssocSnap, Attrib, AttribModes, AttribProps, Block, Circle, Common, DashElement, DimAssoc, DimKind, DimStyle, Dimension, Drawing, Ellipse,
|
||||
Entity, EntityKind, Face3d, Gradient, Group, HAlign, HVal, Handle, Hatch, HatchLoop, Helix, HelixConstrain, Insert, Layer, Layout, Leader, Line,
|
||||
Linetype, Lineweight, LwPolyline, MAX_FRAME_CHARS, MLeaderStyle, MText, MultilineAttrib, NamedView, PageSetup, Point, Polyline3d, RawTag,
|
||||
RayLine, Solid, Table, TableCell, Text, TextStyle, Tolerance, Transparency, Ucs, Unknown, VAlign, Viewport, VportConfig, VportTile, Wipeout,
|
||||
RayLine, Solid, Table, TableCell, Text, TextStyle, Tolerance, Transparency, Ucs, Unknown, VAlign, Viewport, ViewportUcs, VportConfig, VportTile,
|
||||
Wipeout,
|
||||
};
|
||||
use cadcraft_geom::{PolyVertex, Spline, Vec2, Vec3};
|
||||
use craft_dxf::{Tag, record_slices, section_slices};
|
||||
@@ -35,6 +36,15 @@ use tables::{header, tables};
|
||||
|
||||
pub(crate) mod mtext_dxf;
|
||||
|
||||
/// A block record's properties (see [`Rx::block_props`]).
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct BlockProps {
|
||||
units: u8,
|
||||
explodable: bool,
|
||||
scale_uniformly: bool,
|
||||
annotative: bool,
|
||||
}
|
||||
|
||||
/// Handle maps and references gathered while reading.
|
||||
#[derive(Default)]
|
||||
struct Rx {
|
||||
@@ -44,8 +54,9 @@ struct Rx {
|
||||
brs: HashMap<String, String>,
|
||||
/// LTYPE record handle (upper case) → linetype name (DIMLTYPE, DIMLTEX1, DIMLTEX2).
|
||||
ltypes: HashMap<String, String>,
|
||||
/// Upper-case block name → (insertion units, explodable) from its BLOCK_RECORD.
|
||||
block_props: HashMap<String, (u8, bool)>,
|
||||
/// Upper-case block name → its BLOCK_RECORD's properties: units (70), explodable (280),
|
||||
/// scale uniformly (281) and annotative (`AcadAnnotative` xdata).
|
||||
block_props: HashMap<String, BlockProps>,
|
||||
/// Upper-case names of anonymous `*T` blocks drawn by ACAD_TABLE entities.
|
||||
table_blocks: std::collections::HashSet<String>,
|
||||
/// Upper-case block names used by INSERTs.
|
||||
@@ -65,8 +76,10 @@ struct Rx {
|
||||
/// Layer, linetype and text style names in the order of the file's tables, which proxy
|
||||
/// graphics refer to by index (the drawing's own tables are ordered differently).
|
||||
proxy_tables: cadcraft_doc::ProxyTables,
|
||||
/// UCS record handle (upper case) → UCS name (a layout's named UCS, group 345).
|
||||
/// UCS record handle (upper case) → UCS name (VIEWPORT groups 345 and 346).
|
||||
ucss: HashMap<String, String>,
|
||||
/// Upper-case UCS name → UCS name, for a viewport that names its UCS in CADCraft's xdata.
|
||||
ucs_names: HashMap<String, String>,
|
||||
/// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport
|
||||
/// (PAPERVIEW) the reader dropped.
|
||||
paper_views_dropped: Vec<(Option<String>, bool, Option<String>)>,
|
||||
@@ -294,6 +307,9 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize,
|
||||
objs.apply(&mut d, &rx);
|
||||
crate::dxf_image::resolve(&secs, &mut d, &rx.image_defs);
|
||||
crate::dxf_mline::resolve(&secs, &mut d);
|
||||
// Annotation scale contexts, after CADCraft's own record (they are newer when AutoCAD edited
|
||||
// the file since).
|
||||
crate::dxf_anno::resolve(&secs, &mut d);
|
||||
// Keep handles unique against the header's seed.
|
||||
let seed = d.header.str("HANDSEED", "");
|
||||
if let Some(h) = own_seed.or_else(|| Handle::parse_hex(&seed)) {
|
||||
|
||||
@@ -408,8 +408,8 @@ pub(super) fn place_blocks(
|
||||
let mut b = Block::new(&name);
|
||||
b.base = base;
|
||||
b.description = description;
|
||||
if let Some(&(units, explodable)) = rx.block_props.get(&up) {
|
||||
(b.units, b.explodable) = (units, explodable);
|
||||
if let Some(p) = rx.block_props.get(&up) {
|
||||
(b.units, b.explodable, b.scale_uniformly, b.annotative) = (p.units, p.explodable, p.scale_uniformly, p.annotative);
|
||||
}
|
||||
if xref & 4 != 0 {
|
||||
b.xref_path = Some(String::new());
|
||||
|
||||
@@ -5,10 +5,144 @@ use super::text::{attdef, attrib_modes, attrib_props, flatten_tilted, mtext_from
|
||||
use super::{
|
||||
Arc, Attrib, Circle, Common, DimKind, Dimension, Ellipse, EntityKind, Face3d, Handle, HashMap, Helix, HelixConstrain, Insert, Leader, Line,
|
||||
LwPolyline, MAX_FRAME_CHARS, Point, PolyVertex, Polyline3d, RawTag, RayLine, Rx, Solid, Spline, Table, TableCell, Tag, Tolerance, Unknown, Vec2,
|
||||
Vec3, Viewport, Wipeout, record_slices,
|
||||
Vec3, Viewport, ViewportUcs, Wipeout, record_slices,
|
||||
};
|
||||
use cadcraft_doc::PolyfaceMesh;
|
||||
|
||||
/// VIEWPORT groups that are not kept raw in [`Viewport::extra`]: those read into the model, and
|
||||
/// the view twist, direction and target (51, 16, 17), which say where the view centre is measured
|
||||
/// from: carried along while the centre is written in drawing coordinates, they would move the
|
||||
/// view on the next read.
|
||||
const VIEWPORT_NOT_EXTRA: &[i32] = &[
|
||||
10, 20, 30, 40, 41, 68, 69, 12, 22, 45, 90, 340, 341, 331, 71, 110, 120, 130, 111, 121, 131, 112, 122, 132, 79, 146, 345, 346, 51, 16, 26, 36,
|
||||
17, 27, 37,
|
||||
];
|
||||
|
||||
/// The values a viewport nobody set anything on has for the groups below: what the DWG writer
|
||||
/// (the bridge's) puts in every viewport, and the DXF Reference's defaults. A group at its default
|
||||
/// is not "extra" data: a default viewport reads back with no extras, a changed one keeps its
|
||||
/// group. Each entry is a group code with its default; `(x, y)` pairs (13/23 snap base,
|
||||
/// 14/24 snap spacing, 15/25 grid spacing) are default only together.
|
||||
const VIEWPORT_DEFAULTS: &[(i32, f64)] = &[
|
||||
(13, 0.0),
|
||||
(23, 0.0),
|
||||
(14, 10.0),
|
||||
(24, 10.0),
|
||||
(15, 10.0),
|
||||
(25, 10.0),
|
||||
// Lens length, front and back clip planes, snap angle, circle sides, render mode, major grid.
|
||||
(42, 50.0),
|
||||
(43, 0.0),
|
||||
(44, 0.0),
|
||||
(50, 0.0),
|
||||
(72, 1000.0),
|
||||
(281, 0.0),
|
||||
(61, 5.0),
|
||||
// Shade plot mode.
|
||||
(170, 0.0),
|
||||
];
|
||||
|
||||
/// The group that goes with `code` in a coordinate pair (13/23, 14/24, 15/25).
|
||||
fn pair_of(code: i32) -> Option<i32> {
|
||||
match code {
|
||||
13..=15 => Some(code + 10),
|
||||
23..=25 => Some(code - 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the group `code` of `groups` at its default (see [`VIEWPORT_DEFAULTS`])? A value that
|
||||
/// doesn't read as a number is not.
|
||||
fn at_default(groups: &[RawTag], code: i32, value: &str) -> bool {
|
||||
let is = |c: i32, v: &str| {
|
||||
VIEWPORT_DEFAULTS.iter().find(|(k, _)| *k == c).is_some_and(|(_, d)| v.trim().parse::<f64>().is_ok_and(|x| (x - d).abs() < 1e-9))
|
||||
};
|
||||
is(code, value)
|
||||
&& match pair_of(code) {
|
||||
Some(other) => groups.iter().find(|t| t.code == other).is_some_and(|t| is(other, &t.value)),
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Most groups kept raw on one viewport (a VIEWPORT record has about forty).
|
||||
const MAX_VIEWPORT_EXTRA: usize = 512;
|
||||
|
||||
/// The groups of a VIEWPORT's own subclass (after `100 AcDbViewport`, before any xdata).
|
||||
fn viewport_groups(tags: &[Tag]) -> &[Tag] {
|
||||
let Some(start) = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbViewport") else { return &[] };
|
||||
let rest = tags.get(start + 1..).unwrap_or(&[]);
|
||||
rest.get(..rest.iter().position(|t| t.code == 100 || t.code >= 1000).unwrap_or(rest.len())).unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// A VIEWPORT's own UCS (groups 110–112, 79, 146), if it has one. The named and base UCS (345,
|
||||
/// 346) are table handles, resolved once the UCS table is known ([`entity_extras`]).
|
||||
fn viewport_ucs(tags: &[Tag]) -> Option<ViewportUcs> {
|
||||
let g = viewport_groups(tags);
|
||||
// Any UCS group, the base UCS handle (346) alone too: a viewport that only names its base
|
||||
// UCS keeps it.
|
||||
if !g.iter().any(|t| matches!(t.code, 110 | 111 | 112 | 345 | 346)) {
|
||||
return None;
|
||||
}
|
||||
let t = T(g);
|
||||
let has = |c: i32| g.iter().any(|t| t.code == c);
|
||||
let (origin, x_axis, y_axis) =
|
||||
(t.p(110), if has(111) { t.p(111) } else { Vec3::new(1.0, 0.0, 0.0) }, if has(112) { t.p(112) } else { Vec3::new(0.0, 1.0, 0.0) });
|
||||
// Unreadable numbers come through as 0, so a broken axis is one with no length.
|
||||
let finite = [origin, x_axis, y_axis].iter().all(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite());
|
||||
if !finite || x_axis.len() <= 1e-12 || y_axis.len() <= 1e-12 {
|
||||
return None;
|
||||
}
|
||||
// The World UCS of a viewport that names no UCS and keeps none of its own (UCSVP 0) is what a
|
||||
// viewport nobody gave a UCS reads as (a DWG writes one for every viewport): no UCS.
|
||||
let ortho = t.i(79).unwrap_or(0);
|
||||
let nothing_named = !g.iter().any(|t| matches!(t.code, 345 | 346)) && crate::dxf_ext::read_ucs_names(tags) == (None, None);
|
||||
let identity = origin.len() <= 1e-12
|
||||
&& (x_axis - Vec3::new(1.0, 0.0, 0.0)).len() <= 1e-12
|
||||
&& (y_axis - Vec3::new(0.0, 1.0, 0.0)).len() <= 1e-12
|
||||
&& t.f(146).unwrap_or(0.0) == 0.0
|
||||
&& ortho == 0;
|
||||
if identity && nothing_named && t.i(71) != Some(1) {
|
||||
return None;
|
||||
}
|
||||
Some(ViewportUcs {
|
||||
origin,
|
||||
x_axis,
|
||||
y_axis,
|
||||
elevation: t.f(146).filter(|e| e.is_finite()).unwrap_or(0.0),
|
||||
ortho: t.i(79).and_then(|o| u8::try_from(o).ok()).filter(|o| *o <= 6).unwrap_or(0),
|
||||
named: None,
|
||||
base: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A VIEWPORT's groups CADCraft doesn't model, as read ([`VIEWPORT_NOT_EXTRA`]), plus those of
|
||||
/// CADCraft's xdata copy that the record lacks (a DWG drops some).
|
||||
fn viewport_extra(tags: &[Tag]) -> Vec<RawTag> {
|
||||
// Only groups that can stand inside the AcDbViewport subclass: no record start (0), handle (5,
|
||||
// 105), subclass (100), group brace (102) or xdata (1000 on), which written back would break
|
||||
// the record or give it a second handle.
|
||||
let own_group = |code: i32| (1..1000).contains(&code) && !matches!(code, 5 | 100 | 102 | 105);
|
||||
// The record's own pointer groups stay: they are remapped with the record.
|
||||
let mut out: Vec<RawTag> = viewport_groups(tags)
|
||||
.iter()
|
||||
.filter(|t| own_group(t.code) && !VIEWPORT_NOT_EXTRA.contains(&t.code))
|
||||
.take(MAX_VIEWPORT_EXTRA)
|
||||
.map(|t| RawTag { code: t.code, value: t.str() })
|
||||
.collect();
|
||||
for (code, value) in crate::dxf_ext::read_extra(tags) {
|
||||
if out.len() >= MAX_VIEWPORT_EXTRA {
|
||||
break;
|
||||
}
|
||||
if own_group(code) && !VIEWPORT_NOT_EXTRA.contains(&code) && !crate::dxf_raw::is_pointer(code) && !out.iter().any(|t| t.code == code) {
|
||||
out.push(RawTag { code, value });
|
||||
}
|
||||
}
|
||||
let keep: Vec<bool> = out.iter().map(|t| !at_default(&out, t.code, &t.value)).collect();
|
||||
let mut keep = keep.into_iter();
|
||||
out.retain(|_| keep.next().unwrap_or(true));
|
||||
out
|
||||
}
|
||||
|
||||
/// Parse one entity record. POLYLINE/INSERT followers are handled by the caller.
|
||||
pub(super) fn entity(kind: &str, tags: &[Tag]) -> Option<(Common, EntityKind)> {
|
||||
entity_with_table_budget(kind, tags, &mut 4_000_000, &mut CurvePoints::default())
|
||||
@@ -330,6 +464,9 @@ pub(super) fn entity_with_table_budget(
|
||||
clip: t.s(340).and_then(|h| Handle::parse_hex(&h)).filter(|h| h.0 != 0 && t.i(90).unwrap_or(0) & 65536 != 0),
|
||||
on: t.i(90).unwrap_or(0) & 131072 == 0,
|
||||
twist,
|
||||
ucs: viewport_ucs(tags),
|
||||
ucs_per_viewport: t.i(71) == Some(1),
|
||||
extra: viewport_extra(tags),
|
||||
}
|
||||
}),
|
||||
"WIPEOUT" => {
|
||||
@@ -584,6 +721,16 @@ pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityK
|
||||
let named = handles.filter_map(|t| rx.layers.get(&t.str().trim().to_ascii_uppercase()));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
v.frozen_layers = named.chain(&v.frozen_layers).filter(|n| seen.insert(n.to_ascii_uppercase())).cloned().collect();
|
||||
// The named and base UCS, by name: groups 345 and 346, else CADCraft's xdata (which a
|
||||
// DWG keeps when they are dropped). A name that isn't in the UCS table: none.
|
||||
if let Some(u) = &mut v.ucs {
|
||||
let t = T(viewport_groups(tags));
|
||||
let by_handle = |code: i32| t.s(code).and_then(|h| rx.ucss.get(&h.trim().to_ascii_uppercase()).cloned());
|
||||
let (xn, xb) = crate::dxf_ext::read_ucs_names(tags);
|
||||
let known = |n: Option<String>| n.and_then(|n| rx.ucs_names.get(&n.to_ascii_uppercase()).cloned());
|
||||
u.named = by_handle(345).or_else(|| known(xn));
|
||||
u.base = by_handle(346).or_else(|| known(xb));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::common::T;
|
||||
use super::objects::MAX_OBJECTS;
|
||||
use super::{
|
||||
Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, Vec3,
|
||||
VportConfig, VportTile, record_slices,
|
||||
BlockProps, Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2,
|
||||
Vec3, VportConfig, VportTile, record_slices,
|
||||
};
|
||||
use crate::dxf_ext::ByName;
|
||||
use cadcraft_fonts::windows::windows_font;
|
||||
@@ -317,7 +317,13 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
|
||||
}
|
||||
"BLOCK_RECORD" => {
|
||||
let units = table.i(70).and_then(|units| u8::try_from(units).ok()).unwrap_or(0);
|
||||
rx.block_props.insert(name.to_ascii_uppercase(), (units, table.i(280).unwrap_or(1) != 0));
|
||||
let props = BlockProps {
|
||||
units,
|
||||
explodable: table.i(280).unwrap_or(1) != 0,
|
||||
scale_uniformly: table.i(281).unwrap_or(0) != 0,
|
||||
annotative: annotative(tags),
|
||||
};
|
||||
rx.block_props.insert(name.to_ascii_uppercase(), props);
|
||||
if let Some(array) = crate::dxf_ext::read_array(tags) {
|
||||
rx.block_arrays.insert(name.to_ascii_uppercase(), array);
|
||||
}
|
||||
@@ -334,6 +340,7 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
|
||||
rx.layers.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
"UCS" => {
|
||||
rx.ucs_names.entry(name.to_ascii_uppercase()).or_insert_with(|| name.clone());
|
||||
rx.ucss.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -73,6 +73,16 @@ pub(super) fn mtext_from(tags: &[Tag], c: &Common) -> MText {
|
||||
a => a,
|
||||
};
|
||||
}
|
||||
let background = own.i(90).filter(|&m| (m & 0x03) != 0).map(|m| {
|
||||
let mask = (m & 0x03) as u8;
|
||||
let color = if let Some(tc) = own.i(421) {
|
||||
Some(cadcraft_color::Color::True(cadcraft_color::Rgb::from_u32(tc as u32)))
|
||||
} else {
|
||||
own.i(63).map(|aci| cadcraft_color::Color::from_aci(aci as i16))
|
||||
};
|
||||
let scale = own.fd(45, 1.5).clamp(1.0, 5.0);
|
||||
cadcraft_doc::MTextBackground { mask, color, scale }
|
||||
});
|
||||
MText {
|
||||
insert: t.p(10),
|
||||
height: t.fd(40, 0.2).max(1e-9),
|
||||
@@ -89,6 +99,7 @@ pub(super) fn mtext_from(tags: &[Tag], c: &Common) -> MText {
|
||||
line_spacing: t.fd(44, 1.0),
|
||||
line_spacing_exact: t.i(73) == Some(2),
|
||||
columns: columns.map(|(c, _)| c),
|
||||
background,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ use crate::dxf_ext::{self, DimVal, K};
|
||||
mod assoc;
|
||||
mod blocks;
|
||||
mod common;
|
||||
#[cfg(test)]
|
||||
pub(crate) use common::{attdef_definition_visits, reset_attdef_definition_visits};
|
||||
mod ctx;
|
||||
mod entity;
|
||||
mod header;
|
||||
@@ -48,7 +50,7 @@ struct W {
|
||||
pstyles: HashMap<String, String>,
|
||||
/// Upper-case layer name → its LAYER table record handle (group 331/341 of viewports).
|
||||
layers: HashMap<String, String>,
|
||||
/// Upper-case UCS name → its UCS table record handle (group 345 of layouts and viewports).
|
||||
/// Upper-case UCS name → its UCS table record handle (groups 345 and 346 of viewports).
|
||||
ucss: HashMap<String, String>,
|
||||
/// Active VPORT group-345 tags (their index in `t`) waiting for the handle of the named UCS
|
||||
/// (upper case) they refer to, filled in after the UCS table is written.
|
||||
@@ -56,6 +58,9 @@ struct W {
|
||||
/// Persistent reactors of source geometry: the associative hatches and DIMASSOC objects
|
||||
/// that follow it (groups `{ACAD_REACTORS 330 …}`).
|
||||
reactors: HashMap<Handle, Vec<String>>,
|
||||
/// Extension dictionaries of annotative objects (their annotation scale contexts, see
|
||||
/// [`crate::dxf_anno`]), by object; a dimension's DIMASSOC dictionary is written by its own.
|
||||
xdicts: HashMap<Handle, String>,
|
||||
}
|
||||
|
||||
/// Where the writer's own records (tables, objects, dictionaries) start numbering: above every
|
||||
@@ -163,6 +168,45 @@ fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::Hash
|
||||
(tags, kept)
|
||||
}
|
||||
|
||||
/// One record written after an entity's own, at `index`: an INSERT's ATTRIB, then its SEQEND
|
||||
/// (items of a POLYLINE's sequence are not records `entnext` reaches yet). The record's type name
|
||||
/// and groups without its `0` group; its handle (5) and owner (330) are left out: it has no
|
||||
/// handle of its own in the drawing (the writer makes one per file), and its owner is the entity.
|
||||
/// `None` past the last record, and for an entity written as a single record. AutoLISP's
|
||||
/// `entnext` and `entget` read one record at a time through it, never writing the entity's other
|
||||
/// records.
|
||||
pub fn entity_sub_record(d: &Drawing, e: &Entity, index: usize) -> Option<(String, Vec<Tag>)> {
|
||||
let cadcraft_doc::EntityKind::Insert(i) = &e.kind else { return None };
|
||||
if i.attribs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut w = W {
|
||||
t: Vec::new(),
|
||||
next: d.handseed.max(0x100).saturating_add(0x1000),
|
||||
used: HashSet::new(),
|
||||
pstyles: HashMap::new(),
|
||||
layers: HashMap::new(),
|
||||
ucss: HashMap::new(),
|
||||
vport_ucs: Vec::new(),
|
||||
reactors: HashMap::new(),
|
||||
xdicts: HashMap::new(),
|
||||
};
|
||||
let cx = Ctx { target: Version::R2018, legacy_columns: true, ..Ctx::default() };
|
||||
match i.attribs.get(index) {
|
||||
Some(a) => {
|
||||
let base = d.block(&i.block).and_then(|b| common::attdef_base(b, &a.tag));
|
||||
entity::attrib_record(&mut w, d, e, index, a, base, &cx);
|
||||
}
|
||||
None if index == i.attribs.len() => entity::seqend_record(&mut w, e),
|
||||
None => return None,
|
||||
}
|
||||
let mut tags = w.t.into_iter();
|
||||
let kind = tags.next().filter(|t| t.code == 0).map(|t| t.value.as_str())?;
|
||||
let mut tags: Vec<Tag> = tags.filter(|t| t.code != 5 && t.code != 330).collect();
|
||||
// Strings as AutoLISP sees them (`10^2`, not the file's `10^ 2`), as in `entity_groups`.
|
||||
crate::dxf_read::mtext_dxf::map_text_groups(&kind, &mut tags, crate::dxf_read::mtext_dxf::decode_line);
|
||||
Some((kind, tags))
|
||||
}
|
||||
/// The most dash elements a linetype keeps in a DWG. The DWG writer (acadrust) stores the count in
|
||||
/// one byte, so a longer pattern would come back with its count modulo 256 (none at all for 256),
|
||||
/// and a DWG save keeps the first 255 instead ([`dwg_notes`] says so).
|
||||
@@ -276,6 +320,7 @@ pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec<Tag>) {
|
||||
ucss: HashMap::new(),
|
||||
vport_ucs: Vec::new(),
|
||||
reactors: HashMap::new(),
|
||||
xdicts: HashMap::new(),
|
||||
};
|
||||
let cx = Ctx { target: Version::R2018, legacy_columns: true, ..Ctx::default() };
|
||||
let paper = d.space_of(e.handle).is_some_and(|s| !matches!(s, cadcraft_doc::Space::Model));
|
||||
|
||||
@@ -147,6 +147,7 @@ pub(super) fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Ve
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -201,6 +202,7 @@ pub(crate) fn table_block_entities(d: &Drawing, t: &Table, layer: &str) -> Vec<E
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,10 +1,139 @@
|
||||
use std::cell::RefCell;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::ctx::{AssocObj, Ctx};
|
||||
use super::{
|
||||
Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, HAlign, HashMap, Lineweight, Text, Transparency, VAlign, Vec3, Version, W,
|
||||
dxf_ext,
|
||||
Attrib, Block, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, Handle, HashMap, Lineweight, Text, Transparency,
|
||||
VAlign, Vec3, Version, W, dxf_ext,
|
||||
};
|
||||
|
||||
/// `AcadAnnotative` xdata marking an annotative style.
|
||||
/// The most ATTDEF tags the definition indexes on one thread hold in all (a block with none
|
||||
/// counts as one). An index that fits but would pass this total drops the indexes already
|
||||
/// stored, then takes their place. A definition with more distinct tags than this is not indexed:
|
||||
/// its state is remembered as too large, and each read of it scans the definition for the first
|
||||
/// matching ATTDEF and keeps nothing, so one block cannot grow the cache past the budget, and the
|
||||
/// written file still takes its properties from the right definition.
|
||||
const MAX_INDEXED_TAGS: usize = 1 << 18;
|
||||
|
||||
/// The most block states remembered as too large to index; past it the list starts again.
|
||||
const MAX_TOO_LARGE: usize = 1 << 10;
|
||||
|
||||
/// For each state of a block definition's entities read on this thread, by its content token
|
||||
/// ([`cadcraft_doc::EntityStore::content_token`]): the handle of the first ATTDEF of each tag
|
||||
/// (upper case). A token names one state of one store, so an index is never used for another
|
||||
/// copy or another edit of the block, and blocks read in turn keep their indexes. A definition
|
||||
/// past [`MAX_INDEXED_TAGS`] has no entry here.
|
||||
#[derive(Default)]
|
||||
struct AttdefIndexes {
|
||||
/// Order tags from the drawing so lookup cost does not depend on hash collisions.
|
||||
by_store: HashMap<u64, BTreeMap<String, Handle>>,
|
||||
/// Tags held in all, for [`MAX_INDEXED_TAGS`].
|
||||
tags: usize,
|
||||
/// States of definitions with more distinct tags than [`MAX_INDEXED_TAGS`], so a read of one
|
||||
/// goes straight to [`scan_attdef`] without building and dropping an index again.
|
||||
too_large: std::collections::HashSet<u64>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static ATTDEF_INDEXES: RefCell<AttdefIndexes> = RefCell::new(AttdefIndexes::default());
|
||||
/// Entities of a block definition examined while matching an attribute to its ATTDEF.
|
||||
#[cfg(test)]
|
||||
static ATTDEF_VISITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The first ATTDEF of each tag in `block`, by upper-case tag, when there are at most `budget`
|
||||
/// distinct tags. `None` when another distinct tag would pass `budget`: the partial map is
|
||||
/// dropped, so a prefix is not stored in place of the definition.
|
||||
fn attdef_index_within(block: &Block, budget: usize) -> Option<BTreeMap<String, Handle>> {
|
||||
let mut by_tag = BTreeMap::new();
|
||||
for e in block.entities.iter() {
|
||||
count_attdef_visit();
|
||||
if let EntityKind::AttDef(ad) = &e.kind {
|
||||
let key = ad.tag.to_ascii_uppercase();
|
||||
if by_tag.contains_key(&key) {
|
||||
continue;
|
||||
}
|
||||
if by_tag.len() >= budget {
|
||||
return None;
|
||||
}
|
||||
by_tag.insert(key, e.handle);
|
||||
}
|
||||
}
|
||||
Some(by_tag)
|
||||
}
|
||||
|
||||
/// The first ATTDEF of `block` whose tag matches `tag`, ignoring ASCII case: one pass over the
|
||||
/// definition at most, stopping at the match. Nothing from the scan is stored.
|
||||
fn scan_attdef(block: &Block, tag: &str) -> Option<Handle> {
|
||||
for e in block.entities.iter() {
|
||||
count_attdef_visit();
|
||||
if let EntityKind::AttDef(ad) = &e.kind
|
||||
&& ad.tag.eq_ignore_ascii_case(tag)
|
||||
{
|
||||
return Some(e.handle);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The definition properties of the first ATTDEF in `block` whose tag matches `tag`, ignoring
|
||||
/// ASCII case. Each state of a block's entities that fits in [`MAX_INDEXED_TAGS`] is read once
|
||||
/// on a thread: later attributes, of this reference or another, find their definition in its
|
||||
/// index. A definition with more distinct tags is not stored: the first read of that state builds
|
||||
/// at most [`MAX_INDEXED_TAGS`] index entries, then gives up and remembers the state; every read
|
||||
/// of it scans the definition once at most, stopping at the first match.
|
||||
pub(super) fn attdef_base<'a>(block: &'a Block, tag: &str) -> Option<&'a Common> {
|
||||
let token = block.entities.content_token();
|
||||
let want = tag.to_ascii_uppercase();
|
||||
let found = ATTDEF_INDEXES
|
||||
.try_with(|cell| {
|
||||
let Ok(mut ix) = cell.try_borrow_mut() else { return scan_attdef(block, tag) };
|
||||
if let Some(by_tag) = ix.by_store.get(&token) {
|
||||
return by_tag.get(&want).copied();
|
||||
}
|
||||
if ix.too_large.contains(&token) {
|
||||
return scan_attdef(block, tag);
|
||||
}
|
||||
let Some(by_tag) = attdef_index_within(block, MAX_INDEXED_TAGS) else {
|
||||
if ix.too_large.len() >= MAX_TOO_LARGE {
|
||||
ix.too_large.clear();
|
||||
}
|
||||
ix.too_large.insert(token);
|
||||
return scan_attdef(block, tag);
|
||||
};
|
||||
let found = by_tag.get(&want).copied();
|
||||
let cost = by_tag.len().max(1);
|
||||
if ix.tags.saturating_add(cost) > MAX_INDEXED_TAGS {
|
||||
ix.by_store.clear();
|
||||
ix.tags = 0;
|
||||
}
|
||||
ix.tags = ix.tags.saturating_add(cost);
|
||||
ix.by_store.insert(token, by_tag);
|
||||
found
|
||||
})
|
||||
.unwrap_or_else(|_| scan_attdef(block, tag));
|
||||
block.entities.get(found?).map(|e| &e.common)
|
||||
}
|
||||
|
||||
/// One more definition entity examined (counted in tests).
|
||||
fn count_attdef_visit() {
|
||||
#[cfg(test)]
|
||||
ATTDEF_VISITS.with(|n| n.set(n.get().saturating_add(1)));
|
||||
}
|
||||
|
||||
/// How many definition entities attribute reads have examined on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn attdef_definition_visits() -> u64 {
|
||||
ATTDEF_VISITS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// Start a definition-visit count from zero.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reset_attdef_definition_visits() {
|
||||
ATTDEF_VISITS.with(|n| n.set(0));
|
||||
}
|
||||
|
||||
/// `AcadAnnotative` xdata marking an annotative style or block.
|
||||
pub(super) fn annotative_xdata(w: &mut W) {
|
||||
w.s(1001, "AcadAnnotative");
|
||||
w.s(1000, "AnnotativeData");
|
||||
@@ -25,6 +154,7 @@ pub(super) fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) {
|
||||
ucss: HashMap::new(),
|
||||
vport_ucs: Vec::new(),
|
||||
reactors: HashMap::new(),
|
||||
xdicts: HashMap::new(),
|
||||
};
|
||||
let mut sah = false;
|
||||
for (k, v) in &dm.overrides {
|
||||
@@ -92,8 +222,8 @@ pub(super) fn common_x(w: &mut W, e: &Entity, owner: &str, paper: bool, subclass
|
||||
let rs: Vec<&str> = reactors.iter().map(String::as_str).collect();
|
||||
w.group("ACAD_REACTORS", 330, &rs);
|
||||
}
|
||||
if let Some(a) = assoc {
|
||||
w.group("ACAD_XDICTIONARY", 360, &[&a.xdict]);
|
||||
if let Some(xd) = assoc.map(|a| a.xdict.clone()).or_else(|| w.xdicts.get(&e.handle).cloned()) {
|
||||
w.group("ACAD_XDICTIONARY", 360, &[&xd]);
|
||||
}
|
||||
w.s(330, owner);
|
||||
w.s(100, "AcDbEntity");
|
||||
@@ -145,13 +275,10 @@ pub(super) fn layer_and_props(w: &mut W, c: &Common, base: Option<&Common>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The properties attribute `a` of block reference `e` is drawn with: its own, else its
|
||||
/// definition's, from the block's definitions by tag `defs`; an attribute that takes layer 0 from
|
||||
/// its definition is on the reference's layer, one set on layer 0 itself stays there. Also the
|
||||
/// definition's properties.
|
||||
pub(super) fn attrib_common(e: &Entity, defs: &std::collections::BTreeMap<cadcraft_doc::TagKey<'_>, &Entity>, a: &Attrib) -> (Common, Common) {
|
||||
let def = defs.get(&cadcraft_doc::TagKey(&a.tag));
|
||||
let base = def.map(|de| de.common.clone()).unwrap_or_default();
|
||||
/// Attribute `a` takes its own properties over its definition's. A layer 0 inherited from the
|
||||
/// definition takes the reference's layer; an explicit layer 0 stays. Return both properties.
|
||||
pub(super) fn attrib_common(e: &Entity, a: &Attrib, base: Option<&Common>) -> (Common, Common) {
|
||||
let base = base.cloned().unwrap_or_default();
|
||||
let mut c = a.props.over(&base);
|
||||
if a.props.layer.is_none() && c.layer == "0" {
|
||||
c.layer.clone_from(&e.common.layer);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{DimVal, Handle, HashMap, K, Vec3, Version, dxf_ext};
|
||||
use super::{DimVal, Drawing, Entity, Handle, HashMap, K, MLeader, Tag, Vec3, Version, W, dxf_ext};
|
||||
use crate::dxf_ext::ByName;
|
||||
|
||||
/// The `DIMASSOC` object of an associative dimension (stored in the dimension's extension
|
||||
@@ -66,6 +66,8 @@ pub(super) struct Ctx {
|
||||
pub(super) frozen_341: bool,
|
||||
/// MTEXT columns as the legacy groups 75..79 even from R2018 (the groups AutoLISP lists).
|
||||
pub(super) legacy_columns: bool,
|
||||
/// Annotative text, MText and dimensions: their annotation scale contexts.
|
||||
pub(super) anno: crate::dxf_anno::Plan,
|
||||
/// Saved layer states in AutoCAD's form (the LAYER table's extension dictionary).
|
||||
pub(super) layer_states: crate::dxf_layer_states::Plan,
|
||||
}
|
||||
@@ -76,6 +78,27 @@ impl Ctx {
|
||||
pub(super) fn native_mleader(&self) -> bool {
|
||||
self.target >= Version::R2007
|
||||
}
|
||||
/// Annotative object `e` as its groups are written: at its default annotation scale (`None`:
|
||||
/// not written with contexts, as it is).
|
||||
pub(super) fn at_default(&self, e: &Entity) -> Option<Entity> {
|
||||
self.anno.objs.get(&e.handle).map(|o| crate::dxf_anno::at_scale(e, crate::dxf_anno::default_factor(o)))
|
||||
}
|
||||
/// A native MULTILEADER's groups after its `AcDbMLeader` marker.
|
||||
pub(super) fn mleader_tags(&self, d: &Drawing, m: &MLeader) -> Vec<Tag> {
|
||||
let refs = crate::dxf_mleader::Refs {
|
||||
style: self.mleader_style(&m.style),
|
||||
style_def: self.mleader_style_def(d, &m.style),
|
||||
text_style: m.text.as_ref().and_then(|t| self.style(&t.style)),
|
||||
block: m.block.as_ref().and_then(|b| self.block_records.get(&b.block.to_ascii_uppercase()).cloned()),
|
||||
};
|
||||
crate::dxf_mleader::entity_tags(d, m, &refs)
|
||||
}
|
||||
/// `AcadAnnotative` xdata of an object written with contexts.
|
||||
pub(super) fn anno_xdata(&self, w: &mut W, e: &Entity) {
|
||||
if self.anno.objs.contains_key(&e.handle) {
|
||||
w.xdata(crate::dxf_anno::xdata());
|
||||
}
|
||||
}
|
||||
pub(super) fn style(&self, name: &str) -> Option<String> {
|
||||
self.styles.get(&name.to_ascii_uppercase()).cloned()
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@ use super::common::{attrib_common, common, common_x, dim_xdata, layer_and_props,
|
||||
use super::ctx::Ctx;
|
||||
use super::layout::paper_view;
|
||||
use super::{
|
||||
Bounds2, Color, DimKind, Drawing, Entity, EntityKind, Gradient, Handle, HashMap, Hatch, Leader, MLeader, Point, Vec2, Vec3, Version, W, dxf_ext,
|
||||
Attrib, Bounds2, Color, Common, DimKind, Drawing, Entity, EntityKind, Gradient, Handle, HashMap, Hatch, Leader, MLeader, Point, Vec2, Vec3,
|
||||
Version, W, dxf_ext,
|
||||
};
|
||||
|
||||
/// The persistent reactors of boundary objects: each source object of an associative hatch in
|
||||
@@ -303,10 +304,16 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) {
|
||||
match &e.kind {
|
||||
EntityKind::Text(t) => {
|
||||
let scaled = cx.at_default(e);
|
||||
let t = match scaled.as_ref().map(|s| &s.kind) {
|
||||
Some(EntityKind::Text(s)) => s,
|
||||
_ => t,
|
||||
};
|
||||
w.s(0, "TEXT");
|
||||
common(w, e, owner, paper, "AcDbText");
|
||||
thickness(w, e);
|
||||
text_tags(w, d, t, None, None, (e.handle, 0));
|
||||
cx.anno_xdata(w, e);
|
||||
}
|
||||
// Closed polylines, one per loop (`dxf_region`): REGION's own data is ACIS.
|
||||
EntityKind::Region(r) => {
|
||||
@@ -332,6 +339,11 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo
|
||||
}
|
||||
}
|
||||
EntityKind::MText(t) => {
|
||||
let scaled = cx.at_default(e);
|
||||
let t = match scaled.as_ref().map(|s| &s.kind) {
|
||||
Some(EntityKind::MText(s)) => s,
|
||||
_ => t,
|
||||
};
|
||||
w.s(0, "MTEXT");
|
||||
common(w, e, owner, paper, "AcDbMText");
|
||||
w.p(10, t.insert);
|
||||
@@ -357,7 +369,32 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo
|
||||
// Line spacing style: 1 = at least, 2 = exactly.
|
||||
w.i(73, if t.line_spacing_exact { 2 } else { 1 });
|
||||
w.f(44, t.line_spacing);
|
||||
// Why: Strict DXF parsers (e.g. AutoCAD 2027) reject conditional MTEXT background tags
|
||||
// (63/421/45) when group 90 disables the mask or color bit; emit only tags active for
|
||||
// the current bitmask, and keep them before column tags (75/101) where the reader stops.
|
||||
if let Some(bg) = &t.background {
|
||||
let mask = bg.mask & 0x03;
|
||||
if mask != 0 {
|
||||
w.i(90, i64::from(mask));
|
||||
let uses_window_bg = (mask & 2) != 0;
|
||||
if !uses_window_bg
|
||||
&& (mask & 1) != 0
|
||||
&& let Some(c) = bg.color
|
||||
{
|
||||
match c {
|
||||
Color::True(rgb) => {
|
||||
w.i(63, i64::from(cadcraft_color::nearest_aci(rgb)));
|
||||
w.i(421, i64::from(rgb.to_u32()));
|
||||
}
|
||||
c => w.i(63, i64::from(c.to_aci())),
|
||||
}
|
||||
}
|
||||
let scale = if bg.scale.is_finite() { bg.scale.clamp(1.0, 5.0) } else { 1.5 };
|
||||
w.f(45, scale);
|
||||
}
|
||||
}
|
||||
w.t.extend(crate::dxf_read::mtext_dxf::column_tags(t, cx.target >= Version::R2018 && !cx.legacy_columns));
|
||||
cx.anno_xdata(w, e);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -389,33 +426,45 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
|
||||
// The block's definitions by tag, gathered once for all the attributes (#1923).
|
||||
let defs = d.block(&i.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
|
||||
for (index, a) in i.attribs.iter().enumerate() {
|
||||
let ah = w.h();
|
||||
w.s(0, "ATTRIB");
|
||||
w.s(5, ah);
|
||||
w.s(330, e.handle.hex());
|
||||
w.s(100, "AcDbEntity");
|
||||
let (c, base) = attrib_common(e, &defs, a);
|
||||
layer_and_props(w, &c, Some(&base));
|
||||
// Hidden with its definition (a dynamic block's visibility state hides it).
|
||||
if !base.visible {
|
||||
w.i(60, 1);
|
||||
}
|
||||
w.s(100, "AcDbText");
|
||||
text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index));
|
||||
if cx.target >= Version::R2007 {
|
||||
multiline_tags(w, a, false);
|
||||
}
|
||||
let base = defs.get(&cadcraft_doc::TagKey(&a.tag)).map(|de| &de.common);
|
||||
attrib_record(w, d, e, index, a, base, cx);
|
||||
}
|
||||
let sh = w.h();
|
||||
w.s(0, "SEQEND");
|
||||
w.s(5, sh);
|
||||
w.s(330, e.handle.hex());
|
||||
w.s(100, "AcDbEntity");
|
||||
w.s(8, &e.common.layer);
|
||||
seqend_record(w, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One ATTRIB record of the block reference `e`, for its attribute `a` (as written after its
|
||||
/// INSERT): its handle is a new one, its owner the reference's.
|
||||
pub(super) fn attrib_record(w: &mut W, d: &Drawing, e: &Entity, index: usize, a: &Attrib, base: Option<&Common>, cx: &Ctx) {
|
||||
let ah = w.h();
|
||||
w.s(0, "ATTRIB");
|
||||
w.s(5, ah);
|
||||
w.s(330, e.handle.hex());
|
||||
w.s(100, "AcDbEntity");
|
||||
let (c, base) = attrib_common(e, a, base);
|
||||
layer_and_props(w, &c, Some(&base));
|
||||
// Hidden with its definition (a dynamic block's visibility state hides it).
|
||||
if !base.visible {
|
||||
w.i(60, 1);
|
||||
}
|
||||
w.s(100, "AcDbText");
|
||||
text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index));
|
||||
if cx.target >= Version::R2007 {
|
||||
multiline_tags(w, a, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// The SEQEND record that ends a block reference's attributes (written after its last ATTRIB).
|
||||
pub(super) fn seqend_record(w: &mut W, e: &Entity) {
|
||||
let sh = w.h();
|
||||
w.s(0, "SEQEND");
|
||||
w.s(5, sh);
|
||||
w.s(330, e.handle.hex());
|
||||
w.s(100, "AcDbEntity");
|
||||
w.s(8, &e.common.layer);
|
||||
}
|
||||
|
||||
fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) {
|
||||
if let EntityKind::Dimension(dm) = &e.kind {
|
||||
w.s(0, "DIMENSION");
|
||||
@@ -424,7 +473,13 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper
|
||||
w.s(2, bname);
|
||||
w.p(10, dm.defpt);
|
||||
let style = d.dim_style(&dm.style).cloned().unwrap_or_default();
|
||||
let g = cadcraft_render::dimension_geometry(dm, &style, d.header.f64("DIMSCALE", 1.0));
|
||||
// An annotative dimension's text is where its default scale puts it.
|
||||
let scaled = cx.at_default(e);
|
||||
let at = match scaled.as_ref().map(|s| &s.kind) {
|
||||
Some(EntityKind::Dimension(s)) => s,
|
||||
_ => dm,
|
||||
};
|
||||
let g = cadcraft_render::dimension_geometry(at, &style, d.header.f64("DIMSCALE", 1.0));
|
||||
w.p(11, if dm.user_text_pos { dm.text_mid } else { g.text_pos.to3(0.0) });
|
||||
// Group 12: a block read from a file keeps the dimension's moved-by offset (AutoCAD
|
||||
// draws the block translated by it); regenerated geometry already sits where the
|
||||
@@ -510,6 +565,7 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper
|
||||
}
|
||||
}
|
||||
dim_xdata(w, dm, cx);
|
||||
cx.anno_xdata(w, e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -605,15 +661,19 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap
|
||||
match &e.kind {
|
||||
EntityKind::MLeader(m) if !cx.native_mleader() => mleader_fallback(w, d, e, m, owner, paper, cx),
|
||||
EntityKind::MLeader(m) => {
|
||||
let scaled = cx.at_default(e);
|
||||
let m = match scaled.as_ref().map(|s| &s.kind) {
|
||||
Some(EntityKind::MLeader(s)) => s,
|
||||
_ => m,
|
||||
};
|
||||
w.s(0, "MULTILEADER");
|
||||
common(w, e, owner, paper, "AcDbMLeader");
|
||||
let refs = crate::dxf_mleader::Refs {
|
||||
style: cx.mleader_style(&m.style),
|
||||
style_def: cx.mleader_style_def(d, &m.style),
|
||||
text_style: m.text.as_ref().and_then(|t| cx.style(&t.style)),
|
||||
block: m.block.as_ref().and_then(|b| cx.block_records.get(&b.block.to_ascii_uppercase()).cloned()),
|
||||
};
|
||||
w.t.extend(crate::dxf_mleader::entity_tags(d, m, &refs));
|
||||
let mut tags = cx.mleader_tags(d, m);
|
||||
if let Some(o) = cx.anno.objs.get(&e.handle) {
|
||||
crate::dxf_anno::mleader_at(&mut tags, crate::dxf_anno::default_factor(o));
|
||||
}
|
||||
w.t.extend(tags);
|
||||
cx.anno_xdata(w, e);
|
||||
}
|
||||
EntityKind::Leader(l) => {
|
||||
w.s(0, "LEADER");
|
||||
@@ -784,8 +844,30 @@ fn write_viewport_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper:
|
||||
if let Some(h) = clip {
|
||||
w.s(340, h.hex());
|
||||
}
|
||||
// One CADCraft xdata group holds both lists: readers stop at the first group of an app.
|
||||
if !unrecorded.is_empty() || !v.layer_colors.is_empty() {
|
||||
// The viewport's own UCS. Its other unmodelled groups (`extra`) go in after this, just
|
||||
// before the xdata (dxf_raw::finish).
|
||||
if v.ucs.is_some() || v.ucs_per_viewport {
|
||||
w.i(71, i64::from(v.ucs_per_viewport));
|
||||
}
|
||||
// The named and base UCS that are still in the UCS table.
|
||||
let mut ucs_names = (None, None);
|
||||
if let Some(u) = &v.ucs {
|
||||
w.p(110, u.origin);
|
||||
w.p(111, u.x_axis);
|
||||
w.p(112, u.y_axis);
|
||||
w.i(79, i64::from(u.ortho));
|
||||
w.f(146, u.elevation);
|
||||
ucs_names = (live_ucs(&w.ucss, &u.named), live_ucs(&w.ucss, &u.base));
|
||||
for (code, name) in [(345, &ucs_names.0), (346, &ucs_names.1)] {
|
||||
if let Some((_, h)) = name {
|
||||
w.s(code, h.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let has_ucs_names = ucs_names.0.is_some() || ucs_names.1.is_some();
|
||||
let has_extra = v.extra.iter().any(|t| !crate::dxf_raw::is_pointer(t.code));
|
||||
// One CADCraft xdata group holds all the lists: readers stop at the first group of an app.
|
||||
if !unrecorded.is_empty() || !v.layer_colors.is_empty() || has_ucs_names || has_extra {
|
||||
w.s(1001, dxf_ext::APP);
|
||||
if !unrecorded.is_empty() {
|
||||
w.xdata(dxf_ext::frozen_xdata(&unrecorded));
|
||||
@@ -793,6 +875,12 @@ fn write_viewport_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper:
|
||||
if !v.layer_colors.is_empty() {
|
||||
w.xdata(dxf_ext::layer_colors_xdata(&v.layer_colors));
|
||||
}
|
||||
if has_ucs_names {
|
||||
w.xdata(dxf_ext::ucs_xdata(ucs_names.0.map(|(n, _)| n), ucs_names.1.map(|(n, _)| n)));
|
||||
}
|
||||
if has_extra {
|
||||
w.xdata(dxf_ext::extra_xdata(&v.extra));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -945,3 +1033,9 @@ fn hatch_xdata(w: &mut W, h: &Hatch) {
|
||||
w.p(1011, h.origin.to3(0.0));
|
||||
w.s(1000, h.background.map(Color::name).unwrap_or_default());
|
||||
}
|
||||
|
||||
/// A viewport's named or base UCS with its record handle, if the UCS table still has it.
|
||||
fn live_ucs<'a>(ucss: &HashMap<String, String>, name: &'a Option<String>) -> Option<(&'a str, String)> {
|
||||
let n = name.as_deref()?;
|
||||
Some((n, ucss.get(&n.to_ascii_uppercase())?.clone()))
|
||||
}
|
||||
|
||||
@@ -277,6 +277,7 @@ fn write_dimstyles(w: &mut W, d: &Drawing, cx: &mut Ctx, version: Version) {
|
||||
ucss: HashMap::new(),
|
||||
vport_ucs: Vec::new(),
|
||||
reactors: HashMap::new(),
|
||||
xdicts: HashMap::new(),
|
||||
};
|
||||
for (field, code, kind) in dxf_ext::DIM_CODES {
|
||||
let Some(enc) = v.get(*field).and_then(|x| cx.encode(*kind, x)) else { continue };
|
||||
@@ -347,7 +348,7 @@ fn write_header(w: &mut W, d: &Drawing, version: Version) -> usize {
|
||||
seed_pos
|
||||
}
|
||||
|
||||
fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity], wipeout_vars: bool) {
|
||||
fn write_classes(w: &mut W, d: &Drawing, cx: &Ctx, every: &[&Entity], wipeout_vars: bool) {
|
||||
w.s(0, "SECTION");
|
||||
w.s(2, "CLASSES");
|
||||
let mut classes = vec![
|
||||
@@ -381,6 +382,9 @@ fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity], wipeout_vars: bool) {
|
||||
classes.push(("RASTERVARIABLES", "AcDbRasterVariables", 0, false));
|
||||
}
|
||||
classes.push(("SCALE", "AcDbScale", 0, false));
|
||||
for (dxf_name, cpp) in cx.anno.classes(d) {
|
||||
classes.push((dxf_name, cpp, 1153, false));
|
||||
}
|
||||
for (dxf_name, cpp, proxy, is_entity) in classes {
|
||||
w.s(0, "CLASS");
|
||||
w.s(1, dxf_name);
|
||||
@@ -870,7 +874,8 @@ fn write_named_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn write_associative_objects(w: &mut W, cx: &Ctx) {
|
||||
fn write_associative_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
|
||||
let cx = plan.cx;
|
||||
// Dimension associativity: extension dictionary + DIMASSOC per dimension.
|
||||
let mut assoc: Vec<(&Handle, &AssocObj)> = cx.assoc.iter().collect();
|
||||
assoc.sort_by_key(|(h, _)| **h);
|
||||
@@ -885,6 +890,10 @@ fn write_associative_objects(w: &mut W, cx: &Ctx) {
|
||||
w.i(281, 1);
|
||||
w.s(3, "ACAD_DIMASSOC");
|
||||
w.s(360, a.handle.clone());
|
||||
// An annotative dimension's contexts share the dictionary.
|
||||
if let Some(o) = cx.anno.objs.get(dim) {
|
||||
w.t.extend(crate::dxf_anno::xdict_entry(o));
|
||||
}
|
||||
w.s(0, "DIMASSOC");
|
||||
w.s(5, a.handle.clone());
|
||||
w.group("ACAD_REACTORS", 330, &[&a.xdict]);
|
||||
@@ -914,6 +923,17 @@ fn write_associative_objects(w: &mut W, cx: &Ctx) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The annotation scale contexts of annotative text, MText and dimensions.
|
||||
fn write_annotation_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
|
||||
let mut annos: Vec<(&Handle, &crate::dxf_anno::Obj)> = plan.cx.anno.objs.iter().collect();
|
||||
annos.sort_by_key(|(h, _)| **h);
|
||||
for (h, o) in annos {
|
||||
if let Some(e) = plan.d.entity(*h) {
|
||||
w.t.extend(crate::dxf_anno::objects(plan.d, e, o, &|m| plan.cx.mleader_tags(plan.d, m)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_objects(w: &mut W, plan: ObjectWritePlan<'_>) {
|
||||
// Groups (members that still exist) and multileader styles.
|
||||
let group_owner = plan.group_dict.clone();
|
||||
@@ -934,25 +954,114 @@ fn write_objects(w: &mut W, plan: ObjectWritePlan<'_>) {
|
||||
crate::dxf_layer_states::objects(&plan.cx.layer_states, &plan.d.layer_states, &refs)
|
||||
};
|
||||
w.t.extend(layer_states);
|
||||
write_associative_objects(w, plan.cx);
|
||||
write_associative_objects(w, &plan);
|
||||
write_annotation_objects(w, &plan);
|
||||
write_layout_objects(w, &plan);
|
||||
// Raster image definitions.
|
||||
w.t.extend(crate::dxf_image::objects(&plan.cx.images, plan.root_dict));
|
||||
w.s(0, "ENDSEC");
|
||||
}
|
||||
|
||||
/// The next free `*D` block name at or after `*D{n}`.
|
||||
fn fresh_dim_name(d: &Drawing, n: &mut usize) -> String {
|
||||
let mut name = format!("*D{n}");
|
||||
while d.block(&name).is_some() {
|
||||
*n += 1;
|
||||
name = format!("*D{n}");
|
||||
}
|
||||
*n += 1;
|
||||
name
|
||||
}
|
||||
|
||||
type DimDef = (String, String, Vec<Entity>);
|
||||
|
||||
/// An annotative dimension's blocks, one per annotation scale (its default scale's is the
|
||||
/// dimension's own); `None` when it has no scales.
|
||||
fn annotative_dimension_blocks(
|
||||
d: &Drawing,
|
||||
e: &Entity,
|
||||
n: &mut usize,
|
||||
w: &mut W,
|
||||
(cx, dim_defs): (&mut Ctx, &mut Vec<DimDef>),
|
||||
) -> Option<Vec<String>> {
|
||||
// Only dimensions have a block per scale (text and multileaders have none).
|
||||
if !matches!(e.kind, EntityKind::Dimension(_)) {
|
||||
return None;
|
||||
}
|
||||
let (scales, default) = crate::dxf_anno::scales(d, e);
|
||||
let mut names = Vec::new();
|
||||
for s in &scales {
|
||||
let at = crate::dxf_anno::at_scale(e, s.factor());
|
||||
let EntityKind::Dimension(sdm) = &at.kind else { continue };
|
||||
let ents = dim_block_entities(d, sdm, &e.common.layer);
|
||||
let name = fresh_dim_name(d, n);
|
||||
dim_defs.push((name.clone(), w.h(), ents));
|
||||
names.push(name);
|
||||
}
|
||||
cx.dim_blocks.insert(e.handle, names.get(default)?.clone());
|
||||
Some(names)
|
||||
}
|
||||
|
||||
/// The dimensions' anonymous blocks, and the blocks of each annotative dimension by scale (from
|
||||
/// The scales annotative text, MText and dimensions support that the drawing's scale list lacks
|
||||
/// (each context names its SCALE object, so they are added to the list written).
|
||||
fn missing_anno_scales(d: &Drawing, all_spaces: &[&EntityStore]) -> Vec<cadcraft_doc::AnnoScale> {
|
||||
let mut extra: Vec<cadcraft_doc::AnnoScale> = Vec::new();
|
||||
for e in all_spaces.iter().flat_map(|s| s.iter()).filter(|e| crate::dxf_anno::has_contexts(e)) {
|
||||
for s in crate::dxf_anno::scales(d, e).0 {
|
||||
let known = |x: &cadcraft_doc::AnnoScale| x.is_valid() && x.name.eq_ignore_ascii_case(&s.name);
|
||||
if !d.scales.iter().any(known) && !extra.iter().any(known) && extra.len() < cadcraft_doc::MAX_SCALES {
|
||||
extra.push(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
extra
|
||||
}
|
||||
|
||||
/// Plan the annotation scale contexts of annotative text, MText and dimensions: their objects in
|
||||
/// `cx.anno`, and the extension dictionaries made for them in `w.xdicts`.
|
||||
fn plan_anno_contexts(
|
||||
d: &Drawing,
|
||||
all_spaces: &[&EntityStore],
|
||||
scales: &[(&cadcraft_doc::AnnoScale, String)],
|
||||
anno_dim_blocks: &HashMap<Handle, Vec<String>>,
|
||||
w: &mut W,
|
||||
cx: &mut Ctx,
|
||||
) {
|
||||
let scale_handle = |name: &str| scales.iter().find(|(s, _)| s.name.eq_ignore_ascii_case(name)).map(|(_, h)| h.clone());
|
||||
for e in all_spaces.iter().flat_map(|s| s.iter()).filter(|e| crate::dxf_anno::has_contexts(e)) {
|
||||
let xdict = cx.assoc.get(&e.handle).map(|a| a.xdict.clone());
|
||||
let blocks = anno_dim_blocks.get(&e.handle).map(Vec::as_slice);
|
||||
if let Some(o) = crate::dxf_anno::plan_one(d, e, scale_handle, xdict, blocks, || w.h()) {
|
||||
if o.own_xdict {
|
||||
w.xdicts.insert(e.handle, o.xdict.clone());
|
||||
}
|
||||
cx.anno.objs.insert(e.handle, o);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// AutoCAD 2008, the 2007 format: `contexts`).
|
||||
fn dimension_block_definitions(
|
||||
d: &Drawing,
|
||||
all_spaces: &[&EntityStore],
|
||||
dim_plan: &super::blocks::DimBlockPlan,
|
||||
(dim_plan, contexts): (&super::blocks::DimBlockPlan, bool),
|
||||
w: &mut W,
|
||||
cx: &mut Ctx,
|
||||
) -> Vec<(String, String, Vec<Entity>)> {
|
||||
) -> (Vec<DimDef>, HashMap<Handle, Vec<String>>) {
|
||||
let mut dim_defs = Vec::new();
|
||||
let mut anno_dim_blocks: HashMap<Handle, Vec<String>> = HashMap::new();
|
||||
let mut n = 1;
|
||||
let mut reused_handles = std::collections::HashSet::new();
|
||||
for st in all_spaces {
|
||||
for e in st.iter() {
|
||||
if contexts
|
||||
&& crate::dxf_anno::has_contexts(e)
|
||||
&& let Some(names) = annotative_dimension_blocks(d, e, &mut n, w, (cx, &mut dim_defs))
|
||||
{
|
||||
anno_dim_blocks.insert(e.handle, names);
|
||||
continue;
|
||||
}
|
||||
if let EntityKind::Dimension(dm) = &e.kind {
|
||||
let reused = dim_plan.reuse.get(&e.handle);
|
||||
let ents: Vec<Entity>;
|
||||
@@ -973,13 +1082,7 @@ fn dimension_block_definitions(
|
||||
}
|
||||
None => {
|
||||
ents = dim_block_entities(d, dm, &e.common.layer);
|
||||
let mut name = format!("*D{n}");
|
||||
while d.block(&name).is_some() {
|
||||
n += 1;
|
||||
name = format!("*D{n}");
|
||||
}
|
||||
n += 1;
|
||||
name
|
||||
fresh_dim_name(d, &mut n)
|
||||
}
|
||||
};
|
||||
let brh = w.h();
|
||||
@@ -988,7 +1091,7 @@ fn dimension_block_definitions(
|
||||
}
|
||||
}
|
||||
}
|
||||
dim_defs
|
||||
(dim_defs, anno_dim_blocks)
|
||||
}
|
||||
|
||||
fn arrow_block_definitions(
|
||||
@@ -1123,6 +1226,7 @@ pub(super) fn tags_kept_for(
|
||||
ucss: HashMap::new(),
|
||||
vport_ucs: Vec::new(),
|
||||
reactors: hatch_reactors(d),
|
||||
xdicts: HashMap::new(),
|
||||
};
|
||||
// Pre-allocate handles for block records.
|
||||
let paper_layouts = d.paper_space_layouts();
|
||||
@@ -1148,7 +1252,11 @@ pub(super) fn tags_kept_for(
|
||||
let mut cx = Ctx { paper_views: paper_views(d), target, frozen_341, modern_table_values: !bridge && version >= Version::R2007, ..Ctx::default() };
|
||||
cx.block_records = user_blocks.iter().map(|(n, h, _)| (n.to_ascii_uppercase(), h.clone())).collect();
|
||||
let all_spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect();
|
||||
let mut dim_defs = dimension_block_definitions(d, &all_spaces, &dim_plan, &mut w, &mut cx);
|
||||
// Annotation scale contexts (from AutoCAD 2008, the 2007 format). Not through the DWG bridge
|
||||
// yet, which doesn't convert them (storytold/craft-libs#2005): a DWG keeps CADCraft's own
|
||||
// record of the scales instead, as an older format does.
|
||||
let contexts = target >= Version::R2007 && !bridge;
|
||||
let (mut dim_defs, anno_dim_blocks) = dimension_block_definitions(d, &all_spaces, (&dim_plan, contexts), &mut w, &mut cx);
|
||||
// Every entity, including block contents (for arrows, tables and overrides).
|
||||
let every: Vec<&Entity> = all_spaces
|
||||
.iter()
|
||||
@@ -1196,7 +1304,7 @@ pub(super) fn tags_kept_for(
|
||||
if let Some(chunks) = dxf_ext::plot_style_chunks(&d.plot_style_tables) {
|
||||
xrecords.push((dxf_ext::PLOT_STYLES_KEY, w.h(), chunks));
|
||||
}
|
||||
if let Some(chunks) = dxf_ext::anno_chunks(d) {
|
||||
if let Some(chunks) = dxf_ext::anno_chunks(d, contexts) {
|
||||
xrecords.push((dxf_ext::ANNOTATION_KEY, w.h(), chunks));
|
||||
}
|
||||
// The annotation scale list: the ACAD_SCALELIST dictionary of SCALE objects.
|
||||
@@ -1223,7 +1331,14 @@ pub(super) fn tags_kept_for(
|
||||
.map(|v| v.min(1))
|
||||
.filter(|flag| file_flag != Some(*flag));
|
||||
let wipeout_handle = wipeout_frame.map(|_| w.h());
|
||||
let scales: Vec<(&cadcraft_doc::AnnoScale, String)> = d.scales.iter().filter(|s| s.is_valid()).map(|s| (s, w.h())).collect();
|
||||
// Scales annotative objects support that the list lacks are added to it (each context names
|
||||
// its SCALE object).
|
||||
let extra_scales = if contexts { missing_anno_scales(d, &all_spaces) } else { Vec::new() };
|
||||
let scales: Vec<(&cadcraft_doc::AnnoScale, String)> =
|
||||
d.scales.iter().filter(|s| s.is_valid()).chain(extra_scales.iter()).map(|s| (s, w.h())).collect();
|
||||
if contexts {
|
||||
plan_anno_contexts(d, &all_spaces, &scales, &anno_dim_blocks, &mut w, &mut cx);
|
||||
}
|
||||
// Plot style names used by layers and objects (Normal always), each a placeholder object; in
|
||||
// a drawing of named plot styles also those of the layers of saved layer states, which name
|
||||
// theirs by placeholder.
|
||||
@@ -1247,7 +1362,7 @@ pub(super) fn tags_kept_for(
|
||||
|
||||
let seed_pos = write_header(&mut w, d, version);
|
||||
|
||||
write_classes(&mut w, &cx, &every, wipeout_frame.is_some());
|
||||
write_classes(&mut w, d, &cx, &every, wipeout_frame.is_some());
|
||||
|
||||
let max_dashes = bridge.then_some(super::DWG_MAX_LINETYPE_ELEMENTS);
|
||||
let (ltype_handles, linetypes_cut) = write_tables(&mut w, TableWritePlan { d, version, cx: &mut cx, ext: d.extents(&Space::Model), max_dashes });
|
||||
@@ -1262,10 +1377,18 @@ pub(super) fn tags_kept_for(
|
||||
w.s(100, "AcDbBlockTableRecord");
|
||||
w.s(2, name);
|
||||
w.s(340, layout.unwrap_or("0"));
|
||||
// User blocks: insertion units (70) and explodability (280).
|
||||
// User blocks: insertion units (70), explodability (280), uniform scaling (281) and
|
||||
// whether references are annotative (`AcadAnnotative` xdata: without it AutoCAD scales
|
||||
// the references by their units instead of the annotation scale). Not in a DWG yet: the
|
||||
// bridge drops the references' contexts, and the flag alone would have AutoCAD scale them
|
||||
// by the annotation scale once more (storytold/craft-libs#2005).
|
||||
if let Some(b) = blk {
|
||||
w.i(70, i64::from(b.units));
|
||||
w.i(280, i64::from(b.explodable));
|
||||
w.i(281, i64::from(b.scale_uniformly));
|
||||
if b.annotative && !bridge {
|
||||
annotative_xdata(w);
|
||||
}
|
||||
if let Some(a) = &b.array {
|
||||
w.s(1001, dxf_ext::APP);
|
||||
w.xdata(dxf_ext::array_xdata(a));
|
||||
@@ -1400,7 +1523,7 @@ pub(super) fn tags_kept_for(
|
||||
// no data store, so a solid whose geometry is only there is left out of it.
|
||||
// The DWG bridge keeps proxies in the DWG's own layout.
|
||||
let strings = bridge || version >= Version::R2007;
|
||||
let kept = crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013, target >= Version::R2013, strings);
|
||||
let kept = crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013, target >= Version::R2013, strings, bridge);
|
||||
// Kept constraint groups go in the order their reader expects: a DXF's own version. The
|
||||
// bridge's R2000 text is read as the version its kept groups came from when that is newer
|
||||
// (craft-dwg's `encode_kept_noted` declares it), so there they stay as read.
|
||||
|
||||
@@ -7,6 +7,8 @@ mod dwg_hatch;
|
||||
/// What a DXF file holds that CADCraft doesn't model, kept and written back (#528).
|
||||
mod dxf_raw;
|
||||
|
||||
/// Annotative text, MText and dimensions: AutoCAD's annotation scale contexts.
|
||||
mod dxf_anno;
|
||||
/// XCLIP boundaries as SPATIAL_FILTER objects.
|
||||
mod dxf_clip;
|
||||
mod dxf_ext;
|
||||
@@ -38,7 +40,7 @@ pub use cadcraft_doc::Format;
|
||||
pub use craft_dxf::Version;
|
||||
pub use dxf_raw::{ObjectRecord, object_records};
|
||||
pub use dxf_read::entity_from_groups;
|
||||
pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, proxies_lost};
|
||||
pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, entity_sub_record, proxies_lost};
|
||||
pub use pdf::{PdfOptions, pdf, plot};
|
||||
|
||||
/// How a drawing is saved as DXF or DWG.
|
||||
|
||||
@@ -36,6 +36,7 @@ use kr::text::{GlyphId, KrillaGlyph};
|
||||
use crate::{IoError, Result};
|
||||
|
||||
mod fonts;
|
||||
mod outline;
|
||||
|
||||
/// PDF points per millimetre.
|
||||
const PT_PER_MM: f64 = 72.0 / 25.4;
|
||||
@@ -867,7 +868,7 @@ fn krilla_failure(e: KrillaError) -> Failure {
|
||||
/// transparent primitive is stroked on its own (one path is painted once), so where
|
||||
/// primitives overlap they build up, as in PNG plots and on screen. Block contents and
|
||||
/// viewport contents share their reference's handle, so this goes by primitive, not by object.
|
||||
/// Each filled primitive is one path of its triangles.
|
||||
/// Each filled primitive is one path: the outline of its triangles.
|
||||
///
|
||||
/// Primitives that stand for a glyph in an embeddable font (see [`fonts::Fonts`]) are written
|
||||
/// as text instead: the glyph at font size 1 under its glyph matrix (the matrix axes are one
|
||||
@@ -983,14 +984,16 @@ fn stroke_run(s: &mut Surface<'_>, batch: &mut Option<(StrokeStyle, PathBuilder)
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill a set of triangles, clipped to the plot area.
|
||||
/// Fill a set of triangles, clipped to the plot area, as the loops of their outline (see
|
||||
/// [`outline`]), which fill the same as the triangles with far less path data.
|
||||
fn fill_tris(s: &mut Surface<'_>, p: &SheetPage, raw: &[Vec2], rgb: Rgb, t: u8) {
|
||||
let mapped: Vec<Vec2> = raw.iter().map(|q| p.map.pt(*q)).collect();
|
||||
// With a vertex out of range, keep the parts inside the plot area.
|
||||
let tris = if mapped.iter().all(|q| coord(*q).is_some()) { mapped } else { clip::clip_triangles(&mapped, &p.clip_pt) };
|
||||
let tris: Vec<[outline::Pt; 3]> = tris.as_chunks::<3>().0.iter().filter_map(|[a, b, c]| Some([coord(*a)?, coord(*b)?, coord(*c)?])).collect();
|
||||
let rings = outline::loops(&tris).unwrap_or_else(|| tris.iter().map(|t| t.to_vec()).collect());
|
||||
let mut pb = PathBuilder::new();
|
||||
for tri in tris.as_chunks::<3>().0 {
|
||||
let Some(v) = tri.iter().map(|q| coord(*q)).collect::<Option<Vec<_>>>() else { continue };
|
||||
for v in &rings {
|
||||
for (j, (x, y)) in v.iter().enumerate() {
|
||||
if j == 0 {
|
||||
pb.move_to(*x, *y);
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! The outline of a set of filled triangles: closed loops that fill, under the nonzero rule,
|
||||
//! exactly what the triangles fill as one path of one subpath each.
|
||||
//!
|
||||
//! A filled path's nonzero winding number at a point is the sum, over its directed edges, of
|
||||
//! the crossings of a ray from the point. So it depends only on how many times each directed
|
||||
//! edge occurs, less the times it occurs reversed. An edge shared by two neighbouring
|
||||
//! triangles in opposite directions cancels, and so does a zero-length edge. What is left
|
||||
//! enters each vertex as often as it leaves it (each triangle does, and a cancelled pair takes
|
||||
//! one entry and one exit from both its ends), so it splits into closed loops, and any such
|
||||
//! split winds the same as the triangles everywhere off the edges. This holds for overlapping
|
||||
//! triangles, mixed orientations, zero-area triangles and T-junctions alike: edges that do not
|
||||
//! pair stay in the outline, which is then larger but still fills the same.
|
||||
//!
|
||||
//! Vertices are matched by the exact bits of the `f32` coordinates that are written, never by a
|
||||
//! tolerance, so two distinct written points are never merged.
|
||||
|
||||
/// A written vertex.
|
||||
pub(super) type Pt = (f32, f32);
|
||||
|
||||
/// The bits of a vertex, the key it is matched by.
|
||||
fn key(p: Pt) -> u64 {
|
||||
(u64::from(p.0.to_bits()) << 32) | u64::from(p.1.to_bits())
|
||||
}
|
||||
|
||||
/// The loops (each closed back to its first vertex) whose nonzero fill is that of `tris`, or
|
||||
/// `None` when they cannot be traced (which the reasoning above rules out; the caller then
|
||||
/// writes the triangles). Time is `O(n log n)` and memory `O(n)` in the triangle count.
|
||||
pub(super) fn loops(tris: &[[Pt; 3]]) -> Option<Vec<Vec<Pt>>> {
|
||||
let mut keys: Vec<u64> = tris.iter().flatten().map(|p| key(*p)).collect();
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
let pts: Vec<Pt> = keys.iter().map(|k| (f32::from_bits((k >> 32) as u32), f32::from_bits(*k as u32))).collect();
|
||||
let id = |p: &Pt| keys.binary_search(&key(*p)).ok().and_then(|i| u32::try_from(i).ok());
|
||||
// Each edge as (lower id, higher id, +1 when it runs from the lower to the higher).
|
||||
let mut undirected: Vec<(u32, u32, i8)> = Vec::with_capacity(tris.len().saturating_mul(3));
|
||||
for t in tris {
|
||||
let v = [id(&t[0])?, id(&t[1])?, id(&t[2])?];
|
||||
for (a, b) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])] {
|
||||
match a.cmp(&b) {
|
||||
std::cmp::Ordering::Less => undirected.push((a, b, 1)),
|
||||
std::cmp::Ordering::Greater => undirected.push((b, a, -1)),
|
||||
std::cmp::Ordering::Equal => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
undirected.sort_unstable_by_key(|e| (e.0, e.1));
|
||||
// What is left of each edge once opposite directions cancel, by start vertex.
|
||||
let mut edges: Vec<(u32, u32)> = Vec::new();
|
||||
for run in undirected.chunk_by(|x, y| (x.0, x.1) == (y.0, y.1)) {
|
||||
let Some(&(a, b, _)) = run.first() else { continue };
|
||||
let net: i64 = run.iter().map(|e| i64::from(e.2)).sum();
|
||||
let e = if net > 0 { (a, b) } else { (b, a) };
|
||||
edges.extend(std::iter::repeat_n(e, usize::try_from(net.unsigned_abs()).ok()?));
|
||||
}
|
||||
drop(undirected);
|
||||
edges.sort_unstable();
|
||||
// `next[v]..end[v]`: the unused edges leaving vertex `v`.
|
||||
let mut end = vec![0usize; pts.len()];
|
||||
for e in &edges {
|
||||
*end.get_mut(e.0 as usize)? += 1;
|
||||
}
|
||||
let mut next = vec![0usize; pts.len()];
|
||||
let mut at = 0usize;
|
||||
for (n, e) in next.iter_mut().zip(end.iter_mut()) {
|
||||
*n = at;
|
||||
at += *e;
|
||||
*e = at;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for start in 0..pts.len() {
|
||||
while next.get(start)? < end.get(start)? {
|
||||
// Follow unused edges from `start` until one leads back to it. Each step uses an
|
||||
// edge, so this ends; balance means only `start` can be left with no edge out.
|
||||
let mut ring = vec![*pts.get(start)?];
|
||||
let mut cur = start;
|
||||
loop {
|
||||
let i = *next.get(cur)?;
|
||||
if i >= *end.get(cur)? {
|
||||
return None;
|
||||
}
|
||||
*next.get_mut(cur)? += 1;
|
||||
let to = edges.get(i)?.1 as usize;
|
||||
if to == start {
|
||||
break;
|
||||
}
|
||||
ring.push(*pts.get(to)?);
|
||||
cur = to;
|
||||
}
|
||||
out.push(ring);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Fill paths of one subpath per closed ring with the nonzero rule, as a PDF viewer would.
|
||||
/// Aliased, so a pixel is filled exactly when the winding at its sample point is nonzero;
|
||||
/// with anti-aliasing, coverage sums along the triangles' inner edges round differently by
|
||||
/// a level in a few pixels.
|
||||
fn raster(rings: &[Vec<Pt>]) -> Vec<u8> {
|
||||
let mut pb = tiny_skia::PathBuilder::new();
|
||||
for r in rings {
|
||||
for (j, (x, y)) in r.iter().enumerate() {
|
||||
if j == 0 {
|
||||
pb.move_to(*x, *y);
|
||||
} else {
|
||||
pb.line_to(*x, *y);
|
||||
}
|
||||
}
|
||||
pb.close();
|
||||
}
|
||||
let mut pm = tiny_skia::Pixmap::new(64, 64).unwrap();
|
||||
if let Some(path) = pb.finish() {
|
||||
let mut paint = tiny_skia::Paint::default();
|
||||
paint.set_color_rgba8(0, 0, 0, 255);
|
||||
paint.anti_alias = false;
|
||||
pm.fill_path(&path, &paint, tiny_skia::FillRule::Winding, tiny_skia::Transform::identity(), None);
|
||||
}
|
||||
pm.data().to_vec()
|
||||
}
|
||||
|
||||
fn soup(tris: &[[Pt; 3]]) -> Vec<Vec<Pt>> {
|
||||
tris.iter().map(|t| t.to_vec()).collect()
|
||||
}
|
||||
|
||||
fn vertices(rings: &[Vec<Pt>]) -> usize {
|
||||
rings.iter().map(Vec::len).sum()
|
||||
}
|
||||
|
||||
/// A fan of a regular polygon around its centre, `n` triangles.
|
||||
fn fan(c: Pt, r: f32, n: usize, ccw: bool) -> Vec<[Pt; 3]> {
|
||||
let p = |i: usize| {
|
||||
let a = std::f32::consts::TAU * (i % n) as f32 / n as f32;
|
||||
(c.0 + r * a.cos(), c.1 + r * a.sin())
|
||||
};
|
||||
(0..n).map(|i| if ccw { [c, p(i), p(i + 1)] } else { [c, p(i + 1), p(i)] }).collect()
|
||||
}
|
||||
|
||||
/// The outline fills the same pixels as the triangles, and is no larger.
|
||||
fn same_fill(tris: &[[Pt; 3]]) -> Vec<Vec<Pt>> {
|
||||
let rings = loops(tris).expect("traced");
|
||||
let (a, b) = (raster(&rings), raster(&soup(tris)));
|
||||
let differ = a.iter().zip(&b).filter(|(x, y)| x != y).count();
|
||||
assert_eq!(differ, 0, "{rings:?}");
|
||||
assert!(vertices(&rings) <= 3 * tris.len());
|
||||
rings
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fan_becomes_its_rim() {
|
||||
let tris = fan((32.0, 32.0), 25.0, 40, true);
|
||||
let rings = same_fill(&tris);
|
||||
assert_eq!(rings.len(), 1);
|
||||
assert!(vertices(&rings) < tris.len() + 1, "{} vertices for {} triangles", vertices(&rings), tris.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ring_with_a_hole_keeps_the_hole() {
|
||||
// A square annulus: outer 8..56, hole 24..40, as eight triangles.
|
||||
let (o0, o1, i0, i1) = (8.0, 56.0, 24.0, 40.0);
|
||||
let q = |a: Pt, b: Pt, c: Pt, d: Pt| [[a, b, c], [a, c, d]];
|
||||
let mut tris = Vec::new();
|
||||
tris.extend(q((o0, o0), (o1, o0), (i1, i0), (i0, i0)));
|
||||
tris.extend(q((o1, o0), (o1, o1), (i1, i1), (i1, i0)));
|
||||
tris.extend(q((o1, o1), (o0, o1), (i0, i1), (i1, i1)));
|
||||
tris.extend(q((o0, o1), (o0, o0), (i0, i0), (i0, i1)));
|
||||
let rings = same_fill(&tris);
|
||||
assert_eq!(rings.len(), 2, "{rings:?}");
|
||||
let centre = raster(&rings)[(32 * 64 + 32) * 4 + 3];
|
||||
assert_eq!(centre, 0, "the hole stays empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_orientations_overlaps_degenerates_and_t_junctions_fill_the_same() {
|
||||
let mut tris = fan((20.0, 20.0), 15.0, 12, true);
|
||||
// Overlapping, the other way round: where they overlap the windings cancel.
|
||||
tris.extend(fan((34.0, 30.0), 15.0, 9, false));
|
||||
// The same triangle twice.
|
||||
tris.push([(40.0, 40.0), (60.0, 42.0), (50.0, 60.0)]);
|
||||
tris.push([(40.0, 40.0), (60.0, 42.0), (50.0, 60.0)]);
|
||||
// A T-junction: one big triangle beside two that split its edge.
|
||||
tris.push([(2.0, 50.0), (2.0, 62.0), (14.0, 56.0)]);
|
||||
tris.push([(2.0, 50.0), (-4.0, 53.0), (2.0, 56.0)]);
|
||||
tris.push([(2.0, 56.0), (-4.0, 59.0), (2.0, 62.0)]);
|
||||
// Zero-area triangles: collinear, and with a repeated vertex.
|
||||
tris.push([(5.0, 5.0), (10.0, 10.0), (15.0, 15.0)]);
|
||||
tris.push([(30.0, 5.0), (30.0, 5.0), (40.0, 8.0)]);
|
||||
// Vertices a rounding step apart are not merged.
|
||||
tris.push([(50.0, 10.0), (60.0, 10.0), (55.0, 20.0)]);
|
||||
tris.push([(60.0, 10.0), (50.0, 10.000_001), (55.0, 2.0)]);
|
||||
same_fill(&tris);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_in_nothing_out() {
|
||||
assert_eq!(loops(&[]), Some(Vec::new()));
|
||||
assert_eq!(loops(&[[(1.0, 1.0); 3]]), Some(Vec::new()));
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,7 @@ fn sample() -> Drawing {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1089,6 +1090,9 @@ fn pdf_layout_one_to_one_with_viewport() {
|
||||
layer_colors: Vec::new(),
|
||||
clip: None,
|
||||
on: true,
|
||||
ucs: None,
|
||||
ucs_per_viewport: false,
|
||||
extra: Vec::new(),
|
||||
twist: 0.0,
|
||||
}),
|
||||
)
|
||||
@@ -1464,6 +1468,9 @@ fn viewport_frozen_layers_roundtrip() {
|
||||
layer_colors: Vec::new(),
|
||||
clip: None,
|
||||
on: true,
|
||||
ucs: None,
|
||||
ucs_per_viewport: false,
|
||||
extra: Vec::new(),
|
||||
twist: 0.0,
|
||||
})
|
||||
};
|
||||
@@ -1652,6 +1659,9 @@ fn frozen_vp_dxf() -> (Drawing, Vec<(String, String)>) {
|
||||
layer_colors: Vec::new(),
|
||||
clip: None,
|
||||
on: true,
|
||||
ucs: None,
|
||||
ucs_per_viewport: false,
|
||||
extra: Vec::new(),
|
||||
twist: 0.0,
|
||||
});
|
||||
d.add(&paper, Common::default(), vp).unwrap();
|
||||
@@ -1796,6 +1806,9 @@ fn viewport_layer_colors_roundtrip() {
|
||||
layer_colors: colors,
|
||||
clip: None,
|
||||
on: true,
|
||||
ucs: None,
|
||||
ucs_per_viewport: false,
|
||||
extra: Vec::new(),
|
||||
twist: 0.0,
|
||||
})
|
||||
};
|
||||
@@ -3054,6 +3067,7 @@ fn intl_sample() -> Drawing {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
@@ -3298,6 +3312,7 @@ fn mleader_is_written_as_multileader() {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
let m = cadcraft_doc::MLeader {
|
||||
leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0)]],
|
||||
@@ -5472,3 +5487,324 @@ fn a_layer_state_saved_before_masks_restores_everything() {
|
||||
let got: Vec<(&str, u32, &str, &str)> = states.iter().map(|s| (s.name.as_str(), s.mask, s.current.as_str(), s.description.as_str())).collect();
|
||||
assert_eq!(got, [("S", LayerState::ALL, "", "")]);
|
||||
}
|
||||
|
||||
/// The value of group `code` in `tags`.
|
||||
fn tag_text(tags: &[craft_dxf::Tag], code: i32) -> Option<String> {
|
||||
tags.iter().find(|t| t.code == code).map(craft_dxf::Tag::str)
|
||||
}
|
||||
|
||||
/// An INSERT with two attributes, for the records written after it (#1660).
|
||||
fn insert_with_attribs() -> (Drawing, Handle) {
|
||||
let text = |value: &str| Text {
|
||||
insert: Vec3::new(1.0, 2.0, 0.0),
|
||||
align_pt: None,
|
||||
height: 2.5,
|
||||
value: value.into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: HAlign::Left,
|
||||
valign: VAlign::Baseline,
|
||||
backwards: false,
|
||||
upside_down: false,
|
||||
};
|
||||
let attrib = |tag: &str, value: &str| Attrib {
|
||||
tag: tag.into(),
|
||||
text: text(value),
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: AttribProps::default(),
|
||||
multiline: None,
|
||||
modes: AttribModes::default(),
|
||||
};
|
||||
let mut d = Drawing::new_metric();
|
||||
let insert =
|
||||
Insert { block: "B".into(), insert: Vec3::new(10.0, 10.0, 0.0), attribs: vec![attrib("T1", "A1"), attrib("T2", "A2")], ..Insert::default() };
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
|
||||
(d, h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inserts_records_are_read_one_at_a_time() {
|
||||
let (mut d, h) = insert_with_attribs();
|
||||
let e = d.entity(h).expect("the reference");
|
||||
// The reference's own list is its record, with no attribute in it.
|
||||
let (kind, own) = entity_groups(&d, e);
|
||||
assert_eq!(kind, "INSERT");
|
||||
assert_eq!(tag_text(&own, 66).as_deref(), Some("1"));
|
||||
// The records after it: each attribute, then the SEQEND.
|
||||
let first = entity_sub_record(&d, e, 0).expect("the first attribute");
|
||||
assert_eq!(first.0, "ATTRIB");
|
||||
assert_eq!((tag_text(&first.1, 2).as_deref(), tag_text(&first.1, 1).as_deref()), (Some("T1"), Some("A1")));
|
||||
assert_eq!(tag_text(&first.1, 10).as_deref(), Some("1.0"), "its place is written as for the file");
|
||||
let second = entity_sub_record(&d, e, 1).expect("the second attribute");
|
||||
assert_eq!((tag_text(&second.1, 2).as_deref(), tag_text(&second.1, 1).as_deref()), (Some("T2"), Some("A2")));
|
||||
let seqend = entity_sub_record(&d, e, 2).expect("the SEQEND");
|
||||
assert_eq!(seqend.0, "SEQEND");
|
||||
assert!(entity_sub_record(&d, e, 3).is_none(), "past the last record");
|
||||
// They have no handle or owner of their own in the drawing: their names are LISP's.
|
||||
for tags in [&first.1, &second.1, &seqend.1] {
|
||||
assert!(tags.iter().all(|t| t.code != 5 && t.code != 330), "{tags:?}");
|
||||
}
|
||||
// An entity with no records after it has none, at any index.
|
||||
let line = d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).expect("line");
|
||||
let e = d.entity(line).expect("the line");
|
||||
assert!(entity_sub_record(&d, e, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attributes_value_reads_as_lisp_text() {
|
||||
let (mut d, h) = insert_with_attribs();
|
||||
// A caret is written `^ ` and read back as the caret LISP typed: what `entget` lists is
|
||||
// what `entmod` takes again.
|
||||
d.modify_entity(h, |e| {
|
||||
if let EntityKind::Insert(i) = &mut e.kind
|
||||
&& let Some(a) = i.attribs.first_mut()
|
||||
{
|
||||
a.text.value = "10^2".into();
|
||||
}
|
||||
})
|
||||
.expect("modify");
|
||||
let e = d.entity(h).expect("the reference");
|
||||
let (_, tags) = entity_sub_record(&d, e, 0).expect("the first attribute");
|
||||
assert_eq!(tag_text(&tags, 1).as_deref(), Some("10^2"));
|
||||
}
|
||||
|
||||
/// Reading every attribute of one reference examines the block definition once, and an edit of
|
||||
/// the definition once more.
|
||||
#[test]
|
||||
fn reading_attributes_scans_the_definition_once() {
|
||||
const M: usize = 32;
|
||||
let tags: Vec<String> = (0..M).map(|i| format!("T{i}")).collect();
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = add_attributed(&mut d, "B", 1, &tags, "WALLS");
|
||||
crate::dxf_write::reset_attdef_definition_visits();
|
||||
let e = d.entity(h).expect("the reference").clone();
|
||||
for i in 0..M {
|
||||
let (kind, tags) = entity_sub_record(&d, &e, i).expect("attribute");
|
||||
assert_eq!(kind, "ATTRIB");
|
||||
assert_eq!(tag_text(&tags, 8).as_deref(), Some("WALLS"));
|
||||
}
|
||||
assert_eq!(crate::dxf_write::attdef_definition_visits(), M as u64, "one pass over the definition, not one scan per attribute");
|
||||
// An edit of the definition is read on the next read, with one more pass.
|
||||
set_attdef_layer(&mut d, "B", "DOOR");
|
||||
let before = crate::dxf_write::attdef_definition_visits();
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("DOOR"));
|
||||
assert_eq!(crate::dxf_write::attdef_definition_visits() - before, M as u64, "the edit builds the index once");
|
||||
}
|
||||
|
||||
/// An attribute with value V and `tag`, for the definition tests below.
|
||||
fn plain_attrib(tag: &str) -> Attrib {
|
||||
Attrib {
|
||||
tag: tag.into(),
|
||||
text: Text {
|
||||
insert: Vec3::ZERO,
|
||||
align_pt: None,
|
||||
height: 1.0,
|
||||
value: "V".into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: HAlign::Left,
|
||||
valign: VAlign::Baseline,
|
||||
backwards: false,
|
||||
upside_down: false,
|
||||
},
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: AttribProps::default(),
|
||||
multiline: None,
|
||||
modes: AttribModes::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Block `name` with an ATTDEF per tag on `layer`, its handles from `first` up, and a reference
|
||||
/// to it with the same attributes. The reference's handle.
|
||||
fn add_attributed(d: &mut Drawing, name: &str, first: u64, tags: &[String], layer: &str) -> Handle {
|
||||
let mut block = Block::new(name);
|
||||
for (i, tag) in tags.iter().enumerate() {
|
||||
let mut e = Entity::new(Handle(first + i as u64), EntityKind::AttDef(plain_attrib(tag)));
|
||||
e.common.layer = layer.into();
|
||||
block.entities.push(e);
|
||||
}
|
||||
d.blocks.insert(name.into(), std::sync::Arc::new(block));
|
||||
let insert = Insert { block: name.into(), attribs: tags.iter().map(|t| plain_attrib(t)).collect(), ..Insert::default() };
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add")
|
||||
}
|
||||
|
||||
/// Block `name`'s first ATTDEF moved to `layer`: one edit of the definition's store.
|
||||
fn set_attdef_layer(d: &mut Drawing, name: &str, layer: &str) {
|
||||
let b = std::sync::Arc::make_mut(d.blocks.get_mut(name).expect("block"));
|
||||
let h = b.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_))).map(|e| e.handle).expect("an ATTDEF");
|
||||
assert!(b.entities.modify(h, |e| e.common.layer = layer.into()));
|
||||
}
|
||||
|
||||
/// Block B with ATTDEF T on layer BASE and ATTDEF U on layer DOOR, and a reference to it with
|
||||
/// both attributes. The reference's handle.
|
||||
fn add_on_two_layers(d: &mut Drawing) -> Handle {
|
||||
let h = add_attributed(d, "B", 1, &["T".to_string(), "U".to_string()], "DOOR");
|
||||
set_attdef_layer(d, "B", "BASE");
|
||||
h
|
||||
}
|
||||
|
||||
/// Block `name`'s ATTDEFs given `tags` in their order, so a tag can pass to another ATTDEF's
|
||||
/// handle: one edit of the definition's store for each ATTDEF.
|
||||
fn set_attdef_tags(d: &mut Drawing, name: &str, tags: &[&str]) {
|
||||
let b = std::sync::Arc::make_mut(d.blocks.get_mut(name).expect("block"));
|
||||
let handles: Vec<Handle> = b.entities.iter().filter(|e| matches!(e.kind, EntityKind::AttDef(_))).map(|e| e.handle).collect();
|
||||
assert_eq!(handles.len(), tags.len(), "a tag for each ATTDEF");
|
||||
for (h, tag) in handles.into_iter().zip(tags) {
|
||||
assert!(b.entities.modify(h, |e| {
|
||||
if let EntityKind::AttDef(ad) = &mut e.kind {
|
||||
ad.tag = (*tag).into();
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer reference `h`'s first ATTRIB record is read on.
|
||||
fn read_attrib_layer(d: &Drawing, h: Handle) -> Option<String> {
|
||||
let e = d.entity(h)?;
|
||||
let (_, tags) = entity_sub_record(d, e, 0)?;
|
||||
tag_text(&tags, 8)
|
||||
}
|
||||
|
||||
/// The layer the first ATTRIB of `d`'s DXF is written on.
|
||||
fn written_attrib_layer(d: &Drawing) -> Option<String> {
|
||||
let text = write_dxf(d);
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = lines.windows(2).position(|w| w == ["0", "ATTRIB"])?;
|
||||
let pairs = lines.get(at + 2..)?.chunks(2);
|
||||
pairs.take_while(|p| p.first() != Some(&"0")).find(|p| p.first() == Some(&"8")).and_then(|p| p.get(1)).map(|s| s.to_string())
|
||||
}
|
||||
|
||||
/// Two copies of one drawing, each with its definition edited: each reads and writes its own
|
||||
/// definition's properties, whichever was read first. T stays with the first ATTDEF in one copy
|
||||
/// and passes to the second in the other, so an index kept from one copy names the wrong ATTDEF
|
||||
/// in the other.
|
||||
#[test]
|
||||
fn copies_edited_apart_read_their_own_definitions() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = add_on_two_layers(&mut d);
|
||||
let (mut a, mut b) = (d.clone(), d.clone());
|
||||
set_attdef_layer(&mut a, "B", "WALLS");
|
||||
set_attdef_tags(&mut b, "B", &["U", "T"]);
|
||||
assert_eq!(read_attrib_layer(&a, h).as_deref(), Some("WALLS"));
|
||||
assert_eq!(read_attrib_layer(&b, h).as_deref(), Some("DOOR"), "the other copy's edit is its own");
|
||||
assert_eq!(written_attrib_layer(&b).as_deref(), Some("DOOR"));
|
||||
assert_eq!(written_attrib_layer(&a).as_deref(), Some("WALLS"));
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("BASE"), "the drawing both came from is unchanged");
|
||||
}
|
||||
|
||||
/// Undo back to a state, then a different edit of the definition: the edit that was undone is
|
||||
/// not read or written again. The second edit passes T to the other ATTDEF, so the index of
|
||||
/// the undone edit names the wrong one.
|
||||
#[test]
|
||||
fn an_edit_after_undo_reads_its_own_definition() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = add_on_two_layers(&mut d);
|
||||
let mut undone = d.clone();
|
||||
set_attdef_layer(&mut undone, "B", "WALLS");
|
||||
assert_eq!(read_attrib_layer(&undone, h).as_deref(), Some("WALLS"));
|
||||
// Undo: the drawing before the edit, then another edit, read nothing in between.
|
||||
let mut redone = d.clone();
|
||||
set_attdef_tags(&mut redone, "B", &["U", "T"]);
|
||||
assert_eq!(written_attrib_layer(&redone).as_deref(), Some("DOOR"));
|
||||
assert_eq!(read_attrib_layer(&redone, h).as_deref(), Some("DOOR"));
|
||||
}
|
||||
|
||||
/// Reads that alternate between two references of two blocks examine each definition once.
|
||||
#[test]
|
||||
fn alternating_definitions_are_each_indexed_once() {
|
||||
const M: usize = 64;
|
||||
let tags: Vec<String> = (0..M).map(|i| format!("T{i}")).collect();
|
||||
let mut d = Drawing::new_metric();
|
||||
let first = add_attributed(&mut d, "B1", 1, &tags, "ONE");
|
||||
let second = add_attributed(&mut d, "B2", 1 + M as u64, &tags, "TWO");
|
||||
let (first, second) = (d.entity(first).expect("first").clone(), d.entity(second).expect("second").clone());
|
||||
crate::dxf_write::reset_attdef_definition_visits();
|
||||
for i in 0..M {
|
||||
for (e, layer) in [(&first, "ONE"), (&second, "TWO")] {
|
||||
let (_, tags) = entity_sub_record(&d, e, i).expect("attribute");
|
||||
assert_eq!(tag_text(&tags, 8).as_deref(), Some(layer));
|
||||
}
|
||||
}
|
||||
assert_eq!(crate::dxf_write::attdef_definition_visits(), 2 * M as u64, "each definition is read once, not once per read");
|
||||
}
|
||||
|
||||
/// Of two ATTDEFs whose tags differ only in case, the first is the attribute's definition.
|
||||
#[test]
|
||||
fn the_first_definition_of_a_tag_in_any_case_is_used() {
|
||||
let mut block = Block::new("C");
|
||||
for (i, (tag, layer)) in [("t", "FIRST"), ("T", "SECOND")].into_iter().enumerate() {
|
||||
let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(tag)));
|
||||
e.common.layer = layer.into();
|
||||
block.entities.push(e);
|
||||
}
|
||||
let mut d = Drawing::new_metric();
|
||||
d.blocks.insert("C".into(), std::sync::Arc::new(block));
|
||||
let insert = Insert { block: "C".into(), attribs: vec![plain_attrib("T")], ..Insert::default() };
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST"));
|
||||
}
|
||||
|
||||
/// A definition with more distinct tags than the index may store (`1 << 18`) is not cached.
|
||||
/// The first read builds and drops one bounded index and remembers the state; later reads go
|
||||
/// straight to one scan that stops at the first match. The first ATTDEF of the tag still wins,
|
||||
/// in any case.
|
||||
#[test]
|
||||
fn an_oversized_definition_is_not_indexed() {
|
||||
const LIMIT: usize = 1 << 18;
|
||||
// One extra distinct tag past the budget, plus a second ATTDEF of the first tag in
|
||||
// another case, so the first match is not the only entity of that tag.
|
||||
let mut tags = Vec::with_capacity(LIMIT + 2);
|
||||
tags.push("Ab".to_string());
|
||||
tags.push("AB".to_string());
|
||||
for i in 0..LIMIT {
|
||||
tags.push(format!("U{i}"));
|
||||
}
|
||||
let mut block = Block::new("HUGE");
|
||||
for (i, tag) in tags.iter().enumerate() {
|
||||
let layer = if i == 0 { "FIRST" } else { "SECOND" };
|
||||
let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(tag)));
|
||||
e.common.layer = layer.into();
|
||||
block.entities.push(e);
|
||||
}
|
||||
let mut d = Drawing::new_metric();
|
||||
d.blocks.insert("HUGE".into(), std::sync::Arc::new(block));
|
||||
let insert = Insert { block: "HUGE".into(), attribs: vec![plain_attrib("ab")], ..Insert::default() };
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
|
||||
crate::dxf_write::reset_attdef_definition_visits();
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST"));
|
||||
let first = crate::dxf_write::attdef_definition_visits();
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST"));
|
||||
let second = crate::dxf_write::attdef_definition_visits() - first;
|
||||
// The failed index walks every entity (the last tag is the one past the budget), then
|
||||
// the scan reads the first entity, where the tag matches.
|
||||
assert_eq!(first, (LIMIT as u64) + 3, "one bounded pass, then the first match");
|
||||
assert_eq!(second, 1, "the state is remembered as too large: the next read scans to the first match only");
|
||||
}
|
||||
|
||||
/// An attribute whose ATTDEF lies past the index budget, at the end of an oversized definition,
|
||||
/// still reads and writes that definition's properties: the scan for a definition past the
|
||||
/// budget covers all of it.
|
||||
#[test]
|
||||
fn a_definition_past_the_index_budget_matches_its_last_tag() {
|
||||
const LIMIT: usize = 1 << 18;
|
||||
let mut block = Block::new("HUGE");
|
||||
for i in 0..=LIMIT {
|
||||
let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(&format!("U{i}"))));
|
||||
e.common.layer = if i == LIMIT { "LAST".into() } else { "OTHER".into() };
|
||||
block.entities.push(e);
|
||||
}
|
||||
let mut d = Drawing::new_metric();
|
||||
d.blocks.insert("HUGE".into(), std::sync::Arc::new(block));
|
||||
let insert = Insert { block: "HUGE".into(), attribs: vec![plain_attrib(&format!("u{LIMIT}"))], ..Insert::default() };
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
|
||||
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("LAST"), "entget reads the matching definition");
|
||||
assert_eq!(written_attrib_layer(&d).as_deref(), Some("LAST"), "the written ATTRIB keeps the definition's layer");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,782 @@
|
||||
//! An annotative block survives a save: its BLOCK_RECORD keeps the `AcadAnnotative` xdata and
|
||||
//! uniform scaling (281), and a reference keeps its annotation scale contexts (the reference's
|
||||
//! scale at each annotation scale), pointing at the same scales and following the reference when
|
||||
//! it is moved, turned or scaled. Without them AutoCAD scales the reference by its units, or once
|
||||
//! more by the current annotation scale.
|
||||
//!
|
||||
//! The fixture is synthetic: block SIGN (metres) with one line, a reference at (10, 20) scaled 5,
|
||||
//! and its contexts for 1:5 (default, scale 5) and 1:1 (scale 1).
|
||||
|
||||
use cadcraft_doc::geom::Vec2;
|
||||
use cadcraft_doc::{Drawing, Handle};
|
||||
use cadcraft_io::{read_dxf, write_dxf};
|
||||
|
||||
const FIXTURE: &str = "
|
||||
0 SECTION
|
||||
2 HEADER
|
||||
9 $ACADVER
|
||||
1 AC1032
|
||||
9 $INSUNITS
|
||||
70 6
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 TABLES
|
||||
0 TABLE
|
||||
2 BLOCK_RECORD
|
||||
5 1
|
||||
330 0
|
||||
100 AcDbSymbolTable
|
||||
70 1
|
||||
0 BLOCK_RECORD
|
||||
5 1F
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 SIGN
|
||||
70 6
|
||||
280 1
|
||||
281 1
|
||||
1001 AcadAnnotative
|
||||
1000 AnnotativeData
|
||||
1002 {
|
||||
1070 1
|
||||
1070 1
|
||||
1002 }
|
||||
0 ENDTAB
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 BLOCKS
|
||||
0 BLOCK
|
||||
5 20
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 SIGN
|
||||
70 0
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 SIGN
|
||||
1
|
||||
0 LINE
|
||||
5 21
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbLine
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
11 1
|
||||
21 0
|
||||
31 0
|
||||
0 ENDBLK
|
||||
5 22
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 ENTITIES
|
||||
0 INSERT
|
||||
5 40
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 41
|
||||
102 }
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockReference
|
||||
2 SIGN
|
||||
10 10
|
||||
20 20
|
||||
30 0
|
||||
41 5
|
||||
42 5
|
||||
43 5
|
||||
50 0
|
||||
66 1
|
||||
0 ATTRIB
|
||||
5 70
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 71
|
||||
102 }
|
||||
330 40
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbText
|
||||
10 15
|
||||
20 30
|
||||
30 0
|
||||
40 1
|
||||
1 X
|
||||
100 AcDbAttribute
|
||||
2 TAG
|
||||
70 0
|
||||
0 SEQEND
|
||||
5 77
|
||||
330 40
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 OBJECTS
|
||||
0 DICTIONARY
|
||||
5 C
|
||||
330 0
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 ACAD_SCALELIST
|
||||
350 50
|
||||
0 DICTIONARY
|
||||
5 50
|
||||
330 C
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 A0
|
||||
350 51
|
||||
3 A1
|
||||
350 52
|
||||
0 SCALE
|
||||
5 51
|
||||
330 50
|
||||
100 AcDbScale
|
||||
70 0
|
||||
300 1:1
|
||||
140 1
|
||||
141 1
|
||||
290 0
|
||||
0 SCALE
|
||||
5 52
|
||||
330 50
|
||||
100 AcDbScale
|
||||
70 0
|
||||
300 1:5
|
||||
140 1
|
||||
141 5
|
||||
290 0
|
||||
0 DICTIONARY
|
||||
5 41
|
||||
330 40
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 AcDbContextDataManager
|
||||
360 42
|
||||
0 DICTIONARY
|
||||
5 42
|
||||
330 41
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 ACDB_ANNOTATIONSCALES
|
||||
350 43
|
||||
0 DICTIONARY
|
||||
5 43
|
||||
330 42
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 *A1
|
||||
350 44
|
||||
3 *A2
|
||||
350 45
|
||||
0 ACDB_BLKREFOBJECTCONTEXTDATA_CLASS
|
||||
5 44
|
||||
330 43
|
||||
100 AcDbObjectContextData
|
||||
70 4
|
||||
290 1
|
||||
100 AcDbAnnotScaleObjectContextData
|
||||
340 52
|
||||
50 0
|
||||
10 10
|
||||
20 20
|
||||
30 0
|
||||
41 5
|
||||
42 5
|
||||
43 5
|
||||
0 ACDB_BLKREFOBJECTCONTEXTDATA_CLASS
|
||||
5 45
|
||||
330 43
|
||||
100 AcDbObjectContextData
|
||||
70 4
|
||||
290 0
|
||||
100 AcDbAnnotScaleObjectContextData
|
||||
340 51
|
||||
50 0
|
||||
10 10
|
||||
20 20
|
||||
30 0
|
||||
41 1
|
||||
42 1
|
||||
43 1
|
||||
0 DICTIONARY
|
||||
5 71
|
||||
330 70
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 AcDbContextDataManager
|
||||
360 73
|
||||
0 DICTIONARY
|
||||
5 73
|
||||
330 71
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 ACDB_ANNOTATIONSCALES
|
||||
350 74
|
||||
0 DICTIONARY
|
||||
5 74
|
||||
330 73
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 *A1
|
||||
350 75
|
||||
3 *A2
|
||||
350 76
|
||||
0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS
|
||||
5 75
|
||||
330 74
|
||||
100 AcDbObjectContextData
|
||||
70 4
|
||||
290 1
|
||||
100 AcDbAnnotScaleObjectContextData
|
||||
340 52
|
||||
70 0
|
||||
50 0
|
||||
10 15
|
||||
20 30
|
||||
11 15
|
||||
21 30
|
||||
290 0
|
||||
0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS
|
||||
5 76
|
||||
330 74
|
||||
100 AcDbObjectContextData
|
||||
70 4
|
||||
290 0
|
||||
100 AcDbAnnotScaleObjectContextData
|
||||
340 51
|
||||
70 0
|
||||
50 0
|
||||
10 11
|
||||
20 22
|
||||
11 11
|
||||
21 22
|
||||
290 0
|
||||
0 ENDSEC
|
||||
0 EOF
|
||||
";
|
||||
|
||||
fn dxf(src: &str) -> String {
|
||||
src.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(|l| {
|
||||
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
|
||||
format!("{code}\n{value}\n")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A written file's records: (type, groups).
|
||||
fn records(text: &str) -> Vec<(String, Vec<(i32, String)>)> {
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut out: Vec<(String, Vec<(i32, String)>)> = Vec::new();
|
||||
for pair in lines.chunks(2) {
|
||||
let (Some(code), Some(value)) = (pair.first().and_then(|c| c.parse::<i32>().ok()), pair.get(1)) else { continue };
|
||||
if code == 0 {
|
||||
out.push((value.to_string(), Vec::new()));
|
||||
} else if let Some((_, tags)) = out.last_mut() {
|
||||
tags.push((code, value.to_string()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn get(tags: &[(i32, String)], code: i32) -> Option<&str> {
|
||||
tags.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// The written block reference contexts: (scale name, default, insertion, rotation, x scale).
|
||||
fn contexts(text: &str) -> Vec<(String, bool, Vec2, f64, f64)> {
|
||||
let recs = records(text);
|
||||
let scales: std::collections::HashMap<&str, &str> =
|
||||
recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect();
|
||||
let num = |t: &[(i32, String)], c: i32| get(t, c).and_then(|v| v.parse::<f64>().ok()).unwrap_or(f64::NAN);
|
||||
recs.iter()
|
||||
.filter(|(k, _)| k == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS")
|
||||
.map(|(_, t)| {
|
||||
let scale = get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string();
|
||||
(scale, get(t, 290) == Some("1"), Vec2::new(num(t, 10), num(t, 20)), num(t, 50), num(t, 41))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The written attribute contexts: (scale name, insertion point), and the ATTRIB they hang on
|
||||
/// (its tag, through its extension dictionary).
|
||||
fn attribute_contexts(text: &str) -> Vec<(String, Vec2)> {
|
||||
let recs = records(text);
|
||||
let scales: std::collections::HashMap<&str, &str> =
|
||||
recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect();
|
||||
let num = |t: &[(i32, String)], c: i32| get(t, c).and_then(|v| v.parse::<f64>().ok()).unwrap_or(f64::NAN);
|
||||
recs.iter()
|
||||
.filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS")
|
||||
.map(|(_, t)| (get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(), Vec2::new(num(t, 10), num(t, 20))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read() -> Drawing {
|
||||
read_dxf(dxf(FIXTURE).as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_annotative_block_keeps_its_record_and_its_reference_s_contexts() {
|
||||
let d = read();
|
||||
let b = d.block("SIGN").unwrap();
|
||||
assert!(b.annotative && b.scale_uniformly && b.units == 6);
|
||||
let text = write_dxf(&d);
|
||||
// The record: units, uniform scaling and the annotative flag.
|
||||
let recs = records(&text);
|
||||
let (_, rec) = recs.iter().find(|(k, t)| k == "BLOCK_RECORD" && get(t, 2) == Some("SIGN")).unwrap();
|
||||
assert_eq!((get(rec, 70), get(rec, 281)), (Some("6"), Some("1")));
|
||||
assert!(rec.iter().any(|(c, v)| *c == 1001 && v == "AcadAnnotative"), "{rec:?}");
|
||||
// The contexts, as read, at the same scales.
|
||||
let mut ctx = contexts(&text);
|
||||
ctx.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect();
|
||||
assert_eq!(got, [("1:1".to_string(), false, 1.0), ("1:5".to_string(), true, 5.0)]);
|
||||
assert!(ctx.iter().all(|c| c.2 == Vec2::new(10.0, 20.0) && c.3 == 0.0));
|
||||
// Read back: still annotative.
|
||||
assert!(read_dxf(text.as_bytes()).unwrap().block("SIGN").unwrap().annotative);
|
||||
// The attribute's contexts, on the written attribute (its handle is new), as read.
|
||||
let mut actx = attribute_contexts(&text);
|
||||
actx.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]);
|
||||
let recs = records(&text);
|
||||
let (_, attrib) = recs.iter().find(|(k, t)| k == "ATTRIB" && get(t, 2) == Some("TAG")).unwrap();
|
||||
assert!(attrib.iter().any(|(c, v)| *c == 102 && v == "{ACAD_XDICTIONARY"), "{attrib:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_s_contexts_follow_its_reference() {
|
||||
// Moved 5 along x and scaled 2 (the attribute with it, as MOVE and SCALE move it): at 1:5
|
||||
// the attribute goes to (15 + 10, 20 + 20); at 1:1, through the reference's 1:1 context (now
|
||||
// at (15, 20), scale 2), to (15 + 2, 20 + 4).
|
||||
let mut d = read();
|
||||
let r = Handle::parse_hex("40").unwrap();
|
||||
d.modify_entity(r, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0);
|
||||
i.scale = i.scale * 2.0;
|
||||
for a in &mut i.attribs {
|
||||
a.text.insert = cadcraft_doc::geom::Vec3::new(25.0, 40.0, 0.0);
|
||||
a.text.align_pt = Some(a.text.insert);
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let mut actx = attribute_contexts(&write_dxf(&d));
|
||||
actx.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let near = |p: Vec2, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9;
|
||||
assert_eq!(actx.len(), 2);
|
||||
assert!(near(actx[0].1, 17.0, 24.0), "1:1 {:?}", actx[0]);
|
||||
assert!(near(actx[1].1, 25.0, 40.0), "1:5 {:?}", actx[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reference_s_contexts_follow_it_when_it_is_moved_turned_and_scaled() {
|
||||
let mut d = read();
|
||||
let r = Handle::parse_hex("40").unwrap();
|
||||
d.modify_entity(r, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0);
|
||||
i.rotation = 30f64.to_radians();
|
||||
i.scale = i.scale * 2.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let mut ctx = contexts(&write_dxf(&d));
|
||||
ctx.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
for (scale, _, at, rot, sx) in &ctx {
|
||||
assert!((at.x - 15.0).abs() < 1e-9 && (at.y - 20.0).abs() < 1e-9, "{scale}: {at:?}");
|
||||
assert!((rot - 30.0).abs() < 1e-9, "{scale}: {rot}");
|
||||
// Each context doubles: 1 → 2 at 1:1, 5 → 10 at 1:5.
|
||||
let want = if scale == "1:1" { 2.0 } else { 10.0 };
|
||||
assert!((sx - want).abs() < 1e-9, "{scale}: {sx}");
|
||||
}
|
||||
assert_eq!(ctx.len(), 2);
|
||||
}
|
||||
|
||||
/// A reference's annotation contexts as CADCraft's model keeps them: (scale's SCALE handle,
|
||||
/// rotation, x scale) of each, by the order kept.
|
||||
fn kept_contexts(d: &Drawing) -> Vec<(f64, f64)> {
|
||||
let num = |o: &cadcraft_doc::foreign::ForeignObject, c: i32| {
|
||||
o.tags.iter().find(|t| t.code == c).and_then(|t| t.value.trim().parse::<f64>().ok()).unwrap_or(f64::NAN)
|
||||
};
|
||||
d.foreign.objects.iter().filter(|o| o.kind == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS").map(|o| (num(o, 50), num(o, 41))).collect()
|
||||
}
|
||||
|
||||
/// A DWG save leaves the reference's contexts out, and the block's annotative flag with them:
|
||||
/// the DWG bridge doesn't convert block reference contexts yet (storytold/craft-libs#2005), and
|
||||
/// the flag without them would have AutoCAD scale the reference by the annotation scale once
|
||||
/// more. The reference comes back at its own scale; DXF keeps both.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_dwg_save_leaves_the_reference_s_contexts_out() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = read();
|
||||
let r = Handle::parse_hex("40").unwrap();
|
||||
let scale = |d: &Drawing| match d.entity(r).map(|e| &e.kind) {
|
||||
Some(cadcraft_doc::EntityKind::Insert(i)) => i.scale.x,
|
||||
_ => f64::NAN,
|
||||
};
|
||||
let back = cadcraft_io::read(&cadcraft_io::write(&d, "x.dwg").unwrap(), "x.dwg").unwrap();
|
||||
assert!(kept_contexts(&back).is_empty(), "{:?}", kept_contexts(&back));
|
||||
assert!((scale(&back) - scale(&d)).abs() < 1e-9, "{} vs {}", scale(&back), scale(&d));
|
||||
assert!(!kept_contexts(&read_dxf(write_dxf(&d).as_bytes()).unwrap()).is_empty(), "DXF keeps them");
|
||||
}
|
||||
|
||||
/// Every written ACDB_ANNOTATIONSCALES dictionary entry names a written context, and every
|
||||
/// written context is listed once.
|
||||
fn listed_contexts(text: &str) -> usize {
|
||||
let recs = records(text);
|
||||
let handles: std::collections::HashSet<&str> =
|
||||
recs.iter().filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")).filter_map(|(_, t)| get(t, 5)).collect();
|
||||
let mut listed = 0;
|
||||
for (_, t) in recs.iter().filter(|(k, _)| k == "DICTIONARY") {
|
||||
for (c, v) in t {
|
||||
if *c == 350 && handles.contains(v.as_str()) {
|
||||
listed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(listed, handles.len(), "contexts listed in their dictionaries");
|
||||
listed
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_context_whose_scale_was_deleted_is_not_written() {
|
||||
let mut d = read();
|
||||
d.scales.retain(|s| s.name != "1:1");
|
||||
let text = write_dxf(&d);
|
||||
let ctx = contexts(&text);
|
||||
assert_eq!(ctx.iter().map(|c| (c.0.as_str(), c.1)).collect::<Vec<_>>(), [("1:5", true)]);
|
||||
let actx = attribute_contexts(&text);
|
||||
assert_eq!(actx.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(), ["1:5"]);
|
||||
assert_eq!(listed_contexts(&text), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_annotative_reference_s_contexts_follow_its_scales() {
|
||||
// CADCraft's model makes the reference annotative at 1:5 and a new 1:2 (1:1 no longer):
|
||||
// the 1:1 contexts go, 1:2 ones are made from the default 1:5 ones, scaled 2/5 about the
|
||||
// reference's insertion point.
|
||||
let mut d = read();
|
||||
let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0);
|
||||
d.scales.push(half.clone());
|
||||
let five = d.scales.iter().find(|s| s.name == "1:5").cloned().unwrap();
|
||||
d.modify_entity(Handle::parse_hex("40").unwrap(), |e| e.common.anno_scales = vec![five, half]).unwrap();
|
||||
let text = write_dxf(&d);
|
||||
let mut ctx = contexts(&text);
|
||||
ctx.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect();
|
||||
assert_eq!(got.len(), 2, "{got:?}");
|
||||
assert_eq!((got[0].0.as_str(), got[0].1), ("1:2", false));
|
||||
assert!((got[0].2 - 2.0).abs() < 1e-9, "{got:?}");
|
||||
assert_eq!(got[1], ("1:5".to_string(), true, 5.0));
|
||||
assert!(ctx.iter().all(|c| c.2 == Vec2::new(10.0, 20.0)));
|
||||
let mut actx = attribute_contexts(&text);
|
||||
actx.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
assert_eq!(actx.len(), 2, "{actx:?}");
|
||||
assert_eq!(actx[0].0, "1:2");
|
||||
assert!((actx[0].1 - Vec2::new(12.0, 24.0)).len() < 1e-9, "{actx:?}");
|
||||
assert_eq!(actx[1], ("1:5".to_string(), Vec2::new(15.0, 30.0)));
|
||||
assert_eq!(listed_contexts(&text), 4);
|
||||
// Read back, the reference keeps them (and nothing points at a missing scale).
|
||||
let back = read_dxf(text.as_bytes()).unwrap();
|
||||
assert!(contexts(&write_dxf(&back)).iter().all(|c| c.0 != "?"));
|
||||
}
|
||||
|
||||
/// The fixture with every handle moved up to just past 2^48 (AutoCAD writes handles that high):
|
||||
/// the reference (40) lands on 2^48 + 1.
|
||||
fn far_handles(src: &str) -> String {
|
||||
const SHIFT: u64 = (1 << 48) - 0x3F;
|
||||
let is_handle = |code: i32| matches!(code, 5 | 105 | 320..=369 | 390..=399 | 480 | 481 | 1005);
|
||||
let mut out = String::new();
|
||||
for line in src.lines() {
|
||||
let (code, value) = line.trim().split_once(' ').unwrap_or((line.trim(), ""));
|
||||
let moved = match (code.parse::<i32>(), u64::from_str_radix(value, 16)) {
|
||||
(Ok(c), Ok(h)) if is_handle(c) && h != 0 => format!("{:X}", h + SHIFT),
|
||||
_ => value.to_string(),
|
||||
};
|
||||
out.push_str(&format!("{code} {moved}\n"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_contexts_get_their_own_handles_when_the_file_s_are_above_2_pow_48() {
|
||||
// As in the test above, but every file handle is above 2^48: the new 1:2 contexts and their
|
||||
// scale take handles no other object has.
|
||||
let mut d = read_dxf(dxf(&far_handles(FIXTURE)).as_bytes()).unwrap();
|
||||
let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0);
|
||||
d.scales.push(half.clone());
|
||||
let five = d.scales.iter().find(|s| s.name == "1:5").cloned().unwrap();
|
||||
let reference = Handle::parse_hex("1000000000001").unwrap();
|
||||
d.modify_entity(reference, |e| e.common.anno_scales = vec![five, half]).unwrap();
|
||||
let text = write_dxf(&d);
|
||||
let mut names: Vec<String> = contexts(&text).into_iter().map(|c| c.0).collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["1:2", "1:5"]);
|
||||
assert_eq!(attribute_contexts(&text).len(), 2);
|
||||
let mut handles: Vec<String> = records(&text).iter().filter_map(|(_, t)| get(t, 5).map(str::to_string)).collect();
|
||||
let n = handles.len();
|
||||
handles.sort();
|
||||
handles.dedup();
|
||||
assert_eq!(handles.len(), n, "every written handle is unique");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_attributes_with_one_tag_keep_their_own_contexts() {
|
||||
// A second attribute TAG on the reference, with its own extension dictionary (no contexts
|
||||
// in it): each written ATTRIB gets its own dictionary, the first keeps the contexts.
|
||||
let second = "
|
||||
0 ATTRIB
|
||||
5 80
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 81
|
||||
102 }
|
||||
330 40
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbText
|
||||
10 1
|
||||
20 2
|
||||
30 0
|
||||
40 1
|
||||
1 Y
|
||||
100 AcDbAttribute
|
||||
2 TAG
|
||||
70 0
|
||||
0 SEQEND";
|
||||
let objs = "
|
||||
0 DICTIONARY
|
||||
5 81
|
||||
330 80
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 OTHER
|
||||
360 82
|
||||
0 XRECORD
|
||||
5 82
|
||||
330 81
|
||||
100 AcDbXrecord
|
||||
1 kept
|
||||
0 ENDSEC
|
||||
0 EOF";
|
||||
let src = FIXTURE.replacen("0 SEQEND", second, 1);
|
||||
let at = src.rfind("0 ENDSEC").unwrap();
|
||||
let src = format!("{}{objs}", &src[..at]);
|
||||
let d = read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
let text = write_dxf(&d);
|
||||
let recs = records(&text);
|
||||
let xdict = |t: &[(i32, String)]| {
|
||||
let i = t.iter().position(|(c, v)| *c == 102 && v == "{ACAD_XDICTIONARY")?;
|
||||
t.get(i + 1).map(|(_, v)| v.clone())
|
||||
};
|
||||
let attribs: Vec<(String, Option<String>)> =
|
||||
recs.iter().filter(|(k, _)| k == "ATTRIB").map(|(_, t)| (get(t, 1).unwrap_or_default().to_string(), xdict(t))).collect();
|
||||
assert_eq!(attribs.len(), 2, "{attribs:?}");
|
||||
let (x, y) = (attribs[0].1.clone().unwrap(), attribs[1].1.clone().unwrap());
|
||||
assert_ne!(x, y, "{attribs:?}");
|
||||
// The first attribute's dictionary leads to its contexts, the second's to the xrecord.
|
||||
let owner_of = |h: &str| recs.iter().find(|(_, t)| get(t, 5) == Some(h)).and_then(|(_, t)| get(t, 330)).map(str::to_string);
|
||||
let xrec = recs.iter().find(|(k, t)| k == "XRECORD" && get(t, 1) == Some("kept")).map(|(_, t)| get(t, 5).unwrap().to_string()).unwrap();
|
||||
assert_eq!(owner_of(&xrec), Some(y));
|
||||
assert_eq!(attribute_contexts(&text).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_contexts_come_from_one_whose_scale_remains() {
|
||||
// The default context's scale (1:5) is deleted, and the reference is annotative at 1:1 and a
|
||||
// new 1:2: the 1:2 contexts are made from the 1:1 ones (scale 1 → 2 about the insertion
|
||||
// point), and 1:1 becomes the default.
|
||||
let mut d = read();
|
||||
let half = cadcraft_doc::AnnoScale::new("1:2", 1.0, 2.0);
|
||||
d.scales.retain(|s| s.name != "1:5");
|
||||
d.scales.push(half.clone());
|
||||
let one = d.scales.iter().find(|s| s.name == "1:1").cloned().unwrap();
|
||||
d.modify_entity(Handle::parse_hex("40").unwrap(), |e| e.common.anno_scales = vec![one, half]).unwrap();
|
||||
let text = write_dxf(&d);
|
||||
let mut ctx = contexts(&text);
|
||||
ctx.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let got: Vec<(String, bool, f64)> = ctx.iter().map(|c| (c.0.clone(), c.1, c.4)).collect();
|
||||
assert_eq!(got, [("1:1".to_string(), true, 1.0), ("1:2".to_string(), false, 2.0)]);
|
||||
let mut actx = attribute_contexts(&text);
|
||||
actx.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
assert_eq!(actx.len(), 2, "{actx:?}");
|
||||
assert_eq!(actx[0], ("1:1".to_string(), Vec2::new(11.0, 22.0)));
|
||||
assert_eq!(actx[1].0, "1:2");
|
||||
assert!((actx[1].1 - Vec2::new(12.0, 24.0)).len() < 1e-9, "{actx:?}");
|
||||
assert_eq!(listed_contexts(&text), 4);
|
||||
}
|
||||
|
||||
/// The written context of the block reference at scale `name`: (insertion, rotation).
|
||||
fn context_at(text: &str, name: &str) -> (Vec2, f64) {
|
||||
contexts(text).into_iter().find(|c| c.0 == name).map(|c| (c.2, c.3)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_reference_keeps_its_contexts_when_its_default_one_is_elsewhere() {
|
||||
// The reference sits at (11, 20) while its default context says (10, 20): saved unchanged,
|
||||
// every context is written as read (what moves them is what the reference did since).
|
||||
let d = read_dxf(dxf(&FIXTURE.replace("2 SIGN\n10 10\n20 20\n30 0\n41 5", "2 SIGN\n10 11\n20 20\n30 0\n41 5")).as_bytes()).unwrap();
|
||||
let text = write_dxf(&d);
|
||||
for scale in ["1:1", "1:5"] {
|
||||
assert_eq!(context_at(&text, scale).0, Vec2::new(10.0, 20.0), "{scale}");
|
||||
}
|
||||
let mut actx = attribute_contexts(&text);
|
||||
actx.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_context_s_own_offset_scales_turns_and_mirrors_with_the_reference() {
|
||||
// The 1:1 context sits 2 to the right of the reference. Scaled 2 and turned 90°, it is 4
|
||||
// above; mirrored (x scale -5), 2 to the left.
|
||||
let src = FIXTURE.replace("340 51\n50 0\n10 10", "340 51\n50 0\n10 12");
|
||||
let edit = |f: &dyn Fn(&mut cadcraft_doc::Insert)| {
|
||||
let mut d = read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
d.modify_entity(Handle::parse_hex("40").unwrap(), |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
f(i);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
write_dxf(&d)
|
||||
};
|
||||
let near = |p: Vec2, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9;
|
||||
let text = edit(&|i| {
|
||||
i.scale = i.scale * 2.0;
|
||||
i.rotation = 90f64.to_radians();
|
||||
});
|
||||
let (at, rot) = context_at(&text, "1:1");
|
||||
assert!(near(at, 10.0, 24.0) && (rot - 90.0).abs() < 1e-9, "{at:?} {rot}");
|
||||
let text = edit(&|i| i.scale.x = -i.scale.x);
|
||||
let (at, _) = context_at(&text, "1:1");
|
||||
assert!(near(at, 8.0, 20.0), "{at:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_context_is_the_one_whose_first_290_is_1() {
|
||||
// The 1:1 attribute context comes first, turned 10° in its reference, with its own later
|
||||
// 290 set: the 1:5 one is still the default, so an unchanged save keeps the 10°.
|
||||
let at = FIXTURE.find("0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS\n5 76").unwrap();
|
||||
let end = FIXTURE.find("0 ENDSEC\n0 EOF").unwrap();
|
||||
let second = FIXTURE[at..end].replace("50 0\n10 11", "50 10\n10 11").replace("21 22\n290 0", "21 22\n290 1");
|
||||
let first = FIXTURE.find("0 ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS\n5 75").unwrap();
|
||||
let src = format!("{}{second}{}{}", &FIXTURE[..first], &FIXTURE[first..at], &FIXTURE[end..]);
|
||||
let mut d = read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
// Moved, so the attribute contexts are brought up to date.
|
||||
d.modify_entity(Handle::parse_hex("40").unwrap(), |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
i.insert = i.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0);
|
||||
for a in &mut i.attribs {
|
||||
a.text.insert = a.text.insert + cadcraft_doc::geom::Vec3::new(5.0, 0.0, 0.0);
|
||||
a.text.align_pt = Some(a.text.insert);
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let text = write_dxf(&d);
|
||||
let recs = records(&text);
|
||||
let scales: std::collections::HashMap<&str, &str> =
|
||||
recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect();
|
||||
let rot = recs
|
||||
.iter()
|
||||
.filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS")
|
||||
.find(|(_, t)| get(t, 340).and_then(|h| scales.get(h)) == Some(&"1:1"))
|
||||
.and_then(|(_, t)| get(t, 50))
|
||||
.and_then(|v| v.parse::<f64>().ok())
|
||||
.unwrap();
|
||||
assert!((rot - 10.0).abs() < 1e-9, "{rot}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_attribute_turned_at_the_current_scale_keeps_its_contexts_rotation() {
|
||||
// The ATTRIB is turned 20° (it is the attribute at the file's current scale) while its default
|
||||
// context says 0°: saved unchanged, no context turns (what turns them is what the attribute
|
||||
// did since it was read).
|
||||
let d = read_dxf(dxf(&FIXTURE.replace("1 X\n", "1 X\n50 20\n")).as_bytes()).unwrap();
|
||||
let text = write_dxf(&d);
|
||||
let rots: Vec<f64> = records(&text)
|
||||
.iter()
|
||||
.filter(|(k, _)| k == "ACDB_MTEXTATTRIBUTEOBJECTCONTEXTDATA_CLASS")
|
||||
.filter_map(|(_, t)| get(t, 50).and_then(|v| v.parse::<f64>().ok()))
|
||||
.collect();
|
||||
assert_eq!(rots.len(), 2, "{rots:?}");
|
||||
assert!(rots.iter().all(|r| r.abs() < 1e-9), "{rots:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_s_contexts_stay_when_the_reference_s_attributes_are_reordered() {
|
||||
// A second attribute OTHER after TAG, then the reference's attributes reversed (as a block
|
||||
// redefinition's attribute sync can): TAG is found as read by its tag, so saved otherwise
|
||||
// unchanged its contexts don't move.
|
||||
let other = "1 X\n100 AcDbAttribute\n2 TAG\n70 0\n0 ATTRIB\n5 80\n330 40\n100 AcDbEntity\n8 0\n100 AcDbText\n10 1\n20 2\n30 0\n40 1\n1 Y\n100 AcDbAttribute\n2 OTHER\n70 0\n";
|
||||
let src = FIXTURE.replacen("1 X\n100 AcDbAttribute\n2 TAG\n70 0\n", other, 1);
|
||||
let mut d = read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
d.modify_entity(Handle::parse_hex("40").unwrap(), |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
assert_eq!(i.attribs.len(), 2);
|
||||
i.attribs.reverse();
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let mut actx = attribute_contexts(&write_dxf(&d));
|
||||
actx.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
assert_eq!(actx, [("1:1".to_string(), Vec2::new(11.0, 22.0)), ("1:5".to_string(), Vec2::new(15.0, 30.0))]);
|
||||
}
|
||||
|
||||
/// Each written block reference context's elevation (group 30), by scale name.
|
||||
fn context_heights(text: &str) -> Vec<(String, f64)> {
|
||||
let recs = records(text);
|
||||
let scales: std::collections::HashMap<&str, &str> =
|
||||
recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect();
|
||||
let mut out: Vec<(String, f64)> = recs
|
||||
.iter()
|
||||
.filter(|(k, _)| k == "ACDB_BLKREFOBJECTCONTEXTDATA_CLASS")
|
||||
.map(|(_, t)| {
|
||||
let scale = get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string();
|
||||
(scale, get(t, 30).and_then(|v| v.parse::<f64>().ok()).unwrap_or(f64::NAN))
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reference_moved_only_in_elevation_takes_its_contexts_along_at_their_own_heights() {
|
||||
// The 1:1 context 2 units above the reference, as read.
|
||||
let src = FIXTURE.replace("10 10\n20 20\n30 0\n41 1\n", "10 10\n20 20\n30 2\n41 1\n");
|
||||
assert_ne!(src, FIXTURE);
|
||||
let mut d = read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
let r = Handle::parse_hex("40").unwrap();
|
||||
d.modify_entity(r, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
i.insert.z += 3.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let written = write_dxf(&d);
|
||||
let near = |h: &[(String, f64)], scale: &str, z: f64| h.iter().any(|(s, v)| s == scale && (v - z).abs() < 1e-9);
|
||||
let h = context_heights(&written);
|
||||
assert!(near(&h, "1:5", 3.0) && near(&h, "1:1", 5.0), "both rise by 3, the 1:1 one staying 2 above: {h:?}");
|
||||
// Saved and opened again, then saved unchanged: the heights stay.
|
||||
let again = write_dxf(&read_dxf(written.as_bytes()).unwrap());
|
||||
let h = context_heights(&again);
|
||||
assert!(near(&h, "1:5", 3.0) && near(&h, "1:1", 5.0), "{h:?}");
|
||||
}
|
||||
@@ -0,0 +1,800 @@
|
||||
//! Annotative text, MText and dimensions survive a save with their annotation scales: each is
|
||||
//! written at its default scale with AutoCAD's `AcadAnnotative` xdata and one annotation scale
|
||||
//! context per scale (a dimension's naming its geometry block at that scale), and read back from
|
||||
//! the contexts at paper size. Without them AutoCAD shows the objects at one size at every scale,
|
||||
//! and CADCraft read them as plain objects at the default scale's size.
|
||||
//!
|
||||
//! The fixture is synthetic: a TEXT (right-justified), an MTEXT and an aligned DIMENSION, each
|
||||
//! annotative at 1:2 (default) and 1:10, in AutoCAD's layout of the records.
|
||||
|
||||
use cadcraft_doc::{AnnoScale, Common, DimKind, Dimension, Drawing, EntityKind, HAlign, Handle, Space, Text, VAlign};
|
||||
use cadcraft_geom::Vec3;
|
||||
|
||||
const FIXTURE: &str = "
|
||||
0 SECTION
|
||||
2 HEADER
|
||||
9 $ACADVER
|
||||
1 AC1032
|
||||
9 $CANNOSCALE
|
||||
1 1:2
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 ENTITIES
|
||||
0 TEXT
|
||||
5 30
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 31
|
||||
102 }
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbText
|
||||
10 16
|
||||
20 0
|
||||
30 0
|
||||
40 2.5
|
||||
1 RIGHT
|
||||
72 2
|
||||
11 30
|
||||
21 0
|
||||
31 0
|
||||
100 AcDbText
|
||||
1001 AcadAnnotative
|
||||
1000 AnnotativeData
|
||||
1002 {
|
||||
1070 1
|
||||
1070 1
|
||||
1002 }
|
||||
0 MTEXT
|
||||
5 40
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 41
|
||||
102 }
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbMText
|
||||
10 0
|
||||
20 10
|
||||
30 0
|
||||
40 2.5
|
||||
41 20
|
||||
71 1
|
||||
72 5
|
||||
1 Multi
|
||||
1001 AcadAnnotative
|
||||
1000 AnnotativeData
|
||||
1002 {
|
||||
1070 1
|
||||
1070 1
|
||||
1002 }
|
||||
0 DIMENSION
|
||||
5 50
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 51
|
||||
102 }
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbDimension
|
||||
2 *D1
|
||||
10 10
|
||||
20 25
|
||||
30 0
|
||||
11 5
|
||||
21 25
|
||||
31 0
|
||||
70 33
|
||||
3 Standard
|
||||
100 AcDbAlignedDimension
|
||||
13 0
|
||||
23 20
|
||||
33 0
|
||||
14 10
|
||||
24 20
|
||||
34 0
|
||||
1001 AcadAnnotative
|
||||
1000 AnnotativeData
|
||||
1002 {
|
||||
1070 1
|
||||
1070 1
|
||||
1002 }
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 OBJECTS
|
||||
0 DICTIONARY
|
||||
5 C
|
||||
330 0
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 ACAD_SCALELIST
|
||||
350 10
|
||||
0 DICTIONARY
|
||||
5 10
|
||||
330 C
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 A0
|
||||
350 11
|
||||
3 A1
|
||||
350 12
|
||||
3 A2
|
||||
350 13
|
||||
0 SCALE
|
||||
5 11
|
||||
330 10
|
||||
100 AcDbScale
|
||||
70 0
|
||||
300 1:1
|
||||
140 1
|
||||
141 1
|
||||
290 1
|
||||
0 SCALE
|
||||
5 12
|
||||
330 10
|
||||
100 AcDbScale
|
||||
70 0
|
||||
300 1:2
|
||||
140 1
|
||||
141 2
|
||||
290 0
|
||||
0 SCALE
|
||||
5 13
|
||||
330 10
|
||||
100 AcDbScale
|
||||
70 0
|
||||
300 1:10
|
||||
140 1
|
||||
141 10
|
||||
290 0
|
||||
0 DICTIONARY
|
||||
5 31
|
||||
330 30
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 AcDbContextDataManager
|
||||
360 32
|
||||
0 DICTIONARY
|
||||
5 32
|
||||
330 31
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 ACDB_ANNOTATIONSCALES
|
||||
350 33
|
||||
0 DICTIONARY
|
||||
5 33
|
||||
330 32
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 *A1
|
||||
350 34
|
||||
3 *A2
|
||||
350 35
|
||||
0 ACDB_TEXTOBJECTCONTEXTDATA_CLASS
|
||||
5 34
|
||||
330 33
|
||||
100 AcDbObjectContextData
|
||||
70 4
|
||||
290 1
|
||||
100 AcDbAnnotScaleObjectContextData
|
||||
340 12
|
||||
70 2
|
||||
50 0
|
||||
10 16
|
||||
20 0
|
||||
11 30
|
||||
21 0
|
||||
0 ACDB_TEXTOBJECTCONTEXTDATA_CLASS
|
||||
5 35
|
||||
330 33
|
||||
100 AcDbObjectContextData
|
||||
70 4
|
||||
290 0
|
||||
100 AcDbAnnotScaleObjectContextData
|
||||
340 13
|
||||
70 2
|
||||
50 0
|
||||
10 -40
|
||||
20 0
|
||||
11 30
|
||||
21 0
|
||||
0 DICTIONARY
|
||||
5 41
|
||||
330 40
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 AcDbContextDataManager
|
||||
360 42
|
||||
0 DICTIONARY
|
||||
5 42
|
||||
330 41
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 ACDB_ANNOTATIONSCALES
|
||||
350 43
|
||||
0 DICTIONARY
|
||||
5 43
|
||||
330 42
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 *A1
|
||||
350 44
|
||||
3 *A2
|
||||
350 45
|
||||
0 ACDB_MTEXTOBJECTCONTEXTDATA_CLASS
|
||||
5 44
|
||||
330 43
|
||||
100 AcDbObjectContextData
|
||||
70 4
|
||||
290 1
|
||||
100 AcDbAnnotScaleObjectContextData
|
||||
340 12
|
||||
70 1
|
||||
10 1
|
||||
20 0
|
||||
30 0
|
||||
11 0
|
||||
21 10
|
||||
31 0
|
||||
40 20
|
||||
41 0
|
||||
42 8.75
|
||||
43 2.5
|
||||
71 0
|
||||
0 ACDB_MTEXTOBJECTCONTEXTDATA_CLASS
|
||||
5 45
|
||||
330 43
|
||||
100 AcDbObjectContextData
|
||||
70 4
|
||||
290 0
|
||||
100 AcDbAnnotScaleObjectContextData
|
||||
340 13
|
||||
70 1
|
||||
10 1
|
||||
20 0
|
||||
30 0
|
||||
11 0
|
||||
21 10
|
||||
31 0
|
||||
40 100
|
||||
41 0
|
||||
42 43.75
|
||||
43 12.5
|
||||
71 0
|
||||
0 DICTIONARY
|
||||
5 51
|
||||
330 50
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 AcDbContextDataManager
|
||||
360 52
|
||||
0 DICTIONARY
|
||||
5 52
|
||||
330 51
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 ACDB_ANNOTATIONSCALES
|
||||
350 53
|
||||
0 DICTIONARY
|
||||
5 53
|
||||
330 52
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
3 *A1
|
||||
350 54
|
||||
3 *A2
|
||||
350 55
|
||||
0 ACDB_ALDIMOBJECTCONTEXTDATA_CLASS
|
||||
5 54
|
||||
330 53
|
||||
100 AcDbObjectContextData
|
||||
70 4
|
||||
290 1
|
||||
100 AcDbAnnotScaleObjectContextData
|
||||
340 12
|
||||
100 AcDbDimensionObjectContextData
|
||||
2 *D1
|
||||
293 0
|
||||
10 5
|
||||
20 25
|
||||
294 1
|
||||
140 0
|
||||
100 AcDbAlignedDimensionObjectContextData
|
||||
11 10
|
||||
21 25
|
||||
31 0
|
||||
0 ACDB_ALDIMOBJECTCONTEXTDATA_CLASS
|
||||
5 55
|
||||
330 53
|
||||
100 AcDbObjectContextData
|
||||
70 4
|
||||
290 0
|
||||
100 AcDbAnnotScaleObjectContextData
|
||||
340 13
|
||||
100 AcDbDimensionObjectContextData
|
||||
2 *D2
|
||||
293 0
|
||||
10 5
|
||||
20 25
|
||||
294 1
|
||||
140 0
|
||||
100 AcDbAlignedDimensionObjectContextData
|
||||
11 10
|
||||
21 25
|
||||
31 0
|
||||
0 ENDSEC
|
||||
0 EOF
|
||||
";
|
||||
|
||||
fn dxf(src: &str) -> String {
|
||||
src.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(|l| {
|
||||
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
|
||||
format!("{code}\n{value}\n")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
type Rec = (String, Vec<(i32, String)>);
|
||||
|
||||
/// A written file's records: (type, groups).
|
||||
fn records(text: &str) -> Vec<Rec> {
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut out: Vec<Rec> = Vec::new();
|
||||
for pair in lines.chunks(2) {
|
||||
let (Some(code), Some(value)) = (pair.first().and_then(|c| c.parse::<i32>().ok()), pair.get(1)) else { continue };
|
||||
if code == 0 {
|
||||
out.push((value.to_string(), Vec::new()));
|
||||
} else if let Some((_, tags)) = out.last_mut() {
|
||||
tags.push((code, value.to_string()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn get(tags: &[(i32, String)], code: i32) -> Option<&str> {
|
||||
tags.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
fn num(tags: &[(i32, String)], code: i32) -> f64 {
|
||||
get(tags, code).and_then(|v| v.trim().parse::<f64>().ok()).unwrap_or(f64::NAN)
|
||||
}
|
||||
|
||||
/// A written context: (class, scale name, default, groups after the scale).
|
||||
struct Ctx {
|
||||
class: String,
|
||||
scale: String,
|
||||
default: bool,
|
||||
tags: Vec<(i32, String)>,
|
||||
}
|
||||
|
||||
/// The contexts written for the object with handle `owner` (through its extension dictionary,
|
||||
/// context manager and dictionary of contexts).
|
||||
fn contexts_of(text: &str, owner: &str) -> Vec<Ctx> {
|
||||
let recs = records(text);
|
||||
let by_handle: std::collections::HashMap<&str, &Rec> = recs.iter().filter_map(|r| Some((get(&r.1, 5)?, r))).collect();
|
||||
let scales: std::collections::HashMap<&str, &str> =
|
||||
recs.iter().filter(|(k, _)| k == "SCALE").filter_map(|(_, t)| Some((get(t, 5)?, get(t, 300)?))).collect();
|
||||
let entry = |h: &str, key: &str| -> Option<String> {
|
||||
let t = &by_handle.get(h)?.1;
|
||||
let i = t.iter().position(|(c, v)| *c == 3 && v.eq_ignore_ascii_case(key))?;
|
||||
t.get(i + 1).map(|(_, v)| v.clone())
|
||||
};
|
||||
let Some(ent) = by_handle.get(owner) else { return Vec::new() };
|
||||
let xd = ent.1.iter().skip_while(|(c, v)| !(*c == 102 && v == "{ACAD_XDICTIONARY")).nth(1).map(|(_, v)| v.clone());
|
||||
let Some(dict) = xd.and_then(|x| entry(&x, "AcDbContextDataManager")).and_then(|m| entry(&m, "ACDB_ANNOTATIONSCALES")) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(d) = by_handle.get(dict.as_str()) else { return Vec::new() };
|
||||
d.1.iter()
|
||||
.filter(|(c, _)| *c == 350)
|
||||
.filter_map(|(_, h)| by_handle.get(h.as_str()))
|
||||
.map(|(class, t)| {
|
||||
let at = t.iter().position(|(c, _)| *c == 340).unwrap_or(0);
|
||||
Ctx {
|
||||
class: class.clone(),
|
||||
scale: get(t, 340).and_then(|h| scales.get(h)).map_or("?", |s| s).to_string(),
|
||||
default: get(t, 290) == Some("1"),
|
||||
tags: t.get(at + 1..).unwrap_or(&[]).to_vec(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn names(d: &Drawing, h: &str) -> Vec<String> {
|
||||
d.entity(Handle::parse_hex(h).unwrap()).unwrap().common.anno_scales.iter().map(|s| s.name.clone()).collect()
|
||||
}
|
||||
|
||||
fn read() -> Drawing {
|
||||
cadcraft_io::read_dxf(dxf(FIXTURE).as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
fn save(d: &Drawing) -> String {
|
||||
String::from_utf8(cadcraft_io::write(d, "x.dxf").unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contexts_make_text_mtext_and_dimensions_annotative_at_paper_size() {
|
||||
let d = read();
|
||||
for h in ["30", "40", "50"] {
|
||||
assert_eq!(names(&d, h), ["1:2", "1:10"], "{h}");
|
||||
}
|
||||
let Some(EntityKind::Text(t)) = d.entity(Handle(0x30)).map(|e| &e.kind) else { panic!("text") };
|
||||
// 2.5 at 1:2: 1.25 on paper. The start point moves with the size about the alignment point.
|
||||
assert!((t.height - 1.25).abs() < 1e-12, "{}", t.height);
|
||||
assert!((t.insert.x - 23.0).abs() < 1e-12, "{:?}", t.insert);
|
||||
let Some(EntityKind::MText(m)) = d.entity(Handle(0x40)).map(|e| &e.kind) else { panic!("mtext") };
|
||||
assert!((m.height - 1.25).abs() < 1e-12 && (m.width - 10.0).abs() < 1e-12, "{} {}", m.height, m.width);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_object_is_written_at_its_default_scale_with_a_context_per_scale() {
|
||||
let text = save(&read());
|
||||
let recs = records(&text);
|
||||
let ent = |h: &str| recs.iter().find(|(_, t)| get(t, 5) == Some(h)).unwrap();
|
||||
// The current scale (1:2) is the default: the groups are at its size.
|
||||
assert_eq!(num(&ent("30").1, 40), 2.5);
|
||||
assert_eq!(num(&ent("40").1, 40), 2.5);
|
||||
assert_eq!(num(&ent("40").1, 41), 20.0);
|
||||
for h in ["30", "40", "50"] {
|
||||
assert!(ent(h).1.iter().any(|(c, v)| *c == 1001 && v == "AcadAnnotative"), "{h}");
|
||||
let ctx = contexts_of(&text, h);
|
||||
let got: Vec<(&str, bool)> = ctx.iter().map(|c| (c.scale.as_str(), c.default)).collect();
|
||||
assert_eq!(got, [("1:2", true), ("1:10", false)], "{h}");
|
||||
}
|
||||
let text_ctx = contexts_of(&text, "30");
|
||||
assert!(text_ctx.iter().all(|c| c.class == "ACDB_TEXTOBJECTCONTEXTDATA_CLASS"));
|
||||
// Right-justified: the alignment point stays, the start point moves with the size.
|
||||
let starts: Vec<(f64, f64)> = text_ctx.iter().map(|c| (num(&c.tags, 10), num(&c.tags, 11))).collect();
|
||||
assert_eq!(starts, [(16.0, 30.0), (-40.0, 30.0)]);
|
||||
let widths: Vec<f64> = contexts_of(&text, "40").iter().map(|c| num(&c.tags, 40)).collect();
|
||||
assert_eq!(widths, [20.0, 100.0]);
|
||||
// A dimension's contexts name its geometry block at each scale; the default one is its own.
|
||||
let dim = contexts_of(&text, "50");
|
||||
assert!(dim.iter().all(|c| c.class == "ACDB_ALDIMOBJECTCONTEXTDATA_CLASS"));
|
||||
let blocks: Vec<String> = dim.iter().map(|c| get(&c.tags, 2).unwrap().to_string()).collect();
|
||||
assert_eq!(get(&ent("50").1, 2), Some(blocks[0].as_str()));
|
||||
let text_height = |block: &str| {
|
||||
let start = recs.iter().position(|(k, t)| k == "BLOCK" && get(t, 2) == Some(block)).unwrap();
|
||||
let end = start + recs[start..].iter().position(|(k, _)| k == "ENDBLK").unwrap();
|
||||
recs[start..end].iter().find(|(k, _)| k == "MTEXT").map(|(_, t)| num(t, 40)).unwrap()
|
||||
};
|
||||
let (h2, h10) = (text_height(&blocks[0]), text_height(&blocks[1]));
|
||||
assert!((h10 / h2 - 5.0).abs() < 1e-9, "{h2} {h10}");
|
||||
// Only the dimension has blocks per scale: no empty `*D` block for the text or the MText.
|
||||
let d_blocks: Vec<&str> = recs.iter().filter(|(k, _)| k == "BLOCK").filter_map(|(_, t)| get(t, 2)).filter(|n| n.starts_with("*D")).collect();
|
||||
assert_eq!(d_blocks.len(), 2, "{d_blocks:?}");
|
||||
for name in &d_blocks {
|
||||
let start = recs.iter().position(|(k, t)| k == "BLOCK" && get(t, 2) == Some(name)).unwrap();
|
||||
assert_ne!(recs.get(start + 1).map(|(k, _)| k.as_str()), Some("ENDBLK"), "{name} is empty");
|
||||
}
|
||||
// Each context class is declared.
|
||||
for class in ["ACDB_TEXTOBJECTCONTEXTDATA_CLASS", "ACDB_MTEXTOBJECTCONTEXTDATA_CLASS", "ACDB_ALDIMOBJECTCONTEXTDATA_CLASS"] {
|
||||
assert!(recs.iter().any(|(k, t)| k == "CLASS" && get(t, 1) == Some(class)), "{class}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_drawing_reads_back_the_same() {
|
||||
let d = read();
|
||||
let back = cadcraft_io::read_dxf(save(&d).as_bytes()).unwrap();
|
||||
for h in ["30", "40", "50"] {
|
||||
let (a, b) = (d.entity(Handle::parse_hex(h).unwrap()).unwrap(), back.entity(Handle::parse_hex(h).unwrap()).unwrap());
|
||||
assert_eq!(a.common.anno_scales, b.common.anno_scales, "{h}");
|
||||
// A justified text's start point is worked out from its alignment point on save, as
|
||||
// AutoCAD does; the rest reads back as it was.
|
||||
let mut kind = a.kind.clone();
|
||||
if let (EntityKind::Text(t), EntityKind::Text(u)) = (&mut kind, &b.kind)
|
||||
&& t.align_pt.is_some()
|
||||
{
|
||||
t.insert = u.insert;
|
||||
}
|
||||
if !matches!(a.kind, EntityKind::Dimension(_)) {
|
||||
assert_eq!(kind, b.kind, "{h}");
|
||||
}
|
||||
}
|
||||
// Saved again, it reads back exactly.
|
||||
let again = cadcraft_io::read_dxf(save(&back).as_bytes()).unwrap();
|
||||
for h in ["30", "40"] {
|
||||
let h = Handle::parse_hex(h).unwrap();
|
||||
assert_eq!(back.entity(h).unwrap().kind, again.entity(h).unwrap().kind);
|
||||
}
|
||||
// Saved again, the file is the same: nothing piles up.
|
||||
assert_eq!(contexts_of(&save(&back), "30").len(), 2);
|
||||
}
|
||||
|
||||
/// A drawing made in CADCraft: text and a dimension at 1:1 and 1:50, 1:50 current.
|
||||
fn made() -> Drawing {
|
||||
let mut d = Drawing::default();
|
||||
d.header.set_str("CANNOSCALE", "1:50");
|
||||
let scales = vec![AnnoScale::new("1:1", 1.0, 1.0), AnnoScale::new("1:50", 1.0, 50.0)];
|
||||
let common = Common { anno_scales: scales.clone(), ..Common::default() };
|
||||
let t = Text {
|
||||
insert: Vec3::ZERO,
|
||||
align_pt: None,
|
||||
height: 2.5,
|
||||
value: "NOTE".into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: HAlign::Left,
|
||||
valign: VAlign::Baseline,
|
||||
backwards: false,
|
||||
upside_down: false,
|
||||
};
|
||||
d.add(&Space::Model, common.clone(), EntityKind::Text(t)).unwrap();
|
||||
let dm = Dimension {
|
||||
kind: DimKind::Aligned,
|
||||
defpt: Vec3::new(100.0, 20.0, 0.0),
|
||||
text_mid: Vec3::new(50.0, 20.0, 0.0),
|
||||
p13: Vec3::ZERO,
|
||||
p14: Vec3::new(100.0, 0.0, 0.0),
|
||||
p15: Vec3::ZERO,
|
||||
p16: Vec3::ZERO,
|
||||
text: String::new(),
|
||||
style: "Standard".into(),
|
||||
measurement: 100.0,
|
||||
text_rotation: 0.0,
|
||||
user_text_pos: false,
|
||||
block: None,
|
||||
insertion_point: Vec3::ZERO,
|
||||
overrides: Default::default(),
|
||||
assoc: Vec::new(),
|
||||
marks: Default::default(),
|
||||
};
|
||||
d.add(&Space::Model, common, EntityKind::Dimension(dm)).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_made_in_cadcraft_get_contexts_and_read_back() {
|
||||
let d = made();
|
||||
let text = save(&d);
|
||||
let recs = records(&text);
|
||||
let handles: Vec<String> = d.model.iter().map(|e| e.handle.hex()).collect();
|
||||
let t = recs.iter().find(|(_, t)| get(t, 5) == Some(handles[0].as_str())).unwrap();
|
||||
// Written at 1:50, the current scale: 2.5 on paper is 125.
|
||||
assert_eq!(num(&t.1, 40), 125.0);
|
||||
for h in &handles {
|
||||
let got: Vec<(String, bool)> = contexts_of(&text, h).into_iter().map(|c| (c.scale, c.default)).collect();
|
||||
assert_eq!(got, [("1:1".to_string(), false), ("1:50".to_string(), true)], "{h}");
|
||||
}
|
||||
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
for (a, b) in d.model.iter().zip(back.model.iter()) {
|
||||
assert_eq!(a.common.anno_scales, b.common.anno_scales);
|
||||
}
|
||||
let Some(EntityKind::Text(t)) = back.model.iter().next().map(|e| &e.kind) else { panic!("text") };
|
||||
assert!((t.height - 2.5).abs() < 1e-9, "{}", t.height);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scale_missing_from_the_list_is_added_to_it() {
|
||||
let mut d = made();
|
||||
d.scales.retain(|s| s.name != "1:50");
|
||||
let text = save(&d);
|
||||
assert!(records(&text).iter().any(|(k, t)| k == "SCALE" && get(t, 300) == Some("1:50")));
|
||||
let h = d.model.iter().next().unwrap().handle.hex();
|
||||
assert_eq!(contexts_of(&text, &h).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_older_than_annotation_scaling_keep_cadcraft_s_record() {
|
||||
let d = made();
|
||||
let opts = cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2004), binary: false };
|
||||
let bytes = cadcraft_io::write_with(&d, "x.dxf", &opts).unwrap();
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
assert!(!text.contains("OBJECTCONTEXTDATA"));
|
||||
let back = cadcraft_io::read_dxf(&bytes).unwrap();
|
||||
for (a, b) in d.model.iter().zip(back.model.iter()) {
|
||||
assert_eq!(a.common.anno_scales, b.common.anno_scales);
|
||||
if let (EntityKind::Text(x), EntityKind::Text(y)) = (&a.kind, &b.kind) {
|
||||
assert_eq!(x.height, y.height);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dimension_s_associativity_and_contexts_share_its_dictionary() {
|
||||
let mut d = made();
|
||||
let line =
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(100.0, 0.0, 0.0) })).unwrap();
|
||||
let dim = d.model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap().handle;
|
||||
d.modify_entity(dim, |e| {
|
||||
if let EntityKind::Dimension(dm) = &mut e.kind {
|
||||
dm.assoc = vec![
|
||||
cadcraft_doc::DimAssoc { point: "p13".into(), handle: line, snap: cadcraft_doc::AssocSnap::Start },
|
||||
cadcraft_doc::DimAssoc { point: "p14".into(), handle: line, snap: cadcraft_doc::AssocSnap::End },
|
||||
];
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let text = save(&d);
|
||||
let recs = records(&text);
|
||||
let ent = recs.iter().find(|(k, t)| k == "DIMENSION" && get(t, 5) == Some(dim.hex().as_str())).unwrap();
|
||||
let xdicts = ent.1.iter().filter(|(c, v)| *c == 102 && v == "{ACAD_XDICTIONARY").count();
|
||||
assert_eq!(xdicts, 1);
|
||||
assert_eq!(contexts_of(&text, &dim.hex()).len(), 2);
|
||||
let xd = ent.1.iter().skip_while(|(c, v)| !(*c == 102 && v == "{ACAD_XDICTIONARY")).nth(1).unwrap().1.clone();
|
||||
let dict = recs.iter().find(|(_, t)| get(t, 5) == Some(xd.as_str())).unwrap();
|
||||
assert!(dict.1.iter().any(|(c, v)| *c == 3 && v == "ACAD_DIMASSOC"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_contexts_do_not_panic() {
|
||||
// Contexts naming no scale, a scale of zero, a missing dictionary and a cycle.
|
||||
let src = dxf(FIXTURE)
|
||||
.replace("340\n13\n", "340\n99\n")
|
||||
.replace("141\n2\n", "141\n0\n")
|
||||
.replace("360\n42\n", "360\n41\n")
|
||||
.replace("350\n53\n", "350\n51\n");
|
||||
let d = cadcraft_io::read_dxf(src.as_bytes()).unwrap();
|
||||
for h in ["30", "40", "50"] {
|
||||
let n = names(&d, h);
|
||||
assert!(n.len() <= 1, "{h}: {n:?}");
|
||||
}
|
||||
// Saved and opened again: the same scales, every context naming a written SCALE.
|
||||
let text = save(&d);
|
||||
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
for h in ["30", "40", "50"] {
|
||||
assert_eq!(names(&back, h), names(&d, h), "{h}");
|
||||
for c in contexts_of(&text, h) {
|
||||
assert_ne!(c.scale, "?", "{h}: a context names a missing SCALE");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A DWG keeps the objects' scales in CADCraft's own record, not in AutoCAD's contexts: the DWG
|
||||
/// bridge doesn't convert those yet (storytold/craft-libs#2005). The scales, the paper sizes and
|
||||
/// a turned text's rotation come back; the contexts' round trip through DWG follows with the
|
||||
/// bridge.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn text_mtext_and_dimensions_keep_their_scales_through_dwg() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read();
|
||||
d.modify_entity(Handle(0x30), |e| {
|
||||
if let EntityKind::Text(t) = &mut e.kind {
|
||||
t.rotation = 30f64.to_radians();
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
|
||||
let back = cadcraft_io::read(&dwg, "x.dwg").unwrap();
|
||||
for kind in ["text", "mtext", "dimension"] {
|
||||
let e = back.model.iter().find(|e| {
|
||||
matches!((&e.kind, kind), (EntityKind::Text(_), "text") | (EntityKind::MText(_), "mtext") | (EntityKind::Dimension(_), "dimension"))
|
||||
});
|
||||
let e = e.unwrap_or_else(|| panic!("{kind}"));
|
||||
let got: Vec<&str> = e.common.anno_scales.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(got, ["1:2", "1:10"], "{kind}");
|
||||
if let EntityKind::Text(t) = &e.kind {
|
||||
assert!((t.height - 1.25).abs() < 1e-9 && (t.rotation.to_degrees() - 30.0).abs() < 1e-9, "{t:?}");
|
||||
}
|
||||
}
|
||||
let dxf = craft_dwg::dwg_to_dxf(&dwg).unwrap();
|
||||
let recs = records(&String::from_utf8_lossy(&dxf));
|
||||
assert!(!recs.iter().any(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")), "no contexts in the DWG");
|
||||
}
|
||||
|
||||
/// A drawing made in CADCraft with an annotative multileader (text 2.5 on paper, 1:1 and 1:10,
|
||||
/// 1:10 current).
|
||||
fn with_mleader() -> (Drawing, Handle) {
|
||||
let mut d = Drawing::default();
|
||||
d.header.set_str("CANNOSCALE", "1:10");
|
||||
let common = Common { anno_scales: vec![AnnoScale::new("1:1", 1.0, 1.0), AnnoScale::new("1:10", 1.0, 10.0)], ..Common::default() };
|
||||
let text = cadcraft_doc::MText {
|
||||
insert: Vec3::new(10.5, 10.1, 0.0),
|
||||
height: 2.5,
|
||||
width: 0.0,
|
||||
attach: 1,
|
||||
rotation: 0.0,
|
||||
style: "Standard".into(),
|
||||
contents: "Note".into(),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
let m = cadcraft_doc::MLeader {
|
||||
leaders: vec![vec![Vec3::ZERO]],
|
||||
landing: Vec3::new(10.0, 10.0, 0.0),
|
||||
dogleg: 0.36,
|
||||
text: Some(text),
|
||||
style: "Standard".into(),
|
||||
arrow_size: 0.18,
|
||||
spline: false,
|
||||
block: None,
|
||||
};
|
||||
let h = d.add(&Space::Model, common, EntityKind::MLeader(m)).unwrap();
|
||||
(d, h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multileader_gets_its_context_data_at_each_scale() {
|
||||
let (d, h) = with_mleader();
|
||||
let text = save(&d);
|
||||
let recs = records(&text);
|
||||
let ent = recs.iter().find(|(k, t)| k == "MULTILEADER" && get(t, 5) == Some(h.hex().as_str())).unwrap();
|
||||
assert!(ent.1.iter().any(|(c, v)| *c == 1001 && v == "AcadAnnotative"));
|
||||
// The entity is at 1:10, the current scale: overall scale 10 and text 25.
|
||||
assert_eq!(num(&ent.1, 40), 10.0);
|
||||
assert_eq!(num(&ent.1, 41), 25.0);
|
||||
let ctx = contexts_of(&text, &h.hex());
|
||||
let got: Vec<(&str, bool, &str)> = ctx.iter().map(|c| (c.scale.as_str(), c.default, c.class.as_str())).collect();
|
||||
assert_eq!(got, [("1:1", false, "ACDB_MLEADEROBJECTCONTEXTDATA_CLASS"), ("1:10", true, "ACDB_MLEADEROBJECTCONTEXTDATA_CLASS")]);
|
||||
for (c, f) in ctx.iter().zip([1.0, 10.0]) {
|
||||
// AutoCAD's layout: the context groups straight after the scale, no braces of their own.
|
||||
assert_eq!(c.tags.first().map(|t| t.0), Some(40), "{:?}", c.tags);
|
||||
assert!(c.tags.iter().all(|(code, v)| !(*code == 300 && v.starts_with("CONTEXT_DATA")) && *code != 301));
|
||||
assert_eq!(num(&c.tags, 40), f);
|
||||
assert!((num(&c.tags, 41) - 2.5 * f).abs() < 1e-9);
|
||||
assert!((num(&c.tags, 140) - 0.18 * f).abs() < 1e-9);
|
||||
// The text keeps its place about the landing, at the scale's size.
|
||||
assert!((num(&c.tags, 12) - (10.0 + 0.5 * f)).abs() < 1e-9 && (num(&c.tags, 22) - (10.0 + 0.1 * f)).abs() < 1e-9);
|
||||
}
|
||||
// A multileader has no block per scale (only dimensions do).
|
||||
assert!(!recs.iter().any(|(k, t)| k == "BLOCK" && get(t, 2).is_some_and(|n| n.starts_with("*D"))));
|
||||
let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
let (a, b) = (d.entity(h).unwrap(), back.entity(h).unwrap());
|
||||
assert_eq!(a.common.anno_scales, b.common.anno_scales);
|
||||
let (EntityKind::MLeader(x), EntityKind::MLeader(y)) = (&a.kind, &b.kind) else { panic!("multileader") };
|
||||
let (tx, ty) = (x.text.as_ref().unwrap(), y.text.as_ref().unwrap());
|
||||
assert!((tx.height - ty.height).abs() < 1e-9 && (tx.insert - ty.insert).len() < 1e-9, "{ty:?}");
|
||||
assert!((x.arrow_size - y.arrow_size).abs() < 1e-9 && (x.dogleg - y.dogleg).abs() < 1e-9, "{y:?}");
|
||||
}
|
||||
|
||||
/// A multileader's scales come back through DWG from CADCraft's own record (the DWG bridge
|
||||
/// doesn't convert contexts yet, storytold/craft-libs#2005), at its paper size; the DWG holds no
|
||||
/// multileader contexts.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_multileader_keeps_its_scales_through_dwg() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let (d, _) = with_mleader();
|
||||
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
|
||||
let back = cadcraft_io::read(&dwg, "x.dwg").unwrap();
|
||||
let e = back.model.iter().find(|e| matches!(e.kind, EntityKind::MLeader(_))).unwrap();
|
||||
let got: Vec<&str> = e.common.anno_scales.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(got, ["1:1", "1:10"]);
|
||||
let EntityKind::MLeader(m) = &e.kind else { panic!("multileader") };
|
||||
assert!((m.text.as_ref().unwrap().height - 2.5).abs() < 1e-9, "{m:?}");
|
||||
let text = String::from_utf8_lossy(&craft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned();
|
||||
assert!(!records(&text).iter().any(|(k, _)| k == "ACDB_MLEADEROBJECTCONTEXTDATA_CLASS"), "no contexts in the DWG");
|
||||
}
|
||||
|
||||
/// The fixture with AutoCAD's variable dictionary naming 1:10 as the current annotation scale.
|
||||
fn with_current_scale() -> String {
|
||||
dxf(FIXTURE)
|
||||
.replace("3\nACAD_SCALELIST\n350\n10\n", "3\nACAD_SCALELIST\n350\n10\n3\nAcDbVariableDictionary\n350\n60\n")
|
||||
.replace(
|
||||
"0\nENDSEC\n0\nEOF\n",
|
||||
"0\nDICTIONARY\n5\n60\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nCANNOSCALE\n350\n61\n0\nDICTIONARYVAR\n5\n61\n330\n60\n100\nDictionaryVariables\n280\n0\n1\n1:10\n0\nENDSEC\n0\nEOF\n",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_current_scale_is_autocad_s_and_saving_keeps_it_current() {
|
||||
let mut d = cadcraft_io::read_dxf(with_current_scale().as_bytes()).unwrap();
|
||||
assert_eq!(d.header.str("CANNOSCALE", ""), "1:10");
|
||||
// Written at the current scale: the 1:10 context is the default one.
|
||||
let text = save(&d);
|
||||
let got: Vec<(String, bool)> = contexts_of(&text, "30").into_iter().map(|c| (c.scale, c.default)).collect();
|
||||
assert_eq!(got, [("1:2".to_string(), false), ("1:10".to_string(), true)]);
|
||||
// Changed in CADCraft, AutoCAD's variable says so too.
|
||||
d.header.set_str("CANNOSCALE", "1:2");
|
||||
let recs = records(&save(&d));
|
||||
let var = recs.iter().find(|(k, _)| k == "DICTIONARYVAR").unwrap();
|
||||
assert_eq!(get(&var.1, 1), Some("1:2"));
|
||||
assert_eq!(recs.iter().filter(|(k, _)| k == "DICTIONARYVAR").count(), 1);
|
||||
// Naming no scale of the drawing's, it is the 1:1 the contexts are written at.
|
||||
d.header.set_str("CANNOSCALE", "1:999");
|
||||
let recs = records(&save(&d));
|
||||
let var = recs.iter().find(|(k, _)| k == "DICTIONARYVAR").unwrap();
|
||||
assert_eq!(get(&var.1, 1), Some("1:1"));
|
||||
}
|
||||
@@ -395,6 +395,9 @@ fn an_empty_followup_viewport_does_not_mark_an_exact_budget_truncated() {
|
||||
layer_colors: Vec::new(),
|
||||
clip: None,
|
||||
on: true,
|
||||
ucs: None,
|
||||
ucs_per_viewport: false,
|
||||
extra: Vec::new(),
|
||||
twist: 0.0,
|
||||
};
|
||||
let paper = Space::Paper("Layout1".into());
|
||||
|
||||
@@ -28,6 +28,9 @@ fn viewport(id: u32) -> EntityKind {
|
||||
layer_colors: vec![],
|
||||
clip: None,
|
||||
on: true,
|
||||
ucs: None,
|
||||
ucs_per_viewport: false,
|
||||
extra: Vec::new(),
|
||||
twist: 0.0,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ fn mleader_drawing() -> (Drawing, MLeader) {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
style: "Standard".into(),
|
||||
arrow_size: 1.0,
|
||||
|
||||
@@ -2,8 +2,10 @@ mod acad_interop;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod acis_data_store;
|
||||
mod angle_header;
|
||||
mod annotative_block_contexts;
|
||||
mod annotative_orientation;
|
||||
mod annotative_roundtrip;
|
||||
mod annotative_text_contexts;
|
||||
mod assoc_array_roundtrip;
|
||||
mod assoc_dependency_prune;
|
||||
mod attdef_insert_dwg;
|
||||
@@ -64,6 +66,7 @@ mod mleader_roundtrip;
|
||||
mod mline_roundtrip;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod model_layout_plot_type;
|
||||
mod mtext_background_mask;
|
||||
mod mtext_caret_spaces;
|
||||
mod mtext_columns_roundtrip;
|
||||
mod mtext_embedded_object;
|
||||
@@ -75,6 +78,7 @@ mod ole2frame_roundtrip;
|
||||
mod ole_frame;
|
||||
mod paperview_marker;
|
||||
mod passthrough_image_roundtrip;
|
||||
mod pdf_fill_outline;
|
||||
mod pdf_followups;
|
||||
mod pdf_import;
|
||||
mod pdf_layers;
|
||||
@@ -110,6 +114,7 @@ mod user_lin_pat_roundtrip;
|
||||
mod view_tables_roundtrip;
|
||||
mod view_target;
|
||||
mod viewport_clip_roundtrip;
|
||||
mod viewport_ucs_roundtrip;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod visualstyle_dwg;
|
||||
mod vport_circle_sides;
|
||||
|
||||
@@ -32,6 +32,7 @@ fn text_mleader() -> MLeader {
|
||||
line_spacing: 1.25,
|
||||
line_spacing_exact: true,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
style: "Callout".into(),
|
||||
arrow_size: 0.3,
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
//! MTEXT background mask (DXF groups 90, 63/421, 45) conditional emission and round-trip.
|
||||
|
||||
use cadcraft_color::{Color, Rgb};
|
||||
use cadcraft_doc::{Common, Drawing, EntityKind, MText, MTextBackground, MTextColumnType, MTextColumns, Space};
|
||||
use cadcraft_geom::Vec3;
|
||||
use cadcraft_io::{read_dxf, write_dxf};
|
||||
|
||||
fn make_mtext(background: Option<MTextBackground>, columns: Option<MTextColumns>) -> MText {
|
||||
MText {
|
||||
insert: Vec3::new(10.0, 20.0, 0.0),
|
||||
height: 2.5,
|
||||
width: 50.0,
|
||||
attach: 1,
|
||||
rotation: 0.0,
|
||||
style: "Standard".into(),
|
||||
contents: "Hello MTEXT".into(),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns,
|
||||
background,
|
||||
}
|
||||
}
|
||||
|
||||
fn round_trip(t: MText) -> (MText, String) {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
|
||||
let dxf = write_dxf(&d);
|
||||
let back = read_dxf(dxf.as_bytes()).unwrap();
|
||||
let entity = back
|
||||
.model
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
EntityKind::MText(m) => Some(m.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("MText after round trip");
|
||||
(entity, dxf)
|
||||
}
|
||||
|
||||
/// Extract `(group_code, value)` pairs of the first `MTEXT` entity in `ENTITIES`.
|
||||
fn mtext_entity_tags(dxf: &str) -> Vec<(i32, String)> {
|
||||
let mut lines = dxf.lines();
|
||||
let mut pairs = Vec::new();
|
||||
let mut in_entities = false;
|
||||
let mut in_mtext = false;
|
||||
while let (Some(c), Some(v)) = (lines.next(), lines.next()) {
|
||||
let code: i32 = c.trim().parse().expect("group code");
|
||||
let val = v.trim().to_string();
|
||||
if code == 0 && val == "SECTION" {
|
||||
if let (Some(_), Some(sec)) = (lines.next(), lines.next()) {
|
||||
in_entities = sec.trim() == "ENTITIES";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !in_entities {
|
||||
continue;
|
||||
}
|
||||
if code == 0 {
|
||||
if in_mtext {
|
||||
break;
|
||||
}
|
||||
if val == "MTEXT" {
|
||||
in_mtext = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if in_mtext {
|
||||
pairs.push((code, val));
|
||||
}
|
||||
}
|
||||
pairs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_background_mask_zero_omits_conditional_tags() {
|
||||
let bg = MTextBackground { mask: 0, color: Some(Color::True(Rgb(10, 20, 30))), scale: 2.0 };
|
||||
let (back, dxf) = round_trip(make_mtext(Some(bg), None));
|
||||
assert_eq!(back.background, None);
|
||||
|
||||
let tags = mtext_entity_tags(&dxf);
|
||||
for forbidden in [90, 63, 421, 45, 441] {
|
||||
assert!(!tags.iter().any(|(c, _)| *c == forbidden), "mask 0 must not emit group {forbidden}: {tags:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_background_window_fill_omits_color_tags_and_roundtrips() {
|
||||
for mask in [2u8, 3u8] {
|
||||
let bg = MTextBackground { mask, color: Some(Color::Index(1)), scale: 2.25 };
|
||||
let (back, dxf) = round_trip(make_mtext(Some(bg), None));
|
||||
assert_eq!(back.background, Some(MTextBackground { mask, color: None, scale: 2.25 }));
|
||||
|
||||
let tags = mtext_entity_tags(&dxf);
|
||||
assert!(tags.iter().any(|(c, v)| *c == 90 && v == &mask.to_string()), "expected group 90={mask}: {tags:?}");
|
||||
assert!(tags.iter().any(|(c, v)| *c == 45 && v.parse::<f64>().ok() == Some(2.25)), "expected group 45=2.25: {tags:?}");
|
||||
for color_code in [63, 421, 441] {
|
||||
assert!(!tags.iter().any(|(c, _)| *c == color_code), "window background (mask={mask}) must not emit group {color_code}: {tags:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_background_custom_aci_and_truecolor_before_columns_roundtrips() {
|
||||
let cols = MTextColumns { kind: MTextColumnType::Static, count: 2, gutter: 5.0, height: 20.0, ..Default::default() };
|
||||
|
||||
let bg_aci = MTextBackground { mask: 1, color: Some(Color::Index(3)), scale: 1.75 };
|
||||
let (back_aci, dxf_aci) = round_trip(make_mtext(Some(bg_aci.clone()), Some(cols.clone())));
|
||||
assert_eq!(back_aci.background, Some(bg_aci));
|
||||
let tags_aci = mtext_entity_tags(&dxf_aci);
|
||||
let col_pos_aci = tags_aci.iter().position(|(c, _)| *c == 75 || *c == 101).expect("column tags");
|
||||
let p90 = tags_aci.iter().position(|(c, v)| *c == 90 && v == "1").expect("group 90=1");
|
||||
let p63 = tags_aci.iter().position(|(c, v)| *c == 63 && v == "3").expect("group 63=3");
|
||||
let p45 = tags_aci.iter().position(|(c, v)| *c == 45 && v.parse::<f64>().ok() == Some(1.75)).expect("group 45=1.75");
|
||||
assert!(!tags_aci.iter().any(|(c, _)| *c == 421), "ACI color must not emit 421: {tags_aci:?}");
|
||||
assert!(p90 < col_pos_aci && p63 < col_pos_aci && p45 < col_pos_aci, "background tags must precede columns");
|
||||
|
||||
let rgb = Rgb(0x12, 0x34, 0x56);
|
||||
let bg_rgb = MTextBackground { mask: 1, color: Some(Color::True(rgb)), scale: 2.0 };
|
||||
let (back_rgb, dxf_rgb) = round_trip(make_mtext(Some(bg_rgb.clone()), Some(cols)));
|
||||
assert_eq!(back_rgb.background, Some(bg_rgb));
|
||||
let tags_rgb = mtext_entity_tags(&dxf_rgb);
|
||||
let col_pos_rgb = tags_rgb.iter().position(|(c, _)| *c == 75 || *c == 101).expect("column tags");
|
||||
let r90 = tags_rgb.iter().position(|(c, v)| *c == 90 && v == "1").expect("group 90=1");
|
||||
let r63 = tags_rgb.iter().position(|(c, _)| *c == 63).expect("group 63");
|
||||
let r421 = tags_rgb.iter().position(|(c, v)| *c == 421 && v == &rgb.to_u32().to_string()).expect("group 421");
|
||||
let r45 = tags_rgb.iter().position(|(c, v)| *c == 45 && v.parse::<f64>().ok() == Some(2.0)).expect("group 45=2.0");
|
||||
assert!(r90 < col_pos_rgb && r63 < col_pos_rgb && r421 < col_pos_rgb && r45 < col_pos_rgb, "truecolor background tags must precede columns");
|
||||
}
|
||||
@@ -41,6 +41,7 @@ fn drawing() -> Result<(Drawing, Vec<(Handle, String)>), Box<dyn std::error::Err
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
});
|
||||
let handle = d.add(&Space::Model, Common::default(), kind)?;
|
||||
expected.push((handle, contents));
|
||||
|
||||
@@ -18,6 +18,7 @@ fn mtext(contents: &str, rotation: f64, columns: Option<MTextColumns>) -> MText
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns,
|
||||
background: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ fn with_embedded_object(rotation: f64, dir: (f64, f64)) -> String {
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
};
|
||||
d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap();
|
||||
let dxf = write_dxf(&d);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user