mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-03 11:18:30 -06:00
Compare commits
71
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8698649da1 | ||
|
|
a6add77c5a | ||
|
|
4ecd4aed42 | ||
|
|
636dd26f07 | ||
|
|
0d70d25f07 | ||
|
|
15c8926c97 | ||
|
|
300a64f711 | ||
|
|
27a9b91f3c | ||
|
|
e48f8805a5 | ||
|
|
9bbe7b69a3 | ||
|
|
8cde239e64 | ||
|
|
15c3c9564a | ||
|
|
f288082ff3 | ||
|
|
0fd046c4c1 | ||
|
|
7bd33b7ff1 | ||
|
|
9ce7cde286 | ||
|
|
0cf540495f | ||
|
|
6050f3c396 | ||
|
|
3371028cdf | ||
|
|
206d40bc0d | ||
|
|
f796d5c8fc | ||
|
|
03bf451124 | ||
|
|
2659b44569 | ||
|
|
e5f62c9546 | ||
|
|
f5a70b0e98 | ||
|
|
13aa3a5cc6 | ||
|
|
3fe6d7e954 | ||
|
|
5950cbce24 | ||
|
|
88a3069ea2 | ||
|
|
20e2efebf7 | ||
|
|
a193f64e04 | ||
|
|
494dbd965b | ||
|
|
bea1843497 | ||
|
|
f9284510ea | ||
|
|
723997489a | ||
|
|
0bc5f721fb | ||
|
|
e9ac879b83 | ||
|
|
ffde4b3bbe | ||
|
|
0db2d73e02 | ||
|
|
fcb2188143 | ||
|
|
ab183249f9 | ||
|
|
cd4912b003 | ||
|
|
61d1f267cf | ||
|
|
b9c9162b14 | ||
|
|
bbf613e944 | ||
|
|
91acccc36a | ||
|
|
dec54a9ded | ||
|
|
38a239b1e9 | ||
|
|
60ac79d4b5 | ||
|
|
a65a9b36b5 | ||
|
|
808ae34499 | ||
|
|
ebeee968b5 | ||
|
|
2eaf90df4b | ||
|
|
d8cf5fbb62 | ||
|
|
bf3e607bd6 | ||
|
|
6042310fc7 | ||
|
|
1ec5d20c84 | ||
|
|
723810f768 | ||
|
|
60e22f38c4 | ||
|
|
ba63055fd3 | ||
|
|
cec2e0c04a | ||
|
|
8fb5e95f15 | ||
|
|
5f4a17cb7c | ||
|
|
1c02f239c3 | ||
|
|
ea0d0e9595 | ||
|
|
5c24bc3dcf | ||
|
|
5689203791 | ||
|
|
b99ea8905e | ||
|
|
c1c97ed00e | ||
|
|
a551f206e8 | ||
|
|
b70c8609c9 |
@@ -45,6 +45,31 @@ pub struct ForeignExtra {
|
||||
/// 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>,
|
||||
/// A lightweight polyline's vertex identifiers (group 91, DXF 2010 and later) as read: one per
|
||||
/// vertex in the polyline's order; empty when the file gave none. Geometric constraints name the
|
||||
/// polyline's segments by them, so they are written back while the polyline's vertices are
|
||||
/// where they were read ([`vertex_ids_for`]).
|
||||
pub vertex_ids: Vec<VertexId>,
|
||||
}
|
||||
|
||||
/// A vertex of a lightweight polyline as it was read: its identifier and its point as the
|
||||
/// polyline has it once read (a polyline whose normal points down is read mirrored in x).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct VertexId {
|
||||
/// The identifier (group 91); 0 for a vertex without one.
|
||||
pub id: i32,
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
}
|
||||
|
||||
/// The identifiers `kept` gives the vertices at `points`, in their order, while every vertex is
|
||||
/// where it was read. `None` once a vertex was added, removed, moved or the order changed: the
|
||||
/// identifiers no longer say which vertex is which.
|
||||
pub fn vertex_ids_for(kept: &[VertexId], points: impl ExactSizeIterator<Item = (f64, f64)> + Clone) -> Option<Vec<i32>> {
|
||||
if kept.is_empty() || kept.len() != points.len() {
|
||||
return None;
|
||||
}
|
||||
kept.iter().zip(points).all(|(k, (x, y))| k.x == x && k.y == y).then(|| kept.iter().map(|k| k.id).collect())
|
||||
}
|
||||
|
||||
impl ForeignExtra {
|
||||
@@ -55,6 +80,7 @@ impl ForeignExtra {
|
||||
&& self.color_book.is_none()
|
||||
&& self.props.is_empty()
|
||||
&& self.tail.is_empty()
|
||||
&& self.vertex_ids.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -154,6 +154,8 @@ impl Header {
|
||||
// Annotation scale of model space; annotative objects of other scales show (1) or not.
|
||||
h.set_str("CANNOSCALE", "1:1");
|
||||
h.set_i64("ANNOALLVISIBLE", 1);
|
||||
// Written to DXF as $REGENMODE; a header variable the drawing lacks is not written.
|
||||
h.set_i64("REGENMODE", 1);
|
||||
h
|
||||
}
|
||||
|
||||
|
||||
@@ -237,7 +237,7 @@ impl Interactive for SetvarM {
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &Value::String(t)) {
|
||||
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &crate::sysvars::typed_value(&n, t)) {
|
||||
Ok(()) => {
|
||||
s.touch();
|
||||
Ok(Step::Done)
|
||||
|
||||
@@ -149,6 +149,9 @@ pub struct Settings {
|
||||
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
|
||||
/// dialog; on by default, as in AutoCAD (Initial value 1).
|
||||
pub attdia: bool,
|
||||
/// TEXTEVAL: 1 lets a routine's input be read as LISP where it would be text (default: 0).
|
||||
/// Kept for routines that switch it around their prompts; no prompt reads it yet.
|
||||
pub texteval: bool,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
@@ -220,6 +223,7 @@ impl Default for Settings {
|
||||
auditctl: false,
|
||||
attreq: true,
|
||||
attdia: true,
|
||||
texteval: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,14 @@ use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_
|
||||
|
||||
mod table;
|
||||
|
||||
/// ACADVER: the program's release, as a text AutoCAD documents it and `atof` reads back as a
|
||||
/// number. A drawing's `$ACADVER` header is its file version, which is what a save writes, so the
|
||||
/// two are separate values: `get` gives this text, `list` too, and the header stays as read.
|
||||
pub const ACADVER_TEXT: &str = "24.3s (CADCraft)";
|
||||
|
||||
const SESSION_VARS: &[&str] = &[
|
||||
// The release text, with or without a drawing (the header's `$ACADVER` is the file version).
|
||||
"ACADVER",
|
||||
"AUDITCTL",
|
||||
"ATTREQ",
|
||||
"OSMODE",
|
||||
@@ -81,10 +88,54 @@ const SESSION_VARS: &[&str] = &[
|
||||
"SAVETIME",
|
||||
"SAVEFILEPATH",
|
||||
"ISAVEBAK",
|
||||
"DIMASO",
|
||||
"TEXTEVAL",
|
||||
"POPUPS",
|
||||
];
|
||||
|
||||
pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
/// The DIMASSOC mode DIMASO turned off, kept in the drawing's header so undo restores it.
|
||||
/// `CADCRAFT_` names are not listed by SYSVARS and no file writes this one.
|
||||
const DIMASO_MODE: &str = "CADCRAFT_DIMASO_MODE";
|
||||
|
||||
/// The header key above, under any number of `$`: no variable of that name exists.
|
||||
fn is_internal(n: &str) -> bool {
|
||||
n.trim_start_matches('$') == DIMASO_MODE
|
||||
}
|
||||
|
||||
/// The names this session also answers with DXF's `$` in front: the header writes them that way
|
||||
/// (`$DIMASO`, `$TEXTEVAL`, `$REGENMODE`, `$POPUPS`), so a routine may type either form.
|
||||
const DOLLAR_VARS: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"];
|
||||
|
||||
/// [`set`] takes only a number for these: a program's or a routine's text is refused. A value
|
||||
/// typed at the command line arrives as text and goes through [`typed_value`] first.
|
||||
const NUMBER_ONLY: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE"];
|
||||
|
||||
/// The value of `text` typed at a SETVAR prompt for `name`: typed digits are a number for the
|
||||
/// [`NUMBER_ONLY`] variables. Anything else stays text.
|
||||
pub(crate) fn typed_value(name: &str, text: String) -> Value {
|
||||
if NUMBER_ONLY.contains(&bare_name(name).as_str())
|
||||
&& let Ok(number) = text.trim().parse::<i64>()
|
||||
{
|
||||
return json!(number);
|
||||
}
|
||||
Value::String(text)
|
||||
}
|
||||
|
||||
/// `name` trimmed and upper case, without the `$` those names take. Every other name keeps the
|
||||
/// `$` it was typed with: `$ANGBASE` stays a name of its own (LISP converts radians only for the
|
||||
/// plain name) and `$OSMODE` is not the session's OSMODE.
|
||||
fn bare_name(name: &str) -> String {
|
||||
let n = name.trim().to_ascii_uppercase();
|
||||
// Every leading `$`, as the header drops them all when it stores a value.
|
||||
let rest = n.trim_start_matches('$');
|
||||
if rest.len() < n.len() && DOLLAR_VARS.contains(&rest) { rest.to_string() } else { n }
|
||||
}
|
||||
|
||||
pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
let n = bare_name(name);
|
||||
if is_internal(&n) {
|
||||
return None;
|
||||
}
|
||||
let st = &s.settings;
|
||||
let v = match n.as_str() {
|
||||
"OSMODE" => json!(st.osmode),
|
||||
@@ -177,6 +228,12 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
"SAVETIME" => json!(crate::autosave::savetime()),
|
||||
"SAVEFILEPATH" => json!(crate::autosave::savefilepath()),
|
||||
"ISAVEBAK" => json!(i32::from(crate::autosave::isavebak())),
|
||||
// DIMASO is obsolete in AutoCAD and has no value of its own: it reports DIMASSOC.
|
||||
"DIMASO" => json!(i32::from(matches!(dimassoc(s)?, 1 | 2))),
|
||||
// Whether a prompt reads typed text as LISP (routines switch it around their prompts).
|
||||
"TEXTEVAL" => json!(i32::from(st.texteval)),
|
||||
// Dialogs are available (read-only; a batch session is still told 1, as AutoCAD does).
|
||||
"POPUPS" => json!(1),
|
||||
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
|
||||
"DWGNAME" => json!(s.state().map(|d| d.title.clone()).unwrap_or_default()),
|
||||
"DBMOD" => json!(s.state().map(|d| i32::from(d.is_dirty())).unwrap_or(0)),
|
||||
@@ -189,6 +246,9 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
"DWGTITLED" => json!(s.state().map(|d| i32::from(d.path.is_some())).unwrap_or(0)),
|
||||
"CMDACTIVE" => json!(i32::from(s.running.is_some())),
|
||||
"TILEMODE" => json!(i32::from(s.state().is_ok_and(|d| d.space.layout().is_none()))),
|
||||
// The release number as AutoCAD reports it, so `(atof (getvar "ACADVER"))` is 24.3; the
|
||||
// drawing's own `$ACADVER` (its file version) is left alone for the save version.
|
||||
"ACADVER" => json!(ACADVER_TEXT),
|
||||
"PLATFORM" => json!(std::env::consts::OS),
|
||||
"BLOCKEDITOR" => json!(i32::from(s.state().is_ok_and(|d| d.block_edit.is_some()))),
|
||||
// The template NEW/QNEW start from (a profile setting, like FONTALT; "" = none).
|
||||
@@ -257,6 +317,11 @@ fn dwg_prefix(path: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// DIMASSOC's value (0 off, 1 or 2 associative), read where DIMASO reports it from.
|
||||
fn dimassoc(s: &Session) -> Option<i64> {
|
||||
table::get(s, "DIMASSOC")?.as_i64()
|
||||
}
|
||||
|
||||
fn as_bool(v: &Value) -> Option<bool> {
|
||||
v.as_bool().or_else(|| v.as_i64().map(|i| i != 0)).or_else(|| v.as_str().and_then(|s| s.trim().parse::<i64>().ok()).map(|i| i != 0))
|
||||
}
|
||||
@@ -277,6 +342,7 @@ fn as_pt(v: &Value) -> Option<cadcraft_geom::Vec2> {
|
||||
|
||||
/// Variables `get` reports from session or drawing state that `set` can't change.
|
||||
const READ_ONLY: &[&str] = &[
|
||||
"ACADVER",
|
||||
"CMDNAMES",
|
||||
"DWGNAME",
|
||||
"DWGPREFIX",
|
||||
@@ -304,10 +370,15 @@ const READ_ONLY: &[&str] = &[
|
||||
"UCSXDIR",
|
||||
"UCSYDIR",
|
||||
"WORLDUCS",
|
||||
// Dialogs: a session always has them, so the variable is fixed (not saved).
|
||||
"POPUPS",
|
||||
];
|
||||
|
||||
pub fn is_read_only(name: &str) -> bool {
|
||||
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(name.trim())) || table::is_read_only(&name.trim().to_ascii_uppercase())
|
||||
// A header name's `$` is ignored: the header drops it when it stores a value, so `$ACADVER`
|
||||
// would otherwise change ACADVER, and with it the version a save writes.
|
||||
let n = name.trim().trim_start_matches('$').trim();
|
||||
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(n)) || table::is_read_only(&n.to_ascii_uppercase())
|
||||
}
|
||||
|
||||
/// POLARADDANG as typed: up to ten angles in degrees separated by `;` (radians out); `None` when
|
||||
@@ -325,11 +396,17 @@ pub fn format_angle_list(angles: &[f64]) -> String {
|
||||
|
||||
/// Set a system variable, refusing values out of its range and folders the automation roots can't hold.
|
||||
pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
|
||||
let n = name.trim().to_ascii_uppercase();
|
||||
let n = bare_name(name);
|
||||
if is_internal(&n) {
|
||||
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("unknown variable `{n}`") });
|
||||
}
|
||||
if is_read_only(&n) {
|
||||
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("{n} is read-only") });
|
||||
}
|
||||
let bad = || EngineError::BadParams { cmd: "setvar".into(), msg: format!("invalid value for {n}") };
|
||||
if NUMBER_ONLY.contains(&n.as_str()) && !v.is_number() {
|
||||
return Err(bad());
|
||||
}
|
||||
let st = &mut s.settings;
|
||||
match n.as_str() {
|
||||
"OSMODE" => {
|
||||
@@ -436,6 +513,35 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
|
||||
}
|
||||
"SAVEFILEPATH" => crate::autosave::set_savefilepath(v.as_str().ok_or_else(bad)?),
|
||||
"ISAVEBAK" => crate::autosave::set_isavebak(as_bool(v).ok_or_else(bad)?),
|
||||
// DIMASO has no value of its own: 0 turns DIMASSOC off (remembering the mode it had),
|
||||
// 1 restores that mode (2 when none was seen), and 1 while it is on changes nothing. The
|
||||
// mode it remembers is in the drawing's header ([`DIMASO_MODE`]), so each open drawing
|
||||
// keeps its own and undo restores it with DIMASSOC; no file writes it.
|
||||
"DIMASO" => {
|
||||
let on = as_i(v).filter(|i| matches!(i, 0 | 1)).ok_or_else(bad)? == 1;
|
||||
let mode = dimassoc(s).ok_or_else(bad)?;
|
||||
// The drawing is touched only when DIMASSOC changes, so it is not marked modified
|
||||
// and no undo step is left for a value it already has.
|
||||
match (on, mode) {
|
||||
(true, 1 | 2) | (false, 0) => {}
|
||||
// Turned back on, from off or from a file's unknown mode: the mode it had.
|
||||
(true, _) => {
|
||||
let h = &mut s.doc_mut()?.header;
|
||||
// Only a mode DIMASSOC takes: a file's value of anything else restores 2.
|
||||
let restore = h.i64(DIMASO_MODE, 2);
|
||||
h.set_i64("DIMASSOC", if matches!(restore, 1 | 2) { restore } else { 2 });
|
||||
}
|
||||
(false, _) => {
|
||||
let h = &mut s.doc_mut()?.header;
|
||||
if matches!(mode, 1 | 2) {
|
||||
h.set_i64(DIMASO_MODE, mode);
|
||||
}
|
||||
h.set_i64("DIMASSOC", 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Stored for routines that switch it around their prompts; no prompt reads it yet.
|
||||
"TEXTEVAL" => st.texteval = small(v, 1).ok_or_else(bad)? == 1,
|
||||
// A number is in degrees; text is an angle typed in AUNITS (SETVAR at the command line).
|
||||
"ANGBASE" => {
|
||||
let a = match v {
|
||||
|
||||
@@ -73,6 +73,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
|
||||
("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)),
|
||||
("POLYSIDES", Kind::Int(3, 1024), Def::Int(4)),
|
||||
("PROJMODE", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
|
||||
// 1 regenerates the drawing after a command that changes it (stored, nothing reads it yet).
|
||||
("REGENMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
|
||||
("REVCLOUDARCLEN", Kind::Real { min: 0.0, strict: true }, Def::Units(0.5, 15.0)),
|
||||
("SPLINESEGS", Kind::Int(-32768, 32767), Def::Int(8)),
|
||||
("SPLKNOTS", Kind::Choice(&[0, 1, 2]), Def::Int(0)),
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! ACADVER is the program's release as text, as AutoCAD documents it, so `(atof (getvar
|
||||
//! "ACADVER"))` reads a number from it. It is read-only, and the drawing's `$ACADVER` stays the
|
||||
//! file version a save writes, so a drawing read from a 2000 DXF saves as one.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::lisp::value::Value;
|
||||
use serde_json::json;
|
||||
|
||||
/// The release text `getvar` and `(getvar "ACADVER")` report.
|
||||
const RELEASE: &str = "24.3s (CADCraft)";
|
||||
|
||||
/// A 2000 DXF (`$ACADVER` `AC1015`) holding one line.
|
||||
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nENTITIES\n\
|
||||
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n10.0\n21\n0.0\n31\n0.0\n\
|
||||
0\nENDSEC\n0\nEOF\n";
|
||||
|
||||
/// A LISP expression's value, or its error message.
|
||||
fn lisp(s: &mut Session, code: &str) -> Result<Value, String> {
|
||||
match s.lisp_eval(code, false, true, Vec::new()) {
|
||||
Ok(Some(Ok(v))) => Ok(v),
|
||||
Ok(Some(Err(e))) => Err(e),
|
||||
Ok(None) => Err("did not finish".into()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// GETVAR's value.
|
||||
fn getvar(s: &mut Session, name: &str) -> serde_json::Value {
|
||||
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
|
||||
}
|
||||
|
||||
/// The `$ACADVER` a DXF text declares.
|
||||
fn file_version(text: &str) -> Option<String> {
|
||||
let l: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = l.windows(2).position(|w| w == ["9", "$ACADVER"])?;
|
||||
l.get(at + 2).filter(|c| **c == "1").and_then(|_| l.get(at + 3)).map(|v| (*v).to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn getvar_gives_the_release_text_and_atof_reads_the_number() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||
assert_eq!(getvar(&mut s, "acadver"), json!(RELEASE), "lower-case names work");
|
||||
assert!(matches!(lisp(&mut s, "(getvar \"ACADVER\")"), Ok(Value::Str(t)) if &*t == RELEASE), "a LISP string");
|
||||
assert!(matches!(lisp(&mut s, "(atof (getvar \"ACADVER\"))"), Ok(Value::Real(r)) if (r - 24.3).abs() < 1e-9), "(atof) reads the release number");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setvar_refuses_acadver_and_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
let before = s.state().unwrap().doc.header.str("ACADVER", "");
|
||||
let e = s.execute("setvar", &json!({ "name": "ACADVER", "value": "AC1027" })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "{e}");
|
||||
assert!(lisp(&mut s, "(setvar \"ACADVER\" \"AC1027\")").is_err(), "AutoLISP's setvar too");
|
||||
// Typed at the command line, SETVAR reports the variable as read-only at its name prompt.
|
||||
s.cmdline("setvar acadver").unwrap();
|
||||
assert!(s.log.iter().any(|l| l == &format!("ACADVER = {RELEASE} (read only)")), "{:?}", s.log);
|
||||
// Neither the release text nor the drawing's file version moved.
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), before);
|
||||
assert_eq!(before, "AC1032");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2000_drawing_saves_as_2000() {
|
||||
crate::refedit_xref::hooks();
|
||||
let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("acadver-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("r2000.dxf");
|
||||
let name = path.to_string_lossy().into_owned();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "r2000.dxf", Some(name.clone()));
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015", "read as 2000");
|
||||
assert_eq!(cadcraft_io::save_version(&s.state().unwrap().doc), cadcraft_io::Version::R2000);
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE), "still the release text");
|
||||
|
||||
s.execute("qsave", &json!({})).unwrap();
|
||||
let saved = std::fs::read_to_string(&path).unwrap();
|
||||
assert_eq!(file_version(&saved).as_deref(), Some("AC1015"), "the file keeps its 2000 version");
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015");
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||
assert_eq!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.str("ACADVER", ""), "AC1015", "and reopens as 2000");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dollar_name_cannot_change_the_file_version() {
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("setvar", &json!({ "name": "$ACADVER", "value": "AC1027" })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "{e}");
|
||||
assert!(lisp(&mut s, "(setvar \"$ACADVER\" \"AC1015\")").is_err(), "AutoLISP's setvar too");
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1032", "the save version did not move");
|
||||
assert!(cadcraft_engine::sysvars::is_read_only("$acadver"), "SETVAR's prompt sees it as read-only too");
|
||||
// Other `$` names still reach the header as before, in LISP's units.
|
||||
assert!(lisp(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
|
||||
assert!(matches!(lisp(&mut s, "(getvar \"$ANGBASE\")"), Ok(Value::Real(r)) if (r - std::f64::consts::FRAC_PI_2).abs() < 1e-9));
|
||||
let r = s.execute("setvar", &json!({ "name": "$OSMODE", "value": 9 })).unwrap();
|
||||
assert_eq!(r["value"], json!(9), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listings_show_the_release_text_without_a_drawing() {
|
||||
let mut s = Session::empty();
|
||||
let all = s.execute("sysvars", &json!({})).unwrap();
|
||||
let text = all.to_string();
|
||||
assert!(text.contains(RELEASE), "{text}");
|
||||
let mut s = Session::new();
|
||||
let all = s.execute("sysvars", &json!({})).unwrap().to_string();
|
||||
assert!(all.contains(RELEASE) && !all.contains("\"AC1032\""), "{all}");
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
//! Legacy system variables a LISP routine saves and restores around its work: DIMASO (obsolete in
|
||||
//! AutoCAD, which reports and sets DIMASSOC through it), TEXTEVAL, REGENMODE (kept in the drawing
|
||||
//! and its DXF header) and POPUPS (read-only). Before them `(getvar "DIMASO")` read nil, so
|
||||
//! `(setq o (getvar "DIMASO")) … (setvar "DIMASO" o)` failed and the routine left the drawing's
|
||||
//! associativity changed.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::lisp::value::{Value as LispValue, to_text};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn getvar(s: &mut Session, name: &str) -> Value {
|
||||
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
|
||||
}
|
||||
|
||||
fn setvar(s: &mut Session, name: &str, value: Value) -> bool {
|
||||
s.execute("setvar", &json!({ "name": name, "value": value })).is_ok()
|
||||
}
|
||||
|
||||
/// The value of a LISP expression, or the error it left.
|
||||
fn eval(s: &mut Session, src: &str) -> Result<LispValue, String> {
|
||||
match s.lisp_eval(src, false, true, Vec::new()) {
|
||||
Ok(Some(v)) => v,
|
||||
Ok(None) => Err("no value".into()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `(getvar name)` as the integer a routine receives.
|
||||
fn lisp_getvar(s: &mut Session, name: &str) -> i64 {
|
||||
let v = eval(s, &format!("(getvar \"{name}\")")).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
let n = v.as_number().unwrap_or_else(|| panic!("{name} is not a number"));
|
||||
assert_eq!(n.fract(), 0.0, "{name} is a whole number");
|
||||
n as i64
|
||||
}
|
||||
|
||||
/// `(setvar name value)` from LISP: whether it was accepted.
|
||||
fn lisp_setvar(s: &mut Session, name: &str, value: &str) -> bool {
|
||||
eval(s, &format!("(setvar \"{name}\" {value})")).is_ok()
|
||||
}
|
||||
|
||||
/// The DXF pairs `(group code, value)` of a file, both trimmed.
|
||||
fn pairs(text: &str) -> Vec<(i32, String)> {
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut out = Vec::new();
|
||||
for chunk in lines.chunks(2) {
|
||||
let [code, value] = chunk else { break };
|
||||
let Ok(c) = code.parse::<i32>() else { continue };
|
||||
out.push((c, (*value).to_string()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The HEADER variable names a DXF text writes (the value after each group code 9).
|
||||
fn header_names(text: &str) -> Vec<String> {
|
||||
pairs(text).iter().filter(|(c, _)| *c == 9).map(|(_, v)| v.trim_start_matches('$').to_string()).collect()
|
||||
}
|
||||
|
||||
/// The integer a header variable is written with, as `(group code, value)` after its name.
|
||||
fn header_int(text: &str, name: &str) -> Option<(i32, String)> {
|
||||
let ps = pairs(text);
|
||||
let i = ps.iter().position(|(c, v)| *c == 9 && v.trim_start_matches('$') == name)?;
|
||||
ps.get(i + 1).cloned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_values_are_integers_a_routine_reads() {
|
||||
let mut s = Session::new();
|
||||
for (name, want) in [("DIMASO", 1), ("TEXTEVAL", 0), ("REGENMODE", 1), ("POPUPS", 1)] {
|
||||
assert_eq!(getvar(&mut s, name), json!(want), "{name}");
|
||||
assert_eq!(lisp_getvar(&mut s, name), want, "{name} through getvar");
|
||||
let kind = eval(&mut s, &format!("(type (getvar \"{name}\"))")).unwrap();
|
||||
assert_eq!(to_text(&kind, true), "INT", "{name} is an integer to LISP");
|
||||
}
|
||||
// The list a routine sees (`SETVAR ?`) carries them too.
|
||||
let all = cadcraft_engine::sysvars::list(&s);
|
||||
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
|
||||
assert_eq!(all.get(name), Some(&getvar(&mut s, name)), "{name} listed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_routine_saving_and_restoring_each_one_leaves_it_as_it_was() {
|
||||
let mut s = Session::new();
|
||||
for (name, changed) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
|
||||
let before = lisp_getvar(&mut s, name);
|
||||
// (setq o (getvar X)) … (setvar X o) must give back exactly what it read.
|
||||
assert!(eval(&mut s, &format!("(setq o (getvar \"{name}\"))")).is_ok(), "{name} readable");
|
||||
assert!(lisp_setvar(&mut s, name, changed), "{name} takes {changed}");
|
||||
assert_ne!(lisp_getvar(&mut s, name), before, "{name} changed by {changed}");
|
||||
assert!(eval(&mut s, &format!("(setvar \"{name}\" o)")).is_ok(), "{name} restored");
|
||||
assert_eq!(lisp_getvar(&mut s, name), before, "{name} back to {before}");
|
||||
}
|
||||
// REGENMODE is the drawing's, kept in its header; TEXTEVAL only the session's.
|
||||
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimaso_restores_the_dimassoc_mode_it_turned_off() {
|
||||
// The routine's save/restore through DIMASO, for each associative mode.
|
||||
for mode in [1, 2] {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(mode)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1), "DIMASO follows DIMASSOC {mode}");
|
||||
let o = eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number().unwrap();
|
||||
assert!(lisp_setvar(&mut s, "DIMASO", "0"));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "DIMASO 0 turns associativity off");
|
||||
assert!(lisp_setvar(&mut s, "DIMASO", "1"));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number(), Some(o), "DIMASO 1 puts back the DIMASSOC {mode} the routine read");
|
||||
}
|
||||
// Set directly, without ever switching it off first, DIMASO 1 leaves the mode alone.
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
|
||||
// No non-zero mode was seen: turning associativity back on gives AutoCAD's 2.
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(0)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "none was seen: the default 2");
|
||||
// A drawing whose saved DIMASSOC is no mode DIMASO can restore (a hostile file) gives 2.
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
|
||||
// Such a mode is not associative, and DIMASO 1 turns associativity on from it too.
|
||||
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_setvar_still_takes_digits() {
|
||||
for (name, digits) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
|
||||
let want = json!(digits.parse::<i64>().unwrap());
|
||||
let dollar = format!("${name}");
|
||||
// SETVAR with the name, the bare name, and the `$` form, as typed at the command line.
|
||||
for lines in [vec!["setvar", name, digits], vec![name, digits], vec!["setvar", dollar.as_str(), digits]] {
|
||||
let mut s = Session::new();
|
||||
for line in &lines {
|
||||
s.cmdline(line).unwrap();
|
||||
}
|
||||
assert_eq!(getvar(&mut s, name), want, "typed {lines:?}");
|
||||
}
|
||||
// A routine that types the command passes its answers the same way.
|
||||
let mut s = Session::new();
|
||||
eval(&mut s, &format!("(command \"SETVAR\" \"{name}\" \"{digits}\")")).unwrap();
|
||||
assert_eq!(getvar(&mut s, name), want, "(command \"SETVAR\" {name})");
|
||||
// Typed words are still refused.
|
||||
let mut s = Session::new();
|
||||
let before = getvar(&mut s, name);
|
||||
for line in ["setvar", name, "two"] {
|
||||
s.cmdline(line).unwrap();
|
||||
}
|
||||
assert_eq!(getvar(&mut s, name), before, "typed word refused for {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_drawing_writes_regenmode() {
|
||||
let mut s = Session::new();
|
||||
// The first drawing, then a new metric and a new imperial one.
|
||||
for metric in [None, Some(true), Some(false)] {
|
||||
if let Some(metric) = metric {
|
||||
s.new_drawing(metric);
|
||||
}
|
||||
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "1".to_string())), "new drawing, metric {metric:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_values_are_refused_and_change_nothing() {
|
||||
let mut s = Session::new();
|
||||
for (name, v) in [
|
||||
("REGENMODE", json!(2)),
|
||||
("REGENMODE", json!(-1)),
|
||||
("REGENMODE", json!(1.5)),
|
||||
("REGENMODE", json!("two")),
|
||||
("REGENMODE", Value::Null),
|
||||
("TEXTEVAL", json!(-1)),
|
||||
("TEXTEVAL", json!(2)),
|
||||
("TEXTEVAL", json!("two")),
|
||||
("TEXTEVAL", Value::Null),
|
||||
("DIMASO", json!(3)),
|
||||
("DIMASO", json!(-1)),
|
||||
("DIMASO", json!(0.5)),
|
||||
("DIMASO", json!("two")),
|
||||
("DIMASO", Value::Null),
|
||||
// Text a program or a routine passes is refused even when it spells a number.
|
||||
("REGENMODE", json!("0")),
|
||||
("TEXTEVAL", json!("1")),
|
||||
("DIMASO", json!("0")),
|
||||
("TEXTEVAL", json!(true)),
|
||||
] {
|
||||
let before = getvar(&mut s, name);
|
||||
assert!(!setvar(&mut s, name, v.clone()), "{name} = {v} refused");
|
||||
assert_eq!(getvar(&mut s, name), before, "{name} unchanged by {v}");
|
||||
}
|
||||
// The drawing's associativity is untouched by a refused DIMASO.
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(!setvar(&mut s, "DIMASO", json!(3)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
|
||||
// The same through LISP, where nil and a NaN real arrive as values a variable can't take.
|
||||
assert!(!lisp_setvar(&mut s, "REGENMODE", "nil"), "nil refused");
|
||||
assert!(!lisp_setvar(&mut s, "DIMASO", "3"), "DIMASO 3 refused");
|
||||
assert!(!lisp_setvar(&mut s, "DIMASO", "\"two\""), "DIMASO text refused");
|
||||
for (name, v) in [("DIMASO", "\"0\""), ("TEXTEVAL", "\"1\""), ("REGENMODE", "\"0\"")] {
|
||||
assert!(!lisp_setvar(&mut s, name, v), "{name} text {v} refused");
|
||||
}
|
||||
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "-1"), "TEXTEVAL -1 refused");
|
||||
// (- (exp 1000) (exp 1000)) is NaN: not a number JSON can hold, so it is refused as one.
|
||||
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "(- (exp 1000) (exp 1000))"), "NaN refused");
|
||||
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popups_is_read_only() {
|
||||
let mut s = Session::new();
|
||||
assert!(cadcraft_engine::sysvars::is_read_only("popups"));
|
||||
for v in [json!(1), json!(0), json!("1")] {
|
||||
let e = s.execute("setvar", &json!({ "name": "POPUPS", "value": v })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "{v}: {e}");
|
||||
}
|
||||
assert!(!lisp_setvar(&mut s, "POPUPS", "0"));
|
||||
assert_eq!(getvar(&mut s, "POPUPS"), json!(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regenmode_is_saved_in_the_dxf_header_and_read_back() {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "REGENMODE", json!(0)));
|
||||
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
assert!(header_names(&text).contains(&"REGENMODE".to_string()), "$REGENMODE is in the header (has {:?})", header_names(&text));
|
||||
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "0".to_string())), "$REGENMODE is group 70, 0");
|
||||
// A reopened drawing has the value it was saved with, and saves it back.
|
||||
let mut back = Session::new();
|
||||
back.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "regenmode.dxf", None);
|
||||
assert_eq!(getvar(&mut back, "REGENMODE"), json!(0));
|
||||
let again = cadcraft_io::write_dxf(back.doc().unwrap());
|
||||
assert_eq!(header_int(&again, "REGENMODE"), Some((70, "0".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texteval_dimaso_and_popups_are_not_saved() {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "TEXTEVAL", json!(1)));
|
||||
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
let names = header_names(&text);
|
||||
for name in ["TEXTEVAL", "DIMASO", "POPUPS"] {
|
||||
assert!(!names.contains(&name.to_string()), "{name} is not a header variable (has {names:?})");
|
||||
}
|
||||
// TEXTEVAL is the session's: a drawing opened in this session does not bring its own value.
|
||||
s.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "no_legacy_vars.dxf", None);
|
||||
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "opening a drawing leaves the session's value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimaso_remembers_the_mode_of_each_open_drawing() {
|
||||
// The mode DIMASO turns off is the drawing's, not the session's: two open drawings switched
|
||||
// between each put back the DIMASSOC mode they had.
|
||||
let mut s = Session::new();
|
||||
let first = s.active;
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
let second = s.new_drawing(true);
|
||||
assert_eq!(second, first + 1);
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(2)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
s.execute("document.switch", &json!({ "index": first })).unwrap();
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the first drawing restores its own mode");
|
||||
s.execute("document.switch", &json!({ "index": second })).unwrap();
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "the second drawing restores its own mode");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dollar_forms_are_the_same_variables() {
|
||||
// The DXF header writes these names with a `$` ($DIMASO, $TEXTEVAL, $REGENMODE, $POPUPS), so
|
||||
// the command line takes them that way too, in any case and with spaces around them.
|
||||
let mut s = Session::new();
|
||||
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
|
||||
let plain = getvar(&mut s, name);
|
||||
let dollar = format!("${name}");
|
||||
assert_eq!(getvar(&mut s, &dollar), plain, "{dollar} reads like {name}");
|
||||
let typed = format!(" ${} ", name.to_ascii_lowercase());
|
||||
assert_eq!(getvar(&mut s, &typed), plain, "{typed:?} reads like {name}");
|
||||
assert_eq!(cadcraft_engine::sysvars::is_read_only(&dollar), cadcraft_engine::sysvars::is_read_only(name), "{dollar} read-only as {name}");
|
||||
}
|
||||
// DIMASO through its DXF name still turns DIMASSOC off and puts its mode back.
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "$DIMASO", json!(0)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "$DIMASO 0 turns associativity off");
|
||||
assert!(setvar(&mut s, " $dimaso ", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "$DIMASO 1 puts the mode back");
|
||||
// TEXTEVAL: set under one name, read under the other.
|
||||
assert!(setvar(&mut s, "$TEXTEVAL", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "$TEXTEVAL set TEXTEVAL");
|
||||
assert!(setvar(&mut s, "TEXTEVAL", json!(0)));
|
||||
assert_eq!(getvar(&mut s, "$TEXTEVAL"), json!(0));
|
||||
// REGENMODE takes only the values its plain name takes, and stores the ones it takes.
|
||||
assert!(!setvar(&mut s, "$REGENMODE", json!(2)), "$REGENMODE 2 is out of range");
|
||||
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $REGENMODE changed nothing");
|
||||
assert!(!setvar(&mut s, "$REGENMODE", json!(-1)), "$REGENMODE -1 is out of range");
|
||||
assert!(setvar(&mut s, "$REGENMODE", json!(0)));
|
||||
assert_eq!(getvar(&mut s, "$REGENMODE"), json!(0));
|
||||
assert_eq!(getvar(&mut s, "REGENMODE"), json!(0));
|
||||
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 0, "$REGENMODE stored the drawing's value");
|
||||
// POPUPS is read-only under its DXF name too.
|
||||
for v in [json!(0), json!("1")] {
|
||||
let e = s.execute("setvar", &json!({ "name": "$POPUPS", "value": v })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "$POPUPS {v}: {e}");
|
||||
}
|
||||
assert!(!lisp_setvar(&mut s, "$POPUPS", "0"));
|
||||
assert_eq!(getvar(&mut s, "$POPUPS"), json!(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_dollar_names_keep_their_own_handling() {
|
||||
// Only those four take a `$`: LISP's angle variables convert radians for the plain name, and
|
||||
// `$OSMODE` stays a name of its own rather than becoming the session's OSMODE.
|
||||
let mut s = Session::new();
|
||||
assert!(eval(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
|
||||
let base = eval(&mut s, "(getvar \"$ANGBASE\")").unwrap().as_number().unwrap_or(f64::NAN);
|
||||
assert!((base - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "(getvar \"$ANGBASE\") gives pi/2, not {base}");
|
||||
let osmode = eval(&mut s, "(setvar \"$OSMODE\" 9)").unwrap();
|
||||
assert_eq!(to_text(&osmode, true), "9", "(setvar \"$OSMODE\" 9) returns 9");
|
||||
assert_eq!(getvar(&mut s, "OSMODE"), json!(4133), "$OSMODE is not the session's OSMODE");
|
||||
assert_eq!(getvar(&mut s, "$OSMODE"), json!(9), "$OSMODE still reads back what it was set to");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_puts_back_the_mode_dimaso_remembers() {
|
||||
// The mode DIMASO remembers goes back with DIMASSOC when the changes are undone.
|
||||
let mut s = Session::new();
|
||||
for (name, v) in [("DIMASSOC", 1), ("DIMASO", 0), ("DIMASSOC", 2), ("DIMASO", 0)] {
|
||||
assert!(setvar(&mut s, name, json!(v)), "{name} {v}");
|
||||
}
|
||||
s.cmdline("u").unwrap();
|
||||
s.cmdline("u").unwrap();
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "back to after the first DIMASO 0");
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the mode remembered then, not the later 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_dollars_are_the_same_variables() {
|
||||
let mut s = Session::new();
|
||||
assert!(!lisp_setvar(&mut s, "$$REGENMODE", "2"), "out of range under any number of $");
|
||||
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $$REGENMODE changed nothing");
|
||||
assert!(!setvar(&mut s, "$$$POPUPS", json!(0)), "read-only under any number of $");
|
||||
assert!(cadcraft_engine::sysvars::is_read_only("$$POPUPS"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimaso_on_while_already_on_leaves_the_drawing_unmodified() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "a fresh drawing");
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)), "already on");
|
||||
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "nothing changed, so not modified");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_remembered_mode_is_not_a_variable_and_is_not_reported_lost() {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
for name in ["CADCRAFT_DIMASO_MODE", "$CADCRAFT_DIMASO_MODE", "cadcraft_dimaso_mode"] {
|
||||
assert!(s.execute("getvar", &json!({ "name": name })).is_err(), "{name} is not a variable");
|
||||
assert!(!setvar(&mut s, name, json!(2)), "{name} cannot be set");
|
||||
}
|
||||
assert!(eval(&mut s, "(getvar \"CADCRAFT_DIMASO_MODE\")").map_or(true, |v| to_text(&v, false) == "nil"));
|
||||
// Saved and read back, the drawing has lost nothing a save keeps.
|
||||
let before = s.doc().unwrap().clone();
|
||||
let after = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&before).as_bytes()).unwrap();
|
||||
let cmp = cadcraft_io::roundtrip::compare(&before, &after, &cadcraft_io::roundtrip::Options::default());
|
||||
assert!(!cmp.differences.iter().any(|d| d.place.contains("DIMASO")), "{:?}", cmp.differences.iter().map(|d| &d.place).collect::<Vec<_>>());
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#[path = "../support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
mod acadver;
|
||||
mod angle_prompts;
|
||||
mod angle_settings;
|
||||
mod annotate_options;
|
||||
@@ -104,6 +105,7 @@ mod layout_prompts;
|
||||
mod leader_command;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod leader_text_scale;
|
||||
mod legacy_sysvars;
|
||||
mod lisp_answer_by_frames;
|
||||
mod lisp_corpus;
|
||||
mod lisp_findfile;
|
||||
|
||||
@@ -11,7 +11,9 @@ use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, I
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn hooks() {
|
||||
/// The real file formats, for every test in this binary that opens or saves files (the hooks are
|
||||
/// process-wide and the first ones set stay).
|
||||
pub(crate) fn hooks() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
|
||||
@@ -16,7 +16,9 @@ use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
|
||||
use cadcraft_doc::foreign::{
|
||||
Foreign, ForeignExtra, ForeignKey, ForeignObject, VertexId, class_group, class_index, class_number, proxy_has_string_stream,
|
||||
};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
|
||||
use craft_dxf::{SectionRef, Tag, Version};
|
||||
|
||||
@@ -83,6 +85,8 @@ fn leader_acad_rest(chunk: &[Tag]) -> Vec<Tag> {
|
||||
|
||||
/// Most objects kept from one file.
|
||||
const MAX_OBJECTS: usize = 1_000_000;
|
||||
/// Most vertices of one polyline whose identifiers are kept.
|
||||
const MAX_VERTEX_IDS: usize = 1_000_000;
|
||||
/// Most xdata groups kept per record (AutoCAD allows 16 KB of xdata per object).
|
||||
const MAX_XDATA_GROUPS: usize = cadcraft_doc::MAX_XDATA_GROUPS;
|
||||
/// Longest ownership chain followed.
|
||||
@@ -345,9 +349,57 @@ fn extra(kind: &str, tags: &[Tag], entity: bool, unknown: bool, kept: &HashSet<S
|
||||
}
|
||||
x.props = props.iter().filter(|t| matches!(t.code, 347 | 284)).map(raw).collect();
|
||||
}
|
||||
if entity && !unknown && kind == "LWPOLYLINE" {
|
||||
x.vertex_ids = vertex_ids(tags);
|
||||
}
|
||||
x
|
||||
}
|
||||
|
||||
/// A LWPOLYLINE record's vertices with their identifiers (group 91 after a vertex's point): one
|
||||
/// per vertex, identifier 0 for a vertex without one; empty when no vertex has one
|
||||
/// ([`ForeignExtra::vertex_ids`]). The points are as the reader gives them: mirrored in x when
|
||||
/// the normal points down. Groups inside an application's `102 {` … `102 }` are not the
|
||||
/// polyline's.
|
||||
fn vertex_ids(tags: &[Tag]) -> Vec<VertexId> {
|
||||
let mut in_app = false;
|
||||
let own_tags: Vec<&Tag> = tags
|
||||
.iter()
|
||||
.take_while(|t| t.code < 1000)
|
||||
.filter(|t| {
|
||||
if t.code == 102 {
|
||||
in_app = t.str().trim_start().starts_with('{');
|
||||
return false;
|
||||
}
|
||||
!in_app
|
||||
})
|
||||
.collect();
|
||||
let own = || own_tags.iter().copied();
|
||||
let down = own().any(|t| t.code == 230 && t.f64() < 0.0);
|
||||
if !own().any(|t| t.code == 91 && t.i64() != 0) {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut ids: Vec<VertexId> = Vec::new();
|
||||
for t in own() {
|
||||
match t.code {
|
||||
// A polyline past the cap keeps none: identifiers for some of its vertices would be wrong.
|
||||
10 if ids.len() >= MAX_VERTEX_IDS => return Vec::new(),
|
||||
10 => ids.push(VertexId { id: 0, x: if down { -t.f64() } else { t.f64() }, y: 0.0 }),
|
||||
20 => {
|
||||
if let Some(last) = ids.last_mut() {
|
||||
last.y = t.f64();
|
||||
}
|
||||
}
|
||||
91 => {
|
||||
if let Some(last) = ids.last_mut() {
|
||||
last.id = i32::try_from(t.i64()).unwrap_or(0);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// Every entity of the drawing (model space, layouts, blocks).
|
||||
fn all_entities(d: &Drawing) -> impl Iterator<Item = &Entity> {
|
||||
std::iter::once(&d.model)
|
||||
|
||||
@@ -169,7 +169,11 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
w.f(38, elevation);
|
||||
}
|
||||
thickness(w, e);
|
||||
for v in &p.vertices {
|
||||
// The vertex identifiers the file gave the polyline (DXF 2010 and later), while its
|
||||
// vertices are where they were read: geometric constraints name its segments by them.
|
||||
let kept = d.foreign.entities.get(&e.handle).map(|x| x.vertex_ids.as_slice()).filter(|_| cx.target >= Version::R2010);
|
||||
let ids = kept.and_then(|kept| cadcraft_doc::foreign::vertex_ids_for(kept, p.vertices.iter().map(|v| (v.p.x, v.p.y))));
|
||||
for (i, v) in p.vertices.iter().enumerate() {
|
||||
w.p2(10, v.p);
|
||||
if v.start_width != 0.0 || v.end_width != 0.0 {
|
||||
w.f(40, v.start_width);
|
||||
@@ -178,6 +182,9 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
if v.bulge != 0.0 {
|
||||
w.f(42, v.bulge);
|
||||
}
|
||||
if let Some(id) = ids.as_ref().and_then(|ids| ids.get(i)).filter(|id| **id != 0) {
|
||||
w.i(91, i64::from(*id));
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::MLine(m) => {
|
||||
|
||||
@@ -51,6 +51,7 @@ const HEADER_VARS: &[(&str, i32)] = &[
|
||||
("PSTYLEMODE", 290),
|
||||
("INSUNITS", 70),
|
||||
("MEASUREMENT", 70),
|
||||
("REGENMODE", 70),
|
||||
("PSLTSCALE", 70),
|
||||
// The model view the drawing is saved at, as DXF keeps it in HEADER (the `*ACTIVE` VPORT
|
||||
// record below repeats it). Written so a drawing opened on its saved view saves it back.
|
||||
|
||||
@@ -287,8 +287,19 @@ impl<'o> Out<'o> {
|
||||
|
||||
/// Header variables that change on every save (time stamps, the handle seed, GUIDs): not
|
||||
/// compared.
|
||||
pub const VOLATILE_HEADER: &[&str] =
|
||||
&["HANDSEED", "TDCREATE", "TDUCREATE", "TDUPDATE", "TDUUPDATE", "TDINDWG", "TDUSRTIMER", "VERSIONGUID", "FINGERPRINTGUID"];
|
||||
/// `CADCRAFT_DIMASO_MODE` is the engine's memory of the mode DIMASO turned off; no file keeps it.
|
||||
pub const VOLATILE_HEADER: &[&str] = &[
|
||||
"HANDSEED",
|
||||
"TDCREATE",
|
||||
"TDUCREATE",
|
||||
"TDUPDATE",
|
||||
"TDUUPDATE",
|
||||
"TDINDWG",
|
||||
"TDUSRTIMER",
|
||||
"VERSIONGUID",
|
||||
"FINGERPRINTGUID",
|
||||
"CADCRAFT_DIMASO_MODE",
|
||||
];
|
||||
|
||||
/// Compare `before` (the drawing as first opened) with `after` (the same drawing saved and
|
||||
/// reopened). Differences are reported as what `after` lost, gained or changed.
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! A lightweight polyline keeps its vertex identifiers (LWPOLYLINE group 91 after a vertex, DXF
|
||||
//! 2010 and later) through a save while its vertices are where they were read.
|
||||
//! Geometric constraints name a polyline's segments by these identifiers. CADCraft's polyline has
|
||||
//! none, so every save wrote the polyline without them, and what the constraints name was gone.
|
||||
//!
|
||||
//! The DWG is written here with acadrust, the identifiers out of order and the first vertex not
|
||||
//! the smallest, as on a polyline that was edited in another program. The harness builds this
|
||||
//! module only where acadrust builds (see `main.rs`).
|
||||
use std::io::Cursor;
|
||||
|
||||
use acadrust::entities::{EntityType, LwPolyline, LwVertex};
|
||||
use acadrust::{CadDocument, DxfVersion, Vector2};
|
||||
use cadcraft_io::{SaveOptions, Version, read, write_with};
|
||||
|
||||
const VERTEX_IDS: [i32; 4] = [2, 5, 7, 1];
|
||||
|
||||
fn polyline_dwg() -> Vec<u8> {
|
||||
polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], 1.0)
|
||||
}
|
||||
|
||||
/// A DWG with one closed polyline at `points`, its normal along `normal_z` Z.
|
||||
fn polyline_dwg_with(points: [(f64, f64); 4], normal_z: f64) -> Vec<u8> {
|
||||
let mut doc = CadDocument::with_version(DxfVersion::AC1032);
|
||||
let mut polyline = LwPolyline::new();
|
||||
polyline.is_closed = true;
|
||||
polyline.normal = acadrust::Vector3::new(0.0, 0.0, normal_z);
|
||||
for (id, (x, y)) in VERTEX_IDS.iter().zip(points) {
|
||||
polyline.vertices.push(LwVertex { vertex_id: *id, ..LwVertex::new(Vector2::new(x, y)) });
|
||||
}
|
||||
doc.add_entity(EntityType::LwPolyline(polyline)).expect("add the polyline");
|
||||
acadrust::DwgWriter::write_to_vec(&doc).expect("write the DWG")
|
||||
}
|
||||
|
||||
/// The vertex identifiers of the one lightweight polyline in DWG bytes.
|
||||
fn vertex_ids_of(dwg: &[u8]) -> Vec<i32> {
|
||||
let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.to_vec())).read().unwrap();
|
||||
doc.entities()
|
||||
.find_map(|e| match e {
|
||||
EntityType::LwPolyline(p) => Some(p.vertices.iter().map(|v| v.vertex_id).collect()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the polyline is in the DWG")
|
||||
}
|
||||
|
||||
/// The vertex identifiers (groups 91) of the one LWPOLYLINE record in a DXF text.
|
||||
fn dxf_vertex_ids(dxf: &[u8]) -> Vec<String> {
|
||||
let text = String::from_utf8_lossy(dxf);
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut pairs = lines.chunks(2).filter_map(|pair| Some((*pair.first()?, *pair.get(1)?)));
|
||||
let record = pairs.by_ref().skip_while(|pair| *pair != ("0", "LWPOLYLINE")).skip(1);
|
||||
record.take_while(|(code, _)| *code != "0").filter(|(code, _)| *code == "91").map(|(_, value)| value.to_string()).collect()
|
||||
}
|
||||
|
||||
fn save(d: &cadcraft_doc::Drawing, name: &str, version: Version) -> Vec<u8> {
|
||||
write_with(d, name, &SaveOptions { version: Some(version), binary: false }).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_keeps_its_vertex_identifiers_through_a_save() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let dwg = polyline_dwg();
|
||||
assert_eq!(vertex_ids_of(&dwg), VERTEX_IDS, "the fixture as acadrust reads it");
|
||||
let d = read(&dwg, "polyline.dwg").unwrap();
|
||||
for version in [Version::R2010, Version::R2018] {
|
||||
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", version)), VERTEX_IDS, "DWG {version:?}");
|
||||
}
|
||||
assert_eq!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2018)), ["2", "5", "7", "1"]);
|
||||
// A DXF before 2010 has no such group.
|
||||
assert!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2000)).is_empty());
|
||||
let back = read(&save(&d, "saved.dxf", Version::R2018), "saved.dxf").unwrap();
|
||||
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"], "read back from a DXF");
|
||||
}
|
||||
|
||||
/// Once a vertex is elsewhere, the order is another or a vertex is gone, the identifiers no longer
|
||||
/// say which vertex is which: none are written.
|
||||
#[test]
|
||||
fn an_edited_polyline_drops_its_vertex_identifiers() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read(&polyline_dwg(), "polyline.dwg").unwrap();
|
||||
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
|
||||
let mut after = |edit: fn(&mut cadcraft_doc::LwPolyline)| {
|
||||
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
|
||||
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
|
||||
edit(p);
|
||||
}
|
||||
}));
|
||||
vertex_ids_of(&save(&d, "edited.dwg", Version::R2018))
|
||||
};
|
||||
assert_eq!(after(|p| p.vertices.reverse()), [0; 4], "reversed");
|
||||
assert_eq!(after(|p| p.vertices.reverse()), VERTEX_IDS, "reversed back: every vertex is where it was read");
|
||||
assert_eq!(after(|p| p.vertices[1].p.x += 1.0), [0; 4], "a vertex moved");
|
||||
}
|
||||
|
||||
/// A polyline whose normal points down is read mirrored in x; untouched, it keeps its identifiers.
|
||||
#[test]
|
||||
fn a_polyline_facing_down_keeps_its_vertex_identifiers() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = read(&polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], -1.0), "down.dwg").unwrap();
|
||||
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), VERTEX_IDS);
|
||||
}
|
||||
|
||||
/// Reversed, a polyline symmetric about x = 0 has its mirror image's points: the identifiers still
|
||||
/// no longer say which vertex is which.
|
||||
#[test]
|
||||
fn a_reversed_symmetric_polyline_drops_its_vertex_identifiers() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read(&polyline_dwg_with([(-20.0, 0.0), (-20.0, 25.0), (20.0, 25.0), (20.0, 0.0)], 1.0), "sym.dwg").unwrap();
|
||||
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
|
||||
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
|
||||
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
|
||||
p.vertices.reverse();
|
||||
}
|
||||
}));
|
||||
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), [0; 4]);
|
||||
}
|
||||
|
||||
/// A group 91 inside an application's `102 {` group of the record is not a vertex identifier.
|
||||
#[test]
|
||||
fn a_91_inside_an_application_group_is_not_an_identifier() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = read(&polyline_dwg(), "polyline.dwg").unwrap();
|
||||
let dxf = String::from_utf8(save(&d, "saved.dxf", Version::R2018)).unwrap();
|
||||
let mut lines: Vec<&str> = dxf.lines().collect();
|
||||
let start = lines.windows(2).position(|pair| pair[0].trim() == "0" && pair[1].trim() == "LWPOLYLINE").unwrap();
|
||||
// After the first vertex's identifier.
|
||||
let at = (start..lines.len()).step_by(2).find(|i| lines[*i].trim() == "91").unwrap() + 2;
|
||||
lines.splice(at..at, ["102", "{SOMEAPP", " 91", "9", "102", "}"]);
|
||||
let back = read(lines.join("\n").as_bytes(), "app.dxf").unwrap();
|
||||
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"]);
|
||||
}
|
||||
@@ -62,6 +62,8 @@ mod low_handseed;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod ltype_dwg_dash_count;
|
||||
mod ltype_element_cap;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod lwpolyline_vertex_ids;
|
||||
mod minsert_marker;
|
||||
mod mleader_content;
|
||||
mod mleader_roundtrip;
|
||||
|
||||
Reference in New Issue
Block a user