mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-19 20:30:42 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43d7a19256 | ||
|
|
776e871003 | ||
|
|
fc992081a7 | ||
|
|
2b29a566c5 | ||
|
|
cdd069f07a | ||
|
|
12f9c3d119 | ||
|
|
ec23a13e62 | ||
|
|
dd08b2d52e | ||
|
|
a87ec8a5d6 | ||
|
|
b284371c83 | ||
|
|
b52f0a57ee | ||
|
|
2fffb31d24 | ||
|
|
74aed00706 | ||
|
|
8cbade6ec3 | ||
|
|
b42d54a368 | ||
|
|
de6b841d6a | ||
|
|
f097a688fe | ||
|
|
8b5503e865 | ||
|
|
6dfcbf29ba | ||
|
|
e10109e20a | ||
|
|
529b75fb67 | ||
|
|
61cfaab5af | ||
|
|
9cea2f780b | ||
|
|
d4c1ae0e23 | ||
|
|
72ff6c6fd6 | ||
|
|
8cfb9cfa8c | ||
|
|
4efecc2f0e | ||
|
|
99f442d40e | ||
|
|
cebfbebd20 | ||
|
|
99118a2bda | ||
|
|
d4c4c79982 | ||
|
|
387a6e6b1e | ||
|
|
578564403a | ||
|
|
19495fcfa7 | ||
|
|
8a42e8a1ac | ||
|
|
1a64ca23f5 | ||
|
|
8314fb87ef | ||
|
|
b19c3665d9 | ||
|
|
0479ddc6ca | ||
|
|
290e578c2f | ||
|
|
09e4f90740 | ||
|
|
c03fb712eb | ||
|
|
f09c50d6b8 | ||
|
|
0f33f430a7 | ||
|
|
46ee1a817d | ||
|
|
b3af16c621 | ||
|
|
cc1914d84e | ||
|
|
77b301439d | ||
|
|
bf1c514615 |
Generated
+1
@@ -668,6 +668,7 @@ dependencies = [
|
||||
"pollster 1.0.1",
|
||||
"rfd",
|
||||
"ron",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sys-locale",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ clap_mangen = { version = "0.3.3", features = ["env"] }
|
||||
thiserror = "2"
|
||||
same-file = "1"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip", "raw_value"] }
|
||||
log = "0.4"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
|
||||
@@ -208,6 +208,8 @@ The logger is `apps/cadcraft/src/logging.rs`; the web build logs to the browser
|
||||
cadcraft-cli mcp
|
||||
# …or bridged to the running app (start it with --control 7979):
|
||||
cadcraft-cli mcp --connect 127.0.0.1:7979
|
||||
# …or headless, with the agent confined to a work folder:
|
||||
cadcraft-cli mcp --automation-read-root ~/work --automation-write-root ~/work/out
|
||||
|
||||
# One-shot headless runs:
|
||||
cadcraft-cli run --sample --script 'CIRCLE 22,3 1\n' --save out.dxf --export out.png
|
||||
|
||||
@@ -276,6 +276,13 @@ pub(crate) struct McpArgs {
|
||||
/// port first (macOS)
|
||||
#[arg(long, requires = "connect")]
|
||||
pub(crate) launch: bool,
|
||||
/// The only folder the agent's commands may read from; reads are also allowed under the write
|
||||
/// root (headless only)
|
||||
#[arg(long, value_name = "DIR")]
|
||||
pub(crate) automation_read_root: Option<String>,
|
||||
/// The only folder the agent's commands may write to, never the folder itself (headless only)
|
||||
#[arg(long, value_name = "DIR")]
|
||||
pub(crate) automation_write_root: Option<String>,
|
||||
#[command(flatten)]
|
||||
pub(crate) settings: Settings,
|
||||
}
|
||||
@@ -408,12 +415,18 @@ enum UsageError {
|
||||
/// The output is one of the input files, so writing it would replace the original.
|
||||
#[error("{} is an input file, so the result would replace the original: choose another output, or pass --in-place to overwrite it", .0.display())]
|
||||
OutIsInput(PathBuf),
|
||||
/// The automation roots confine the headless server; a running app enforces its own access.
|
||||
#[error(
|
||||
"--automation-read-root and --automation-write-root confine the headless MCP server; a running app enforces its own file access (not yet available: see issue #1585)"
|
||||
)]
|
||||
AutomationRootsNeedHeadless,
|
||||
}
|
||||
|
||||
impl UsageError {
|
||||
/// This error in clap's form, so it prints with the usual usage text.
|
||||
fn into_clap(self, cmd: &mut clap::Command) -> clap::Error {
|
||||
let kind = match self {
|
||||
Self::FramingNeedsImage { .. } | Self::OutIsInput(_) => ErrorKind::ArgumentConflict,
|
||||
Self::FramingNeedsImage { .. } | Self::OutIsInput(_) | Self::AutomationRootsNeedHeadless => ErrorKind::ArgumentConflict,
|
||||
};
|
||||
cmd.error(kind, self)
|
||||
}
|
||||
@@ -485,6 +498,13 @@ fn framing_error(cli: &Cli) -> Option<UsageError> {
|
||||
(!cadcraft_io::is_image(out)).then(|| UsageError::FramingNeedsImage { flag, out: out.to_path_buf() })
|
||||
}
|
||||
|
||||
/// The automation roots confine the headless server only, as the other Craft apps' do.
|
||||
fn roots_need_headless(cli: &Cli) -> Option<UsageError> {
|
||||
let Command::Mcp(m) = &cli.command else { return None };
|
||||
(m.connect.is_some() && (m.automation_read_root.is_some() || m.automation_write_root.is_some()))
|
||||
.then_some(UsageError::AutomationRootsNeedHeadless)
|
||||
}
|
||||
|
||||
/// An output that is the same file as an input, without `--in-place`. An output that doesn't exist
|
||||
/// can't be an input, and an I/O error in the comparison is left to the open or write that follows.
|
||||
fn out_is_input(cli: &Cli) -> Option<UsageError> {
|
||||
@@ -503,19 +523,20 @@ fn out_is_input(cli: &Cli) -> Option<UsageError> {
|
||||
/// The backend `cadcraft-cli mcp` serves from.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum McpTarget {
|
||||
/// An in-process drawing session (no `--connect`).
|
||||
Headless,
|
||||
/// An in-process drawing session (no `--connect`), optionally confined to the two folders.
|
||||
Headless { read_root: Option<String>, write_root: Option<String> },
|
||||
/// The running app's control channel at `HOST:PORT`; `lazy`: reached at the first call;
|
||||
/// `launch`: opened then if it isn't running.
|
||||
Connect { addr: String, lazy: bool, launch: bool },
|
||||
}
|
||||
|
||||
impl McpArgs {
|
||||
/// What these arguments ask the server to talk to.
|
||||
pub(crate) fn target(&self) -> McpTarget {
|
||||
match &self.connect {
|
||||
// `--launch` connects at the first call too (the app opens then).
|
||||
Some(addr) => McpTarget::Connect { addr: addr.clone(), lazy: self.lazy || self.launch, launch: self.launch },
|
||||
None => McpTarget::Headless,
|
||||
None => McpTarget::Headless { read_root: self.automation_read_root.clone(), write_root: self.automation_write_root.clone() },
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -588,7 +609,7 @@ fn parse_with(mut cmd: clap::Command, args: &[OsString]) -> Result<Cli, clap::Er
|
||||
if let (Command::Run(r), Some((_, m))) = (&mut cli.command, matches.subcommand()) {
|
||||
(r.drawings, r.steps) = run_order(m);
|
||||
}
|
||||
if let Some(e) = framing_error(&cli).or_else(|| out_is_input(&cli)) {
|
||||
if let Some(e) = framing_error(&cli).or_else(|| out_is_input(&cli)).or_else(|| roots_need_headless(&cli)) {
|
||||
if let Some(sub) = matches.subcommand_name().and_then(|n| cmd.find_subcommand_mut(n)) {
|
||||
return Err(e.into_clap(sub));
|
||||
}
|
||||
@@ -644,9 +665,24 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Without `--connect` the server runs headless, confining nothing unless asked.
|
||||
#[test]
|
||||
fn mcp_without_connect_is_headless() {
|
||||
assert_eq!(mcp(&[]).unwrap(), McpTarget::Headless);
|
||||
assert_eq!(mcp(&[]).unwrap(), McpTarget::Headless { read_root: None, write_root: None });
|
||||
}
|
||||
|
||||
/// The automation roots confine a headless server; `--connect` is refused with the reason
|
||||
/// (the running app's control channel is not confined yet, #1585).
|
||||
#[test]
|
||||
fn mcp_automation_roots_confine_a_headless_server_only() {
|
||||
assert_eq!(
|
||||
mcp(&["--automation-read-root", "/work", "--automation-write-root=/work/out"]).unwrap(),
|
||||
McpTarget::Headless { read_root: Some("/work".into()), write_root: Some("/work/out".into()) }
|
||||
);
|
||||
let e = mcp(&["--connect", "127.0.0.1:7979", "--automation-read-root", "/work"]).unwrap_err().to_string();
|
||||
assert!(e.contains("headless MCP server") && e.contains("#1585"), "{e}");
|
||||
let e = mcp(&["--automation-write-root=/work", "--connect", "127.0.0.1:7979"]).unwrap_err().to_string();
|
||||
assert!(e.contains("headless MCP server"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -27,6 +27,9 @@ pub(crate) enum CliError {
|
||||
NotUnicode(std::path::PathBuf),
|
||||
#[error("cannot connect to {addr}: {source}")]
|
||||
McpConnect { addr: String, source: std::io::Error },
|
||||
/// An `--automation-*-root` that cannot be opened (missing, a file, a link that escapes).
|
||||
#[error("{0}")]
|
||||
AutomationRoots(String),
|
||||
}
|
||||
|
||||
pub(crate) type Result<T = (), E = CliError> = std::result::Result<T, E>;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::args::{McpArgs, McpTarget};
|
||||
use super::error::{CliError, Result};
|
||||
|
||||
/// Serve MCP on stdin and stdout against the running app or a headless session held to any roots given.
|
||||
pub(crate) fn mcp(a: &McpArgs) -> Result {
|
||||
let backend: Box<dyn cadcraft_mcp::Backend> = match a.target() {
|
||||
McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)),
|
||||
@@ -8,7 +9,14 @@ pub(crate) fn mcp(a: &McpArgs) -> Result {
|
||||
Ok(r) => Box::new(r),
|
||||
Err(source) => return Err(CliError::McpConnect { addr, source }),
|
||||
},
|
||||
McpTarget::Headless => Box::new(cadcraft_mcp::Headless::default()),
|
||||
McpTarget::Headless { read_root, write_root } => {
|
||||
let roots = cadcraft_engine::file_access::AutomationRoots::new(
|
||||
read_root.as_deref().map(std::path::Path::new),
|
||||
write_root.as_deref().map(std::path::Path::new),
|
||||
)
|
||||
.map_err(CliError::AutomationRoots)?;
|
||||
Box::new(cadcraft_mcp::Headless::default().with_automation_roots(roots))
|
||||
}
|
||||
};
|
||||
let stdin = std::io::stdin();
|
||||
let stdout = std::io::stdout();
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
//! `cadcraft-cli mcp --automation-read-root <dir> --automation-write-root <dir>` (#1472): through
|
||||
//! the MCP protocol, files open only from inside the read root and are saved, exported, plotted and
|
||||
//! rendered only inside the write root; `..` and links that leave a root are refused, and nothing is
|
||||
//! written outside. Without roots nothing changes.
|
||||
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Never crash).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output, Stdio};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const INIT: &str = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#;
|
||||
|
||||
/// A folder of a test's own, removed when the test ends, also when it fails.
|
||||
struct TestDir(PathBuf);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
type Target = Path;
|
||||
/// The folder itself.
|
||||
fn deref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestDir {
|
||||
/// Removes the folder and all it holds; a failure here must not hide the test's own.
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new folder of this test's own: made here, so nothing else put it there first.
|
||||
fn fresh_dir(tag: &str) -> TestDir {
|
||||
let mut n = 0u32;
|
||||
loop {
|
||||
let dir = std::env::temp_dir().join(format!("cc-mcp-roots-{tag}-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => return TestDir(dir),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1,
|
||||
Err(e) => panic!("{}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder holding `in` (the read root, with `a.dxf`), `out` (the write root), `outside` (with
|
||||
/// `b.dxf`) and `in2` (a sibling with the same prefix as `in`).
|
||||
fn folders(tag: &str) -> TestDir {
|
||||
let base = fresh_dir(tag);
|
||||
for d in ["in", "out", "outside", "in2"] {
|
||||
std::fs::create_dir_all(base.join(d)).unwrap();
|
||||
}
|
||||
for p in ["in/a.dxf", "outside/b.dxf", "in2/c.dxf"] {
|
||||
let drawing = cadcraft_engine::doc::Drawing::new_imperial();
|
||||
std::fs::write(base.join(p), cadcraft_io::write(&drawing, "x.dxf").unwrap()).unwrap();
|
||||
}
|
||||
base
|
||||
}
|
||||
|
||||
/// `p` as the text a tool call passes.
|
||||
fn s(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// One tool call's result: `isError` and its first text block.
|
||||
struct Tool {
|
||||
error: bool,
|
||||
text: String,
|
||||
}
|
||||
|
||||
/// Run `cadcraft-cli mcp` with `args`, initialise, then make each call in order.
|
||||
fn run(args: &[&str], calls: &[(&str, Value)]) -> (Output, Vec<Tool>) {
|
||||
run_env(args, calls, &[])
|
||||
}
|
||||
|
||||
/// [`run`], with `env` set for the server process (a private settings folder).
|
||||
fn run_env(args: &[&str], calls: &[(&str, Value)], env: &[(&str, &str)]) -> (Output, Vec<Tool>) {
|
||||
let mut input = format!("{INIT}\n");
|
||||
for (i, (name, arguments)) in calls.iter().enumerate() {
|
||||
let req = json!({"jsonrpc": "2.0", "id": i + 2, "method": "tools/call", "params": {"name": name, "arguments": arguments}});
|
||||
input.push_str(&req.to_string());
|
||||
input.push('\n');
|
||||
}
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli"))
|
||||
.arg("mcp")
|
||||
.args(args)
|
||||
.envs(env.iter().copied())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn cadcraft-cli");
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
stdin.write_all(input.as_bytes()).unwrap();
|
||||
}
|
||||
let out = child.wait_with_output().expect("wait for cadcraft-cli");
|
||||
let replies: Vec<Value> = String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| serde_json::from_str(l).ok()).collect();
|
||||
let tools = calls
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (name, arguments))| {
|
||||
let id = (i + 2) as u64;
|
||||
let reply = replies.iter().find(|v| v["id"] == id).unwrap_or_else(|| panic!("no reply to {name} {arguments}: {replies:?}"));
|
||||
assert!(reply.get("error").is_none() && reply["result"].is_object(), "{name} {arguments} got an error reply, not a tool result: {reply}");
|
||||
let result = &reply["result"];
|
||||
Tool { error: result["isError"] == true, text: result["content"][0]["text"].as_str().unwrap_or_default().to_string() }
|
||||
})
|
||||
.collect();
|
||||
(out, tools)
|
||||
}
|
||||
|
||||
/// The call succeeded.
|
||||
fn ok(t: &Tool) {
|
||||
assert!(!t.error, "should be allowed: {}", t.text);
|
||||
}
|
||||
|
||||
/// The call was refused, saying `why`.
|
||||
fn refused(t: &Tool, why: &str) {
|
||||
assert!(t.error, "should be refused ({why}): {}", t.text);
|
||||
assert!(t.text.contains(why), "should say `{why}`: {}", t.text);
|
||||
}
|
||||
|
||||
/// `open` and every other read stay inside the read root or the write root.
|
||||
#[test]
|
||||
fn files_open_only_from_inside_the_read_root() {
|
||||
let base = folders("open");
|
||||
let (out, t) = run(
|
||||
&["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))],
|
||||
&[
|
||||
("open", json!({"path": s(&base.join("in/a.dxf"))})),
|
||||
("open", json!({"path": s(&base.join("outside/b.dxf"))})),
|
||||
("open", json!({"path": s(&base.join("in2/c.dxf"))})),
|
||||
("open", json!({"path": format!("{}/../outside/b.dxf", s(&base.join("in")))})),
|
||||
("execute", json!({"command": "circle", "params": {"center": [0, 0], "radius": 1}})),
|
||||
],
|
||||
);
|
||||
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
|
||||
ok(&t[0]);
|
||||
refused(&t[1], "outside the read root");
|
||||
refused(&t[2], "outside the read root");
|
||||
refused(&t[3], "outside the read root");
|
||||
// A refused path is an ordinary tool error; the session keeps working.
|
||||
ok(&t[4]);
|
||||
}
|
||||
|
||||
/// Writes stay inside the write root, the root itself is refused, and no temporary file is left outside.
|
||||
#[test]
|
||||
fn writes_go_only_into_the_write_root_and_leave_no_temp_file_outside() {
|
||||
let base = folders("write");
|
||||
let out = s(&base.join("out"));
|
||||
let (out_run, t) = run(
|
||||
&["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &out],
|
||||
&[
|
||||
("open", json!({"path": s(&base.join("in/a.dxf"))})),
|
||||
("save", json!({"path": s(&base.join("out/saved.dxf"))})),
|
||||
("save", json!({"path": s(&base.join("outside/saved.dxf"))})),
|
||||
("save", json!({"path": s(&base.join("in/a.dxf"))})),
|
||||
("save", json!({"path": format!("{}/../outside/up.dxf", s(&base.join("out")))})),
|
||||
("save", json!({"path": out})),
|
||||
("save", json!({"path": format!("{out}/../out")})),
|
||||
("execute", json!({"command": "export", "params": {"path": s(&base.join("out/art.png")), "format": "png"}})),
|
||||
("execute", json!({"command": "export", "params": {"path": s(&base.join("outside/art.png")), "format": "png"}})),
|
||||
("render", json!({"path": s(&base.join("out/view.png"))})),
|
||||
("render", json!({"path": s(&base.join("outside/view.png"))})),
|
||||
("execute", json!({"command": "circle", "params": {"center": [0, 0], "radius": 1}})),
|
||||
],
|
||||
);
|
||||
assert!(out_run.status.success(), "stderr: {}", String::from_utf8_lossy(&out_run.stderr));
|
||||
ok(&t[0]);
|
||||
ok(&t[1]);
|
||||
assert!(base.join("out/saved.dxf").is_file());
|
||||
refused(&t[2], "outside the write root");
|
||||
refused(&t[3], "outside the write root");
|
||||
refused(&t[4], "outside the write root");
|
||||
refused(&t[5], "the write root itself cannot be written");
|
||||
refused(&t[6], "the write root itself cannot be written");
|
||||
ok(&t[7]);
|
||||
assert!(base.join("out/art.png").is_file());
|
||||
refused(&t[8], "outside the write root");
|
||||
ok(&t[9]);
|
||||
assert!(base.join("out/view.png").is_file());
|
||||
refused(&t[10], "outside the write root");
|
||||
ok(&t[11]);
|
||||
|
||||
assert!(!base.join("outside/saved.dxf").exists());
|
||||
assert!(!base.join("outside/art.png").exists());
|
||||
assert!(!base.join("outside/view.png").exists());
|
||||
// The save's temporary file is beside the destination, inside the root; none is outside.
|
||||
assert!(!base.join("outside/saved.dxf.cadcraft-tmp").exists());
|
||||
assert!(!base.join("outside/up.dxf.cadcraft-tmp").exists());
|
||||
assert!(!base.join("out.cadcraft-tmp").exists(), "writing to the root must not leave its temporary file beside it");
|
||||
let leftovers: Vec<String> =
|
||||
std::fs::read_dir(base.join("outside")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
assert_eq!(leftovers, ["b.dxf"], "nothing was written outside the roots");
|
||||
let temps: Vec<String> =
|
||||
std::fs::read_dir(&*base).unwrap().filter_map(|e| e.ok()?.file_name().into_string().ok()).filter(|n| n.ends_with(".cadcraft-tmp")).collect();
|
||||
assert!(temps.is_empty(), "no temporary file beside or outside the roots: {temps:?}");
|
||||
}
|
||||
|
||||
/// A root left out grants none of its own access: a read root allows no writes, while a write root also allows reads.
|
||||
#[test]
|
||||
fn a_root_left_out_grants_none_of_its_access() {
|
||||
let base = folders("left-out");
|
||||
let (out, t) = run(
|
||||
&["--automation-read-root", &s(&base.join("in"))],
|
||||
&[("open", json!({"path": s(&base.join("in/a.dxf"))})), ("save", json!({"path": s(&base.join("out/a.dxf"))})), ("save", json!({}))],
|
||||
);
|
||||
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
|
||||
ok(&t[0]);
|
||||
refused(&t[1], "write authority is absent");
|
||||
// QSAVE writes over the opened drawing's own path, which is not writable either.
|
||||
refused(&t[2], "write authority is absent");
|
||||
|
||||
let (out, t) = run(
|
||||
&["--automation-write-root", &s(&base.join("out"))],
|
||||
&[
|
||||
("open", json!({"path": s(&base.join("in/a.dxf"))})),
|
||||
("save", json!({"path": s(&base.join("out/new.dxf"))})),
|
||||
// Reads are allowed under the write root: the agent can reopen what it saved.
|
||||
("open", json!({"path": s(&base.join("out/new.dxf"))})),
|
||||
],
|
||||
);
|
||||
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
|
||||
refused(&t[0], "outside the read root (or the write root)");
|
||||
ok(&t[1]);
|
||||
assert!(base.join("out/new.dxf").is_file());
|
||||
ok(&t[2]);
|
||||
}
|
||||
|
||||
/// The shared plotter settings folder is outside the roots: every action refuses and it is unchanged.
|
||||
#[test]
|
||||
fn plotter_settings_outside_the_roots_are_refused() {
|
||||
let base = folders("plotters");
|
||||
let config = base.join("config");
|
||||
let settings = config.join("plotters");
|
||||
std::fs::create_dir_all(&settings).unwrap();
|
||||
let device = cadcraft_engine::doc::PlotterConfig {
|
||||
name: "Office".into(),
|
||||
description: "not the agent's".into(),
|
||||
papers: vec![cadcraft_engine::doc::DevicePaper { name: "A4".into(), width: 210.0, height: 297.0, margins: [5.0; 4] }],
|
||||
..Default::default()
|
||||
};
|
||||
let file = settings.join("Office.plotter.json");
|
||||
let original = device.to_file_text();
|
||||
std::fs::write(&file, &original).unwrap();
|
||||
|
||||
let text = original.clone();
|
||||
let (out, t) = run_env(
|
||||
&["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))],
|
||||
&[
|
||||
("execute", json!({"command": "plottermanager", "params": {}})),
|
||||
("execute", json!({"command": "plottermanager", "params": {"action": "get", "name": "Office"}})),
|
||||
("execute", json!({"command": "plottermanager", "params": {"action": "new", "name": "Leak", "output": "pdf"}})),
|
||||
("execute", json!({"command": "plottermanager", "params": {"action": "set", "name": "Office", "description": "changed"}})),
|
||||
("execute", json!({"command": "plottermanager", "params": {"action": "load", "text": text, "name": "Leaked Copy"}})),
|
||||
("execute", json!({"command": "plottermanager", "params": {"action": "delete", "name": "Office"}})),
|
||||
],
|
||||
&[("CADCRAFT_CONFIG_DIR", &s(&config))],
|
||||
);
|
||||
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
|
||||
refused(&t[0], "outside the read root (or the write root)");
|
||||
refused(&t[1], "unknown plotter");
|
||||
refused(&t[2], "outside the write root");
|
||||
refused(&t[3], "unknown plotter");
|
||||
refused(&t[4], "outside the write root");
|
||||
refused(&t[5], "unknown plotter");
|
||||
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), original, "the shared file is unchanged");
|
||||
let names: Vec<String> = std::fs::read_dir(&settings).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
assert_eq!(names, ["Office.plotter.json"], "nothing was created or deleted in the settings folder");
|
||||
assert!(!settings.join("Office.plotter.json.cadcraft-tmp").exists());
|
||||
}
|
||||
|
||||
/// With no roots nothing changes: files anywhere can be reached.
|
||||
#[test]
|
||||
fn without_roots_files_are_reachable_as_before() {
|
||||
let base = folders("none");
|
||||
let (out, t) =
|
||||
run(&[], &[("open", json!({"path": s(&base.join("outside/b.dxf"))})), ("save", json!({"path": s(&base.join("outside/new.dxf"))}))]);
|
||||
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
|
||||
ok(&t[0]);
|
||||
ok(&t[1]);
|
||||
assert!(base.join("outside/new.dxf").is_file());
|
||||
}
|
||||
|
||||
/// A link inside a root leading out is refused for reads and writes.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn links_out_of_a_root_are_refused() {
|
||||
let base = folders("links");
|
||||
std::os::unix::fs::symlink(base.join("outside"), base.join("out/away")).unwrap();
|
||||
std::os::unix::fs::symlink(base.join("outside/b.dxf"), base.join("in/leak.dxf")).unwrap();
|
||||
let (out, t) = run(
|
||||
&["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))],
|
||||
&[("open", json!({"path": s(&base.join("in/leak.dxf"))})), ("save", json!({"path": s(&base.join("out/away/new.dxf"))}))],
|
||||
);
|
||||
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
|
||||
refused(&t[0], "outside the read root");
|
||||
refused(&t[1], "outside the write root");
|
||||
assert!(!base.join("outside/new.dxf").exists());
|
||||
}
|
||||
|
||||
/// Each kind of command that touches a file is refused outside the roots.
|
||||
#[test]
|
||||
fn every_file_a_command_touches_is_held_to_the_roots() {
|
||||
let base = folders("commands");
|
||||
let drawing = cadcraft_engine::doc::Drawing::new_imperial();
|
||||
std::fs::write(base.join("in/x.dxf"), cadcraft_io::write(&drawing, "x.dxf").unwrap()).unwrap();
|
||||
std::fs::write(base.join("in/ok.scr"), "CIRCLE 0,0 1\n").unwrap();
|
||||
std::fs::write(base.join("outside/bad.scr"), "CIRCLE 0,0 1\n").unwrap();
|
||||
let (out, t) = run(
|
||||
&["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))],
|
||||
&[
|
||||
("open", json!({"path": s(&base.join("in/a.dxf"))})),
|
||||
// SCRIPT
|
||||
("execute", json!({"command": "script", "params": {"path": s(&base.join("in/ok.scr"))}})),
|
||||
("execute", json!({"command": "script", "params": {"path": s(&base.join("outside/bad.scr"))}})),
|
||||
// XATTACH reads the referenced drawing, INSERT and IMPORT read their files.
|
||||
("execute", json!({"command": "xattach", "params": {"path": s(&base.join("in/x.dxf")), "name": "ok"}})),
|
||||
("execute", json!({"command": "xattach", "params": {"path": s(&base.join("outside/b.dxf")), "name": "bad"}})),
|
||||
("execute", json!({"command": "insert", "params": {"name": "blk", "file": s(&base.join("outside/b.dxf")), "at": [0, 0]}})),
|
||||
("execute", json!({"command": "import", "params": {"path": s(&base.join("outside/b.dxf"))}})),
|
||||
// Support files (a linetype file here) and a plot style table.
|
||||
("execute", json!({"command": "linetype", "params": {"file": s(&base.join("outside/b.dxf"))}})),
|
||||
("execute", json!({"command": "stylesmanager", "params": {"action": "load", "path": s(&base.join("outside/b.dxf"))}})),
|
||||
// PLOT writes only inside the write root; the inside plot works.
|
||||
("execute", json!({"command": "plot", "params": {"path": s(&base.join("out/plot.pdf"))}})),
|
||||
("execute", json!({"command": "plot", "params": {"path": s(&base.join("outside/plot.pdf"))}})),
|
||||
],
|
||||
);
|
||||
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
|
||||
ok(&t[0]);
|
||||
ok(&t[1]);
|
||||
refused(&t[2], "outside the read root");
|
||||
ok(&t[3]);
|
||||
refused(&t[4], "outside the read root");
|
||||
refused(&t[5], "outside the read root");
|
||||
refused(&t[6], "outside the read root");
|
||||
refused(&t[7], "outside the read root");
|
||||
refused(&t[8], "outside the read root");
|
||||
ok(&t[9]);
|
||||
assert!(base.join("out/plot.pdf").is_file());
|
||||
refused(&t[10], "outside the write root");
|
||||
assert!(!base.join("outside/plot.pdf").exists());
|
||||
}
|
||||
|
||||
/// A root that can't be opened, or roots with `--connect`, stop the server at startup.
|
||||
#[test]
|
||||
fn missing_roots_and_roots_with_connect_fail_at_startup() {
|
||||
let base = folders("bad-roots");
|
||||
let input = format!("{INIT}\n");
|
||||
let start = |args: &[&str]| {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli"))
|
||||
.arg("mcp")
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn cadcraft-cli");
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
let _ = stdin.write_all(input.as_bytes());
|
||||
}
|
||||
child.wait_with_output().expect("wait for cadcraft-cli")
|
||||
};
|
||||
let out = start(&["--automation-read-root", &s(&base.join("nope"))]);
|
||||
assert!(!out.status.success() && out.stdout.is_empty());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("cannot open the automation read root"));
|
||||
|
||||
let out = start(&["--automation-write-root", &s(&base.join("in/a.dxf"))]);
|
||||
assert!(!out.status.success() && out.stdout.is_empty());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("cannot open the automation write root"));
|
||||
|
||||
let out = start(&["--connect", "127.0.0.1:1", "--automation-read-root", &s(&base.join("in"))]);
|
||||
assert!(!out.status.success() && out.stdout.is_empty());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("headless MCP server"));
|
||||
}
|
||||
|
||||
/// A UNC, device or non-disk verbatim path is refused by the server before it is opened.
|
||||
/// The reply names the prefix. It is not an operating-system error from opening the path.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_network_path_is_refused_before_it_is_opened() {
|
||||
let base = folders("unc");
|
||||
let (out, t) = run(
|
||||
&["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))],
|
||||
&[
|
||||
("open", json!({"path": r"\\203.0.113.5\s\x.dwg"})),
|
||||
("open", json!({"path": r"\\?\UNC\203.0.113.5\s\x.dwg"})),
|
||||
("open", json!({"path": r"\\host@SSL\share\x.dwg"})),
|
||||
("open", json!({"path": r"\\.\PhysicalDrive0"})),
|
||||
("open", json!({"path": r"\\?\Volume{00000000-0000-0000-0000-000000000000}\x.dwg"})),
|
||||
("execute", json!({"command": "circle", "params": {"center": [0, 0], "radius": 1}})),
|
||||
],
|
||||
);
|
||||
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
|
||||
let kinds = ["UNC", "UNC", "UNC", "device path", "verbatim path"];
|
||||
for (tool, kind) in t.iter().zip(kinds) {
|
||||
refused(tool, kind);
|
||||
assert!(!tool.text.contains("cannot resolve") && !tool.text.to_ascii_lowercase().contains("os error"), "{}", tool.text);
|
||||
}
|
||||
ok(&t[5]);
|
||||
}
|
||||
@@ -0,0 +1,749 @@
|
||||
//! Walks every command in the registry through the real MCP server with paths outside the
|
||||
//! automation roots (#1472). Reads show as a changed access time and writes as a changed size or
|
||||
//! modification time, a removed file, or a file that was not there before, whatever the command
|
||||
//! does with the path. The same walk without roots has to find escapes, or finding none under
|
||||
//! roots would prove nothing.
|
||||
#![cfg(unix)]
|
||||
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Never crash).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fs::{File, FileTimes};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Longest a call may take before the server counts as hung.
|
||||
const CALL_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
/// The extensions commands choose their behaviour by.
|
||||
const EXTENSIONS: &[&str] = &["dxf", "dwg", "dwt", "scr", "lsp", "lin", "pat", "pgp", "csv", "txt", "png", "pdf", "svg", "ctb"];
|
||||
/// The parameter names a command might take a path under.
|
||||
const PATH_KEYS: &[&str] =
|
||||
&["path", "file", "template", "patternFile", "from", "to", "source", "target", "output", "folder", "dir", "filename", "document"];
|
||||
/// A valid 1x1 PNG.
|
||||
const PNG: &[u8] = &[
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 0x1F, 0x15, 0xC4,
|
||||
0x89, 0, 0, 0, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0, 1, 0, 0, 5, 0, 1, 0x0D, 0x0A, 0x2D, 0xB4, 0, 0, 0, 0, 0x49, 0x45, 0x4E, 0x44,
|
||||
0xAE, 0x42, 0x60, 0x82,
|
||||
];
|
||||
|
||||
/// `p` as the text a tool call passes.
|
||||
fn s(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// A running `cadcraft-cli mcp`.
|
||||
struct Server {
|
||||
child: Child,
|
||||
stdin: ChildStdin,
|
||||
replies: Receiver<Value>,
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Start the real binary as an MCP server and initialize it.
|
||||
fn start(args: &[String], cwd: &Path, config: &Path) -> Self {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli"))
|
||||
.arg("mcp")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.env("CADCRAFT_CONFIG_DIR", config)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("spawn cadcraft-cli");
|
||||
let stdin = child.stdin.take().unwrap();
|
||||
let stdout = child.stdout.take().unwrap();
|
||||
let (tx, replies) = channel();
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
|
||||
if let Ok(v) = serde_json::from_str::<Value>(&line)
|
||||
&& tx.send(v).is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut server = Self { child, stdin, replies, next: 1 };
|
||||
server.request("initialize", json!({"protocolVersion": "2025-06-18"})).expect("initialize");
|
||||
server
|
||||
}
|
||||
|
||||
/// Send one JSON-RPC request; `None` if the server stopped answering.
|
||||
fn request(&mut self, method: &str, params: Value) -> Option<Value> {
|
||||
let id = self.next;
|
||||
self.next += 1;
|
||||
let req = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
|
||||
writeln!(self.stdin, "{req}").ok()?;
|
||||
loop {
|
||||
let reply = self.replies.recv_timeout(CALL_TIMEOUT).ok()?;
|
||||
if reply["id"] == id {
|
||||
return Some(reply);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tool's first text block, or `None` when the server hung or stopped.
|
||||
fn tool(&mut self, name: &str, arguments: Value) -> Option<String> {
|
||||
let reply = self.request("tools/call", json!({"name": name, "arguments": arguments}))?;
|
||||
Some(reply["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
/// Like [`Self::tool`] for a call that must work: an error reply, or a result flagged as an
|
||||
/// error, fails the test.
|
||||
fn tool_ok(&mut self, name: &str, arguments: Value) -> String {
|
||||
let reply = self.request("tools/call", json!({"name": name, "arguments": arguments})).expect("the server answered");
|
||||
assert!(reply.get("error").is_none() && reply["result"]["isError"] != true, "{name} should have worked: {reply}");
|
||||
reply["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// Run an engine command through the `execute` tool.
|
||||
fn execute(&mut self, command: &str, params: Value) -> Option<String> {
|
||||
self.tool("execute", json!({"command": command, "params": params}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Server {
|
||||
/// Stops the server it started.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// The folders of one walk: `in` and `out` are the roots, nothing under `outside` may be touched.
|
||||
/// A new folder of this test's own: made here, so nothing else put it there first.
|
||||
fn fresh_dir(tag: &str) -> PathBuf {
|
||||
let mut n = 0u32;
|
||||
loop {
|
||||
let dir = std::env::temp_dir().join(format!("cc-walk-{tag}-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => return dir,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1,
|
||||
Err(e) => panic!("{}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the file or folder at `p`.
|
||||
fn remove(p: &Path) {
|
||||
let _ = if p.is_dir() { std::fs::remove_dir_all(p) } else { std::fs::remove_file(p) };
|
||||
}
|
||||
|
||||
/// Remove what `dir` holds, if it exists.
|
||||
fn clear(dir: &Path) {
|
||||
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
remove(&entry.path());
|
||||
}
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
base: PathBuf,
|
||||
outside: PathBuf,
|
||||
/// Each path under `outside`, with its size, modification time and access time.
|
||||
baseline: BTreeMap<PathBuf, (u64, SystemTime, SystemTime)>,
|
||||
/// Whether this file system records reads at all (`noatime` doesn't).
|
||||
sees_reads: bool,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
/// A new fixture, finding out whether this file system records reads.
|
||||
fn new(tag: &str) -> Self {
|
||||
let base = fresh_dir(tag);
|
||||
for d in ["in", "out"] {
|
||||
std::fs::create_dir(base.join(d)).unwrap();
|
||||
}
|
||||
let probe = base.join("probe");
|
||||
std::fs::write(&probe, "x").unwrap();
|
||||
age_access_time(&probe);
|
||||
let before = std::fs::metadata(&probe).unwrap().accessed().unwrap();
|
||||
std::fs::read(&probe).unwrap();
|
||||
let sees_reads = std::fs::metadata(&probe).unwrap().accessed().unwrap() != before;
|
||||
let outside = base.join("outside");
|
||||
let mut f = Self { base, outside, baseline: BTreeMap::new(), sees_reads };
|
||||
f.reset();
|
||||
f
|
||||
}
|
||||
|
||||
/// Lay out `outside` afresh and start watching it.
|
||||
fn reset(&mut self) {
|
||||
let o = self.outside.clone();
|
||||
// The running server's working directory stays: without it a relative path can't be resolved.
|
||||
clear(&o.join("cwd"));
|
||||
for entry in std::fs::read_dir(&o).into_iter().flatten().flatten() {
|
||||
if entry.file_name() != "cwd" {
|
||||
remove(&entry.path());
|
||||
}
|
||||
}
|
||||
for d in ["cwd", "config/plotters", "recover"] {
|
||||
std::fs::create_dir_all(o.join(d)).unwrap();
|
||||
}
|
||||
let dxf = cadcraft_io::write(&cadcraft_engine::doc::Drawing::new_imperial(), "x.dxf").unwrap();
|
||||
for ext in EXTENSIONS {
|
||||
let body: &[u8] = match *ext {
|
||||
"dxf" | "dwg" | "dwt" => &dxf,
|
||||
"scr" => b"CIRCLE 0,0 5\n",
|
||||
"lsp" => b"(princ 1)\n",
|
||||
"lin" => b"*WALK,walk\nA,1,-1\n",
|
||||
"pat" => b"*WALK,walk\n0,0,0,0,1\n",
|
||||
"pgp" => b"W,*LINE\n",
|
||||
"csv" | "txt" => b"a,b\n1,2\n",
|
||||
"png" => PNG,
|
||||
_ => b"canary",
|
||||
};
|
||||
std::fs::write(o.join(format!("canary.{ext}")), body).unwrap();
|
||||
}
|
||||
// Two images, so that a drawing naming both loads them on threads of their own.
|
||||
std::fs::write(o.join("second.png"), PNG).unwrap();
|
||||
let device = cadcraft_engine::doc::PlotterConfig { name: "Office".into(), ..Default::default() };
|
||||
std::fs::write(o.join("config/plotters/Office.plotter.json"), device.to_file_text()).unwrap();
|
||||
self.watch();
|
||||
}
|
||||
|
||||
/// Start watching what is under `outside` now.
|
||||
fn watch(&mut self) {
|
||||
let o = self.outside.clone();
|
||||
self.baseline.clear();
|
||||
for p in tree(&o) {
|
||||
age_access_time(&p);
|
||||
let m = std::fs::metadata(&p).unwrap();
|
||||
self.baseline.insert(p, (m.len(), m.modified().unwrap(), m.accessed().unwrap()));
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened under `outside` since [`Self::reset`]. Metadata is read before any directory
|
||||
/// listing, and directory access times are put back afterwards: the listing is how a new file
|
||||
/// is seen when the folder's modification time has not moved, and it must not look like a read.
|
||||
fn touched(&self) -> Vec<String> {
|
||||
let mut seen = Vec::new();
|
||||
for (p, (len, modified, accessed)) in &self.baseline {
|
||||
let name = p.strip_prefix(&self.outside).unwrap_or(p).display();
|
||||
match std::fs::metadata(p) {
|
||||
Err(_) => seen.push(format!("removed {name}")),
|
||||
Ok(m) if m.modified().unwrap() != *modified || (!m.is_dir() && m.len() != *len) => seen.push(format!("wrote {name}")),
|
||||
Ok(m) if self.sees_reads && m.accessed().unwrap() != *accessed => seen.push(format!("read {name}")),
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
for p in tree(&self.outside) {
|
||||
if !self.baseline.contains_key(&p) {
|
||||
let name = p.strip_prefix(&self.outside).unwrap_or(&p).display();
|
||||
seen.push(format!("created {name}"));
|
||||
}
|
||||
}
|
||||
for (p, (_, _, accessed)) in &self.baseline {
|
||||
if p.is_dir() {
|
||||
let _ = File::open(p).and_then(|f| f.set_times(FileTimes::new().set_accessed(*accessed)));
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
/// Removes the fixture folder when the test ends, also when it fails.
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.base);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file and folder under `dir`.
|
||||
fn tree(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut out = vec![dir.to_path_buf()];
|
||||
for e in std::fs::read_dir(dir).unwrap().flatten() {
|
||||
if e.path().is_dir() {
|
||||
out.extend(tree(&e.path()));
|
||||
} else {
|
||||
out.push(e.path());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Put `p`'s access time in the past, so that the next read updates it even under `relatime`.
|
||||
fn age_access_time(p: &Path) {
|
||||
let past = SystemTime::now() - Duration::from_secs(3 * 24 * 3600);
|
||||
File::open(p).unwrap().set_times(FileTimes::new().set_accessed(past)).unwrap();
|
||||
}
|
||||
|
||||
/// The `action` or `option` values a parameter doc lists: `action?: list|open|discard (…)`.
|
||||
fn actions(doc: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for key in ["action", "option"] {
|
||||
let Some(at) = doc.find(key) else { continue };
|
||||
let rest = doc[at + key.len()..].trim_start_matches(['?', ':', ' ']);
|
||||
let end = rest.find([',', '}', '(']).unwrap_or(rest.len());
|
||||
out.extend(rest[..end].split('|').map(|w| w.trim().trim_matches('"').to_string()).filter(|w| !w.is_empty()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The calls to try for command `id`: every path-like key set to `target`, with each action.
|
||||
fn variants(doc: &str, target: &str, handle: &str, table: &str) -> Vec<Value> {
|
||||
let mut base = json!({"handle": table, "handles": [handle], "at": [0, 0], "name": "walk"});
|
||||
for key in PATH_KEYS {
|
||||
base[*key] = json!(target);
|
||||
}
|
||||
let mut named = base.clone();
|
||||
named["name"] = json!(target);
|
||||
let mut device = base.clone();
|
||||
device["name"] = json!("Office");
|
||||
// Commands refuse parameters that don't go together, so each key the doc names goes on its own too.
|
||||
let lower = doc.to_ascii_lowercase();
|
||||
let documented = PATH_KEYS.iter().filter(|key| **key == "path" || lower.contains(&key.to_ascii_lowercase()));
|
||||
let alone = documented.flat_map(|key| {
|
||||
[
|
||||
json!({*key: target}),
|
||||
json!({*key: target, "handles": [handle]}),
|
||||
json!({*key: target, "handle": table}),
|
||||
json!({*key: target, "name": "Office"}),
|
||||
]
|
||||
});
|
||||
let mut out = Vec::new();
|
||||
for v in [base, named, device].into_iter().chain(alone) {
|
||||
out.push(v.clone());
|
||||
for a in actions(doc) {
|
||||
let mut with = v.clone();
|
||||
with["action"] = json!(a);
|
||||
with["option"] = json!(a);
|
||||
out.push(with);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether a command's doc says it takes a file. These get every extension; the rest, one.
|
||||
fn takes_a_file(doc: &str) -> bool {
|
||||
let d = doc.to_ascii_lowercase();
|
||||
["path", "file", "template", "folder", "action", "option"].iter().any(|w| d.contains(w))
|
||||
}
|
||||
|
||||
/// A fresh drawing with a circle and a table, selected; the circle's and table's handles.
|
||||
fn seed(server: &mut Server) -> Option<(String, String)> {
|
||||
// Closed first: the walk starts tens of thousands of drawings, and they would all stay open.
|
||||
server.execute("closeall", json!({}))?;
|
||||
server.execute("new", json!({}))?;
|
||||
let handle_of = |text: &str| serde_json::from_str::<Value>(text).ok().and_then(|v| v["handle"].as_str().map(str::to_string)).unwrap_or_default();
|
||||
let circle = server.execute("circle", json!({"center": [0, 0], "radius": 1}))?;
|
||||
let table = server.execute("table", json!({"at": [5, 5], "rows": 2, "columns": 2}))?;
|
||||
server.execute("selectall", json!({}))?;
|
||||
Some((handle_of(&circle), handle_of(&table)))
|
||||
}
|
||||
|
||||
/// What one walk saw.
|
||||
struct Walk {
|
||||
/// The command and the call that touched each file outside.
|
||||
escapes: BTreeMap<String, Vec<String>>,
|
||||
calls: usize,
|
||||
commands: usize,
|
||||
/// Calls that hung or stopped the server.
|
||||
lost: Vec<String>,
|
||||
sees_reads: bool,
|
||||
}
|
||||
|
||||
/// Run the walk, under `in` and `out` as roots or with no roots at all.
|
||||
fn walk(tag: &str, roots: bool) -> Walk {
|
||||
let mut f = Fixture::new(tag);
|
||||
let args = if roots {
|
||||
vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))]
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let cwd = f.outside.join("cwd");
|
||||
let config = f.outside.join("config");
|
||||
let start = |f: &mut Fixture| {
|
||||
let server = Server::start(&args, &cwd, &config);
|
||||
f.reset();
|
||||
server
|
||||
};
|
||||
let mut server = start(&mut f);
|
||||
let listed = server.tool("list_commands", json!({})).expect("list_commands");
|
||||
let specs: Vec<Value> = serde_json::from_str(&listed).expect("the command list");
|
||||
assert!(specs.len() > 400, "the walk has to see the registry: {} commands", specs.len());
|
||||
let mut result = Walk { escapes: BTreeMap::new(), calls: 0, commands: specs.len(), lost: Vec::new(), sees_reads: f.sees_reads };
|
||||
|
||||
let mut steps: Vec<(String, Value)> = Vec::new();
|
||||
let o = f.outside.clone();
|
||||
let canary = |ext: &str| s(&o.join(format!("canary.{ext}")));
|
||||
let (circle, table) = seed(&mut server).expect("seed");
|
||||
assert!(!circle.is_empty(), "the seed circle has no handle");
|
||||
assert!(!table.is_empty(), "the seed table has no handle");
|
||||
for spec in &specs {
|
||||
let id = spec["id"].as_str().unwrap().to_string();
|
||||
let doc = spec["params"].as_str().unwrap_or_default();
|
||||
let mut targets: Vec<String> = if takes_a_file(doc) { EXTENSIONS.iter().map(|e| canary(e)).collect() } else { vec![canary("dxf")] };
|
||||
if takes_a_file(doc) {
|
||||
// A file that isn't there yet, in a folder that isn't there yet, and a relative path.
|
||||
targets.extend(["dxf", "png", "pdf", "csv"].iter().map(|e| s(&o.join(format!("fresh/x.{e}")))));
|
||||
targets.push("../canary.dxf".to_string());
|
||||
}
|
||||
for target in targets {
|
||||
for v in variants(doc, &target, &circle, &table) {
|
||||
steps.push((id.clone(), v));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let run_step =
|
||||
|server: &mut Server, f: &mut Fixture, result: &mut Walk, id: &str, label: String, call: &mut dyn FnMut(&mut Server) -> Option<String>| {
|
||||
result.calls += 1;
|
||||
let done = call(server);
|
||||
let touched = f.touched();
|
||||
if !touched.is_empty() {
|
||||
for what in touched {
|
||||
result.escapes.entry(id.to_string()).or_default().push(format!("{what}: {label}"));
|
||||
}
|
||||
}
|
||||
if done.is_none() {
|
||||
result.lost.push(format!("{id}: {label}"));
|
||||
}
|
||||
done.is_some()
|
||||
};
|
||||
|
||||
for (id, params) in &steps {
|
||||
let label = params.to_string();
|
||||
let params = params.clone();
|
||||
let alive = run_step(&mut server, &mut f, &mut result, id, label, &mut |sv| sv.execute(id, params.clone()));
|
||||
let dirty = !f.touched().is_empty();
|
||||
if !alive {
|
||||
server = start(&mut f);
|
||||
} else if dirty {
|
||||
f.reset();
|
||||
}
|
||||
// A command can stop the server without its own reply being lost.
|
||||
if seed(&mut server).is_none() {
|
||||
result.lost.push(format!("after {id}: {params}"));
|
||||
server = start(&mut f);
|
||||
seed(&mut server);
|
||||
}
|
||||
}
|
||||
|
||||
// The ways in that aren't one command with a path parameter.
|
||||
let dxf = canary("dxf");
|
||||
let png = canary("png");
|
||||
let scr = canary("scr");
|
||||
let lsp = canary("lsp");
|
||||
let tools: Vec<(&str, &str, Value)> = vec![
|
||||
("tool:open", "open", json!({"path": dxf})),
|
||||
("tool:save", "save", json!({"path": dxf})),
|
||||
("tool:save-new", "save", json!({"path": s(&o.join("fresh/y.dxf"))})),
|
||||
("tool:render", "render", json!({"path": png})),
|
||||
("tool:command_line", "command_line", json!({"text": format!("SCRIPT {scr}")})),
|
||||
("tool:command_line", "command_line", json!({"text": format!("OPEN {dxf}")})),
|
||||
("tool:command_line", "command_line", json!({"text": format!("SAVEAS {dxf}")})),
|
||||
("tool:script", "script", json!({"text": format!("OPEN {dxf}\n")})),
|
||||
];
|
||||
for (label, name, a) in tools {
|
||||
let text = a.to_string();
|
||||
let a = a.clone();
|
||||
let alive = run_step(&mut server, &mut f, &mut result, label, text, &mut |sv| sv.tool(name, a.clone()));
|
||||
if alive {
|
||||
f.reset();
|
||||
} else {
|
||||
server = start(&mut f);
|
||||
}
|
||||
seed(&mut server);
|
||||
}
|
||||
let lisp = [
|
||||
format!("(setq f (open {dxf:?} \"r\")) (read-line f) (close f)"),
|
||||
format!("(setq f (open {dxf:?} \"w\")) (write-line \"x\" f) (close f)"),
|
||||
format!("(setq f (open {:?} \"w\")) (write-line \"x\" f) (close f)", s(&o.join("new.txt"))),
|
||||
format!("(load {lsp:?})"),
|
||||
];
|
||||
for code in lisp {
|
||||
let label = code.clone();
|
||||
run_step(&mut server, &mut f, &mut result, "lisp:code", label, &mut |sv| sv.execute("lisp", json!({"code": code})));
|
||||
f.reset();
|
||||
seed(&mut server);
|
||||
}
|
||||
// Settings that name a file or a folder, then the commands that use them.
|
||||
let chained: Vec<(&str, Vec<(&str, Value)>)> = vec![
|
||||
(
|
||||
"stylesmanager",
|
||||
vec![
|
||||
("stylesmanager", json!({"action": "new", "name": "walk.ctb"})),
|
||||
("stylesmanager", json!({"action": "save", "name": "walk.ctb", "path": canary("ctb")})),
|
||||
("stylesmanager", json!({"action": "load", "path": canary("ctb")})),
|
||||
],
|
||||
),
|
||||
(
|
||||
"pdfbook",
|
||||
vec![("pline", json!({"points": [[0, 0], [210, 0], [210, 297], [0, 297]], "closed": true})), ("pdfbook", json!({"path": canary("pdf")}))],
|
||||
),
|
||||
("setvar:SAVEFILEPATH", vec![("setvar", json!({"name": "SAVEFILEPATH", "value": s(&o.join("recover"))})), ("drawingrecovery", json!({}))]),
|
||||
("setvar:QNEWTEMPLATE", vec![("setvar", json!({"name": "QNEWTEMPLATE", "value": dxf})), ("new", json!({}))]),
|
||||
];
|
||||
for (label, calls) in chained {
|
||||
for (id, params) in calls {
|
||||
run_step(&mut server, &mut f, &mut result, label, format!("{id} {params}"), &mut |sv| sv.execute(id, params.clone()));
|
||||
}
|
||||
f.reset();
|
||||
seed(&mut server);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// One line saying what a walk saw.
|
||||
fn summary(w: &Walk) -> String {
|
||||
format!(
|
||||
"{} commands, {} calls, reads seen: {}, {} commands touched files outside, {} calls lost the server",
|
||||
w.commands,
|
||||
w.calls,
|
||||
w.sees_reads,
|
||||
w.escapes.len(),
|
||||
w.lost.len()
|
||||
)
|
||||
}
|
||||
|
||||
/// Under roots, nothing in the registry reaches a file outside them.
|
||||
#[test]
|
||||
fn no_command_escapes_the_roots() {
|
||||
let w = walk("roots", true);
|
||||
println!("under roots: {}", summary(&w));
|
||||
let found: Vec<String> = w.escapes.iter().flat_map(|(id, what)| what.iter().take(3).map(move |l| format!("{id}: {l}"))).collect();
|
||||
assert!(found.is_empty(), "escapes under the roots:\n{}", found.join("\n"));
|
||||
assert!(w.lost.is_empty(), "calls that lost the server: {:?}", w.lost);
|
||||
}
|
||||
|
||||
/// The control: without roots the same walk finds these commands reaching the same files. If this
|
||||
/// fails, the walk has stopped reaching them and [`no_command_escapes_the_roots`] proves nothing.
|
||||
#[test]
|
||||
fn the_walk_finds_escapes_without_roots() {
|
||||
let w = walk("control", false);
|
||||
println!("without roots: {}", summary(&w));
|
||||
let found: BTreeSet<&str> = w.escapes.keys().map(String::as_str).collect();
|
||||
println!("touched files outside: {}", found.iter().copied().collect::<Vec<_>>().join(" "));
|
||||
let writers = [
|
||||
"saveas",
|
||||
"export",
|
||||
"plot",
|
||||
"exportpdf",
|
||||
"publish",
|
||||
"pdfbook",
|
||||
"wblock",
|
||||
"-wblock",
|
||||
"layout.saveas",
|
||||
"layout",
|
||||
"stylesmanager",
|
||||
"tableexport",
|
||||
"dataextraction",
|
||||
"tool:save",
|
||||
"tool:save-new",
|
||||
"tool:render",
|
||||
"lisp:code",
|
||||
];
|
||||
// What a command touched is kept with its kind (`wrote`, `created`, `removed`, `read`): a writer
|
||||
// must show a write, not just a read, or a writer that only reads would still pass.
|
||||
let kinds = |id: &str, kinds: &[&str]| w.escapes.get(id).is_some_and(|e| e.iter().any(|l| kinds.iter().any(|k| l.starts_with(k))));
|
||||
let not_writing: Vec<&str> = writers.into_iter().filter(|id| !kinds(id, &["wrote ", "created ", "removed "])).collect();
|
||||
assert!(not_writing.is_empty(), "the walk no longer finds these writing outside: {not_writing:?}; touched: {:?}", w.escapes);
|
||||
if w.sees_reads {
|
||||
for id in [
|
||||
"open",
|
||||
"new",
|
||||
"recover",
|
||||
"script",
|
||||
"import",
|
||||
"insert",
|
||||
"minsert",
|
||||
"xattach",
|
||||
"-xref",
|
||||
"compare",
|
||||
"imageattach",
|
||||
"attach",
|
||||
"aliasedit",
|
||||
"linetype",
|
||||
"hatch.patterns",
|
||||
"plottermanager",
|
||||
"appload",
|
||||
"datalink",
|
||||
"tool:open",
|
||||
"setvar:QNEWTEMPLATE",
|
||||
"setvar:SAVEFILEPATH",
|
||||
] {
|
||||
assert!(kinds(id, &["read "]), "the walk no longer finds `{id}` reading outside: {found:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A drawing inside the roots can't bring in what it names outside them: an image or an xref saved
|
||||
/// with a path outside stays unloaded, and nothing outside is read.
|
||||
#[test]
|
||||
fn a_drawing_cannot_reach_files_it_names_outside_the_roots() {
|
||||
let mut f = Fixture::new("named");
|
||||
let host = f.base.join("in/host.dxf");
|
||||
{
|
||||
// Made without roots: a drawing someone hands the agent.
|
||||
let mut free = Server::start(&[], &f.outside.join("cwd"), &f.outside.join("config"));
|
||||
free.execute("new", json!({})).unwrap();
|
||||
let image = free.execute("imageattach", json!({"path": s(&f.outside.join("canary.png"))})).unwrap();
|
||||
assert!(image.contains("handle"), "the image attaches: {image}");
|
||||
let second = free.execute("imageattach", json!({"path": s(&f.outside.join("second.png"))})).unwrap();
|
||||
assert!(second.contains("handle"), "the second image attaches: {second}");
|
||||
let xref = free.execute("xattach", json!({"path": s(&f.outside.join("canary.dxf")), "name": "walk"})).unwrap();
|
||||
assert!(xref.contains("handle"), "the xref attaches: {xref}");
|
||||
free.execute("saveas", json!({"path": s(&host)})).unwrap();
|
||||
}
|
||||
let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))];
|
||||
let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config"));
|
||||
f.reset();
|
||||
let opened = server.tool("open", json!({"path": s(&host)})).unwrap();
|
||||
let images = server.execute("image", json!({})).unwrap();
|
||||
let xrefs = server.execute("xref", json!({})).unwrap();
|
||||
server.tool_ok("render", json!({}));
|
||||
let touched = f.touched();
|
||||
assert!(touched.is_empty(), "{touched:?}\nopen: {opened}\nimage: {images}\nxref: {xrefs}");
|
||||
assert!(images.contains("canary.png") && !images.contains("\"Loaded\""), "the image stays unloaded: {images}");
|
||||
assert!(images.contains("\"foundAt\": null") || images.contains("\"foundAt\":null"), "and it isn't said to exist: {images}");
|
||||
assert!(!xrefs.contains("\"Loaded\""), "the xref stays unloaded: {xrefs}");
|
||||
}
|
||||
|
||||
/// A font linked into the drawing's folder isn't read from where the link leads.
|
||||
#[test]
|
||||
fn a_font_linked_beside_a_drawing_is_not_followed_out() {
|
||||
let mut f = Fixture::new("font");
|
||||
let host = f.base.join("in/host.dxf");
|
||||
{
|
||||
let mut free = Server::start(&[], &f.outside.join("cwd"), &f.outside.join("config"));
|
||||
free.execute("new", json!({})).unwrap();
|
||||
free.execute("style", json!({"name": "Walk", "font": "walkfont.shx"})).unwrap();
|
||||
free.execute("style.current", json!({"name": "Walk"})).unwrap();
|
||||
let text = free.execute("text", json!({"at": [0, 0], "height": 5, "text": "walk"})).unwrap();
|
||||
assert!(text.contains("handle"), "the text is drawn: {text}");
|
||||
free.execute("saveas", json!({"path": s(&host)})).unwrap();
|
||||
}
|
||||
let saved = std::fs::read_to_string(&host).unwrap();
|
||||
assert!(saved.to_ascii_lowercase().contains("walkfont.shx"), "the drawing names the font");
|
||||
std::fs::write(f.outside.join("walkfont.shx"), b"AutoCAD-86 shapes 1.0").unwrap();
|
||||
std::os::unix::fs::symlink(f.outside.join("walkfont.shx"), f.base.join("in/walkfont.shx")).unwrap();
|
||||
let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))];
|
||||
let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config"));
|
||||
f.reset();
|
||||
std::fs::write(f.outside.join("walkfont.shx"), b"AutoCAD-86 shapes 1.0").unwrap();
|
||||
f.watch();
|
||||
server.tool_ok("open", json!({"path": s(&host)}));
|
||||
server.tool_ok("render", json!({}));
|
||||
let touched = f.touched();
|
||||
assert!(touched.is_empty(), "{touched:?}");
|
||||
}
|
||||
|
||||
/// Saving through a link that stands outside the roots and points in doesn't leave a backup
|
||||
/// beside the link.
|
||||
#[test]
|
||||
fn a_backup_stays_inside_the_roots() {
|
||||
let f = Fixture::new("backup");
|
||||
let target = f.base.join("out/t.dxf");
|
||||
std::fs::write(&target, cadcraft_io::write(&cadcraft_engine::doc::Drawing::new_imperial(), "x.dxf").unwrap()).unwrap();
|
||||
let link = f.outside.join("link.dxf");
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))];
|
||||
let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config"));
|
||||
server.tool("new_drawing", json!({})).unwrap();
|
||||
let saved = server.tool("save", json!({"path": s(&link)})).unwrap();
|
||||
assert!(saved.contains("outside the write root"), "{saved}");
|
||||
assert!(!f.outside.join("link.dxf.bak").exists() && !f.outside.join("link.bak").exists(), "{saved}");
|
||||
}
|
||||
|
||||
/// Deleting a plotter acts on the entry in the settings folder, whatever it points at.
|
||||
#[test]
|
||||
fn a_plotter_link_outside_the_roots_is_not_removed() {
|
||||
let f = Fixture::new("plotter");
|
||||
let inside = f.base.join("out/kept.plotter.json");
|
||||
std::fs::write(&inside, cadcraft_engine::doc::PlotterConfig { name: "Kept".into(), ..Default::default() }.to_file_text()).unwrap();
|
||||
let entry = f.outside.join("config/plotters/Kept.plotter.json");
|
||||
std::os::unix::fs::symlink(&inside, &entry).unwrap();
|
||||
let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))];
|
||||
let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config"));
|
||||
let reply = server.execute("plottermanager", json!({"action": "delete", "name": "Kept"})).unwrap();
|
||||
assert!(std::fs::symlink_metadata(&entry).is_ok(), "the link is still there: {reply}");
|
||||
}
|
||||
|
||||
/// Without roots, a settings folder that can't be read leaves the built-in devices listed.
|
||||
#[test]
|
||||
fn without_roots_an_unreadable_settings_folder_still_lists_devices() {
|
||||
let f = Fixture::new("devices");
|
||||
let not_a_folder = f.outside.join("canary.txt");
|
||||
let mut server = Server::start(&[], &f.outside.join("cwd"), ¬_a_folder);
|
||||
let list = server.execute("plottermanager", json!({"action": "list"})).unwrap();
|
||||
assert!(list.contains("devices"), "{list}");
|
||||
}
|
||||
|
||||
/// A font beside a drawing inside the roots is still used.
|
||||
#[test]
|
||||
fn a_font_beside_a_drawing_inside_the_roots_is_used() {
|
||||
let f = Fixture::new("font-inside");
|
||||
let host = f.base.join("in/host.dxf");
|
||||
{
|
||||
let mut free = Server::start(&[], &f.outside.join("cwd"), &f.outside.join("config"));
|
||||
free.execute("new", json!({})).unwrap();
|
||||
free.execute("style", json!({"name": "Walk", "font": "walkinside.shx"})).unwrap();
|
||||
free.execute("style.current", json!({"name": "Walk"})).unwrap();
|
||||
free.execute("text", json!({"at": [0, 0], "height": 5, "text": "walk"})).unwrap();
|
||||
free.execute("saveas", json!({"path": s(&host)})).unwrap();
|
||||
}
|
||||
let font = f.base.join("in/walkinside.shx");
|
||||
std::fs::write(&font, b"AutoCAD-86 shapes 1.0").unwrap();
|
||||
age_access_time(&font);
|
||||
let before = std::fs::metadata(&font).unwrap().accessed().unwrap();
|
||||
let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))];
|
||||
let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config"));
|
||||
server.tool_ok("open", json!({"path": s(&host)}));
|
||||
server.tool_ok("render", json!({}));
|
||||
if f.sees_reads {
|
||||
assert_ne!(std::fs::metadata(&font).unwrap().accessed().unwrap(), before, "the font was read");
|
||||
}
|
||||
}
|
||||
|
||||
/// One font that is a link leading out doesn't cost the drawing the other fonts beside it, and
|
||||
/// nothing outside is touched.
|
||||
#[test]
|
||||
fn a_font_link_leading_out_does_not_cost_the_fonts_beside_it() {
|
||||
let mut f = Fixture::new("font-mixed");
|
||||
let host = f.base.join("in/host.dxf");
|
||||
{
|
||||
let mut free = Server::start(&[], &f.outside.join("cwd"), &f.outside.join("config"));
|
||||
free.execute("new", json!({})).unwrap();
|
||||
for (style, font) in [("Good", "walkgood.shx"), ("Bad", "walkbad.shx")] {
|
||||
free.execute("style", json!({"name": style, "font": font})).unwrap();
|
||||
free.execute("style.current", json!({"name": style})).unwrap();
|
||||
free.execute("text", json!({"at": [0, 0], "height": 5, "text": style})).unwrap();
|
||||
}
|
||||
free.execute("saveas", json!({"path": s(&host)})).unwrap();
|
||||
}
|
||||
let good = f.base.join("in/walkgood.shx");
|
||||
std::fs::write(&good, b"AutoCAD-86 shapes 1.0").unwrap();
|
||||
age_access_time(&good);
|
||||
let before = std::fs::metadata(&good).unwrap().accessed().unwrap();
|
||||
let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))];
|
||||
let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config"));
|
||||
f.reset();
|
||||
std::fs::write(f.outside.join("walkbad.shx"), b"AutoCAD-86 shapes 1.0").unwrap();
|
||||
std::os::unix::fs::symlink(f.outside.join("walkbad.shx"), f.base.join("in/walkbad.shx")).unwrap();
|
||||
f.watch();
|
||||
server.tool_ok("open", json!({"path": s(&host)}));
|
||||
server.tool_ok("render", json!({}));
|
||||
let touched = f.touched();
|
||||
assert!(touched.is_empty(), "{touched:?}");
|
||||
if f.sees_reads {
|
||||
assert_ne!(std::fs::metadata(&good).unwrap().accessed().unwrap(), before, "the good font was read");
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixture leaves the server's working directory in place, so a relative path meets the roots
|
||||
/// and not a folder that has gone.
|
||||
#[test]
|
||||
fn a_relative_path_is_refused_by_the_roots() {
|
||||
let mut f = Fixture::new("relative");
|
||||
let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))];
|
||||
let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config"));
|
||||
f.reset();
|
||||
let reply = server.tool("open", json!({"path": "../canary.dxf"})).unwrap();
|
||||
assert!(reply.contains("outside the read root"), "{reply}");
|
||||
let touched = f.touched();
|
||||
assert!(touched.is_empty(), "{touched:?}");
|
||||
}
|
||||
@@ -20,6 +20,8 @@ cadcraft-mcp = { workspace = true }
|
||||
eframe = { workspace = true, features = ["clipboard", "wgpu", "accesskit", "wayland", "x11", "links", "persistence"] }
|
||||
egui = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
# The control request parser reads only its own keys (control_server.rs `Fields`).
|
||||
serde = { workspace = true }
|
||||
log = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
@@ -221,12 +221,17 @@ fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize, h
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest request `id` (it is copied into the reply).
|
||||
const MAX_ID_BYTES: usize = 4096;
|
||||
|
||||
/// One request line, parsed.
|
||||
enum Line {
|
||||
enum Line<'a> {
|
||||
Request {
|
||||
id: Value,
|
||||
method: String,
|
||||
params: Value,
|
||||
/// Left as text until the token is checked: decoding it first would let an unauthenticated
|
||||
/// peer turn a flat array into many owned JSON values.
|
||||
params: Option<&'a serde_json::value::RawValue>,
|
||||
token: Option<String>,
|
||||
},
|
||||
Blank,
|
||||
@@ -235,7 +240,7 @@ enum Line {
|
||||
}
|
||||
|
||||
/// Parse a UTF-8 JSON request and its optional token, distinguishing blank lines from rejected input.
|
||||
fn parse_line(bytes: &[u8]) -> Line {
|
||||
fn parse_line(bytes: &[u8]) -> Line<'_> {
|
||||
let Ok(text) = std::str::from_utf8(bytes) else {
|
||||
return Line::Reject("not a control request (invalid UTF-8); closing the connection".into());
|
||||
};
|
||||
@@ -246,22 +251,78 @@ fn parse_line(bytes: &[u8]) -> Line {
|
||||
if is_http_request_line(text) {
|
||||
return Line::Reject("HTTP is not served here: this port takes JSON lines; closing the connection".into());
|
||||
}
|
||||
let msg = match serde_json::from_str::<Value>(text) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return Line::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")),
|
||||
};
|
||||
let Value::Object(mut obj) = msg else {
|
||||
// Checked without building values; then only the object's own keys are read, each value kept as text.
|
||||
if let Err(e) = serde_json::from_str::<&serde_json::value::RawValue>(text) {
|
||||
return Line::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection"));
|
||||
}
|
||||
let Ok(obj) = serde_json::from_str::<Fields<'_>>(text) else {
|
||||
return Line::Reject("not a control request (expected a JSON object); closing the connection".into());
|
||||
};
|
||||
let Some(Value::String(method)) = obj.remove("method") else {
|
||||
// `method` and `token` are decoded as strings only (anything else is no string); `id` is echoed back
|
||||
// in replies, so it is decoded but bounded.
|
||||
let string = |v: Option<&serde_json::value::RawValue>| v.and_then(|r| serde_json::from_str::<String>(r.get()).ok());
|
||||
let Some(method) = string(obj.method) else {
|
||||
return Line::Reject("not a control request (missing string `method`); closing the connection".into());
|
||||
};
|
||||
// Moved out of the parsed object, not cloned: `params` can be most of the line.
|
||||
Line::Request {
|
||||
id: obj.remove("id").unwrap_or(Value::Null),
|
||||
method,
|
||||
params: obj.remove("params").unwrap_or(json!({})),
|
||||
token: obj.remove("token").and_then(|t| if let Value::String(t) = t { Some(t) } else { None }),
|
||||
let id = match obj.id {
|
||||
None => Value::Null,
|
||||
Some(r) if r.get().len() <= MAX_ID_BYTES => match serde_json::from_str(r.get()) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return Line::Reject(format!("bad `id` ({e}); closing the connection")),
|
||||
},
|
||||
Some(_) => return Line::Reject(format!("`id` is longer than {MAX_ID_BYTES} bytes; closing the connection")),
|
||||
};
|
||||
Line::Request { id, method, params: obj.params, token: string(obj.token) }
|
||||
}
|
||||
|
||||
/// The request object's own keys, each value kept as JSON text. Other keys are skipped without
|
||||
/// being stored: collecting them (in a map) would let an unauthenticated peer turn a line of many
|
||||
/// short distinct keys into many owned strings and map nodes. A repeated key takes the last value.
|
||||
#[derive(Default)]
|
||||
struct Fields<'a> {
|
||||
id: Option<&'a serde_json::value::RawValue>,
|
||||
method: Option<&'a serde_json::value::RawValue>,
|
||||
params: Option<&'a serde_json::value::RawValue>,
|
||||
token: Option<&'a serde_json::value::RawValue>,
|
||||
}
|
||||
|
||||
impl<'de> serde::Deserialize<'de> for Fields<'de> {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(field_identifier, rename_all = "lowercase")]
|
||||
enum Key {
|
||||
Id,
|
||||
Method,
|
||||
Params,
|
||||
Token,
|
||||
#[serde(other)]
|
||||
Other,
|
||||
}
|
||||
struct Object;
|
||||
impl<'de> serde::de::Visitor<'de> for Object {
|
||||
type Value = Fields<'de>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("a JSON object")
|
||||
}
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let mut fields = Fields::default();
|
||||
while let Some(key) = map.next_key::<Key>()? {
|
||||
let slot = match key {
|
||||
Key::Id => &mut fields.id,
|
||||
Key::Method => &mut fields.method,
|
||||
Key::Params => &mut fields.params,
|
||||
Key::Token => &mut fields.token,
|
||||
Key::Other => {
|
||||
map.next_value::<serde::de::IgnoredAny>()?;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
*slot = Some(map.next_value()?);
|
||||
}
|
||||
Ok(fields)
|
||||
}
|
||||
}
|
||||
d.deserialize_map(Object)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,6 +366,16 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
|
||||
let _ = writeln!(out, "{r}");
|
||||
break;
|
||||
}
|
||||
// Absent `params` is `{}`; ones that cannot be decoded (an unpaired surrogate escape) are an
|
||||
// error, not a request run with defaults.
|
||||
let params = match params.map(|r| serde_json::from_str::<Value>(r.get())) {
|
||||
None => json!({}),
|
||||
Some(Ok(v)) => v,
|
||||
Some(Err(e)) => {
|
||||
let _ = writeln!(out, "{}", json!({"ok": false, "error": format!("bad params ({e}); closing the connection"), "id": id}));
|
||||
break;
|
||||
}
|
||||
};
|
||||
let (req, pending) = ControlRequest::new(method, params);
|
||||
let mut r = match tx.try_send(req) {
|
||||
Ok(()) => {
|
||||
@@ -372,6 +443,36 @@ mod tests {
|
||||
assert_eq!(input.len(), 100 - 11, "the rest of the line is left unread");
|
||||
}
|
||||
|
||||
/// The parameters stay text until the token is checked, and a request decodes as before.
|
||||
#[test]
|
||||
fn params_are_decoded_only_as_text_by_the_parser() {
|
||||
let line = br#"{"id":7,"method":"m","token":"t","params":[1,2,{"a":[3]}],"extra":null}"#;
|
||||
let Line::Request { id, method, params, token } = parse_line(line) else { panic!("a request") };
|
||||
assert_eq!((id, method.as_str(), token.as_deref()), (json!(7), "m", Some("t")));
|
||||
assert_eq!(params.map(|p| p.get()), Some(r#"[1,2,{"a":[3]}]"#));
|
||||
assert!(matches!(parse_line(b"[1,2,3]"), Line::Reject(e) if e.contains("expected a JSON object")));
|
||||
assert!(matches!(parse_line(b"{\"method\":"), Line::Reject(e) if e.contains("bad JSON")));
|
||||
assert!(matches!(parse_line(br#"{"id":[1],"method":5}"#), Line::Reject(e) if e.contains("missing string `method`")));
|
||||
let long_id = format!(r#"{{"id":"{}","method":"m"}}"#, "x".repeat(MAX_ID_BYTES));
|
||||
assert!(matches!(parse_line(long_id.as_bytes()), Line::Reject(e) if e.contains("`id` is longer")));
|
||||
assert!(matches!(parse_line(br#"{"id":"\ud800","method":"m"}"#), Line::Reject(e) if e.contains("bad `id`")));
|
||||
assert!(matches!(parse_line(br#"{"id":1}"#), Line::Reject(e) if e.contains("missing string `method`")));
|
||||
}
|
||||
|
||||
/// Keys other than the request's own are skipped, not kept, however many there are; a repeated
|
||||
/// key still takes the last value, and an escaped key name is the same key.
|
||||
#[test]
|
||||
fn unknown_keys_are_skipped_and_the_last_repeated_key_wins() {
|
||||
let mut line = String::from(r#"{"method":"first","#);
|
||||
for i in 0..100_000 {
|
||||
line.push_str(&format!(r#""k{i}":{i},"#));
|
||||
}
|
||||
line.push_str(r#""method":"m","params":{"a":1},"params":[2],"token":"t"}"#);
|
||||
let Line::Request { id, method, params, token } = parse_line(line.as_bytes()) else { panic!("a request") };
|
||||
assert_eq!((id, method.as_str(), token.as_deref()), (Value::Null, "m", Some("t")));
|
||||
assert_eq!(params.map(|p| p.get()), Some("[2]"));
|
||||
}
|
||||
|
||||
fn held() -> Held {
|
||||
Held::new(Budget::new(usize::MAX))
|
||||
}
|
||||
|
||||
@@ -931,49 +931,11 @@ pub struct Ucs {
|
||||
pub y_axis: Vec3,
|
||||
}
|
||||
|
||||
/// A saved layer state (LAYERSTATE), as AutoCAD keeps one in the LAYER table's
|
||||
/// `ACAD_LAYERSTATES` dictionary.
|
||||
/// A saved layer state (LAYERSTATE).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct LayerState {
|
||||
pub name: String,
|
||||
pub layers: Vec<Layer>,
|
||||
/// The properties restoring sets ([`LayerState::ON`] …): AutoCAD's mask (group 91 of the
|
||||
/// state's XRECORD). Bits CADCraft doesn't use are kept as read.
|
||||
pub mask: u32,
|
||||
/// The layer restoring makes current; empty, or a layer the drawing doesn't have, leaves the
|
||||
/// current layer as it is (AutoCAD 2024, measured).
|
||||
pub current: String,
|
||||
/// Group 301 of the state's XRECORD: empty as AutoCAD 2024's -LAYER saves a state; a text a
|
||||
/// file holds there is kept.
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
impl Default for LayerState {
|
||||
fn default() -> Self {
|
||||
LayerState { name: String::new(), layers: Vec::new(), mask: LayerState::ALL, current: String::new(), description: String::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl LayerState {
|
||||
pub const ON: u32 = 1;
|
||||
pub const FROZEN: u32 = 2;
|
||||
pub const LOCKED: u32 = 4;
|
||||
pub const PLOT: u32 = 8;
|
||||
pub const VP_FREEZE_NEW: u32 = 16;
|
||||
pub const COLOR: u32 = 32;
|
||||
pub const LINETYPE: u32 = 64;
|
||||
pub const LINEWEIGHT: u32 = 128;
|
||||
pub const PLOT_STYLE: u32 = 256;
|
||||
pub const TRANSPARENCY: u32 = 1024;
|
||||
/// Every property: the mask of AutoCAD 2024's -LAYER stAte Save with its defaults (2047; bit
|
||||
/// 512, which no property toggles, is always set).
|
||||
pub const ALL: u32 = 2047;
|
||||
|
||||
/// A state of every property of `layers`, with `current` the layer restoring makes current.
|
||||
pub fn new(name: impl Into<String>, layers: Vec<Layer>, current: impl Into<String>) -> Self {
|
||||
LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// A named group of entities (GROUP).
|
||||
|
||||
@@ -27,10 +27,6 @@ mod edit;
|
||||
|
||||
/// Most preview entities drawn while the array is edited.
|
||||
const PREVIEW_LIMIT: usize = 2000;
|
||||
/// Most objects whose key points are searched for a Key point base point.
|
||||
const MAX_KEY_OBJECTS: usize = 10_000;
|
||||
/// The prompt after the Key point option of a base point.
|
||||
const KEY_POINT_PROMPT: &str = "Specify key point on source objects to use as base point";
|
||||
/// Keyword-only prompts: each typed token is matched on its own (no free text).
|
||||
const KEYWORDS: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
|
||||
|
||||
@@ -45,13 +41,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("arrayrect", "Rectangular Array", run_arrayrect)
|
||||
.menu(&["Modify", "Array", "Rectangular Array"])
|
||||
.params(
|
||||
"{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
|
||||
"{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
|
||||
)
|
||||
.interactive(|_| Ok(Box::new(RectM::default()))),
|
||||
CommandSpec::new("arraypolar", "Polar Array", run_arraypolar)
|
||||
.menu(&["Modify", "Array", "Polar Array"])
|
||||
.params(
|
||||
"{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
|
||||
"{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
|
||||
)
|
||||
.interactive(|_| Ok(Box::new(PolarM::default()))),
|
||||
CommandSpec::new("-array", "Array", classic::run_classic)
|
||||
@@ -250,45 +246,6 @@ fn bounds(d: &Drawing, hs: &[Handle]) -> Bounds2 {
|
||||
hs.iter().filter_map(|h| d.entity(*h).map(|e| cadcraft_doc::entity_bounds(d, e, 0))).fold(Bounds2::EMPTY, |a, b| a.union(&b))
|
||||
}
|
||||
|
||||
/// The key point of `ents`, placed by `m`, nearest `at`: one of their grips (end points,
|
||||
/// midpoints, centres, vertices, insertion points). `None` when they have none. More than
|
||||
/// [`MAX_KEY_OBJECTS`] objects are refused: searching only some could miss the nearest one.
|
||||
pub(crate) fn nearest_key_point<'a>(ents: impl Iterator<Item = &'a Entity>, m: &Mat3, at: Vec2) -> Result<Option<Vec2>> {
|
||||
if !at.is_finite() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut best: Option<(Vec2, f64)> = None;
|
||||
for (n, e) in ents.enumerate() {
|
||||
if n >= MAX_KEY_OBJECTS {
|
||||
return Err(other(format!("Too many objects to search for a key point (at most {MAX_KEY_OBJECTS}); specify a point.")));
|
||||
}
|
||||
let mut k = e.kind.clone();
|
||||
k.transform(m);
|
||||
for g in k.grips().into_iter().filter(|g| g.is_finite()) {
|
||||
let d = g.dist(at);
|
||||
if best.is_none_or(|(_, bd)| d < bd) {
|
||||
best = Some((g, d));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(best.map(|b| b.0))
|
||||
}
|
||||
|
||||
/// `keyPoint` of a JSON form: absent or null is none; anything else must be a point, rather than
|
||||
/// be taken as none and the base point found another way.
|
||||
pub(crate) fn key_point_param(cmd: &str, p: &Value) -> Result<Option<Vec2>> {
|
||||
match p.get("keyPoint") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(_) => point_param(p, "keyPoint").map(Some).ok_or_else(|| bad(cmd, "`keyPoint` must be a point [x, y]")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The key point of objects `hs` in the drawing nearest `at`.
|
||||
pub(crate) fn key_point_of(d: &Drawing, hs: &[Handle], at: Vec2) -> Result<Vec2> {
|
||||
nearest_key_point(hs.iter().filter_map(|h| d.entity(*h)).map(|e| &**e), &Mat3::IDENTITY, at)?
|
||||
.ok_or_else(|| other("The objects have no key point; specify a point."))
|
||||
}
|
||||
|
||||
/// The centre of the first object (the point a non-rotated polar copy is moved by).
|
||||
fn first_center(d: &Drawing, hs: &[Handle]) -> Option<Vec2> {
|
||||
hs.first().and_then(|h| d.entity(*h)).map(|e| cadcraft_doc::entity_bounds(d, e, 0).center()).filter(|c| c.is_finite())
|
||||
@@ -429,10 +386,9 @@ fn run_arrayrect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
row_elevation: f64_or(p, "rowElevation", 0.0),
|
||||
});
|
||||
let rs = f64_or(p, "rowSpacing", 1.0);
|
||||
let base = match (key_point_param("arrayrect", p)?, point_param(p, "base")) {
|
||||
(Some(k), _) => key_point_of(s.doc()?, &hs, k)?,
|
||||
(None, Some(b)) => b,
|
||||
(None, None) => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(),
|
||||
let base = match point_param(p, "base") {
|
||||
Some(b) => b,
|
||||
None => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(),
|
||||
};
|
||||
let p2 = params(kind, levels, f64_or(p, "levelSpacing", rs));
|
||||
let associative = bool_or(p, "associative", assoc_default(s));
|
||||
@@ -446,10 +402,7 @@ fn run_arraypolar(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let rows = count_or("arraypolar", p, "rows", 1)?;
|
||||
let levels = count_or("arraypolar", p, "levels", 1)?;
|
||||
check_size(s, n.saturating_mul(rows).saturating_mul(levels), hs.len())?;
|
||||
let base = match key_point_param("arraypolar", p)? {
|
||||
Some(k) => key_point_of(s.doc()?, &hs, k)?,
|
||||
None => point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c),
|
||||
};
|
||||
let base = point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c);
|
||||
let row_spacing = f64_or(p, "rowSpacing", 1.0);
|
||||
let fill = f64_or(p, "angle", 360.0);
|
||||
if !(fill.abs() >= 1e-9 && fill.abs() <= 360.0 + 1e-9) {
|
||||
@@ -550,8 +503,6 @@ enum RStage {
|
||||
Main,
|
||||
Assoc,
|
||||
Base,
|
||||
/// Base point: Key point (a grip of the source objects).
|
||||
BaseKey,
|
||||
/// COUnt: columns, then rows.
|
||||
CountCols,
|
||||
CountRows,
|
||||
@@ -712,7 +663,6 @@ impl Interactive for RectM {
|
||||
.default("eXit"),
|
||||
Assoc => assoc_prompt(self.assoc),
|
||||
Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
|
||||
BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
|
||||
CountCols | ColsCount => cols(),
|
||||
CountRows | RowsCount => rows(),
|
||||
SpaceCols => dist("Specify the distance between columns", self.cs).kw(&["Unit cell"]),
|
||||
@@ -762,12 +712,10 @@ impl Interactive for RectM {
|
||||
self.base = self.centroid;
|
||||
Main
|
||||
}
|
||||
(Base, Input::Keyword(_)) => BaseKey,
|
||||
(BaseKey, Input::Point(p)) => {
|
||||
self.base = key_point_of(s.doc()?, &self.objs, *p)?;
|
||||
Main
|
||||
(Base, Input::Keyword(_)) => {
|
||||
s.echo("Key points are not available yet; specify a point.");
|
||||
Base
|
||||
}
|
||||
(BaseKey, Input::Enter) => Base,
|
||||
(CountCols | ColsCount, _) => match count(&i, self.cols, max_count(s, self.rows.saturating_mul(self.levels), n))? {
|
||||
Some(c) => {
|
||||
self.cols = c;
|
||||
@@ -910,9 +858,6 @@ enum PStage {
|
||||
Main,
|
||||
Assoc,
|
||||
Base,
|
||||
/// Key point of the base point asked from the center prompt, or from the main prompt.
|
||||
CenterBaseKey,
|
||||
BaseKey,
|
||||
Items,
|
||||
Between,
|
||||
Fill,
|
||||
@@ -1089,7 +1034,6 @@ impl Interactive for PolarM {
|
||||
match self.stage {
|
||||
Center => Prompt::new("Specify center point of array", Accept::POINT).kw(&["Base point", "Axis of rotation"]),
|
||||
CenterBase | Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
|
||||
CenterBaseKey | BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
|
||||
Main => Prompt::new("Select grip to edit array", Accept::POINT)
|
||||
.kw(&["ASsociative", "Base point", "Items", "Angle between", "Fill angle", "ROWs", "Levels", "ROTate items", "eXit"])
|
||||
.default("eXit"),
|
||||
@@ -1148,14 +1092,10 @@ impl Interactive for PolarM {
|
||||
self.base = None;
|
||||
if stage == CenterBase { Center } else { Main }
|
||||
}
|
||||
(CenterBase, Input::Keyword(_)) => CenterBaseKey,
|
||||
(Base, Input::Keyword(_)) => BaseKey,
|
||||
(CenterBaseKey | BaseKey, Input::Point(p)) => {
|
||||
self.base = Some(key_point_of(s.doc()?, &self.objs, *p)?);
|
||||
if stage == CenterBaseKey { Center } else { Main }
|
||||
(CenterBase | Base, Input::Keyword(_)) => {
|
||||
s.echo("Key points are not available yet; specify a point.");
|
||||
stage
|
||||
}
|
||||
(CenterBaseKey, Input::Enter) => CenterBase,
|
||||
(BaseKey, Input::Enter) => Base,
|
||||
(Items, _) => match count(&i, self.items, max_count(s, self.rows.saturating_mul(self.levels), n))? {
|
||||
Some(c) => {
|
||||
self.items = c;
|
||||
|
||||
@@ -18,9 +18,7 @@ use super::super::helpers::v3;
|
||||
use super::super::machines::{SelOutcome, SelectPhase, number};
|
||||
use super::super::{CommandSpec, bad, bool_or, point_param, targets};
|
||||
|
||||
use super::{
|
||||
KEY_POINT_PROMPT, KEYWORDS, angle, check_size, count, fmt, key_point_of, key_point_param, nearest_key_point, nesting, other, yes, yes_no,
|
||||
};
|
||||
use super::{KEYWORDS, angle, check_size, count, fmt, nesting, other, yes, yes_no};
|
||||
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
@@ -28,7 +26,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("arrayedit", "Edit Array", run_arrayedit)
|
||||
.menu(&["Modify", "Object", "Array"])
|
||||
.params(
|
||||
"{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, keyPoint? ([x, y]: the new base point is the source objects' key point nearest it, on the item there), replace?.keyPoint? ([x, y]: the replacement objects' key point nearest it is their base point), source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}",
|
||||
"{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}",
|
||||
)
|
||||
.interactive(|_| Ok(Box::new(EditM::default()))),
|
||||
CommandSpec::new("arrayclose", "Close Array Editing", run_arrayclose)
|
||||
@@ -217,16 +215,6 @@ fn item_at(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Option<(u32, u32, u32)
|
||||
best.map(|b| b.0)
|
||||
}
|
||||
|
||||
/// ARRAYEDIT Key point: the key point of the source objects nearest `at`, with the objects as
|
||||
/// placed at the item under `at` (within `tol`).
|
||||
fn source_key_point(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Result<Vec2> {
|
||||
let item = item_at(d, h, at, tol).ok_or_else(|| other("No array item there; specify a point on an item of the array."))?;
|
||||
let (ins, blk, p) = array_of(d, h)?;
|
||||
let src = d.block(&p.source).ok_or_else(|| other("The array's source block is missing."))?;
|
||||
let m = ins.transform(blk.base.xy()).then_before(item_place(&p, item)?).then_before(Mat3::translate(-src.base.xy()));
|
||||
nearest_key_point(src.entities.iter().map(|e| e.as_ref()), &m, at)?.ok_or_else(|| other("The source objects have no key point; specify a point."))
|
||||
}
|
||||
|
||||
/// Move the base point of array `h` to world point `base` without moving the items.
|
||||
fn rebase(s: &mut Session, h: Handle, base: Vec2) -> Result<()> {
|
||||
let d = s.doc()?;
|
||||
@@ -355,9 +343,6 @@ fn close_source(s: &mut Session, save: bool) -> Result<Value> {
|
||||
|
||||
// ---------------- JSON ----------------
|
||||
|
||||
/// How far outside an item's extents a JSON `keyPoint` may be.
|
||||
const KEY_POINT_TOLERANCE: f64 = 1e-6;
|
||||
|
||||
fn item_param(v: &Value) -> Option<(u32, u32, u32)> {
|
||||
let a = v.as_array()?;
|
||||
let n = |k: usize| a.get(k).and_then(Value::as_u64).and_then(|x| u32::try_from(x).ok());
|
||||
@@ -464,7 +449,9 @@ fn fill_from_between(b: f64, items: u32) -> Result<f64> {
|
||||
fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let h = super::super::curves::handle_param(p, "handle").ok_or_else(|| bad("arrayedit", "`handle` (the array) is required"))?;
|
||||
refuse_while_editing(s)?;
|
||||
array_of(s.doc()?, h)?;
|
||||
let (ins, blk, _) = array_of(s.doc()?, h)?;
|
||||
let w = ins.transform(blk.base.xy());
|
||||
let to_local = w.inverse().ok_or_else(|| other("The array's scale is zero."))?;
|
||||
if bool_or(p, "reset", false) {
|
||||
let (_, _, mut a) = array_of(s.doc()?, h)?;
|
||||
a.replaced.clear();
|
||||
@@ -472,10 +459,7 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
if let Some(r) = p.get("replace").filter(|v| !v.is_null()) {
|
||||
let hs = targets(s, r)?;
|
||||
let base = match key_point_param("arrayedit", r)? {
|
||||
Some(k) => key_point_of(s.doc()?, &hs, k)?,
|
||||
None => point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default()),
|
||||
};
|
||||
let base = point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default());
|
||||
let name = block_from(s, h, &hs, base)?;
|
||||
let (_, _, mut a) = array_of(s.doc()?, h)?;
|
||||
match r.get("items") {
|
||||
@@ -493,13 +477,7 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(b) = point_param(p, "base") {
|
||||
rebase(s, h, b)?;
|
||||
}
|
||||
if let Some(k) = key_point_param("arrayedit", p)? {
|
||||
let at = source_key_point(s.doc()?, h, k, KEY_POINT_TOLERANCE)?;
|
||||
rebase(s, h, at)?;
|
||||
}
|
||||
// A new base point moves the array's insertion point: read `center` in its placement after.
|
||||
let (ins, blk, mut a) = array_of(s.doc()?, h)?;
|
||||
let to_local = ins.transform(blk.base.xy()).inverse().ok_or_else(|| other("The array's scale is zero."))?;
|
||||
let (_, _, mut a) = array_of(s.doc()?, h)?;
|
||||
let before = a.clone();
|
||||
apply_params(&mut a, p, &to_local)?;
|
||||
if a != before {
|
||||
@@ -529,8 +507,6 @@ enum Stage {
|
||||
Select,
|
||||
Main,
|
||||
Base,
|
||||
/// Base point: Key point (of the source objects).
|
||||
BaseKey,
|
||||
ColsCount,
|
||||
ColsSpace,
|
||||
ColsTotal,
|
||||
@@ -548,8 +524,6 @@ enum Stage {
|
||||
/// REPlace: objects, their base point, then the items to replace.
|
||||
RepSelect,
|
||||
RepBase,
|
||||
/// REPlace base point: Key point (of the replacement objects).
|
||||
RepKey,
|
||||
RepItems,
|
||||
/// Source: the item whose objects are placed for editing.
|
||||
SourceItem,
|
||||
@@ -685,7 +659,6 @@ impl Interactive for EditM {
|
||||
.kw(&["Source", "REPlace", "Base point", "Rows", "Columns", "Levels", "RESet", "eXit"])
|
||||
.default("eXit"),
|
||||
Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
|
||||
BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
|
||||
ColsCount => Prompt::new("Enter the number of columns", Accept::NUMBER).default(cols.to_string()),
|
||||
ColsSpace => dist("Specify the distance between columns", cs).kw(&["Total"]),
|
||||
ColsTotal => dist("Specify the distance between the first and last column", total(cols, cs)),
|
||||
@@ -714,7 +687,6 @@ impl Interactive for EditM {
|
||||
Rotate => Prompt::new("Rotate arrayed items?", KEYWORDS).kw(&["Yes", "No"]).default(yes(polar.as_ref().is_none_or(|k| k.rotate))),
|
||||
RepSelect => Prompt::new("Select replacement objects", Accept::SELECT),
|
||||
RepBase => Prompt::new("Select base point of replacement objects", Accept::POINT).kw(&["Key point"]).default("centroid"),
|
||||
RepKey => Prompt::new("Specify key point on replacement objects to use as base point", Accept::POINT),
|
||||
RepItems => Prompt::new("Select an item in array to replace", Accept::POINT).kw(&["Source objects"]),
|
||||
SourceItem => Prompt::new("Select item in array", Accept::POINT),
|
||||
}
|
||||
@@ -774,21 +746,10 @@ impl Interactive for EditM {
|
||||
}
|
||||
Main
|
||||
}
|
||||
(Base, Input::Keyword(_)) => BaseKey,
|
||||
(RepBase, Input::Keyword(_)) => RepKey,
|
||||
(BaseKey, Input::Point(p)) => {
|
||||
let tol = s.pixel_size() * s.settings.pickbox;
|
||||
let at = source_key_point(s.doc()?, h, *p, tol)?;
|
||||
rebase(s, h, at)?;
|
||||
Main
|
||||
(Base | RepBase, Input::Keyword(_)) => {
|
||||
s.echo("Key points are not available yet; specify a point.");
|
||||
stage
|
||||
}
|
||||
(BaseKey, Input::Enter) => Base,
|
||||
(RepKey, Input::Point(p)) => {
|
||||
let base = key_point_of(s.doc()?, &self.rep_objs, *p)?;
|
||||
self.rep_block = Some(block_from(s, h, &self.rep_objs.clone(), base)?);
|
||||
RepItems
|
||||
}
|
||||
(RepKey, Input::Enter) => RepBase,
|
||||
(ColsCount | Items, _) => match count(&i, c64, self.max_for(s, r64.saturating_mul(l64)))? {
|
||||
Some(n) => {
|
||||
let n = super::count32(n);
|
||||
|
||||
@@ -134,6 +134,7 @@ fn run_recover(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Write the report to the `.adt` file beside the saved drawing, held to the automation roots.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_audit_log(s: &Session, report: &crate::audit::Report) {
|
||||
let (path_str, title) = match s.state() {
|
||||
@@ -143,6 +144,10 @@ fn write_audit_log(s: &Session, report: &crate::audit::Report) {
|
||||
// An unsaved drawing has no folder of its own to hold the log.
|
||||
let Some(path) = &path_str else { return };
|
||||
let adt_path = std::path::PathBuf::from(path).with_extension("adt");
|
||||
if let Err(e) = crate::file_access::check_write(&adt_path) {
|
||||
log::warn!("AUDITCTL: not writing audit log {}: {e}", adt_path.display());
|
||||
return;
|
||||
}
|
||||
let content = report.format_adt(&title, path_str.as_deref());
|
||||
// Write through an exclusively-created temporary and rename over the companion path, so a
|
||||
// planted `.adt` symlink beside the drawing cannot redirect the report onto another file
|
||||
@@ -156,10 +161,13 @@ fn write_audit_log(s: &Session, report: &crate::audit::Report) {
|
||||
fn write_audit_log(_: &Session, _: &crate::audit::Report) {}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// The bytes of the file at `path`, once the automation roots allow reading it.
|
||||
fn read_path(cmd: &str, path: &str) -> Result<Vec<u8>> {
|
||||
crate::file_access::check_read(path).map_err(|e| bad(cmd, e))?;
|
||||
crate::capped_read::read_capped(std::path::Path::new(path), file::MAX_DRAWING_BYTES).map_err(|e| bad(cmd, format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
/// The bytes of the drawing at `path`, held to the automation roots.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn read_path(cmd: &str, _path: &str) -> Result<Vec<u8>> {
|
||||
Err(bad(cmd, "paths are not available on the web; pass `data`"))
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
use cadcraft_doc::color::Color;
|
||||
use cadcraft_doc::{AttribProps, Common, EntityKind, HAlign, Handle, Text, VAlign};
|
||||
use cadcraft_geom::Vec3;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::cmd::curves::KW;
|
||||
@@ -154,19 +153,6 @@ fn set_value(text: &mut Text, value: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move `text` so the point it is placed by lands on `to`: the alignment point of justified text,
|
||||
/// else the insertion point. Both points move by the same offset, so aligned and fit text keep the
|
||||
/// baseline between them.
|
||||
fn move_text(text: &mut Text, to: cadcraft_geom::Vec2) {
|
||||
let anchor = match text.align_pt {
|
||||
Some(ap) if !matches!((text.halign, text.valign), (HAlign::Left, VAlign::Baseline) | (HAlign::Aligned | HAlign::Fit, _)) => ap,
|
||||
_ => text.insert,
|
||||
};
|
||||
let d = Vec3::new(to.x - anchor.x, to.y - anchor.y, 0.0);
|
||||
text.insert = text.insert + d;
|
||||
text.align_pt = text.align_pt.map(|ap| ap + d);
|
||||
}
|
||||
|
||||
/// Change the properties set on attribute `k` of block reference `h`.
|
||||
fn set_props(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut AttribProps)) -> Result<()> {
|
||||
s.doc_mut()?.modify_entity(h, |e| {
|
||||
@@ -179,18 +165,6 @@ fn set_props(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut Attri
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Modify the attribute `k` of block reference `h`.
|
||||
fn modify_attrib(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut cadcraft_doc::Attrib)) -> Result<()> {
|
||||
s.doc_mut()?.modify_entity(h, |e| {
|
||||
if let EntityKind::Insert(ins) = &mut e.kind
|
||||
&& let Some(a) = ins.attribs.get_mut(k)
|
||||
{
|
||||
f(a);
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The layer and colour attribute `k` of block reference `h` is drawn with: its own, else its
|
||||
/// definition's (layer 0 is the reference's layer).
|
||||
fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)> {
|
||||
@@ -206,14 +180,6 @@ fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)
|
||||
Some((layer, c.color))
|
||||
}
|
||||
|
||||
/// The current text properties of attribute `k` of block reference `h`.
|
||||
fn current_text(s: &Session, (h, k): (Handle, usize)) -> Option<cadcraft_doc::Text> {
|
||||
let d = s.doc().ok()?;
|
||||
let e = d.entity(h)?;
|
||||
let EntityKind::Insert(ins) = &e.kind else { return None };
|
||||
ins.attribs.get(k).map(|a| a.text.clone())
|
||||
}
|
||||
|
||||
/// Replace every `find` in `value` with `with`, unless the result would be too long.
|
||||
fn replaced(value: &str, find: &str, with: &str) -> Option<String> {
|
||||
if find.is_empty() || !value.contains(find) {
|
||||
@@ -326,10 +292,6 @@ enum Stage {
|
||||
Select,
|
||||
/// One at a time: what to do with the current attribute.
|
||||
Option,
|
||||
Position,
|
||||
Height,
|
||||
Angle,
|
||||
Style,
|
||||
ValueKind,
|
||||
NewValue,
|
||||
Layer,
|
||||
@@ -403,7 +365,6 @@ impl Interactive for DashAtteditM {
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
let cur = self.items.get(self.cur).and_then(|it| current_props(s, *it));
|
||||
let cur_text = self.items.get(self.cur).and_then(|it| current_text(s, *it));
|
||||
match self.stage {
|
||||
Stage::OneAtATime => Prompt::new("Edit attributes one at a time?", KW).kw(&["Yes", "No"]).default("Y"),
|
||||
Stage::VisibleOnly => Prompt::new("Edit only attributes visible on screen?", KW).kw(&["Yes", "No"]).default("Y"),
|
||||
@@ -411,31 +372,7 @@ impl Interactive for DashAtteditM {
|
||||
Stage::TagSpec => Prompt::new("Enter attribute tag specification", Accept::TEXT).default("*"),
|
||||
Stage::ValueSpec => Prompt::new("Enter attribute value specification", Accept::TEXT).default("*"),
|
||||
Stage::Select => Prompt::new("Select attributes", Accept::SELECT),
|
||||
Stage::Option => {
|
||||
Prompt::new("Enter an option", KW).kw(&["Value", "Position", "Height", "Angle", "Style", "Layer", "Color", "Next"]).default("N")
|
||||
}
|
||||
Stage::Position => Prompt::new("Enter new text insertion point", Accept::POINT),
|
||||
Stage::Height => {
|
||||
let p = Prompt::new("Enter new text height", Accept::POINT_OR_NUMBER);
|
||||
match cur_text {
|
||||
Some(t) => p.default(format!("{:.4}", t.height)),
|
||||
None => p,
|
||||
}
|
||||
}
|
||||
Stage::Angle => {
|
||||
let p = Prompt::new("Enter new text rotation angle", Accept::POINT_OR_NUMBER);
|
||||
match cur_text {
|
||||
Some(t) => p.default(format!("{:.4}", t.rotation.to_degrees())),
|
||||
None => p,
|
||||
}
|
||||
}
|
||||
Stage::Style => {
|
||||
let p = Prompt::new("Enter new text style", Accept::TEXT);
|
||||
match cur_text {
|
||||
Some(t) => p.default(t.style),
|
||||
None => p,
|
||||
}
|
||||
}
|
||||
Stage::Option => Prompt::new("Enter an option", KW).kw(&["Value", "Layer", "Color", "Next"]).default("N"),
|
||||
Stage::ValueKind => Prompt::new("Enter type of value modification", KW).kw(&["Change", "Replace"]).default("R"),
|
||||
Stage::NewValue => Prompt::new("Enter new attribute value", Accept::TEXT),
|
||||
Stage::Layer => {
|
||||
@@ -509,10 +446,6 @@ impl Interactive for DashAtteditM {
|
||||
}
|
||||
Stage::Option => match &i {
|
||||
Input::Keyword(k) if k == "Value" => self.stage = Stage::ValueKind,
|
||||
Input::Keyword(k) if k == "Position" => self.stage = Stage::Position,
|
||||
Input::Keyword(k) if k == "Height" => self.stage = Stage::Height,
|
||||
Input::Keyword(k) if k == "Angle" => self.stage = Stage::Angle,
|
||||
Input::Keyword(k) if k == "Style" => self.stage = Stage::Style,
|
||||
Input::Keyword(k) if k == "Layer" => self.stage = Stage::Layer,
|
||||
Input::Keyword(k) if k == "Color" => self.stage = Stage::Color,
|
||||
Input::Keyword(_) | Input::Enter => {
|
||||
@@ -524,105 +457,14 @@ impl Interactive for DashAtteditM {
|
||||
}
|
||||
Input::Text(t) => {
|
||||
let tl = t.trim().to_ascii_lowercase();
|
||||
let opts = ["Value", "Position", "Height", "Angle", "Style", "Layer", "Color", "Next"];
|
||||
match opts.iter().find(|k| !tl.is_empty() && k.to_ascii_lowercase().starts_with(&tl)) {
|
||||
Some(&"Value") => self.stage = Stage::ValueKind,
|
||||
Some(&"Position") => self.stage = Stage::Position,
|
||||
Some(&"Height") => self.stage = Stage::Height,
|
||||
Some(&"Angle") => self.stage = Stage::Angle,
|
||||
Some(&"Style") => self.stage = Stage::Style,
|
||||
Some(&"Layer") => self.stage = Stage::Layer,
|
||||
Some(&"Color") => self.stage = Stage::Color,
|
||||
Some(&"Next") => {
|
||||
self.cur += 1;
|
||||
if self.cur >= self.items.len() {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
self.show_current(s);
|
||||
}
|
||||
_ => return Err(invalid_keyword()),
|
||||
}
|
||||
let later = ["Position", "Height", "Angle", "Style"];
|
||||
return match later.iter().find(|k| !tl.is_empty() && k.to_ascii_lowercase().starts_with(&tl)) {
|
||||
Some(k) => Err(EngineError::Other(format!("{k} is not available yet."))),
|
||||
None => Err(invalid_keyword()),
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Stage::Position => {
|
||||
let p = match i {
|
||||
Input::Point(p) => p,
|
||||
Input::Enter => {
|
||||
self.stage = Stage::Option;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
if let Some(it) = self.items.get(self.cur).copied() {
|
||||
modify_attrib(s, it, |a| move_text(&mut a.text, p))?;
|
||||
}
|
||||
self.stage = Stage::Option;
|
||||
}
|
||||
Stage::Height => {
|
||||
let h = match &i {
|
||||
Input::Point(p) => {
|
||||
let cur_pt = self.items.get(self.cur).and_then(|it| current_text(s, *it)).map(|t| t.insert.xy());
|
||||
match cur_pt {
|
||||
Some(base) => base.dist(*p).max(1e-9),
|
||||
None => p.len().max(1e-9),
|
||||
}
|
||||
}
|
||||
Input::Text(t) if !t.trim().is_empty() => crate::units::parse_distance(t.trim())
|
||||
.filter(|v| *v > 0.0)
|
||||
.ok_or_else(|| EngineError::Other("Requires a positive number.".into()))?,
|
||||
Input::Enter => {
|
||||
self.stage = Stage::Option;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
if let Some(it) = self.items.get(self.cur).copied() {
|
||||
modify_attrib(s, it, |a| {
|
||||
a.text.height = h;
|
||||
})?;
|
||||
}
|
||||
self.stage = Stage::Option;
|
||||
}
|
||||
Stage::Angle => {
|
||||
let ang = match &i {
|
||||
Input::Point(p) => {
|
||||
let cur_pt = self.items.get(self.cur).and_then(|it| current_text(s, *it)).map(|t| t.insert.xy());
|
||||
match cur_pt {
|
||||
Some(base) => base.angle_to(*p),
|
||||
None => p.y.atan2(p.x),
|
||||
}
|
||||
}
|
||||
Input::Text(t) if !t.trim().is_empty() => {
|
||||
s.angle_settings().direction(t.trim()).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?
|
||||
}
|
||||
Input::Enter => {
|
||||
self.stage = Stage::Option;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
if let Some(it) = self.items.get(self.cur).copied() {
|
||||
modify_attrib(s, it, |a| {
|
||||
a.text.rotation = ang;
|
||||
})?;
|
||||
}
|
||||
self.stage = Stage::Option;
|
||||
}
|
||||
Stage::Style => {
|
||||
let Some(t) = text else { return Ok(Step::Continue) };
|
||||
let t = t.trim();
|
||||
if !t.is_empty() {
|
||||
let st =
|
||||
s.doc()?.text_style(t).map(|st| st.name.clone()).ok_or_else(|| EngineError::Other(format!("Cannot find style \"{t}\".")))?;
|
||||
if let Some(it) = self.items.get(self.cur).copied() {
|
||||
modify_attrib(s, it, |a| {
|
||||
a.text.style = st;
|
||||
})?;
|
||||
}
|
||||
}
|
||||
self.stage = Stage::Option;
|
||||
}
|
||||
Stage::ValueKind => match &i {
|
||||
Input::Keyword(k) if k == "Change" => self.stage = Stage::Find,
|
||||
Input::Keyword(_) | Input::Enter => self.stage = Stage::NewValue,
|
||||
|
||||
@@ -260,9 +260,11 @@ fn csv(columns: &[String], rows: &[Vec<Cell>], sep: char) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// Write the extracted table to `path`, held to the automation roots.
|
||||
fn write_file(path: &str, text: &str) -> Result<()> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_write(path).map_err(EngineError::Other)?;
|
||||
std::fs::write(path, text).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -88,9 +88,11 @@ pub(super) fn read_drawing(path: &str) -> Result<Drawing> {
|
||||
Err(last.unwrap_or_else(|| bad("insert", format!("{path}: file not found"))))
|
||||
}
|
||||
|
||||
/// The bytes of the drawing to insert, held to the automation roots.
|
||||
fn read_file(_path: &str) -> Result<Vec<u8>> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_read(_path).map_err(|e| bad("insert", e))?;
|
||||
crate::capped_read::read_capped(std::path::Path::new(_path), crate::cmd::file::MAX_DRAWING_BYTES)
|
||||
.map_err(|e| bad("insert", format!("{_path}: {e}")))
|
||||
}
|
||||
|
||||
@@ -70,6 +70,8 @@ fn stamp(path: &str) -> Option<(u64, Option<SystemTime>)> {
|
||||
/// A library drawing, read once and kept while the file is as it was: placing a block must not
|
||||
/// parse the whole file again.
|
||||
fn cached_drawing(path: &str) -> Result<Arc<Drawing>> {
|
||||
// Before the cache too: a drawing read earlier must not be handed out past the roots.
|
||||
crate::file_access::check_read(path).map_err(|e| bad("blocklibrary", e))?;
|
||||
// The reader sniffs the bytes, so a DXF named `part.bin` would load: the contract is DWG/DXF by name.
|
||||
if !is_drawing(Path::new(path)) {
|
||||
return Err(bad("blocklibrary", format!("{path}: expected a DWG or DXF file")));
|
||||
@@ -186,6 +188,9 @@ pub fn read_library_file(path: &str) -> Result<Arc<Drawing>> {
|
||||
/// What BLOCKLIBRARY answers for `path`. It needs no session, so the palette reads big drawings
|
||||
/// and slow folders on a worker thread.
|
||||
pub fn list_library(path: &str) -> Result<Value> {
|
||||
// Before anything looks at the path: a folder's listing, or whether it is one, says what is
|
||||
// outside the automation roots.
|
||||
crate::file_access::check_read(path).map_err(|e| bad("blocklibrary", e))?;
|
||||
if is_folder(path) {
|
||||
let (files, truncated) = folder_files(Path::new(path))?;
|
||||
let list: Vec<Value> = files.iter().map(|(name, file)| json!({ "name": name, "file": file })).collect();
|
||||
@@ -356,6 +361,26 @@ fn run_libraries(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Under the automation roots a library folder or file outside them is refused before it is
|
||||
/// listed or read.
|
||||
#[test]
|
||||
fn the_automation_roots_hold_library_paths() {
|
||||
let base = std::env::temp_dir().join(format!("cadcraft-library-roots-{}", std::process::id()));
|
||||
let (inside, outside) = (base.join("in"), base.join("outside"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(outside.join("parts.dxf"), b"0\nEOF\n").unwrap();
|
||||
let roots = crate::file_access::AutomationRoots::new(Some(&inside), None).unwrap();
|
||||
crate::file_access::confine(roots.as_ref(), || {
|
||||
let folder = list_library(&outside.to_string_lossy()).map(|v| v.to_string());
|
||||
assert!(folder.as_ref().is_err_and(|e| e.to_string().contains("automation")), "{folder:?}");
|
||||
let file = list_library(&outside.join("parts.dxf").to_string_lossy()).map(|v| v.to_string());
|
||||
assert!(file.as_ref().is_err_and(|e| e.to_string().contains("automation")), "{file:?}");
|
||||
assert!(list_library(&inside.to_string_lossy()).is_ok());
|
||||
});
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A list that could not be written stays the list of this session, whatever the file says.
|
||||
#[test]
|
||||
fn a_failed_write_keeps_the_list_in_memory() {
|
||||
|
||||
@@ -105,6 +105,8 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
|
||||
let bytes = (hooks.write)(&d, path).map_err(|e| bad(cmd, e))?;
|
||||
// Through a temporary file, as SAVE writes, so a failed write keeps the file it replaces.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
let lost = if drops_unknown(path) { not_saved(&d) } else { BTreeMap::new() };
|
||||
Ok((d.model.len(), bytes.len(), lost))
|
||||
@@ -170,7 +172,9 @@ fn output_path(typed: &str) -> String {
|
||||
fn exists(path: &str) -> bool {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
std::path::Path::new(path).exists()
|
||||
// Outside the automation roots the answer would say whether a file is there; the write
|
||||
// that follows is refused anyway.
|
||||
crate::file_access::check_write(path).is_ok() && std::path::Path::new(path).exists()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
|
||||
@@ -408,6 +408,7 @@ fn run_xbind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "bound": bound }))
|
||||
}
|
||||
|
||||
/// Open the file a selected reference points at, as its own drawing.
|
||||
fn run_xopen(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = s.doc()?;
|
||||
let name = match str_param(p, "name") {
|
||||
@@ -429,6 +430,9 @@ fn run_xopen(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let file = load::find(&path, host.as_deref().map(std::path::Path::new), false).map_err(|m| match m {
|
||||
load::Missing::NotFound => bad("xopen", format!("{path}: file not found")),
|
||||
load::Missing::Refused(r) => bad("xopen", format!("{path}: not opened, {r}")),
|
||||
load::Missing::OutsideRoots => {
|
||||
bad("xopen", format!("{path}: not opened, automation path rejected: outside the read root (or the write root)"))
|
||||
}
|
||||
})?;
|
||||
s.execute("open", &json!({ "path": file.to_string_lossy() }))
|
||||
}
|
||||
|
||||
@@ -145,9 +145,12 @@ pub(crate) enum Missing {
|
||||
NotFound,
|
||||
/// The saved path isn't followed, and there is no file of its name beside the host.
|
||||
Refused(Refused),
|
||||
/// The automation roots don't reach the file ([`crate::file_access`]).
|
||||
OutsideRoots,
|
||||
}
|
||||
|
||||
impl Missing {
|
||||
/// The status and message a reference gets when its file can't be loaded.
|
||||
fn outcome(self, path: &str) -> (XrefStatus, String) {
|
||||
match self {
|
||||
Self::NotFound => {
|
||||
@@ -155,6 +158,9 @@ impl Missing {
|
||||
(XrefStatus::NotFound, format!("{path}: {why}"))
|
||||
}
|
||||
Self::Refused(r) => (XrefStatus::Unresolved, format!("{path}: not opened, {r}")),
|
||||
Self::OutsideRoots => {
|
||||
(XrefStatus::Unresolved, format!("{path}: not opened, automation path rejected: outside the read root (or the write root)"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,14 +214,36 @@ pub(crate) fn find(path: &str, host: Option<&Path>, chosen: bool) -> Result<Path
|
||||
return Err(Missing::NotFound);
|
||||
}
|
||||
let (files, refused) = candidates(path, host, chosen);
|
||||
// Outside the automation roots a place isn't even looked at, so the answer can't tell whether a
|
||||
// file is there. A match found by ignoring case is checked again: it can be a link leading out.
|
||||
let allowed = |p: &PathBuf| crate::file_access::check_read(p).is_ok();
|
||||
let looked_for = files.len();
|
||||
let files: Vec<PathBuf> = files.into_iter().filter(allowed).collect();
|
||||
let outside = files.len() < looked_for;
|
||||
// A match found by ignoring case that the roots refuse counts as outside them too.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let found = files.iter().find(|p| p.is_file()).cloned().or_else(|| files.iter().find_map(|p| case_insensitive(p)));
|
||||
let mut refused_match = false;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let found = files.iter().find(|p| p.is_file()).cloned().or_else(|| {
|
||||
files.iter().find_map(|p| {
|
||||
let c = match case_insensitive(p) {
|
||||
Ok(Some(c)) => c,
|
||||
Ok(None) => return None,
|
||||
Err(()) => {
|
||||
refused_match = true;
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let ok = allowed(&c);
|
||||
refused_match |= !ok;
|
||||
ok.then_some(c)
|
||||
})
|
||||
});
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let outside = outside || refused_match;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let found: Option<PathBuf> = {
|
||||
let _ = files;
|
||||
None
|
||||
};
|
||||
found.ok_or(refused.map_or(Missing::NotFound, Missing::Refused))
|
||||
let found: Option<PathBuf> = None;
|
||||
found.ok_or(if outside { Missing::OutsideRoots } else { refused.map_or(Missing::NotFound, Missing::Refused) })
|
||||
}
|
||||
|
||||
/// Upper bound on directory entries scanned per path component by [`case_insensitive`].
|
||||
@@ -225,10 +253,16 @@ const MAX_CASE_SCAN: usize = 10_000;
|
||||
/// The existing file `p` names when its letters' case is ignored, on file systems that don't
|
||||
/// ignore it themselves. Drawings made on Windows often store a reference as `PLAN.DWG` for
|
||||
/// `Plan.dwg`; Windows finds it, and so should Linux. Each missing component is matched against
|
||||
/// its folder's entries; an exact match always wins, and an ambiguous one finds nothing.
|
||||
/// its folder's entries; an exact match always wins, and an ambiguous one finds nothing. `Err` when
|
||||
/// the automation roots refuse a place it would have to look in.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn case_insensitive(p: &Path) -> Option<PathBuf> {
|
||||
fn case_insensitive(p: &Path) -> Result<Option<PathBuf>, ()> {
|
||||
use std::path::Component;
|
||||
// Under the automation roots a place is probed only when the roots allow it, or when it lies on
|
||||
// the way to `p` as it was spelled (which was checked): a name corrected to another case could be
|
||||
// a link leading out, and looking inside it would look outside the roots.
|
||||
let mut corrected = false;
|
||||
let probe = |q: &Path, corrected: bool| (!corrected && p.starts_with(q)) || crate::file_access::check_read(q).is_ok();
|
||||
let mut out = PathBuf::new();
|
||||
for c in p.components() {
|
||||
let Component::Normal(name) = c else {
|
||||
@@ -236,23 +270,27 @@ fn case_insensitive(p: &Path) -> Option<PathBuf> {
|
||||
continue;
|
||||
};
|
||||
let exact = out.join(name);
|
||||
if !probe(&exact, corrected) {
|
||||
return Err(());
|
||||
}
|
||||
if exact.exists() {
|
||||
out = exact;
|
||||
continue;
|
||||
}
|
||||
let want = name.to_str()?.to_lowercase();
|
||||
let mut hits = std::fs::read_dir(if out.as_os_str().is_empty() { Path::new(".") } else { &out })
|
||||
.ok()?
|
||||
.take(MAX_CASE_SCAN)
|
||||
.flatten()
|
||||
.filter(|e| e.file_name().to_str().is_some_and(|n| n.to_lowercase() == want));
|
||||
let hit = hits.next()?;
|
||||
let Some(want) = name.to_str().map(str::to_lowercase) else { return Ok(None) };
|
||||
let Ok(entries) = std::fs::read_dir(if out.as_os_str().is_empty() { Path::new(".") } else { &out }) else { return Ok(None) };
|
||||
let mut hits = entries.take(MAX_CASE_SCAN).flatten().filter(|e| e.file_name().to_str().is_some_and(|n| n.to_lowercase() == want));
|
||||
let Some(hit) = hits.next() else { return Ok(None) };
|
||||
if hits.next().is_some() {
|
||||
return None;
|
||||
return Ok(None);
|
||||
}
|
||||
out.push(hit.file_name());
|
||||
corrected = true;
|
||||
if !probe(&out, corrected) {
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
out.is_file().then_some(out)
|
||||
Ok(out.is_file().then_some(out))
|
||||
}
|
||||
|
||||
/// Read a drawing file through the host's io hooks, counting its bytes against the load's total.
|
||||
@@ -261,6 +299,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use std::io::Read;
|
||||
crate::file_access::check_read(file)?;
|
||||
let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes);
|
||||
let limit = MAX_XREF_BYTES.min(left);
|
||||
let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?;
|
||||
@@ -603,6 +642,48 @@ mod tests {
|
||||
assert_eq!(find("", Some(&host), false), Err(Missing::NotFound));
|
||||
}
|
||||
|
||||
/// A name corrected to another case is checked against the roots before it is looked inside, and a
|
||||
/// match they refuse leaves the other candidates to be tried.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_name_corrected_to_a_link_out_of_the_roots_is_not_looked_inside() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
let base = std::env::temp_dir().join(format!("cc-xref-case-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
for d in ["in/sub", "outside"] {
|
||||
std::fs::create_dir_all(base.join(d)).unwrap();
|
||||
}
|
||||
std::fs::write(base.join("outside/target.dxf"), "x").unwrap();
|
||||
std::fs::write(base.join("in/Mixed.dxf"), "x").unwrap();
|
||||
std::os::unix::fs::symlink(base.join("outside"), base.join("in/Alias")).unwrap();
|
||||
std::os::unix::fs::symlink(base.join("outside/target.dxf"), base.join("in/sub/Mixed.dxf")).unwrap();
|
||||
if base.join("in/alias").exists() {
|
||||
// A case-insensitive file system never needs a name corrected: nothing to test.
|
||||
eprintln!("skipped: this file system ignores case");
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
return;
|
||||
}
|
||||
let roots = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap();
|
||||
confine(Some(&roots), || {
|
||||
// `alias` isn't there but `Alias` is, a link out: the probe stops before looking in it.
|
||||
assert_eq!(case_insensitive(&base.join("in/alias/target.dxf")), Err(()));
|
||||
// A match that leaves the roots doesn't end the search: the next candidate is tried.
|
||||
let host = base.join("in/host.dxf");
|
||||
let found = find("sub/mixed.dxf", Some(&host), true).unwrap();
|
||||
assert_eq!(found, base.join("in/Mixed.dxf"));
|
||||
// With no other candidate it is still a refusal by the roots, not a missing file.
|
||||
std::fs::create_dir_all(base.join("in/lone")).unwrap();
|
||||
std::os::unix::fs::symlink(base.join("outside/target.dxf"), base.join("in/lone/Only.dxf")).unwrap();
|
||||
assert_eq!(find("lone/only.dxf", Some(&host), true), Err(Missing::OutsideRoots));
|
||||
});
|
||||
assert_eq!(
|
||||
case_insensitive(&base.join("in/alias/target.dxf")),
|
||||
Ok(Some(base.join("in/Alias/target.dxf"))),
|
||||
"without roots the link is followed"
|
||||
);
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefixes_ignore_case() {
|
||||
assert!(has_prefix("SITE|Walls", "site|"));
|
||||
|
||||
@@ -82,6 +82,7 @@ fn write_file(cmd: &str, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
{
|
||||
// Exclusively create a fresh temporary file and rename it into place so a planted
|
||||
// `<path>.cadcraft-tmp` symlink cannot redirect the export write (CWE-59).
|
||||
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
|
||||
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -201,9 +202,11 @@ fn import_drawing(s: &mut Session, src: &Drawing, at: Vec2, scale: f64, file: &s
|
||||
}))
|
||||
}
|
||||
|
||||
/// The bytes of the file to import, held to the automation roots.
|
||||
fn read_file(_path: &str) -> Result<Vec<u8>> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_read(_path).map_err(|e| bad("import", e))?;
|
||||
crate::capped_read::read_capped(std::path::Path::new(_path), crate::cmd::file::MAX_DRAWING_BYTES)
|
||||
.map_err(|e| bad("import", format!("{_path}: {e}")))
|
||||
}
|
||||
|
||||
@@ -240,6 +240,7 @@ fn run_script(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = _path;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_read(path).map_err(|e| bad("script", e))?;
|
||||
let bytes =
|
||||
crate::capped_read::read_capped(std::path::Path::new(path), MAX_SCRIPT_BYTES).map_err(|e| bad("script", format!("{path}: {e}")))?;
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
@@ -320,6 +321,7 @@ pub fn read_file(path: &std::path::Path) -> std::result::Result<ReadFile, String
|
||||
let Some(text_path) = path.to_str() else {
|
||||
return Err(bad("open", format!("{shown}: the file name is not valid Unicode, so CADCraft can't save back to it")));
|
||||
};
|
||||
crate::file_access::check_read(text_path).map_err(|e| bad("open", e))?;
|
||||
let bytes = crate::capped_read::read_capped(path, MAX_DRAWING_BYTES).map_err(|e| bad("open", format!("{shown}: {e}")))?;
|
||||
read_bytes(&bytes, text_path, Some(text_path.to_string()))
|
||||
});
|
||||
@@ -344,6 +346,7 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result<Value> {
|
||||
Ok(opened(s, i, true))
|
||||
}
|
||||
|
||||
/// Parse a drawing's bytes, and search its folder for fonts where the automation roots allow.
|
||||
fn read_bytes(bytes: &[u8], name: &str, path: Option<String>) -> Result<ReadFile> {
|
||||
let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?;
|
||||
let drawing = (hooks.read)(bytes, name).map_err(|e| bad("open", e))?;
|
||||
@@ -354,7 +357,17 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option<String>) -> Result<ReadFile
|
||||
if let Some(dir) = path.as_deref().and_then(|p| std::path::Path::new(p).parent()) {
|
||||
// A bare file name is in the current folder.
|
||||
let dir = if dir.as_os_str().is_empty() { std::path::Path::new(".") } else { dir };
|
||||
cadcraft_fonts::shx::add_drawing_dir(&std::path::absolute(dir).unwrap_or_else(|_| dir.to_path_buf()));
|
||||
let dir = std::path::absolute(dir).unwrap_or_else(|_| dir.to_path_buf());
|
||||
match crate::file_access::current() {
|
||||
None => cadcraft_fonts::shx::add_drawing_dir(&dir),
|
||||
// The folder holds no record of the roots, and a font's name there can be a link leading
|
||||
// out of them: the search asks the roots about each file before it opens one.
|
||||
Some(roots) => {
|
||||
let owner = format!("{:?}|{:?}", roots.read_root(), roots.write_root());
|
||||
let guard = std::sync::Arc::new(move |font: &std::path::Path| roots.check(font, crate::file_access::Access::Read).is_ok());
|
||||
cadcraft_fonts::shx::add_drawing_dir_guarded(&dir, &owner, guard);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(ReadFile { drawing, binary_dxf: craft_dxf::is_binary(bytes), name: name.to_string(), path })
|
||||
}
|
||||
@@ -397,6 +410,7 @@ fn run_open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = _path;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_read(path).map_err(|e| bad("open", e))?;
|
||||
let bytes =
|
||||
crate::capped_read::read_capped(std::path::Path::new(path), MAX_DRAWING_BYTES).map_err(|e| bad("open", format!("{path}: {e}")))?;
|
||||
let i = open_bytes(s, &bytes, path, Some(path.to_string()))?;
|
||||
@@ -482,6 +496,7 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<usiz
|
||||
fn store(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_write(path).map_err(|e| bad("save", e))?;
|
||||
// A file in a folder still to be made has nothing to back up.
|
||||
if is_drawing_file(path) && crate::autosave::isavebak() && crate::atomic_write::missing_folder(std::path::Path::new(path)).is_none() {
|
||||
backup(std::path::Path::new(path))
|
||||
@@ -691,7 +706,9 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> {
|
||||
};
|
||||
let (head, tail, len) = ends(&mut src)?;
|
||||
let bak = backup_path(path);
|
||||
if !backup_replaced(&head, &tail, len, bak.exists()) {
|
||||
// Whether the .bak name is taken is asked without following a link there: a link leading out of
|
||||
// the roots (or to another computer) isn't looked at.
|
||||
if !backup_replaced(&head, &tail, len, std::fs::symlink_metadata(&bak).is_ok()) {
|
||||
log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display());
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1055,6 +1072,20 @@ mod tests {
|
||||
use crate::Session;
|
||||
use crate::temp_dir::TempDir;
|
||||
|
||||
/// Whether the `.bak` name is taken is asked without following a link there: a dangling link
|
||||
/// counts as taken, so a file that doesn't look like a drawing leaves it alone.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_link_at_the_bak_name_counts_as_a_backup_without_being_followed() {
|
||||
let dir = TempDir::new("cc-bak-link");
|
||||
let path = dir.join("plain.dxf");
|
||||
std::fs::write(&path, "just some text, not a drawing").unwrap();
|
||||
let bak = super::backup_path(&path);
|
||||
std::os::unix::fs::symlink(dir.join("nowhere"), &bak).unwrap();
|
||||
super::backup(&path).unwrap();
|
||||
assert!(std::fs::symlink_metadata(&bak).unwrap().file_type().is_symlink(), "the link is left as it was");
|
||||
}
|
||||
|
||||
/// A backup is never more open than the drawing or the old `.bak`, and loses the group bits when
|
||||
/// it would keep the old `.bak`'s group while the drawing is in another.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -107,9 +107,11 @@ fn other_drawing(s: &Session, p: &Value) -> Result<(Arc<Drawing>, String)> {
|
||||
Ok((Arc::new(d), name))
|
||||
}
|
||||
|
||||
/// The bytes of the drawing to compare with, held to the automation roots.
|
||||
fn read_path(_path: &str) -> Result<Vec<u8>> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_read(_path).map_err(|e| bad("compare", e))?;
|
||||
crate::capped_read::read_capped(std::path::Path::new(_path), super::MAX_DRAWING_BYTES).map_err(|e| bad("compare", format!("{_path}: {e}")))
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -128,8 +128,8 @@ pub fn alias_name(a: &str) -> std::result::Result<String, String> {
|
||||
}
|
||||
|
||||
/// The aliases of a `.pgp` file's text, and its problems.
|
||||
fn parse(text: &str) -> (Vec<(String, String)>, Vec<String>) {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
fn parse(text: &str) -> (BTreeMap<String, String>, Vec<String>) {
|
||||
let mut out = BTreeMap::new();
|
||||
let mut warnings = Vec::new();
|
||||
let mut warn = |no: usize, msg: String| {
|
||||
if warnings.len() < MAX_WARNINGS {
|
||||
@@ -165,13 +165,13 @@ fn parse(text: &str) -> (Vec<(String, String)>, Vec<String>) {
|
||||
warn(no, format!("{}: unknown command {}; skipped", alias.trim(), target.trim()));
|
||||
continue;
|
||||
};
|
||||
// Once full, stop at the next valid definition, even if it repeats an alias.
|
||||
if out.len() >= MAX_ALIASES {
|
||||
warn(no, format!("more than {MAX_ALIASES} aliases; the rest are skipped"));
|
||||
break;
|
||||
}
|
||||
// A later line for the same alias wins, as it would when typed into the file twice.
|
||||
out.retain(|(a, _)| *a != name);
|
||||
out.push((name, id));
|
||||
// A later definition wins without scanning all the aliases accumulated so far.
|
||||
out.insert(name, id);
|
||||
}
|
||||
(out, warnings)
|
||||
}
|
||||
@@ -185,7 +185,7 @@ fn listing(warnings: &[String], added: usize) -> Value {
|
||||
fn load(text: &str, path: Option<String>) -> (usize, Vec<String>) {
|
||||
let (aliases, warnings) = parse(text);
|
||||
let mut st = store();
|
||||
st.map = aliases.into_iter().collect();
|
||||
st.map = aliases;
|
||||
if path.is_some() {
|
||||
st.file = path;
|
||||
}
|
||||
|
||||
@@ -73,10 +73,13 @@ fn read_template(path: &str) -> Result<Drawing> {
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// The bytes of the template at `path`, once the automation roots allow reading it.
|
||||
fn read_bytes(path: &str) -> Result<Vec<u8>> {
|
||||
crate::file_access::check_read(path).map_err(|e| bad("new", e))?;
|
||||
crate::capped_read::read_capped(std::path::Path::new(path), super::MAX_DRAWING_BYTES).map_err(|e| bad("new", format!("template {path}: {e}")))
|
||||
}
|
||||
|
||||
/// The bytes of the template at `path`, held to the automation roots.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn read_bytes(path: &str) -> Result<Vec<u8>> {
|
||||
Err(bad("new", format!("template {path}: paths are not available on the web")))
|
||||
|
||||
@@ -115,8 +115,10 @@ pub fn support_text(cmd: &str, p: &serde_json::Value, path_key: &str, text_key:
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// The text of the support file at `path`, once the automation roots allow reading it, up to the size limit.
|
||||
fn read_support_file(cmd: &str, path: &str) -> crate::Result<String> {
|
||||
use std::io::Read;
|
||||
crate::file_access::check_read(path).map_err(|e| super::bad(cmd, e))?;
|
||||
let f = std::fs::File::open(path).map_err(|e| super::bad(cmd, format!("{path}: {e}")))?;
|
||||
let mut bytes = Vec::new();
|
||||
f.take(MAX_SUPPORT_FILE_BYTES + 1).read_to_end(&mut bytes).map_err(|e| super::bad(cmd, format!("{path}: {e}")))?;
|
||||
@@ -126,6 +128,7 @@ fn read_support_file(cmd: &str, path: &str) -> crate::Result<String> {
|
||||
Ok(String::from_utf8_lossy(&bytes).into_owned())
|
||||
}
|
||||
|
||||
/// The text of a support file (a linetype or hatch pattern file, say), size-limited and held to the automation roots.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn read_support_file(cmd: &str, _path: &str) -> crate::Result<String> {
|
||||
Err(super::bad(cmd, "paths are not available on the web; pass the file's contents"))
|
||||
|
||||
@@ -75,6 +75,7 @@ fn read_file(path: &str, host: Option<&str>) -> std::result::Result<Vec<u8>, Str
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?;
|
||||
crate::file_access::check_read(&file)?;
|
||||
let len = std::fs::metadata(&file).map_err(|e| e.to_string())?.len();
|
||||
if len > MAX_IMAGE_BYTES {
|
||||
return Err(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20));
|
||||
@@ -180,14 +181,18 @@ fn decode_files(paths: &[&str], host: Option<&str>) -> Vec<std::result::Result<R
|
||||
if loaders > 1 {
|
||||
// Each loader takes the next file nobody has started.
|
||||
let next = AtomicUsize::new(0);
|
||||
// The automation roots are per thread, so they go along with each loader.
|
||||
let roots = crate::file_access::current();
|
||||
let work = || {
|
||||
let mut done = Vec::new();
|
||||
loop {
|
||||
let index = next.fetch_add(1, Ordering::Relaxed);
|
||||
let Some(path) = paths.get(index) else { break };
|
||||
done.push((index, load(path)));
|
||||
}
|
||||
done
|
||||
crate::file_access::confine(roots.as_ref(), || {
|
||||
let mut done = Vec::new();
|
||||
loop {
|
||||
let index = next.fetch_add(1, Ordering::Relaxed);
|
||||
let Some(path) = paths.get(index) else { break };
|
||||
done.push((index, load(path)));
|
||||
}
|
||||
done
|
||||
})
|
||||
};
|
||||
let finished: Vec<_> = std::thread::scope(|scope| {
|
||||
let started: Vec<_> = (0..loaders).filter_map(|_| std::thread::Builder::new().spawn_scoped(scope, work).ok()).collect();
|
||||
|
||||
+16
-246
@@ -1,7 +1,6 @@
|
||||
//! Layers: LAYER (programmatic sub-ids, -LAYER prompts), layer tools (LAYMCUR, LAYISO, LAYOFF, LAYFRZ…).
|
||||
|
||||
mod prompts;
|
||||
mod state_prompts;
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::{Layer, Lineweight};
|
||||
@@ -56,9 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("layon", "Turn All Layers On", |s, _| all_layers(s, |l| l.on = true)),
|
||||
CommandSpec::new("laythw", "Thaw All Layers", |s, _| all_layers(s, |l| l.frozen = false)),
|
||||
CommandSpec::new("layerp", "Previous Layer", run_layerp).menu(&["Format", "Layer Tools", "Previous Layer"]),
|
||||
CommandSpec::new("layerstate.save", "Save Layer State", run_state_save)
|
||||
.menu(&["Format", "Layer States Manager..."])
|
||||
.params("{name, mask? (properties restoring sets: 1 on, 2 frozen, 4 locked, 8 plot, 16 new viewport freeze, 32 color, 64 linetype, 128 lineweight, 256 plot style, 1024 transparency; default all)}"),
|
||||
CommandSpec::new("layerstate.save", "Save Layer State", run_state_save).menu(&["Format", "Layer States Manager..."]).params("{name}"),
|
||||
CommandSpec::new("layerstate.restore", "Restore Layer State", run_state_restore).params("{name}"),
|
||||
CommandSpec::new("layerstate.list", "List Layer States", run_state_list).params("{} → states").noundo(),
|
||||
CommandSpec::new("layerstate.delete", "Delete Layer State", run_state_delete).params("{name}"),
|
||||
@@ -403,108 +400,31 @@ fn all_layers(s: &mut Session, f: fn(&mut Layer)) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn run_state_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use cadcraft_doc::LayerState as S;
|
||||
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.save", "`name` is required"))?.to_string();
|
||||
// As -LAYER stAte Save and layerstate.rename take names: none empty, over 255 characters, with a
|
||||
// control character or with one AutoCAD 2024 refuses (measured for Save).
|
||||
if !valid_name(&name) {
|
||||
return Err(bad("layerstate.save", "invalid name"));
|
||||
}
|
||||
// The properties restoring sets; bit 512, which no property toggles, is always set, as AutoCAD
|
||||
// 2024 saves it (measured: On alone is 513).
|
||||
let mask = match p.get("mask") {
|
||||
None | Some(Value::Null) => S::ALL,
|
||||
Some(v) => {
|
||||
let m = v.as_u64().filter(|m| m & !u64::from(S::ALL) == 0);
|
||||
m.and_then(|m| u32::try_from(m).ok()).ok_or_else(|| bad("layerstate.save", "`mask` must be a sum of layer state bits (0 to 2047)"))? | 512
|
||||
}
|
||||
};
|
||||
let d = s.doc_mut()?;
|
||||
let layers = d.layers.clone();
|
||||
let current = d.header.str("CLAYER", "0");
|
||||
// Replace the state Restore and Delete reach (the same spelling, else another case), so a
|
||||
// drawing keeps one state per name: AutoCAD 2024 finds states without regard to case. Its
|
||||
// -LAYER stAte Save and layerstate-save refuse `s1` after `S1` (measured), as the command line
|
||||
// here does; this command replaces, as it does a state of the same spelling. When a file holds
|
||||
// both `S1` and `s1`, only the one spelled so is replaced.
|
||||
if let Some(i) = state_index(d, &name) {
|
||||
d.layer_states.remove(i);
|
||||
}
|
||||
d.layer_states.push(S { mask, ..S::new(name, layers, current) });
|
||||
d.layer_states.retain(|st| st.name != name);
|
||||
d.layer_states.push(cadcraft_doc::LayerState { name, layers });
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The saved state called `name`: the one spelled so, else the first whose name differs only in
|
||||
/// case. AutoCAD 2024 finds layer states without regard to case (measured: Restore, Edit, Name
|
||||
/// and Delete of `s1` reach `S1`); case is compared as for layers and view snapshots.
|
||||
pub(super) fn state_index(d: &cadcraft_doc::Drawing, name: &str) -> Option<usize> {
|
||||
d.layer_states.iter().position(|st| st.name == name).or_else(|| d.layer_states.iter().position(|st| st.name.eq_ignore_ascii_case(name)))
|
||||
}
|
||||
|
||||
fn run_state_restore(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.restore", "`name` is required"))?;
|
||||
let d = s.doc_mut()?;
|
||||
let st = state_index(d, name).and_then(|i| d.layer_states.get(i)).cloned().ok_or_else(|| bad("layerstate.restore", "no such layer state"))?;
|
||||
restore_state(d, &st);
|
||||
let st = d.layer_states.iter().find(|st| st.name == name).cloned().ok_or_else(|| bad("layerstate.restore", "no such layer state"))?;
|
||||
restore_layers(d, st.layers);
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Restore a saved layer state as AutoCAD 2024 does (measured): first the current layer it
|
||||
/// names, when the drawing has it and the restore doesn't leave it frozen, then on each drawing
|
||||
/// layer the state names (without regard to case) the properties its mask covers. The current
|
||||
/// layer is never frozen; other properties (descriptions, names) stay as they are.
|
||||
pub(crate) fn restore_state(d: &mut cadcraft_doc::Drawing, st: &cadcraft_doc::LayerState) {
|
||||
use cadcraft_doc::LayerState as S;
|
||||
// A frozen layer only thaws with Frozen in the mask and an entry of its own: without one
|
||||
// AutoCAD 2024 keeps the current layer (measured).
|
||||
let thaws = |l: &Layer| st.mask & S::FROZEN != 0 && st.layers.iter().any(|saved| saved.name.eq_ignore_ascii_case(&l.name));
|
||||
if let Some(l) = d.layer(&st.current).filter(|l| !l.frozen || thaws(l)) {
|
||||
let name = l.name.clone();
|
||||
d.header.set_str("CLAYER", &name);
|
||||
}
|
||||
let current = d.header.str("CLAYER", "0");
|
||||
let index = layer_index(d);
|
||||
let has = |bit: u32| st.mask & bit != 0;
|
||||
for saved in &st.layers {
|
||||
let Some(l) = index.get(&saved.name.to_ascii_lowercase()).and_then(|&i| d.layers.get_mut(i)) else { continue };
|
||||
if has(S::ON) {
|
||||
l.on = saved.on;
|
||||
}
|
||||
if has(S::FROZEN) {
|
||||
l.frozen = saved.frozen && !l.name.eq_ignore_ascii_case(¤t);
|
||||
}
|
||||
if has(S::LOCKED) {
|
||||
l.locked = saved.locked;
|
||||
}
|
||||
if has(S::PLOT) {
|
||||
l.plot = saved.plot;
|
||||
}
|
||||
if has(S::VP_FREEZE_NEW) {
|
||||
l.vp_freeze_new = saved.vp_freeze_new;
|
||||
}
|
||||
if has(S::COLOR) {
|
||||
l.color = saved.color;
|
||||
}
|
||||
if has(S::LINETYPE) {
|
||||
l.linetype.clone_from(&saved.linetype);
|
||||
}
|
||||
if has(S::LINEWEIGHT) {
|
||||
l.lineweight = saved.lineweight;
|
||||
}
|
||||
if has(S::PLOT_STYLE) {
|
||||
l.plot_style.clone_from(&saved.plot_style);
|
||||
}
|
||||
if has(S::TRANSPARENCY) {
|
||||
l.transparency = saved.transparency;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the saved layers back over the drawing's layers of the same name (without regard to case);
|
||||
/// saved layers the drawing no longer has are skipped. Both lists can come from a file, so the
|
||||
/// drawing's layers are looked up in an index rather than scanned per saved layer.
|
||||
pub(crate) fn restore_layers(d: &mut cadcraft_doc::Drawing, saved: Vec<Layer>) {
|
||||
let index = layer_index(d);
|
||||
let mut index: std::collections::HashMap<String, usize> = std::collections::HashMap::with_capacity(d.layers.len());
|
||||
for (i, l) in d.layers.iter().enumerate() {
|
||||
// The first of names that differ only in case, as `Drawing::layer_mut` finds it.
|
||||
index.entry(l.name.to_ascii_lowercase()).or_insert(i);
|
||||
}
|
||||
for layer in saved {
|
||||
if let Some(l) = index.get(&layer.name.to_ascii_lowercase()).and_then(|&i| d.layers.get_mut(i)) {
|
||||
*l = layer;
|
||||
@@ -512,16 +432,6 @@ pub(crate) fn restore_layers(d: &mut cadcraft_doc::Drawing, saved: Vec<Layer>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawing's layers by lower-case name: the first of names that differ only in case, as
|
||||
/// `Drawing::layer_mut` finds it.
|
||||
fn layer_index(d: &cadcraft_doc::Drawing) -> std::collections::HashMap<String, usize> {
|
||||
let mut index = std::collections::HashMap::with_capacity(d.layers.len());
|
||||
for (i, l) in d.layers.iter().enumerate() {
|
||||
index.entry(l.name.to_ascii_lowercase()).or_insert(i);
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
fn run_state_list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let d = s.doc()?;
|
||||
let states: Vec<Value> = d.layer_states.iter().map(|st| json!({ "name": st.name, "layers": st.layers.len() })).collect();
|
||||
@@ -536,8 +446,10 @@ fn run_state_list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
fn run_state_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.delete", "`name` is required"))?;
|
||||
let d = s.doc_mut()?;
|
||||
let i = state_index(d, name).ok_or_else(|| bad("layerstate.delete", "no such layer state"))?;
|
||||
d.layer_states.remove(i);
|
||||
if !d.layer_states.iter().any(|st| st.name == name) {
|
||||
return Err(bad("layerstate.delete", "no such layer state"));
|
||||
}
|
||||
d.layer_states.retain(|st| st.name != name);
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -548,12 +460,10 @@ fn run_state_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad("layerstate.rename", "invalid name"));
|
||||
}
|
||||
let d = s.doc_mut()?;
|
||||
// A name in another case counts, the state's own too (AutoCAD 2024 refuses `S1` to `s1`,
|
||||
// measured).
|
||||
if d.layer_states.iter().any(|st| st.name.eq_ignore_ascii_case(&to)) {
|
||||
if d.layer_states.iter().any(|st| st.name == to) {
|
||||
return Err(bad("layerstate.rename", format!("layer state `{to}` already exists")));
|
||||
}
|
||||
let st = state_index(d, from).and_then(|i| d.layer_states.get_mut(i)).ok_or_else(|| bad("layerstate.rename", "no such layer state"))?;
|
||||
let st = d.layer_states.iter_mut().find(|st| st.name == from).ok_or_else(|| bad("layerstate.rename", "no such layer state"))?;
|
||||
st.name = to;
|
||||
ok()
|
||||
}
|
||||
@@ -606,146 +516,6 @@ mod tests {
|
||||
assert!(used.contains(&true) && used.contains(&false));
|
||||
}
|
||||
|
||||
/// Restoring follows AutoCAD 2024 (measured with -LAYER stAte and states written into a DXF):
|
||||
/// the current layer first, then only the properties the mask covers; the current layer stays
|
||||
/// thawed; a current layer that is empty or gone leaves the current layer as it is.
|
||||
#[test]
|
||||
fn layer_state_restore_follows_the_mask_and_current_layer() {
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::LayerState;
|
||||
let mut s = Session::new();
|
||||
s.execute("layer.new", &json!({ "name": "A", "color": 1, "current": true })).unwrap();
|
||||
s.execute("layer.new", &json!({ "name": "B" })).unwrap();
|
||||
s.execute("layerstate.save", &json!({ "name": "all" })).unwrap();
|
||||
let saved = s.doc().unwrap().layer_states[0].clone();
|
||||
assert_eq!((saved.mask, saved.current.as_str()), (LayerState::ALL, "A"));
|
||||
// Only On: A's colour stays green, B comes back on (AutoCAD's S7, mask 513).
|
||||
let d = s.doc_mut().unwrap();
|
||||
d.layer_states.push(LayerState { name: "on".into(), mask: LayerState::ON | 512, ..saved.clone() });
|
||||
s.execute("layer.set", &json!({ "name": "A", "color": 3 })).unwrap();
|
||||
s.execute("layer.set", &json!({ "name": "B", "on": false, "locked": true })).unwrap();
|
||||
s.execute("layer.current", &json!({ "name": "B" })).unwrap();
|
||||
s.execute("layerstate.restore", &json!({ "name": "on" })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.header.str("CLAYER", ""), "A");
|
||||
let (a, b) = (d.layer("A").unwrap(), d.layer("B").unwrap());
|
||||
assert_eq!((a.color, b.on, b.locked), (Color::Index(3), true, true));
|
||||
// Every property.
|
||||
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!((d.layer("A").unwrap().color, d.layer("B").unwrap().locked), (Color::Index(1), false));
|
||||
// A state that freezes B with no current layer of its own (or one that is gone), restored
|
||||
// with B current: B stays current and thawed; A is turned off.
|
||||
for current in ["", "NOSUCH"] {
|
||||
let mut frozen = s.doc().unwrap().layers.clone();
|
||||
for l in &mut frozen {
|
||||
l.frozen = l.name == "B";
|
||||
l.on = l.name != "A";
|
||||
}
|
||||
s.doc_mut().unwrap().layer_states.push(LayerState::new(format!("f{current}"), frozen.clone(), current));
|
||||
s.execute("layer.current", &json!({ "name": "B" })).unwrap();
|
||||
s.execute("layerstate.restore", &json!({ "name": format!("f{current}") })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.header.str("CLAYER", ""), "B", "{current:?}");
|
||||
assert!(!d.layer("B").unwrap().frozen && !d.layer("A").unwrap().on, "{current:?}");
|
||||
// Naming A current, it becomes current and B freezes.
|
||||
s.doc_mut().unwrap().layer_states.push(LayerState::new("fA", frozen, "A"));
|
||||
s.execute("layerstate.restore", &json!({ "name": "fA" })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.header.str("CLAYER", ""), "A");
|
||||
assert!(d.layer("B").unwrap().frozen);
|
||||
s.doc_mut().unwrap().layer_states.retain(|st| st.name != "fA");
|
||||
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
|
||||
}
|
||||
// A current layer the state's mask leaves frozen doesn't become current (AutoCAD's S9: On
|
||||
// only, current B; restored with A current and B frozen).
|
||||
let mut on_only = s.doc().unwrap().layer_states[0].clone();
|
||||
(on_only.name, on_only.mask, on_only.current) = ("S9".into(), LayerState::ON | 512, "B".into());
|
||||
s.doc_mut().unwrap().layer_states.push(on_only);
|
||||
s.execute("layer.current", &json!({ "name": "A" })).unwrap();
|
||||
s.execute("layer.set", &json!({ "name": "B", "frozen": true })).unwrap();
|
||||
s.execute("layerstate.restore", &json!({ "name": "S9" })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.header.str("CLAYER", ""), "A");
|
||||
assert!(d.layer("B").unwrap().frozen);
|
||||
// With Frozen in the mask B is thawed and made current.
|
||||
let mut thaw = s.doc().unwrap().layer_states[0].clone();
|
||||
(thaw.name, thaw.current) = ("thaw".into(), "B".into());
|
||||
s.doc_mut().unwrap().layer_states.push(thaw);
|
||||
s.execute("layerstate.restore", &json!({ "name": "thaw" })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.header.str("CLAYER", ""), "B");
|
||||
assert!(!d.layer("B").unwrap().frozen);
|
||||
// Frozen in the mask, but no entry for B (a state written elsewhere): nothing would thaw
|
||||
// B, so A stays current and B frozen (AutoCAD 2024, measured).
|
||||
let mut no_entry = s.doc().unwrap().layer_states[0].clone();
|
||||
(no_entry.name, no_entry.current) = ("no entry".into(), "B".into());
|
||||
no_entry.layers.retain(|l| l.name != "B");
|
||||
s.doc_mut().unwrap().layer_states.push(no_entry);
|
||||
s.execute("layer.current", &json!({ "name": "A" })).unwrap();
|
||||
s.execute("layer.set", &json!({ "name": "B", "frozen": true })).unwrap();
|
||||
s.execute("layerstate.restore", &json!({ "name": "no entry" })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.header.str("CLAYER", ""), "A");
|
||||
assert!(d.layer("B").unwrap().frozen);
|
||||
// An entry spelled in another case is B's (layer names ignore case, as the restore of the
|
||||
// properties does): B is thawed and made current.
|
||||
let mut other_case = s.doc().unwrap().layer_states[0].clone();
|
||||
(other_case.name, other_case.current) = ("other case".into(), "B".into());
|
||||
for l in other_case.layers.iter_mut().filter(|l| l.name == "B") {
|
||||
l.name = "b".into();
|
||||
}
|
||||
s.doc_mut().unwrap().layer_states.push(other_case);
|
||||
s.execute("layerstate.restore", &json!({ "name": "other case" })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.header.str("CLAYER", ""), "B");
|
||||
assert!(!d.layer("B").unwrap().frozen);
|
||||
// What a state doesn't hold stays: the description.
|
||||
s.execute("layer.set", &json!({ "name": "A", "description": "kept" })).unwrap();
|
||||
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
|
||||
assert_eq!(s.doc().unwrap().layer("A").unwrap().description, "kept");
|
||||
}
|
||||
|
||||
/// Plotting, freezing in new viewports, linetype, lineweight, plot style and transparency each
|
||||
/// come back under their own mask bit only: a state of one bit restores that property and
|
||||
/// leaves the other five as they are.
|
||||
#[test]
|
||||
fn layer_state_restores_each_property_under_its_own_bit_only() {
|
||||
use cadcraft_doc::{Drawing, LayerState as S, Lineweight};
|
||||
let mut s = Session::new();
|
||||
s.execute("layer.new", &json!({ "name": "A" })).unwrap();
|
||||
s.execute("layerstate.save", &json!({ "name": "all" })).unwrap();
|
||||
let saved = s.doc().unwrap().layer_states[0].clone();
|
||||
let props = |d: &Drawing| {
|
||||
let l = d.layer("A").unwrap();
|
||||
(l.plot, l.vp_freeze_new, l.linetype.clone(), l.lineweight, l.plot_style.clone(), l.transparency)
|
||||
};
|
||||
let change = |d: &mut Drawing| {
|
||||
let l = d.layer_mut("A").unwrap();
|
||||
(l.plot, l.vp_freeze_new, l.linetype, l.lineweight, l.plot_style, l.transparency) =
|
||||
(false, true, "DASHED".into(), Lineweight::from_dxf(50), "Thick".into(), 40);
|
||||
};
|
||||
let before = props(s.doc().unwrap());
|
||||
change(s.doc_mut().unwrap());
|
||||
let after = props(s.doc().unwrap());
|
||||
for bit in [S::PLOT, S::VP_FREEZE_NEW, S::LINETYPE, S::LINEWEIGHT, S::PLOT_STYLE, S::TRANSPARENCY] {
|
||||
let name = format!("b{bit}");
|
||||
s.doc_mut().unwrap().layer_states.push(S { name: name.clone(), mask: bit | 512, ..saved.clone() });
|
||||
change(s.doc_mut().unwrap());
|
||||
s.execute("layerstate.restore", &json!({ "name": name })).unwrap();
|
||||
let mut want = after.clone();
|
||||
match bit {
|
||||
S::PLOT => want.0 = before.0,
|
||||
S::VP_FREEZE_NEW => want.1 = before.1,
|
||||
S::LINETYPE => want.2.clone_from(&before.2),
|
||||
S::LINEWEIGHT => want.3 = before.3,
|
||||
S::PLOT_STYLE => want.4.clone_from(&before.4),
|
||||
_ => want.5 = before.5,
|
||||
}
|
||||
assert_eq!(props(s.doc().unwrap()), want, "mask {bit}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_layer_set_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -8,7 +8,6 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::super::find_command;
|
||||
use super::super::qselect::wildcard;
|
||||
use super::state_prompts;
|
||||
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
const OPTIONS: &[&str] = &[
|
||||
@@ -35,9 +34,9 @@ const OPTIONS: &[&str] = &[
|
||||
];
|
||||
|
||||
/// Keyword-only: spaces separate inputs.
|
||||
pub(super) const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
|
||||
const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
|
||||
/// A name or value: Space ends the input, as it does in AutoCAD scripts.
|
||||
pub(super) const NAME: Accept = Accept { number: true, ..Accept::TEXT };
|
||||
const NAME: Accept = Accept { number: true, ..Accept::TEXT };
|
||||
|
||||
/// A per-layer change applied to a list of layer names.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -112,8 +111,6 @@ enum Stage {
|
||||
Layers(Change),
|
||||
/// Turning the current layer off asks first.
|
||||
ConfirmOff(Vec<String>),
|
||||
/// stAte and its options.
|
||||
State(state_prompts::Stage),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -126,19 +123,19 @@ fn current_layer(s: &Session) -> String {
|
||||
}
|
||||
|
||||
/// Run a layer command's body directly: the running command records the single undo step.
|
||||
pub(super) fn call(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
|
||||
fn call(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
|
||||
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
(spec.run)(s, p)
|
||||
}
|
||||
|
||||
pub(super) fn message(e: &EngineError) -> String {
|
||||
fn message(e: &EngineError) -> String {
|
||||
match e {
|
||||
EngineError::BadParams { msg, .. } => msg.clone(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn retry(msg: impl Into<String>) -> EngineError {
|
||||
fn retry(msg: impl Into<String>) -> EngineError {
|
||||
EngineError::Other(msg.into())
|
||||
}
|
||||
|
||||
@@ -191,9 +188,8 @@ impl LayerM {
|
||||
"LOck" => Stage::Layers(Change::Lock),
|
||||
"Unlock" => Stage::Layers(Change::Unlock),
|
||||
"Description" => Stage::Description,
|
||||
"stAte" => Stage::State(state_prompts::Stage::Option),
|
||||
other => {
|
||||
// MATerial, rEconcile: report and stay at the option prompt.
|
||||
// MATerial, stAte, rEconcile: report and stay at the option prompt.
|
||||
s.echo(format!("-LAYER {other} is not available yet."));
|
||||
Stage::Option
|
||||
}
|
||||
@@ -266,7 +262,7 @@ impl LayerM {
|
||||
Ok(Step::Continue)
|
||||
};
|
||||
match stage {
|
||||
Stage::Option | Stage::State(_) => Ok(Step::Continue),
|
||||
Stage::Option => Ok(Step::Continue),
|
||||
Stage::List => {
|
||||
self.list(s, text.as_deref().unwrap_or("*"));
|
||||
Ok(Step::Continue)
|
||||
@@ -438,18 +434,9 @@ impl Interactive for LayerM {
|
||||
if enter_is_current { p.default(cur) } else { p }
|
||||
}
|
||||
Stage::ConfirmOff(_) => Prompt::new(format!("Really want layer \"{cur}\" (the CURRENT layer) off?"), KW).kw(&["Yes", "No"]).default("N"),
|
||||
Stage::State(st) => st.prompt(),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
if let Stage::State(st) = &mut self.stage
|
||||
&& !matches!(i, Input::Cancel)
|
||||
{
|
||||
if !st.input(s, &i)? {
|
||||
self.stage = Stage::Option;
|
||||
}
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
match (&self.stage, &i) {
|
||||
(_, Input::Cancel) => Ok(Step::Cancel),
|
||||
(Stage::Option, Input::Enter) => Ok(Step::Done),
|
||||
|
||||
@@ -1,256 +0,0 @@
|
||||
//! -LAYER stAte: save, restore, edit, rename, delete and list the drawing's layer states, with
|
||||
//! AutoCAD 2024's prompts and messages (measured). Save, Restore, Name and Delete run the
|
||||
//! `layerstate.*` commands; Edit changes the state's mask in place.
|
||||
|
||||
use cadcraft_doc::LayerState as LS;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::prompts::{KW, NAME, call, message, retry};
|
||||
use super::{state_index, valid_name};
|
||||
use crate::{Input, Prompt, Result, Session};
|
||||
|
||||
/// The options after stAte. Import and EXport (layer state files) are not available yet.
|
||||
const OPTIONS: &[&str] = &["?", "Save", "Restore", "Edit", "Name", "Delete", "Import", "EXport"];
|
||||
|
||||
/// "Enter states to change": each keyword, the name AutoCAD 2024 lists it by and its mask bit, in
|
||||
/// AutoCAD's order.
|
||||
const TOGGLES: [(&str, &str, u32); 10] = [
|
||||
("On", "On", LS::ON),
|
||||
("Frozen", "Frozen", LS::FROZEN),
|
||||
("Lock", "Lock", LS::LOCKED),
|
||||
("Plot", "Plot", LS::PLOT),
|
||||
("Newvpfreeze", "Newvpfreeze", LS::VP_FREEZE_NEW),
|
||||
("Color", "Color", LS::COLOR),
|
||||
("lineType", "lineType", LS::LINETYPE),
|
||||
("lineWeight", "lineWeight", LS::LINEWEIGHT),
|
||||
("TRansparency", "Transparency", LS::TRANSPARENCY),
|
||||
("plotStyle", "plotStyle", LS::PLOT_STYLE),
|
||||
];
|
||||
|
||||
/// The options that ask for a saved state's name.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) enum Pick {
|
||||
Restore,
|
||||
Edit,
|
||||
Name,
|
||||
Delete,
|
||||
}
|
||||
|
||||
impl Pick {
|
||||
fn verb(self) -> &'static str {
|
||||
match self {
|
||||
Pick::Restore => "restore",
|
||||
Pick::Edit => "edit",
|
||||
Pick::Name => "rename",
|
||||
Pick::Delete => "delete",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(super) enum Stage {
|
||||
#[default]
|
||||
Option,
|
||||
/// Save: the new state's name.
|
||||
SaveName,
|
||||
/// Restore, Edit, Name or Delete: the saved state's name.
|
||||
Pick(Pick),
|
||||
/// Name: the new name of the state called so.
|
||||
RenameTo(String),
|
||||
/// "Enter states to change" for the state `name`: one Save makes on Enter, or one Edit
|
||||
/// changes (`edit`).
|
||||
Toggles { name: String, mask: u32, edit: bool },
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
pub(super) fn prompt(&self) -> Prompt {
|
||||
match self {
|
||||
Stage::Option => Prompt::new("Enter an option", KW).kw(OPTIONS),
|
||||
Stage::SaveName | Stage::RenameTo(_) => Prompt::new("Enter new layer state name", NAME),
|
||||
Stage::Pick(p) => Prompt::new(format!("Enter name of layer state to {}", p.verb()), NAME).kw(&["?"]),
|
||||
Stage::Toggles { .. } => Prompt::new("Enter states to change", KW).kw(&TOGGLES.map(|t| t.0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One input. `Ok(false)`: back to -LAYER's options. An invalid input leaves the stage as it
|
||||
/// is, so the prompt is asked again.
|
||||
pub(super) fn input(&mut self, s: &mut Session, i: &Input) -> Result<bool> {
|
||||
let text = match i {
|
||||
Input::Text(t) | Input::Keyword(t) => Some(t.trim().to_string()).filter(|t| !t.is_empty()),
|
||||
_ => None,
|
||||
};
|
||||
let next = match std::mem::take(self) {
|
||||
Stage::Option => match i {
|
||||
Input::Enter => return Ok(false),
|
||||
Input::Keyword(k) => option(s, k),
|
||||
_ => return Err(retry("Invalid option keyword.")),
|
||||
},
|
||||
Stage::SaveName => match text {
|
||||
None => Stage::Option,
|
||||
Some(n) => save_name(s, n),
|
||||
},
|
||||
Stage::Pick(p) => match (i, text) {
|
||||
(Input::Keyword(k), _) if k == "?" => {
|
||||
list(s);
|
||||
Stage::Pick(p)
|
||||
}
|
||||
(_, None) => Stage::Option,
|
||||
(_, Some(n)) => pick(s, p, &n),
|
||||
},
|
||||
Stage::RenameTo(from) => {
|
||||
if let Some(to) = text {
|
||||
rename(s, &from, &to);
|
||||
}
|
||||
Stage::Option
|
||||
}
|
||||
Stage::Toggles { name, mut mask, edit } => match i {
|
||||
Input::Keyword(k) => {
|
||||
if let Some(&(_, _, bit)) = TOGGLES.iter().find(|t| t.0 == k) {
|
||||
mask ^= bit;
|
||||
}
|
||||
show(s, mask);
|
||||
Stage::Toggles { name, mask, edit }
|
||||
}
|
||||
Input::Enter => {
|
||||
finish(s, &name, mask, edit);
|
||||
Stage::Option
|
||||
}
|
||||
_ => {
|
||||
*self = Stage::Toggles { name, mask, edit };
|
||||
return Err(retry("Invalid option keyword."));
|
||||
}
|
||||
},
|
||||
};
|
||||
*self = next;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
fn option(s: &mut Session, k: &str) -> Stage {
|
||||
match k {
|
||||
"?" => {
|
||||
list(s);
|
||||
Stage::Option
|
||||
}
|
||||
"Save" => Stage::SaveName,
|
||||
"Restore" => Stage::Pick(Pick::Restore),
|
||||
"Edit" => Stage::Pick(Pick::Edit),
|
||||
"Name" => Stage::Pick(Pick::Name),
|
||||
"Delete" => Stage::Pick(Pick::Delete),
|
||||
other => {
|
||||
s.echo(format!("-LAYER stAte {other} is not available yet."));
|
||||
Stage::Option
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a saved state has the name `n` in any case.
|
||||
fn taken(s: &Session, n: &str) -> bool {
|
||||
s.doc().is_ok_and(|d| d.layer_states.iter().any(|st| st.name.eq_ignore_ascii_case(n)))
|
||||
}
|
||||
|
||||
/// Save's name: refused (asked again) when it has a character AutoCAD 2024 refuses (the layer
|
||||
/// name ones, measured one by one), is longer than 255 characters (measured 256), or is a saved
|
||||
/// state's name in any case (measured `s1` after `S1`).
|
||||
fn save_name(s: &mut Session, n: String) -> Stage {
|
||||
if !valid_name(&n) {
|
||||
s.echo(format!("\"{n}\" is an invalid layer state name."));
|
||||
return Stage::SaveName;
|
||||
}
|
||||
if taken(s, &n) {
|
||||
s.echo(format!("Layer state \"{n}\" already exists."));
|
||||
return Stage::SaveName;
|
||||
}
|
||||
let mask = s.settings.layer_state_mask;
|
||||
show(s, mask);
|
||||
Stage::Toggles { name: n, mask, edit: false }
|
||||
}
|
||||
|
||||
fn pick(s: &mut Session, p: Pick, n: &str) -> Stage {
|
||||
let found = s.doc().ok().and_then(|d| state_index(d, n).and_then(|i| d.layer_states.get(i)).map(|st| (st.name.clone(), st.mask)));
|
||||
let Some((name, mask)) = found else {
|
||||
s.echo("Unknown layer state name.");
|
||||
return Stage::Pick(p);
|
||||
};
|
||||
match p {
|
||||
Pick::Restore => {
|
||||
run(s, "layerstate.restore", &json!({ "name": name }));
|
||||
Stage::Option
|
||||
}
|
||||
Pick::Delete => {
|
||||
run(s, "layerstate.delete", &json!({ "name": name }));
|
||||
Stage::Option
|
||||
}
|
||||
Pick::Edit => {
|
||||
show(s, mask);
|
||||
Stage::Toggles { name, mask, edit: true }
|
||||
}
|
||||
Pick::Name => Stage::RenameTo(name),
|
||||
}
|
||||
}
|
||||
|
||||
/// Name's new name. A name some state has in any case, the state's own too, is refused with
|
||||
/// AutoCAD 2024's two lines (measured `S2` onto `S2`, `S1` onto `s1`). A name with a character
|
||||
/// AutoCAD refuses leaves the state as it is with no message, as AutoCAD does (measured `a,b`,
|
||||
/// `a<b`); AutoCAD renames to a name starting with "*" as an anonymous `*A1`, and CADCraft leaves
|
||||
/// that state as it is too.
|
||||
fn rename(s: &mut Session, from: &str, to: &str) {
|
||||
if taken(s, to) {
|
||||
s.echo("Layer state could not be renamed.");
|
||||
s.echo(format!("{to} already exists."));
|
||||
} else if valid_name(to) {
|
||||
run(s, "layerstate.rename", &json!({ "from": from, "to": to }));
|
||||
}
|
||||
}
|
||||
|
||||
/// Enter at "Enter states to change": Save makes the state with this mask and keeps the toggles
|
||||
/// for the next Save; Edit sets the state's mask and keeps the bits no toggle reaches (AutoCAD's
|
||||
/// 65536 after a restore). Edit leaves the next Save's toggles alone (measured).
|
||||
fn finish(s: &mut Session, name: &str, mask: u32, edit: bool) {
|
||||
if !edit {
|
||||
if run(s, "layerstate.save", &json!({ "name": name, "mask": mask & LS::ALL })) {
|
||||
s.settings.layer_state_mask = mask & LS::ALL;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Only a changed mask touches the drawing.
|
||||
let Ok(d) = s.doc() else { return };
|
||||
let Some(i) = state_index(d, name).filter(|&i| d.layer_states.get(i).is_some_and(|st| st.mask != mask)) else { return };
|
||||
if let Ok(d) = s.doc_mut()
|
||||
&& let Some(st) = d.layer_states.get_mut(i)
|
||||
{
|
||||
st.mask = mask;
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a `layerstate.*` command, reporting a refusal; `true` when it ran.
|
||||
fn run(s: &mut Session, id: &str, p: &Value) -> bool {
|
||||
match call(s, id, p) {
|
||||
Ok(_) => true,
|
||||
Err(e) => {
|
||||
s.echo(message(&e));
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The toggles as AutoCAD 2024 lists them before "Enter states to change".
|
||||
fn show(s: &mut Session, mask: u32) {
|
||||
s.echo("States");
|
||||
for (_, label, bit) in TOGGLES {
|
||||
s.echo(format!("{label:<20}{}", if mask & bit != 0 { "Yes" } else { "No" }));
|
||||
}
|
||||
}
|
||||
|
||||
/// `?`: every saved state by name without regard to case, as AutoCAD 2024 lists them (measured:
|
||||
/// `S2`, `b`, `S1` saved in that order list as `b`, `S1`, `S2`; a name starting with "*", its
|
||||
/// `*A1`, is listed too).
|
||||
fn list(s: &mut Session) {
|
||||
let mut names: Vec<String> = s.doc().map(|d| d.layer_states.iter().map(|st| st.name.clone()).collect()).unwrap_or_default();
|
||||
names.sort_by_cached_key(|n| n.to_ascii_lowercase());
|
||||
s.echo("Layer state");
|
||||
s.echo("-".repeat(29));
|
||||
for n in names {
|
||||
s.echo(n);
|
||||
}
|
||||
}
|
||||
@@ -864,6 +864,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
let path = _path;
|
||||
// Exclusively create a fresh temporary file and rename it into place so a planted
|
||||
// `<path>.cadcraft-tmp` symlink cannot redirect the plot write (CWE-59).
|
||||
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
|
||||
let folder = super::file::new_folder(path);
|
||||
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
|
||||
|
||||
@@ -187,6 +187,7 @@ fn edit_style(cmd: &str, st: &mut PlotStyle, v: &Value) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// List, read, change, load and export plot style tables; any file is held to the automation roots.
|
||||
fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "stylesmanager";
|
||||
let action = str_param(p, "action").unwrap_or("list").to_ascii_lowercase();
|
||||
@@ -303,6 +304,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, Some(_path)) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_read(_path).map_err(|e| bad(cmd, e))?;
|
||||
let bytes = crate::capped_read::read_capped(std::path::Path::new(_path), cadcraft_doc::MAX_TABLE_FILE)
|
||||
.map_err(|e| bad(cmd, format!("{_path}: {e}")))?;
|
||||
String::from_utf8(bytes).map_err(|e| bad(cmd, format!("{_path}: {e}")))?
|
||||
@@ -331,6 +333,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(_path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_write(_path).map_err(|e| bad(cmd, e))?;
|
||||
crate::atomic_write::write_atomic(std::path::Path::new(_path), text.as_bytes())
|
||||
.map_err(|e| bad(cmd, format!("{_path}: {e}")))?;
|
||||
Ok(json!({ "name": name, "path": _path, "bytes": text.len() }))
|
||||
|
||||
@@ -145,6 +145,7 @@ fn store(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
{
|
||||
// Exclusively create a fresh temporary file and rename it into place so a planted
|
||||
// `<path>.cadcraft-tmp` symlink cannot redirect the write (CWE-59).
|
||||
crate::file_access::check_write(path).map_err(|e| bad("layout.saveas", e))?;
|
||||
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), bytes).map_err(|e| bad("layout.saveas", format!("{path}: {e}")))
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -79,7 +79,9 @@ impl PlotterStore {
|
||||
}
|
||||
PlotterStore {
|
||||
list: || {
|
||||
let rd = match std::fs::read_dir(dir()?) {
|
||||
let d = dir()?;
|
||||
crate::file_access::check_read(&d)?;
|
||||
let rd = match std::fs::read_dir(d) {
|
||||
Ok(rd) => rd,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(e) => return Err(e.to_string()),
|
||||
@@ -92,6 +94,7 @@ impl PlotterStore {
|
||||
},
|
||||
read: |n| {
|
||||
let p = file(n)?;
|
||||
crate::file_access::check_read(&p)?;
|
||||
let len = std::fs::metadata(&p).map_err(|e| format!("{n}: {e}"))?.len();
|
||||
if len > cadcraft_doc::MAX_PLOTTER_FILE as u64 {
|
||||
return Err(format!("{n}: the plotter configuration file is too large"));
|
||||
@@ -100,10 +103,16 @@ impl PlotterStore {
|
||||
},
|
||||
write: |n, t| {
|
||||
let p = file(n)?;
|
||||
// Checked before the folder it lives in is created. The temporary file sits beside it.
|
||||
crate::file_access::check_write(&p)?;
|
||||
std::fs::create_dir_all(dir()?).map_err(|e| e.to_string())?;
|
||||
crate::atomic_write::write_atomic(&p, t.as_bytes()).map_err(|e| format!("{n}: {e}"))
|
||||
},
|
||||
delete: |n| std::fs::remove_file(file(n)?).map_err(|e| format!("{n}: {e}")),
|
||||
delete: |n| {
|
||||
let p = file(n)?;
|
||||
crate::file_access::check_write(&p)?;
|
||||
std::fs::remove_file(p).map_err(|e| format!("{n}: {e}"))
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -547,11 +556,18 @@ fn edit_device(cmd: &str, c: &mut PlotterConfig, p: &Value) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// List, read, change, load, export and delete plotter configurations; any file is held to the automation roots.
|
||||
fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "plottermanager";
|
||||
let action = str_param(p, "action").unwrap_or("list").trim().to_ascii_lowercase();
|
||||
match action.as_str() {
|
||||
"list" => Ok(json!({ "devices": devices().iter().map(summary).collect::<Vec<_>>() })),
|
||||
"list" => {
|
||||
// Under the roots a refused settings folder is an error, not a short list.
|
||||
if crate::file_access::current().is_some() {
|
||||
(store().list)().map_err(|e| bad(cmd, e))?;
|
||||
}
|
||||
Ok(json!({ "devices": devices().iter().map(summary).collect::<Vec<_>>() }))
|
||||
}
|
||||
"get" => {
|
||||
let n = device_name(cmd, p)?;
|
||||
let c = find_device(&n).ok_or_else(|| unknown_device(cmd, &n))?;
|
||||
@@ -636,6 +652,7 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(_path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_write(_path).map_err(|e| bad(cmd, e))?;
|
||||
std::fs::write(_path, &text).map_err(|e| bad(cmd, format!("{_path}: {e}")))?;
|
||||
Ok(json!({ "name": name, "path": _path }))
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("rename", "Rename...", run_rename)
|
||||
.menu(&["Format", "Rename..."])
|
||||
.alias(&["ren", "-rename"])
|
||||
.params("{table: layer|linetype|style|dimstyle|block|mleaderstyle|tablestyle|view|ucs|vport, from, to}")
|
||||
.params("{table: layer|linetype|style|dimstyle|block|mleaderstyle|tablestyle|view|ucs, from, to}")
|
||||
.interactive(|_| Ok(Box::new(rename::RenameM::default()))),
|
||||
]
|
||||
}
|
||||
@@ -995,7 +995,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
"block" => rename::block(s, &from, &to)?,
|
||||
"mleaderstyle" | "multileaderstyle" => rename::simple(s, "mleaderstyle", &from, &to)?,
|
||||
"tablestyle" | "view" | "ucs" | "vport" => rename::simple(s, &table, &from, &to)?,
|
||||
"tablestyle" | "view" | "ucs" => rename::simple(s, &table, &from, &to)?,
|
||||
"style" | "textstyle" => {
|
||||
run_style_rename(s, &json!({ "from": from, "to": to }))?;
|
||||
}
|
||||
|
||||
@@ -93,8 +93,6 @@ pub(super) fn simple(s: &mut Session, table: &str, from: &str, to: &str) -> Resu
|
||||
"tablestyle" => d.table_styles.iter_mut().map(|t| &mut t.name).collect(),
|
||||
"view" => d.views.iter_mut().map(|t| &mut t.name).collect(),
|
||||
"ucs" => d.ucss.iter_mut().map(|t| &mut t.name).collect(),
|
||||
// A saved viewport configuration, every tile of it; never the one shown (`*Active`).
|
||||
"vport" => d.vports.iter_mut().filter(|v| !v.is_active()).map(|t| &mut t.name).collect(),
|
||||
_ => return Err(bad("rename", "unsupported table")),
|
||||
};
|
||||
if !to.eq_ignore_ascii_case(from) && names.iter().any(|n| n.eq_ignore_ascii_case(&to)) {
|
||||
@@ -136,47 +134,35 @@ const TYPES: &[(&str, Option<&str>, &str)] = &[
|
||||
("Plotstyle", None, "plot style"),
|
||||
("textStyle", Some("style"), "text style"),
|
||||
("Tablestyle", Some("tablestyle"), "table style"),
|
||||
("Ucs", Some("ucs"), "ucs"),
|
||||
("Ucs", Some("ucs"), "UCS"),
|
||||
("VIew", Some("view"), "view"),
|
||||
("VPort", Some("vport"), "viewport configuration"),
|
||||
("VPort", None, "viewport configuration"),
|
||||
];
|
||||
|
||||
/// The noun in "Cannot find …" and "Invalid … name.": AutoCAD 2024 writes "UCS" there, "ucs" in
|
||||
/// its prompts and in "A ucs named … already exists." (measured).
|
||||
fn title(noun: &str) -> &str {
|
||||
if noun == "ucs" { "UCS" } else { noun }
|
||||
}
|
||||
|
||||
/// Keyword-only: spaces separate inputs.
|
||||
const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
|
||||
/// A name: Space ends the input.
|
||||
const NAME: Accept = Accept { number: true, ..Accept::TEXT };
|
||||
|
||||
fn any_named<'a>(mut names: impl Iterator<Item = &'a String>, name: &str) -> Option<String> {
|
||||
names.find(|n| n.eq_ignore_ascii_case(name)).cloned()
|
||||
fn any_named<'a>(mut names: impl Iterator<Item = &'a String>, name: &str) -> bool {
|
||||
names.any(|n| n.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The name as the drawing spells it of the `table` entry named `name` (without regard to case).
|
||||
fn stored(d: &Drawing, table: &str, name: &str) -> Option<String> {
|
||||
fn exists(d: &Drawing, table: &str, name: &str) -> bool {
|
||||
match table {
|
||||
"block" => d.block(name).map(|t| t.name.clone()),
|
||||
"layer" => d.layer(name).map(|t| t.name.clone()),
|
||||
"linetype" => d.linetype(name).map(|t| t.name.clone()),
|
||||
"style" => d.text_style(name).map(|t| t.name.clone()),
|
||||
"dimstyle" => d.dim_style(name).map(|t| t.name.clone()),
|
||||
"block" => d.block(name).is_some(),
|
||||
"layer" => d.layer(name).is_some(),
|
||||
"linetype" => d.linetype(name).is_some(),
|
||||
"style" => d.text_style(name).is_some(),
|
||||
"dimstyle" => d.dim_style(name).is_some(),
|
||||
"mleaderstyle" => any_named(d.mleader_styles.iter().map(|t| &t.name), name),
|
||||
"tablestyle" => any_named(d.table_styles.iter().map(|t| &t.name), name),
|
||||
"view" => any_named(d.views.iter().map(|t| &t.name), name),
|
||||
"ucs" => any_named(d.ucss.iter().map(|t| &t.name), name),
|
||||
"vport" => any_named(d.vports.iter().filter(|v| !v.is_active()).map(|t| &t.name), name),
|
||||
_ => Some(name.to_string()),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn exists(d: &Drawing, table: &str, name: &str) -> bool {
|
||||
stored(d, table, name).is_some()
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
enum Stage {
|
||||
#[default]
|
||||
@@ -213,15 +199,6 @@ impl Interactive for RenameM {
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
// No new name is an invalid one (AutoCAD 2024, measured for layers, blocks, views and
|
||||
// viewport configurations).
|
||||
if i == Input::Enter
|
||||
&& let Stage::New(t, _) = &self.stage
|
||||
&& let Some((_, Some(_), noun)) = TYPES.get(*t)
|
||||
{
|
||||
s.echo(format!("Invalid {} name.", title(noun)));
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
if matches!(i, Input::Cancel | Input::Enter) {
|
||||
return Ok(if i == Input::Cancel { Step::Cancel } else { Step::Done });
|
||||
}
|
||||
@@ -240,41 +217,12 @@ impl Interactive for RenameM {
|
||||
self.stage = Stage::Old(t);
|
||||
return Ok(Step::Continue);
|
||||
};
|
||||
// AutoCAD 2024 ends -RENAME on an old name it won't rename (measured): "Invalid … name."
|
||||
// for a viewport configuration or block whose name starts with "*" (*Active,
|
||||
// *Model_Space, an anonymous block's *U0) and for linetypes ByLayer and ByBlock;
|
||||
// "Cannot rename …" and "*Invalid*" for layer 0 and linetype Continuous.
|
||||
let invalid = match *table {
|
||||
Some("vport" | "block") => name.starts_with('*'),
|
||||
Some("linetype") => name.eq_ignore_ascii_case("bylayer") || name.eq_ignore_ascii_case("byblock"),
|
||||
_ => false,
|
||||
};
|
||||
if invalid {
|
||||
s.echo(format!("Invalid {} name.", title(noun)));
|
||||
return Ok(Step::Done);
|
||||
if let Some(table) = table
|
||||
&& !exists(s.doc()?, table, &name)
|
||||
{
|
||||
self.stage = Stage::Old(t);
|
||||
return Err(EngineError::Other(format!("No {noun} named \"{name}\".")));
|
||||
}
|
||||
let fixed = match *table {
|
||||
Some("layer") => name == "0",
|
||||
Some("linetype") => name.eq_ignore_ascii_case("continuous"),
|
||||
_ => false,
|
||||
};
|
||||
if fixed {
|
||||
s.echo(format!("Cannot rename {} \"{name}\".", title(noun)));
|
||||
s.echo("*Invalid*");
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
// The old name as the drawing spells it: a new name in another case than that is a
|
||||
// rename, even when it is the old name as typed (AutoCAD 2024, measured).
|
||||
let name = match table {
|
||||
Some(table) => match stored(s.doc()?, table, &name) {
|
||||
Some(n) => n,
|
||||
None => {
|
||||
s.echo(format!("Cannot find {} \"{name}\".", title(noun)));
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
},
|
||||
None => name,
|
||||
};
|
||||
self.stage = Stage::New(t, name);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
@@ -287,19 +235,6 @@ impl Interactive for RenameM {
|
||||
s.echo(format!("Renaming a {noun} is not available yet."));
|
||||
return Ok(Step::Done);
|
||||
};
|
||||
// AutoCAD 2024's messages, each ending the command (measured).
|
||||
if !valid_name(&name) {
|
||||
s.echo(format!("Invalid {} name.", title(noun)));
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
if !name.eq_ignore_ascii_case(&old) && exists(s.doc()?, table, &name) {
|
||||
s.echo(format!("A {noun} named \"{name}\" already exists."));
|
||||
s.echo("*Invalid*");
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
if name == old {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
match super::run_rename(s, &json!({ "table": table, "from": old, "to": name })) {
|
||||
Ok(_) => Ok(Step::Done),
|
||||
Err(e) => {
|
||||
|
||||
@@ -238,6 +238,7 @@ fn read_link(id: &str, file: &std::path::Path) -> Result<String> {
|
||||
let path = file.display();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_read(file).map_err(|e| bad(id, e))?;
|
||||
// The limit is enforced on the bytes read, not on reported metadata, so a device or FIFO
|
||||
// that misreports its length can't be buffered to EOF.
|
||||
let bytes = crate::capped_read::read_capped(file, MAX_LINK_BYTES).map_err(|e| bad(id, format!("{path}: {e}")))?;
|
||||
|
||||
@@ -514,6 +514,7 @@ pub(crate) fn table_csv(t: &Table, sep: char) -> String {
|
||||
fn write_text(path: &str, text: &str) -> Result<()> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::file_access::check_write(path).map_err(|e| bad("tableexport", e))?;
|
||||
std::fs::write(path, text).map_err(|e| bad("tableexport", format!("{path}: {e}")))
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -138,7 +138,7 @@ fn save(s: &mut Session, name: &str, window: Option<Bounds2>, snapshot: bool) ->
|
||||
let layer_state = snapshot.then(|| {
|
||||
let state = snapshot_name(name);
|
||||
d.layer_states.retain(|l| !l.name.eq_ignore_ascii_case(&state));
|
||||
d.layer_states.push(LayerState::new(state.clone(), d.layers.clone(), ""));
|
||||
d.layer_states.push(LayerState { name: state.clone(), layers: d.layers.clone() });
|
||||
state
|
||||
});
|
||||
if let Some(old) = &replaced {
|
||||
|
||||
@@ -0,0 +1,781 @@
|
||||
//! The folders automation may read and write (#1472).
|
||||
//!
|
||||
//! `cadcraft-cli mcp --automation-read-root <dir> --automation-write-root <dir>` confines the files
|
||||
//! an agent's commands reach. [`AutomationRoots`] holds the two folders. While they are in force,
|
||||
//! every path a command reads goes through [`check_read`] and every path it writes through
|
||||
//! [`check_write`]:
|
||||
//!
|
||||
//! - The path is made absolute against the working directory, as the file system reads it. Its
|
||||
//! links are followed: for a file that doesn't exist yet, the links of its nearest existing
|
||||
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
|
||||
//! is a link that leads nowhere).
|
||||
//! - On Windows a network path (`\\server\share`, `\\?\UNC\...`), a device path (`\\.\...`) or a
|
||||
//! verbatim path that isn't a disk is refused before anything opens it, unless a root is already
|
||||
//! on that same server and share (or that same device or prefix). A link whose target is one of
|
||||
//! those is refused from the target text, before the link is followed. Opening such a path would
|
||||
//! contact a host the agent named.
|
||||
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
|
||||
//! `/work`) and exactly: both sides have been through the file system, which gives each folder
|
||||
//! its real name, and a Windows folder can be case sensitive, with `Root` beside `root`.
|
||||
//! - Reads may lie under either root; writes only under the write root, and never at the write
|
||||
//! root itself (its save-style temporary file would be outside). A root given alone grants
|
||||
//! reads under it even when it is the write root; a read root grants no writes.
|
||||
//!
|
||||
//! Roots are in force on a thread inside [`confine`]. The MCP headless backend runs every call in
|
||||
//! it; without roots nothing is checked, so the app and the command line keep working everywhere.
|
||||
//!
|
||||
//! A path is checked, then opened: a process that can change the folders in between (swapping in
|
||||
//! a link) can still win that race. A network, device or non-disk verbatim path is not opened at
|
||||
//! all. The roots keep an agent to the files it was given; they don't guard against other
|
||||
//! programs on the computer.
|
||||
|
||||
pub mod commands;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Read access or write access.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Access {
|
||||
Read,
|
||||
Write,
|
||||
}
|
||||
|
||||
/// The folders automation may read and write; a root left out grants no access of its kind.
|
||||
#[derive(Debug)]
|
||||
pub struct AutomationRoots {
|
||||
read: Option<PathBuf>,
|
||||
write: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// The folder at `path`, which must exist, made absolute with its links followed: what paths are
|
||||
/// compared with.
|
||||
fn open_root(path: &Path, access: Access) -> Result<PathBuf, String> {
|
||||
let kind = match access {
|
||||
Access::Read => "read",
|
||||
Access::Write => "write",
|
||||
};
|
||||
std::fs::canonicalize(path)
|
||||
.and_then(|p| if p.is_dir() { Ok(p) } else { Err(std::io::ErrorKind::NotADirectory.into()) })
|
||||
.map_err(|e| format!("cannot open the automation {kind} root `{}`: {e}", path.display()))
|
||||
}
|
||||
|
||||
impl AutomationRoots {
|
||||
/// The roots `read` and `write`, which must be existing folders; `None` when neither is given
|
||||
/// (nothing is confined then).
|
||||
pub fn new(read: Option<&Path>, write: Option<&Path>) -> Result<Option<Arc<Self>>, String> {
|
||||
if read.is_none() && write.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let read = read.map(|p| open_root(p, Access::Read)).transpose()?;
|
||||
let write = write.map(|p| open_root(p, Access::Write)).transpose()?;
|
||||
Ok(Some(Arc::new(Self { read, write })))
|
||||
}
|
||||
|
||||
/// The read root, absolute with its links followed.
|
||||
pub fn read_root(&self) -> Option<&Path> {
|
||||
self.read.as_deref()
|
||||
}
|
||||
|
||||
/// The write root, absolute with its links followed.
|
||||
pub fn write_root(&self) -> Option<&Path> {
|
||||
self.write.as_deref()
|
||||
}
|
||||
|
||||
/// May the file or folder at `path` be read (or written)? `Err` says why not.
|
||||
///
|
||||
/// A read may lie under either root: the read root, or the write root (files the agent may
|
||||
/// write it may also read back). A write may lie only under the write root, and not at the
|
||||
/// root itself, whose save-style temporary file would sit beside it. Its name must stand there
|
||||
/// too: a link outside pointing in is refused, since what is written beside the name (a
|
||||
/// drawing's `.bak`) or done to it (a delete) happens in the folder that holds it.
|
||||
///
|
||||
/// A path is taken as it is: turned into text on the way, a name that isn't text would name a
|
||||
/// different file.
|
||||
pub fn check(&self, given: impl AsRef<Path>, access: Access) -> Result<(), String> {
|
||||
let given = given.as_ref();
|
||||
let target = resolve(given, self)?;
|
||||
let path = given.display();
|
||||
if access == Access::Read {
|
||||
let roots = [self.read.as_ref(), self.write.as_ref()];
|
||||
if roots.iter().flatten().any(|r| inside(&target, r)) {
|
||||
return Ok(());
|
||||
}
|
||||
if roots.iter().all(|r| r.is_none()) {
|
||||
return Err(format!("automation filesystem access is not granted: read authority is absent: {path}"));
|
||||
}
|
||||
return Err(format!("automation path rejected: outside the read root (or the write root): {path}"));
|
||||
}
|
||||
let Some(folder) = self.write.as_ref() else {
|
||||
return Err(format!("automation filesystem access is not granted: write authority is absent: {path}"));
|
||||
};
|
||||
if !inside(&target, folder) {
|
||||
return Err(format!("automation path rejected: outside the write root {}: {path}", folder.display()));
|
||||
}
|
||||
// A write to the root itself would put its temporary file beside the root, outside it.
|
||||
if same(&target, folder) {
|
||||
return Err(format!("automation path rejected: the write root itself cannot be written: {path}"));
|
||||
}
|
||||
if !inside(&resolve(given.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")), self)?, folder) {
|
||||
return Err(format!("automation path rejected: stands outside the write root {}: {path}", folder.display()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The roots in force on this thread.
|
||||
static ROOTS: RefCell<Option<Arc<AutomationRoots>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Puts the roots it replaced back when dropped (also when `f` panics).
|
||||
struct Restore(Option<Arc<AutomationRoots>>);
|
||||
|
||||
impl Drop for Restore {
|
||||
/// Puts the roots it replaced back.
|
||||
fn drop(&mut self) {
|
||||
ROOTS.with(|r| *r.borrow_mut() = self.0.take());
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` with `roots` in force on this thread (`None`: as things stand).
|
||||
pub fn confine<T>(roots: Option<&Arc<AutomationRoots>>, f: impl FnOnce() -> T) -> T {
|
||||
let previous = ROOTS.with(|r| r.replace(roots.cloned()));
|
||||
let _restore = Restore(previous);
|
||||
f()
|
||||
}
|
||||
|
||||
/// This thread's roots, if any.
|
||||
pub fn current() -> Option<Arc<AutomationRoots>> {
|
||||
ROOTS.with(|r| r.borrow().clone())
|
||||
}
|
||||
|
||||
/// May `path` be read here? Always, without roots in force.
|
||||
pub fn check_read(path: impl AsRef<Path>) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Read))
|
||||
}
|
||||
|
||||
/// May `path` be written here? Always, without roots in force.
|
||||
pub fn check_write(path: impl AsRef<Path>) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))
|
||||
}
|
||||
|
||||
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
|
||||
/// existing folder's links followed and the rest appended.
|
||||
///
|
||||
/// A Windows network, device or non-disk verbatim prefix is refused before any of that, unless
|
||||
/// `roots` already stands on the same server and share (or the same device or prefix).
|
||||
fn resolve(path: &Path, roots: &AutomationRoots) -> Result<PathBuf, String> {
|
||||
let shown = path.display();
|
||||
if path.as_os_str().is_empty() {
|
||||
return Err("automation path rejected: path is empty".into());
|
||||
}
|
||||
// Checked as given: making `…\NUL` absolute gives the device path `\\.\NUL` on Windows.
|
||||
if cfg!(windows) && path.components().any(|c| matches!(c, Component::Normal(n) if n.to_str().is_some_and(is_device_name))) {
|
||||
return Err(format!("automation path rejected: reserved device names are not allowed: {shown}"));
|
||||
}
|
||||
// Before `absolute` too: on Windows that call asks the system about the path.
|
||||
if let Some(why) = refused_prefix(path, roots) {
|
||||
return Err(format!("automation path rejected: {why}: {shown}"));
|
||||
}
|
||||
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))?;
|
||||
if let Some(why) = refused_prefix(&absolute, roots) {
|
||||
return Err(format!("automation path rejected: {why}: {shown}"));
|
||||
}
|
||||
// The names below the nearest existing folder, last first.
|
||||
let mut missing: Vec<OsString> = vec![];
|
||||
let mut at = absolute.as_path();
|
||||
loop {
|
||||
// A link to a network path is judged from the target text. Canonicalizing it would follow
|
||||
// the link and contact that host. Only Windows has those prefixes, so other targets skip
|
||||
// the walk.
|
||||
#[cfg(windows)]
|
||||
if let Some(why) = link_leads_to_refused_prefix(at, roots) {
|
||||
return Err(format!("automation path rejected: {why}: {shown}"));
|
||||
}
|
||||
match std::fs::canonicalize(at) {
|
||||
Ok(mut found) => {
|
||||
found.extend(missing.iter().rev());
|
||||
return Ok(found);
|
||||
}
|
||||
Err(e) => match std::fs::symlink_metadata(at) {
|
||||
Ok(m) if m.file_type().is_symlink() => return Err(format!("automation path rejected: a link that leads nowhere: {shown}")),
|
||||
// There, yet its real path can't be had (no permission): nothing to compare.
|
||||
Ok(_) => return Err(format!("automation path rejected: cannot resolve {shown}: {e}")),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(format!("automation path rejected: cannot resolve {shown}: {e}")),
|
||||
},
|
||||
}
|
||||
let parent = at.parent();
|
||||
match (at.components().next_back(), parent) {
|
||||
(Some(Component::Normal(name)), Some(parent)) => {
|
||||
missing.push(name.to_os_string());
|
||||
at = parent;
|
||||
}
|
||||
(Some(Component::ParentDir), _) => {
|
||||
return Err(format!("automation path rejected: parent traversal below a folder that doesn't exist: {shown}"));
|
||||
}
|
||||
// Down to the root (or drive) and it doesn't exist either.
|
||||
_ => {
|
||||
let e = std::io::Error::from(std::io::ErrorKind::NotFound);
|
||||
return Err(format!("automation path rejected: cannot resolve {shown}: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `path` must not be opened: it is a Windows network, device or non-disk verbatim path, and
|
||||
/// no root already uses that prefix. A local disk path returns `None`.
|
||||
///
|
||||
/// The comparison is ASCII case only, so `FileServer` matches `fileserver` and U+212A does not
|
||||
/// match `k`. Matching only decides whether that host may be contacted; [`inside`] still decides
|
||||
/// the folder.
|
||||
fn refused_prefix(path: &Path, roots: &AutomationRoots) -> Option<&'static str> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let key = windows_prefix(path)?;
|
||||
let allowed = [roots.read.as_ref(), roots.write.as_ref()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|root| windows_prefix(root).is_some_and(|root_key| prefixes_match(&root_key, &key)));
|
||||
if allowed { None } else { Some(key.refusal()) }
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = (path, roots);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The refusal for a link in `path`, taken from the link's own text.
|
||||
///
|
||||
/// Folders are inspected from the root downward with [`std::fs::symlink_metadata`], which does not
|
||||
/// follow a link, and the target is read with [`std::fs::read_link`]. A link to a network path is
|
||||
/// therefore refused before [`std::fs::canonicalize`] would open that host, including when the
|
||||
/// link is only an ancestor of the name. At most [`MAX_LINK_HOPS`] links are followed; one more,
|
||||
/// or a link whose target cannot be read, is refused instead of being opened.
|
||||
#[cfg(windows)]
|
||||
fn link_leads_to_refused_prefix(path: &Path, roots: &AutomationRoots) -> Option<&'static str> {
|
||||
follow_links(path, roots, MAX_LINK_HOPS)
|
||||
}
|
||||
|
||||
/// [`link_leads_to_refused_prefix`], with `hops_left` links still allowed.
|
||||
#[cfg(windows)]
|
||||
fn follow_links(path: &Path, roots: &AutomationRoots, hops_left: usize) -> Option<&'static str> {
|
||||
if let Some(why) = refused_prefix(path, roots) {
|
||||
return Some(why);
|
||||
}
|
||||
let mut ancestors: Vec<&Path> = path.ancestors().collect();
|
||||
ancestors.reverse();
|
||||
for prefix in ancestors {
|
||||
// A relative path's ancestor list ends at an empty name. Absolute paths, which are all
|
||||
// this is called with, have no empty ancestor; skip it rather than treating it as missing.
|
||||
if prefix.as_os_str().is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(why) = refused_prefix(prefix, roots) {
|
||||
return Some(why);
|
||||
}
|
||||
let Ok(meta) = std::fs::symlink_metadata(prefix) else { return None };
|
||||
if !meta.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
if hops_left == 0 {
|
||||
return Some("too many links");
|
||||
}
|
||||
let Ok(target) = std::fs::read_link(prefix) else { return Some("a link that leads nowhere") };
|
||||
let joined = if target.is_absolute() {
|
||||
target
|
||||
} else {
|
||||
match prefix.parent() {
|
||||
Some(parent) if !parent.as_os_str().is_empty() => parent.join(target),
|
||||
_ => target,
|
||||
}
|
||||
};
|
||||
let rest = match path.strip_prefix(prefix) {
|
||||
Ok(rest) if !rest.as_os_str().is_empty() => rest,
|
||||
_ => Path::new(""),
|
||||
};
|
||||
let next = if rest.as_os_str().is_empty() { joined } else { joined.join(rest) };
|
||||
if let Some(why) = refused_prefix(&next, roots) {
|
||||
return Some(why);
|
||||
}
|
||||
return follow_links(&next, roots, hops_left - 1);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// How many links [`link_leads_to_refused_prefix`] follows before it stops.
|
||||
#[cfg(windows)]
|
||||
const MAX_LINK_HOPS: usize = 40;
|
||||
|
||||
/// A Windows prefix that is not a local disk.
|
||||
#[cfg(windows)]
|
||||
enum WindowsPrefix {
|
||||
/// `\\server\share` or `\\?\UNC\server\share`.
|
||||
Unc(OsString, OsString),
|
||||
/// `\\.\device`.
|
||||
Device(OsString),
|
||||
/// `\\?\` that is neither a disk nor `UNC`.
|
||||
Verbatim(OsString),
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl WindowsPrefix {
|
||||
/// The error text for a path with this prefix.
|
||||
fn refusal(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Unc(_, _) => "UNC paths are refused unless a root is on the same server and share",
|
||||
Self::Device(_) => "device paths are refused unless a root uses the same device",
|
||||
Self::Verbatim(_) => "verbatim paths are refused unless a root uses the same prefix",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `path`'s Windows prefix when it is not a local disk.
|
||||
#[cfg(windows)]
|
||||
fn windows_prefix(path: &Path) -> Option<WindowsPrefix> {
|
||||
use std::path::Prefix;
|
||||
let Component::Prefix(prefix) = path.components().next()? else { return None };
|
||||
match prefix.kind() {
|
||||
Prefix::Disk(_) | Prefix::VerbatimDisk(_) => None,
|
||||
Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => Some(WindowsPrefix::Unc(server.to_os_string(), share.to_os_string())),
|
||||
Prefix::DeviceNS(device) => Some(WindowsPrefix::Device(device.to_os_string())),
|
||||
Prefix::Verbatim(rest) => Some(WindowsPrefix::Verbatim(rest.to_os_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` may be opened because `root` already stands on the same server and share,
|
||||
/// device or verbatim prefix. ASCII case only.
|
||||
#[cfg(windows)]
|
||||
fn prefixes_match(root: &WindowsPrefix, path: &WindowsPrefix) -> bool {
|
||||
let same = |a: &std::ffi::OsStr, b: &std::ffi::OsStr| a.eq_ignore_ascii_case(b);
|
||||
match (root, path) {
|
||||
(WindowsPrefix::Unc(server, share), WindowsPrefix::Unc(path_server, path_share)) => same(server, path_server) && same(share, path_share),
|
||||
(WindowsPrefix::Device(root_device), WindowsPrefix::Device(path_device)) => same(root_device, path_device),
|
||||
(WindowsPrefix::Verbatim(root_prefix), WindowsPrefix::Verbatim(path_prefix)) => same(root_prefix, path_prefix),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `path` (resolved) `root` or inside it, component by component?
|
||||
fn inside(path: &Path, root: &Path) -> bool {
|
||||
let mut path = path.components();
|
||||
root.components().all(|r| path.next() == Some(r))
|
||||
}
|
||||
|
||||
/// Is `path` (resolved) exactly `root`, compared like [`inside`] does?
|
||||
fn same(path: &Path, root: &Path) -> bool {
|
||||
path.components().eq(root.components())
|
||||
}
|
||||
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`, `LPT¹`… also with an extension or a `:`), which
|
||||
/// names no file.
|
||||
fn is_device_name(component: &str) -> bool {
|
||||
let stem = component.split(['.', ':']).next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
|
||||
let numbered = |prefix: &str| {
|
||||
stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"))
|
||||
};
|
||||
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A folder of a test's own, removed when the test ends, also when it fails.
|
||||
struct TestDir(PathBuf);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
type Target = Path;
|
||||
/// The folder itself.
|
||||
fn deref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestDir {
|
||||
/// Removes the folder and all it holds; a failure here must not hide the test's own.
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new folder of this test's own: made here, so nothing else put it there first.
|
||||
fn fresh_dir(tag: &str) -> TestDir {
|
||||
let mut n = 0u32;
|
||||
loop {
|
||||
let dir = std::env::temp_dir().join(format!("cc-file-access-{tag}-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => return TestDir(dir),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1,
|
||||
Err(e) => panic!("{}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder holding `in` (read root), `out` (write root) and `outside`.
|
||||
fn folders(name: &str) -> (TestDir, Arc<AutomationRoots>) {
|
||||
let base = fresh_dir(name);
|
||||
for d in ["in/sub", "out", "outside", "in2"] {
|
||||
std::fs::create_dir_all(base.join(d)).unwrap();
|
||||
}
|
||||
std::fs::write(base.join("in/a.dxf"), "0\nEOF\n").unwrap();
|
||||
std::fs::write(base.join("outside/secret.dxf"), "0\nEOF\n").unwrap();
|
||||
let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("out"))).unwrap().unwrap();
|
||||
(base, roots)
|
||||
}
|
||||
|
||||
/// `p` as a string a command would pass.
|
||||
fn s(p: PathBuf) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Paths under either root may be read; writes stay inside the write root.
|
||||
#[test]
|
||||
fn paths_inside_the_roots_pass_and_others_dont() {
|
||||
let (base, roots) = folders("inside");
|
||||
assert_eq!(roots.check(s(base.join("in/a.dxf")), Access::Read), Ok(()));
|
||||
assert_eq!(roots.check(s(base.join("in")), Access::Read), Ok(()), "the root itself");
|
||||
assert_eq!(roots.check(s(base.join("in/sub/new.dxf")), Access::Read), Ok(()), "missing files are checked by their folder");
|
||||
assert_eq!(roots.check(s(base.join("out/new/deeper/x.png")), Access::Write), Ok(()), "and by their nearest folder");
|
||||
let e = roots.check(s(base.join("outside/secret.dxf")), Access::Read).unwrap_err();
|
||||
assert!(e.starts_with("automation path rejected: outside the read root"), "{e}");
|
||||
// Reads are allowed under the write root too; writes are not allowed under the read root.
|
||||
assert_eq!(roots.check(s(base.join("out/x.png")), Access::Read), Ok(()), "the write root also grants reads");
|
||||
let e = roots.check(s(base.join("in/a.dxf")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
}
|
||||
|
||||
/// A write-only root still permits reads inside it; reads outside both roots are refused.
|
||||
#[test]
|
||||
fn reads_are_allowed_under_either_root() {
|
||||
let (base, _) = folders("either");
|
||||
let write_only = AutomationRoots::new(None, Some(&base.join("out"))).unwrap().unwrap();
|
||||
assert_eq!(write_only.check(s(base.join("out/new.dxf")), Access::Read), Ok(()), "a file to read back");
|
||||
let e = write_only.check(s(base.join("in/a.dxf")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("outside the read root (or the write root)"), "{e}");
|
||||
let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap();
|
||||
assert_eq!(read_only.check(s(base.join("in/a.dxf")), Access::Read), Ok(()));
|
||||
assert!(read_only.check(s(base.join("out/new.dxf")), Access::Read).is_err(), "a read root alone grants no read of another folder");
|
||||
}
|
||||
|
||||
/// A write to the write root itself would put its `.cadcraft-tmp` file beside the root: refused.
|
||||
#[test]
|
||||
fn writing_to_the_write_root_itself_is_refused() {
|
||||
let (base, roots) = folders("write-root");
|
||||
let out = s(base.join("out"));
|
||||
let sep = std::path::MAIN_SEPARATOR;
|
||||
for p in [out.clone(), format!("{out}{sep}."), format!("{out}{sep}..{sep}out")] {
|
||||
let e = roots.check(&p, Access::Write).unwrap_err();
|
||||
assert!(e.contains("the write root itself cannot be written"), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(roots.check(&out, Access::Read), Ok(()), "reading the root stays allowed");
|
||||
assert_eq!(roots.check(s(base.join("out/new/x.png")), Access::Write), Ok(()), "a normal save inside still works");
|
||||
}
|
||||
|
||||
/// `in2` starts like `in` and isn't inside it.
|
||||
#[test]
|
||||
fn a_sibling_with_the_same_prefix_is_outside() {
|
||||
let (base, roots) = folders("prefix");
|
||||
std::fs::write(base.join("in2/b.dxf"), "0\nEOF\n").unwrap();
|
||||
assert!(roots.check(s(base.join("in2/b.dxf")), Access::Read).is_err(), "in2 is not inside in");
|
||||
assert!(roots.check(format!("{}2/c.dxf", s(base.join("in"))), Access::Read).is_err());
|
||||
}
|
||||
|
||||
/// `..` is followed where it can be, and refused below a missing folder.
|
||||
#[test]
|
||||
fn parent_traversal_is_resolved_or_refused() {
|
||||
let (base, roots) = folders("dotdot");
|
||||
let sep = std::path::MAIN_SEPARATOR;
|
||||
let up = format!("{}{sep}..{sep}outside{sep}secret.dxf", s(base.join("in")));
|
||||
assert!(roots.check(&up, Access::Read).unwrap_err().contains("outside the read root"), "`..` out of the root");
|
||||
let back = format!("{}{sep}..{sep}a.dxf", s(base.join("in/sub")));
|
||||
assert_eq!(roots.check(&back, Access::Read), Ok(()), "`..` that stays inside");
|
||||
let missing = format!("{}{sep}nope{sep}..{sep}..{sep}outside{sep}x.dxf", s(base.join("out")));
|
||||
let e = roots.check(&missing, Access::Write).unwrap_err();
|
||||
// Windows resolves `..` by name first (so does opening the file there): then it's outside.
|
||||
assert!(e.contains("parent traversal below a folder that doesn't exist") || e.contains("outside the write root"), "{e}");
|
||||
}
|
||||
|
||||
/// A relative path means the working directory, and an empty one is refused.
|
||||
#[test]
|
||||
fn relative_paths_resolve_against_the_working_directory() {
|
||||
let (_base, roots) = folders("relative");
|
||||
// The tests' working directory is the crate's folder: not inside the roots.
|
||||
assert!(roots.check("a.dxf", Access::Read).unwrap_err().contains("outside the read root"));
|
||||
assert!(roots.check("", Access::Read).unwrap_err().contains("path is empty"));
|
||||
}
|
||||
|
||||
/// A root must be a folder that exists; no roots at all confines nothing.
|
||||
#[test]
|
||||
fn a_missing_root_is_an_error_and_none_is_no_confinement() {
|
||||
let (base, _) = folders("missing");
|
||||
let e = AutomationRoots::new(Some(&base.join("nope")), None).unwrap_err();
|
||||
assert!(e.starts_with("cannot open the automation read root"), "{e}");
|
||||
let e = AutomationRoots::new(None, Some(&base.join("in/a.dxf"))).unwrap_err();
|
||||
assert!(
|
||||
e.starts_with("cannot open the automation write root")
|
||||
&& e.ends_with(&std::io::Error::from(std::io::ErrorKind::NotADirectory).to_string()),
|
||||
"{e}"
|
||||
);
|
||||
assert!(AutomationRoots::new(Some(Path::new("")), None).unwrap_err().starts_with("cannot open the automation read root ``"));
|
||||
assert!(AutomationRoots::new(None, None).unwrap().is_none());
|
||||
// One root alone grants only its own access.
|
||||
let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap();
|
||||
let e = read_only.check(s(base.join("in/x.dxf")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("write authority is absent"), "{e}");
|
||||
}
|
||||
|
||||
/// Links are judged by where they lead, so a link out is refused and one inside is fine.
|
||||
#[test]
|
||||
fn links_are_followed_before_comparing() {
|
||||
let (base, roots) = folders("links");
|
||||
#[cfg(unix)]
|
||||
let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok();
|
||||
#[cfg(windows)]
|
||||
let made = |target: &Path, link: &Path| {
|
||||
let made =
|
||||
if target.is_dir() { std::os::windows::fs::symlink_dir(target, link) } else { std::os::windows::fs::symlink_file(target, link) };
|
||||
made.is_ok()
|
||||
};
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let made = |_: &Path, _: &Path| false;
|
||||
// Windows needs Developer Mode or elevation to make links: nothing to test without them.
|
||||
if !made(&base.join("outside/secret.dxf"), &base.join("in/leak.dxf")) {
|
||||
eprintln!("skipped: symbolic links can't be made here");
|
||||
return;
|
||||
}
|
||||
assert!(roots.check(s(base.join("in/leak.dxf")), Access::Read).unwrap_err().contains("outside the read root"), "a file link out");
|
||||
assert!(made(&base.join("outside"), &base.join("out/away")));
|
||||
let e = roots.check(s(base.join("out/away/new.png")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "a folder link out: {e}");
|
||||
assert!(made(&base.join("outside/gone.dxf"), &base.join("out/dangling.png")));
|
||||
let e = roots.check(s(base.join("out/dangling.png")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("a link that leads nowhere"), "writing would create the file outside: {e}");
|
||||
// A link to a folder inside the root stays inside.
|
||||
assert!(made(&base.join("in/sub"), &base.join("in/alias")));
|
||||
assert_eq!(roots.check(s(base.join("in/alias/x.dxf")), Access::Read), Ok(()));
|
||||
// A root given through a link is the folder it leads to.
|
||||
assert!(made(&base.join("in"), &base.join("in-link")));
|
||||
let linked = AutomationRoots::new(Some(&base.join("in-link")), None).unwrap().unwrap();
|
||||
assert_eq!(linked.check(s(base.join("in/a.dxf")), Access::Read), Ok(()));
|
||||
}
|
||||
|
||||
/// Names are compared exactly: `Root` isn't `root`, which a case-sensitive folder can hold beside it.
|
||||
#[test]
|
||||
fn a_name_differing_only_in_case_is_not_the_root() {
|
||||
assert!(!inside(Path::new("/w/Root/x"), Path::new("/w/root")));
|
||||
assert!(!same(Path::new("/w/Root"), Path::new("/w/root")));
|
||||
assert!(inside(Path::new("/w/root/x"), Path::new("/w/root")));
|
||||
assert!(same(Path::new("/w/root"), Path::new("/w/root")));
|
||||
}
|
||||
|
||||
/// The superscript ports, `COM0`, `LPT0` and the `:` form are device names.
|
||||
#[test]
|
||||
fn device_names_include_the_superscript_ports() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.dxf", "NUL ", "COM¹", "lpt³.txt", "com²", "NUL:", "con:stream", "COM0", "lpt0.txt"] {
|
||||
assert!(is_device_name(d), "{d}");
|
||||
}
|
||||
for d in ["console.txt", "COM", "COM10", "LPT⁴", "a.nul", "nullable"] {
|
||||
assert!(!is_device_name(d), "{d}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A name that isn't text is checked as itself: the text of it names a file that isn't there,
|
||||
/// which would pass, when the name itself is a link leading out.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_name_that_is_not_text_is_judged_as_itself() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let (base, roots) = folders("not-text");
|
||||
let name = std::ffi::OsStr::from_bytes(b"a\xff.dxf");
|
||||
let link = base.join("in").join(name);
|
||||
// APFS and others refuse such a name: nothing to test there.
|
||||
if std::os::unix::fs::symlink(base.join("outside/secret.dxf"), &link).is_err() {
|
||||
eprintln!("skipped: this file system refuses a name that isn't text");
|
||||
return;
|
||||
}
|
||||
assert!(roots.check(&link, Access::Read).is_err());
|
||||
assert_eq!(roots.check(&*link.to_string_lossy(), Access::Read), Ok(()), "as text it is another file, which isn't there");
|
||||
}
|
||||
|
||||
/// A name is judged by the folder it stands in as well as by where it leads.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_link_standing_outside_the_write_root_is_refused() {
|
||||
let (base, roots) = folders("entry");
|
||||
std::fs::write(base.join("out/t.dxf"), "x").unwrap();
|
||||
let link = base.join("outside/link.dxf");
|
||||
std::os::unix::fs::symlink(base.join("out/t.dxf"), &link).unwrap();
|
||||
assert!(roots.check(&link, Access::Write).unwrap_err().contains("stands outside the write root"));
|
||||
assert_eq!(roots.check(&link, Access::Read), Ok(()), "reading it reads what is inside");
|
||||
let inner = base.join("out/link.dxf");
|
||||
std::os::unix::fs::symlink(base.join("out/t.dxf"), &inner).unwrap();
|
||||
assert_eq!(roots.check(&inner, Access::Write), Ok(()));
|
||||
assert_eq!(roots.check(base.join("out/new/deep/x.dxf"), Access::Write), Ok(()));
|
||||
}
|
||||
|
||||
/// On a real case-sensitive folder, `Root` beside the root `root` is outside it.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_case_sensitive_windows_folder_can_hold_a_sibling_of_the_root() {
|
||||
let base = fresh_dir("sensitive");
|
||||
let sensitive = std::process::Command::new("fsutil").args(["file", "setCaseSensitiveInfo"]).arg(&*base).arg("enable").output();
|
||||
if !sensitive.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("this runner can't make a case-sensitive folder: skipped");
|
||||
return;
|
||||
}
|
||||
std::fs::create_dir(base.join("root")).unwrap();
|
||||
std::fs::create_dir(base.join("Root")).unwrap();
|
||||
std::fs::write(base.join("Root/secret.dxf"), "x").unwrap();
|
||||
let roots = AutomationRoots::new(Some(&base.join("root")), Some(&base.join("root"))).unwrap().unwrap();
|
||||
for p in ["Root/secret.dxf", "Root/new.dxf"] {
|
||||
assert!(roots.check(s(base.join(p)), Access::Read).is_err(), "{p}");
|
||||
assert!(roots.check(s(base.join(p)), Access::Write).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(roots.check(s(base.join("root/new.dxf")), Access::Write), Ok(()));
|
||||
}
|
||||
|
||||
/// On an ordinary Windows folder any case finds the root, and device names are refused.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_gives_a_root_its_real_spelling_and_refuses_devices() {
|
||||
let (base, roots) = folders("case");
|
||||
let upper = s(base.join("IN/A.DXF"));
|
||||
assert_eq!(roots.check(upper.as_str(), Access::Read), Ok(()), "{upper}");
|
||||
assert_eq!(roots.check(s(base.join("In/Sub/New.dxf")), Access::Read), Ok(()));
|
||||
let e = roots.check(s(base.join("out/NUL")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("reserved device names"), "{e}");
|
||||
assert!(roots.check(s(base.join("out/com1.txt")), Access::Write).is_err());
|
||||
assert!(roots.check(s(base.join("out/COM¹")), Access::Write).is_err());
|
||||
assert_eq!(roots.check(s(base.join("out/console.txt")), Access::Write), Ok(()));
|
||||
}
|
||||
|
||||
/// A network, device or non-disk verbatim path is refused before the file system is asked.
|
||||
/// The error names the prefix. It is not the error canonicalize would return.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_network_path_is_refused_before_it_is_opened() {
|
||||
let (base, roots) = folders("unc");
|
||||
let paths = [
|
||||
(r"\\203.0.113.5\s\x.dwg", "UNC"),
|
||||
(r"\\?\UNC\203.0.113.5\s\x.dwg", "UNC"),
|
||||
(r"//203.0.113.5/s/x.dwg", "UNC"),
|
||||
(r"\\host@SSL\share\x.dwg", "UNC"),
|
||||
(r"\\host@SSL@443\share\x.dwg", "UNC"),
|
||||
(r"\\.\PhysicalDrive0", "device path"),
|
||||
(r"\\?\Volume{00000000-0000-0000-0000-000000000000}\x.dwg", "verbatim path"),
|
||||
];
|
||||
for (p, kind) in paths {
|
||||
for access in [Access::Read, Access::Write] {
|
||||
let e = roots.check(p, access).unwrap_err();
|
||||
assert!(e.starts_with("automation path rejected:"), "{p}: {e}");
|
||||
assert!(e.contains(kind), "{p}: {e}");
|
||||
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
let e = roots.check(s(base.join("outside/secret.dxf")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
|
||||
let root = windows_prefix(Path::new(r"\\?\UNC\FileServer\Projects\work")).unwrap();
|
||||
let same = windows_prefix(Path::new(r"\\fileserver\projects\a.dwg")).unwrap();
|
||||
let other_share = windows_prefix(Path::new(r"\\fileserver\secret\a.dwg")).unwrap();
|
||||
let other_host = windows_prefix(Path::new(r"\\203.0.113.5\Projects\a.dwg")).unwrap();
|
||||
let kelvin = windows_prefix(Path::new("\\\\wor\u{212a}\\Projects\\a.dwg")).unwrap();
|
||||
assert!(prefixes_match(&root, &same), "the same server and share, in either spelling");
|
||||
assert!(!prefixes_match(&root, &other_share));
|
||||
assert!(!prefixes_match(&root, &other_host));
|
||||
assert!(!prefixes_match(&root, &kelvin), "U+212A is not k");
|
||||
assert!(windows_prefix(Path::new(r"C:\Projects\a.dwg")).is_none());
|
||||
assert!(windows_prefix(Path::new(r"\\?\C:\Projects\a.dwg")).is_none());
|
||||
}
|
||||
|
||||
/// U+212A is a different folder from `k`, so a write there is outside the root and creates nothing.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_kelvin_sign_is_not_a_way_out_of_the_write_root() {
|
||||
let base = fresh_dir("kelvin");
|
||||
let root = base.join("work");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let roots = AutomationRoots::new(Some(&root), Some(&root)).unwrap().unwrap();
|
||||
let sibling = base.join("wor\u{212a}").join("x.dwg");
|
||||
let e = roots.check(s(sibling), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
assert!(!base.join("wor\u{212a}").exists(), "the check must not create the folder");
|
||||
assert_eq!(roots.check(s(root.join("new.dxf")), Access::Write), Ok(()));
|
||||
}
|
||||
|
||||
/// A junction needs no extra privilege. One that leads out of the write root is outside it.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_junction_out_of_the_write_root_is_refused() {
|
||||
let (base, roots) = folders("junction");
|
||||
let link = base.join("out").join("away");
|
||||
let made = std::process::Command::new("cmd").args(["/c", "mklink", "/J"]).arg(&link).arg(base.join("outside")).status();
|
||||
if !made.is_ok_and(|s| s.success()) {
|
||||
eprintln!("skipped: junctions can't be made here");
|
||||
return;
|
||||
}
|
||||
let e = roots.check(s(link.join("new.png")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
assert!(!base.join("outside/new.png").exists());
|
||||
}
|
||||
|
||||
/// A link whose text names a network path is refused before that path is opened.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_link_to_a_network_path_is_refused_before_it_is_followed() {
|
||||
let (base, roots) = folders("unc-link");
|
||||
let link = base.join("in/leak.dxf");
|
||||
if std::os::windows::fs::symlink_file(r"\\203.0.113.5\s\x.dwg", &link).is_err() {
|
||||
eprintln!("skipped: symbolic links can't be made here");
|
||||
return;
|
||||
}
|
||||
let e = roots.check(link.as_path(), Access::Read).unwrap_err();
|
||||
assert!(e.contains("UNC"), "{e}");
|
||||
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
|
||||
}
|
||||
|
||||
/// An alternate data stream is still the file it hangs off: outside the roots it is refused.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn an_alternate_stream_outside_the_roots_is_refused() {
|
||||
let (base, roots) = folders("ads");
|
||||
let e = roots.check(s(base.join("outside/secret.dxf:zone")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
assert_eq!(roots.check(s(base.join("out/new.dxf:zone")), Access::Write), Ok(()));
|
||||
}
|
||||
|
||||
/// Roots end with their scope, also when a nested scope or a panic ends it.
|
||||
#[test]
|
||||
fn scopes_nest_and_restore_after_a_panic() {
|
||||
let (base, roots) = folders("scopes");
|
||||
let outside = s(base.join("outside/secret.dxf"));
|
||||
assert_eq!(check_read(&outside), Ok(()), "nothing is confined by default");
|
||||
confine(Some(&roots), || {
|
||||
assert!(check_read(&outside).is_err());
|
||||
// A nested scope replaces the outer one and gives it back on the way out.
|
||||
confine(None, || assert_eq!(check_read(&outside), Ok(())));
|
||||
assert!(check_read(&outside).is_err(), "restored after the inner scope");
|
||||
});
|
||||
assert_eq!(check_read(&outside), Ok(()), "restored after confine");
|
||||
let r = std::panic::catch_unwind(|| confine(Some(&roots), || panic!("boom")));
|
||||
assert!(r.is_err());
|
||||
assert_eq!(check_read(&outside), Ok(()), "restored after a panic");
|
||||
assert_eq!(confine(None, || check_read(&outside)), Ok(()));
|
||||
}
|
||||
|
||||
/// The plain device names, and names that only look like them.
|
||||
#[test]
|
||||
fn device_names() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL "] {
|
||||
assert!(is_device_name(d), "{d}");
|
||||
}
|
||||
for f in ["console", "com10", "lpt", "a.svg", "nul-x"] {
|
||||
assert!(!is_device_name(f), "{f}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
//! Which commands automation may run while the automation roots are in force ([`super`]).
|
||||
//!
|
||||
//! The checks that hold a path to the roots sit where the file is touched, and a new command that
|
||||
//! touches a file through a new route would get past them. So a command runs under the roots only
|
||||
//! if it is listed here: anything else is refused, whatever it does. Adding a command to the
|
||||
//! registry means adding it to one of these lists (`every_command_is_classified` says so).
|
||||
|
||||
/// Commands that read or write files, each path held to the roots where the file is touched.
|
||||
pub const FILES: &[&str] = &[
|
||||
"-linetype",
|
||||
"-plottermanager",
|
||||
"-wblock",
|
||||
"-xref",
|
||||
"aliasedit",
|
||||
"appload",
|
||||
"attach",
|
||||
"blocklibimport",
|
||||
"blocklibrary",
|
||||
"audit",
|
||||
"compare",
|
||||
"compareexport",
|
||||
"dataextraction",
|
||||
"datalink",
|
||||
"datalinkupdate",
|
||||
"eattext",
|
||||
"export",
|
||||
"exportpdf",
|
||||
"hatch",
|
||||
"hatch.patterns",
|
||||
"image",
|
||||
"imageattach",
|
||||
"import",
|
||||
"insert",
|
||||
"layout",
|
||||
"layout.saveas",
|
||||
"linetype",
|
||||
"lisp",
|
||||
"minsert",
|
||||
"new",
|
||||
"open",
|
||||
"options",
|
||||
"pagesetup",
|
||||
"pdfbook",
|
||||
"plot",
|
||||
"plotstyle",
|
||||
"plottermanager",
|
||||
"preview",
|
||||
"publish",
|
||||
"qsave",
|
||||
"recover",
|
||||
"reinit",
|
||||
"saveas",
|
||||
"script",
|
||||
"setvar",
|
||||
"share",
|
||||
"stylesmanager",
|
||||
"tableexport",
|
||||
"wblock",
|
||||
"xattach",
|
||||
"xbind",
|
||||
"xopen",
|
||||
"xref",
|
||||
];
|
||||
|
||||
/// Commands that can't be held to the roots, and why.
|
||||
pub const REFUSED: &[(&str, &str)] = &[
|
||||
("drawingrecovery", "it works on the autosave folder (SAVEFILEPATH), which is the server's own"),
|
||||
("blocklibraries", "it keeps its list of libraries in the settings folder, which is the server's own"),
|
||||
];
|
||||
|
||||
/// Commands that touch no file.
|
||||
pub const NO_FILES: &[&str] = &[
|
||||
"blockspalette",
|
||||
"dimoverride.clear",
|
||||
"-dimstyle",
|
||||
"dimstyle.overrides",
|
||||
"dimstyle.saveas",
|
||||
"properties.describe",
|
||||
"close",
|
||||
"closeall",
|
||||
"document.switch",
|
||||
"document.bytes",
|
||||
"u",
|
||||
"undo",
|
||||
"redo",
|
||||
"mredo",
|
||||
"cutclip",
|
||||
"cutbase",
|
||||
"copyclip",
|
||||
"copybase",
|
||||
"pasteclip",
|
||||
"pasteblock",
|
||||
"pasteorig",
|
||||
"erase.selection",
|
||||
"selectall",
|
||||
"ai_deselect",
|
||||
"select",
|
||||
"qselect",
|
||||
"qselect.info",
|
||||
"selectsimilar",
|
||||
"isolateobjects",
|
||||
"hideobjects",
|
||||
"unisolateobjects",
|
||||
"xclip",
|
||||
"xclipframe",
|
||||
"zoom",
|
||||
"zoom.realtime",
|
||||
"zoom.dynamic",
|
||||
"zoom.previous",
|
||||
"zoom.window",
|
||||
"zoom.in",
|
||||
"zoom.out",
|
||||
"zoom.all",
|
||||
"zoom.extents",
|
||||
"zoom.object",
|
||||
"pan",
|
||||
"pan.left",
|
||||
"pan.right",
|
||||
"pan.up",
|
||||
"pan.down",
|
||||
"regen",
|
||||
"regenall",
|
||||
"redraw",
|
||||
"dview",
|
||||
"view.set",
|
||||
"view.get",
|
||||
"layout.set",
|
||||
"view",
|
||||
"-vports",
|
||||
"vports.activate",
|
||||
"vports.named",
|
||||
"line",
|
||||
"pline",
|
||||
"circle",
|
||||
"arc",
|
||||
"rectang",
|
||||
"polygon",
|
||||
"ellipse",
|
||||
"point",
|
||||
"point.multiple",
|
||||
"xline",
|
||||
"ray",
|
||||
"spline",
|
||||
"donut",
|
||||
"solid",
|
||||
"text",
|
||||
"mtext",
|
||||
"arc.sce",
|
||||
"arc.sca",
|
||||
"arc.scl",
|
||||
"arc.sea",
|
||||
"arc.sed",
|
||||
"arc.ser",
|
||||
"arc.cse",
|
||||
"arc.csa",
|
||||
"arc.csl",
|
||||
"arc.continue",
|
||||
"circle.cd",
|
||||
"circle.2p",
|
||||
"circle.3p",
|
||||
"circle.ttr",
|
||||
"circle.ttt",
|
||||
"ellipse.axis",
|
||||
"ellipse.arc",
|
||||
"divide",
|
||||
"measure",
|
||||
"revcloud",
|
||||
"revcloud.polygonal",
|
||||
"revcloud.freehand",
|
||||
"wipeout",
|
||||
"3dpoly",
|
||||
"helix",
|
||||
"spline.cv",
|
||||
"centermark",
|
||||
"centerline",
|
||||
"mline",
|
||||
"mlstyle",
|
||||
"mledit",
|
||||
"breakline",
|
||||
"dimlinear",
|
||||
"dimaligned",
|
||||
"dimradius",
|
||||
"dimdiameter",
|
||||
"dimangular",
|
||||
"dimarc",
|
||||
"dimordinate",
|
||||
"dimcontinue",
|
||||
"dimbaseline",
|
||||
"qdim",
|
||||
"dim",
|
||||
"mleader",
|
||||
"leader",
|
||||
"dimstyle.update",
|
||||
"dimoverride",
|
||||
"dimreassociate",
|
||||
"dimdisassociate",
|
||||
"dimtedit.home",
|
||||
"dimtedit.angle",
|
||||
"dimtedit.left",
|
||||
"dimtedit.center",
|
||||
"dimtedit.right",
|
||||
"dimtedit",
|
||||
"dimspace",
|
||||
"dimedit",
|
||||
"dimedit.oblique",
|
||||
"dimjogged",
|
||||
"dimjogline",
|
||||
"dimbreak",
|
||||
"diminspect",
|
||||
"mleaderedit",
|
||||
"mleaderedit.add",
|
||||
"mleaderedit.remove",
|
||||
"mleaderalign",
|
||||
"mleadercollect",
|
||||
"scalelistedit",
|
||||
"objectscale",
|
||||
"aiobjectscaleadd",
|
||||
"aiobjectscaleremove",
|
||||
"annoreset",
|
||||
"annoupdate",
|
||||
"annovisible.current",
|
||||
"annovisible.all",
|
||||
"annovisible.toggle",
|
||||
"gradient",
|
||||
"boundary",
|
||||
"region",
|
||||
"hatchedit",
|
||||
"hatchpick",
|
||||
"overkill",
|
||||
"block",
|
||||
"-block",
|
||||
"attdef",
|
||||
"attedit",
|
||||
"-attedit",
|
||||
"base",
|
||||
"blocks.dynamic",
|
||||
"blocks.reference",
|
||||
"blocks.reference.set",
|
||||
"blocks.reference.grips",
|
||||
"blocks.reference.grip",
|
||||
"purge",
|
||||
"blocks.list",
|
||||
"battman",
|
||||
"attdisp",
|
||||
"attsync",
|
||||
"burst",
|
||||
"blockreplace",
|
||||
"blocks.description",
|
||||
"attdisp.normal",
|
||||
"attdisp.on",
|
||||
"attdisp.off",
|
||||
"refedit",
|
||||
"refset",
|
||||
"refclose",
|
||||
"bedit",
|
||||
"bsave",
|
||||
"bsaveas",
|
||||
"bclose",
|
||||
"erase",
|
||||
"oops",
|
||||
"move",
|
||||
"copy",
|
||||
"rotate",
|
||||
"scale",
|
||||
"mirror",
|
||||
"stretch",
|
||||
"offset",
|
||||
"trim",
|
||||
"extend",
|
||||
"fillet",
|
||||
"chamfer",
|
||||
"explode",
|
||||
"break",
|
||||
"breakatpoint",
|
||||
"join",
|
||||
"draworder",
|
||||
"draworder.front",
|
||||
"draworder.back",
|
||||
"draworder.above",
|
||||
"draworder.under",
|
||||
"texttofront",
|
||||
"texttofront.text",
|
||||
"texttofront.dimensions",
|
||||
"texttofront.leaders",
|
||||
"texttofront.all",
|
||||
"hatchtoback",
|
||||
"array",
|
||||
"arrayrect",
|
||||
"arraypolar",
|
||||
"-array",
|
||||
"arrayedit",
|
||||
"arrayclose",
|
||||
"pedit",
|
||||
"splinedit",
|
||||
"lengthen",
|
||||
"align",
|
||||
"blend",
|
||||
"reverse",
|
||||
"ncopy",
|
||||
"mocoro",
|
||||
"chspace",
|
||||
"flatten",
|
||||
"arraypath",
|
||||
"textedit",
|
||||
"group",
|
||||
"ungroup",
|
||||
"groupedit",
|
||||
"groups.list",
|
||||
"-group",
|
||||
"pickstyle",
|
||||
"grip.move",
|
||||
"grip.stretch",
|
||||
"grip.rotate",
|
||||
"grip.scale",
|
||||
"grip.mirror",
|
||||
"grip.option",
|
||||
"grip",
|
||||
"compare.next",
|
||||
"compare.previous",
|
||||
"compareclose",
|
||||
"layer",
|
||||
"layer.new",
|
||||
"layer.set",
|
||||
"layer.current",
|
||||
"layer.delete",
|
||||
"laymcur",
|
||||
"laymch",
|
||||
"laycur",
|
||||
"layiso",
|
||||
"layuniso",
|
||||
"layfrz",
|
||||
"layoff",
|
||||
"laylck",
|
||||
"layulk",
|
||||
"layon",
|
||||
"laythw",
|
||||
"layerp",
|
||||
"layerstate.save",
|
||||
"layerstate.restore",
|
||||
"layerstate.list",
|
||||
"layerstate.delete",
|
||||
"layerstate.rename",
|
||||
"laymrg",
|
||||
"laydel",
|
||||
"layout.new",
|
||||
"layout.delete",
|
||||
"layout.rename",
|
||||
"layout.copy",
|
||||
"layout.list",
|
||||
"mview",
|
||||
"mview.polygonal",
|
||||
"vpclip",
|
||||
"vports",
|
||||
"vports.1",
|
||||
"vports.2",
|
||||
"vports.3",
|
||||
"vports.4",
|
||||
"viewport.set",
|
||||
"vplayer",
|
||||
"mspace",
|
||||
"pspace",
|
||||
"plotwindow",
|
||||
"3dorbit",
|
||||
"properties",
|
||||
"properties.set",
|
||||
"chprop",
|
||||
"change",
|
||||
"matchprop",
|
||||
"color",
|
||||
"lweight",
|
||||
"ltscale",
|
||||
"units",
|
||||
"-units",
|
||||
"thickness",
|
||||
"limits",
|
||||
"style",
|
||||
"style.list",
|
||||
"style.rename",
|
||||
"style.delete",
|
||||
"style.current",
|
||||
"dimstyle",
|
||||
"dimstyle.dimension",
|
||||
"dimstyle.list",
|
||||
"dimstyle.rename",
|
||||
"dimstyle.delete",
|
||||
"dimstyle.current",
|
||||
"dimstyle.override",
|
||||
"tablestyle",
|
||||
"mleaderstyle",
|
||||
"ddptype",
|
||||
"rename",
|
||||
"dist",
|
||||
"id",
|
||||
"list",
|
||||
"area",
|
||||
"time",
|
||||
"status",
|
||||
"drawing.inspect",
|
||||
"entities",
|
||||
"shapes",
|
||||
"usage",
|
||||
"loops",
|
||||
"texts",
|
||||
"countlist",
|
||||
"counttable",
|
||||
"count",
|
||||
"union",
|
||||
"subtract",
|
||||
"intersect",
|
||||
"massprop",
|
||||
"ortho",
|
||||
"grid",
|
||||
"snap",
|
||||
"polar",
|
||||
"otrack",
|
||||
"dynmode",
|
||||
"lwdisplay",
|
||||
"isodraft",
|
||||
"isoplane",
|
||||
"transparencydisplay",
|
||||
"qpmode",
|
||||
"selectioncycling",
|
||||
"osnap",
|
||||
"dsettings",
|
||||
"getvar",
|
||||
"sysvars",
|
||||
"cal",
|
||||
"quickcalc.pick",
|
||||
"find",
|
||||
"measuregeom",
|
||||
"radius.measure",
|
||||
"angle.measure",
|
||||
"volume.measure",
|
||||
"table",
|
||||
"table.set",
|
||||
"table.insertrow",
|
||||
"table.deleterow",
|
||||
"table.insertcol",
|
||||
"table.deletecol",
|
||||
"table.merge",
|
||||
"table.unmerge",
|
||||
"tablestyle.cellstyle",
|
||||
"table.cellstyle",
|
||||
"table.formula",
|
||||
"table.recalc",
|
||||
"tabledit",
|
||||
"table.break",
|
||||
"tolerance",
|
||||
"txt2mtxt",
|
||||
"geomconstraint",
|
||||
"gccoincident",
|
||||
"gcperpendicular",
|
||||
"gcparallel",
|
||||
"gctangent",
|
||||
"gchorizontal",
|
||||
"gcvertical",
|
||||
"gccollinear",
|
||||
"gcconcentric",
|
||||
"gcsmooth",
|
||||
"gcsymmetric",
|
||||
"gcequal",
|
||||
"gcfix",
|
||||
"autoconstrain",
|
||||
"constraintbar",
|
||||
"constraintbar.showall",
|
||||
"constraintbar.hideall",
|
||||
"dimconstraint",
|
||||
"dcaligned",
|
||||
"dchorizontal",
|
||||
"dcvertical",
|
||||
"dcangular",
|
||||
"dcradius",
|
||||
"dcdiameter",
|
||||
"dclinear",
|
||||
"dcdisplay",
|
||||
"dcdisplay.showall",
|
||||
"dcdisplay.hideall",
|
||||
"delconstraint",
|
||||
"parameters",
|
||||
"constraintsettings",
|
||||
"constraintinfer",
|
||||
"constraints.inspect",
|
||||
"constraints.dof",
|
||||
];
|
||||
|
||||
/// Why command `id` may not run here; `None` when it may. Without roots in force everything may.
|
||||
pub fn refusal(id: &str) -> Option<String> {
|
||||
super::current()?;
|
||||
if let Some((_, why)) = REFUSED.iter().find(|(c, _)| *c == id) {
|
||||
return Some(format!("automation command refused: {why}"));
|
||||
}
|
||||
if FILES.contains(&id) || NO_FILES.contains(&id) {
|
||||
return None;
|
||||
}
|
||||
Some("automation command refused: it is not classified for the automation roots".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::panic)]
|
||||
mod tests {
|
||||
use super::super::{AutomationRoots, confine};
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Words in a command's parameter doc that usually name a file. In these commands they don't:
|
||||
/// `array` and `arraypath` follow a path of objects, and `blocks.reference.grips` reports a
|
||||
/// direction.
|
||||
const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"];
|
||||
|
||||
/// The words of a command's documentation, lower case.
|
||||
fn words(doc: &str) -> BTreeSet<String> {
|
||||
doc.to_ascii_lowercase().split(|c: char| !c.is_ascii_alphanumeric()).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// Walks the registry: every command is on exactly one list, and the lists name no command
|
||||
/// that is gone. A command whose parameters name a file can't be on the no-files list.
|
||||
#[test]
|
||||
fn every_command_is_classified() {
|
||||
let refused: Vec<&str> = REFUSED.iter().map(|(c, _)| *c).collect();
|
||||
let lists = [FILES, refused.as_slice(), NO_FILES];
|
||||
let specs = crate::command_specs();
|
||||
for spec in specs {
|
||||
let on = lists.iter().filter(|l| l.contains(&spec.id)).count();
|
||||
assert_eq!(on, 1, "`{}` is on {on} lists: add it to one in file_access/commands.rs", spec.id);
|
||||
let doc = words(spec.params);
|
||||
let names_a_file = ["path", "file", "template", "patternfile", "folder", "dir"].iter().any(|w| doc.contains(*w));
|
||||
if names_a_file && NO_FILES.contains(&spec.id) && !NOT_FILES.contains(&spec.id) {
|
||||
panic!("`{}` takes a file ({}): it belongs on FILES, with its paths checked", spec.id, spec.params);
|
||||
}
|
||||
}
|
||||
for id in lists.iter().flat_map(|l| l.iter()) {
|
||||
assert!(specs.iter().any(|s| s.id == *id), "`{id}` is listed but no longer a command");
|
||||
}
|
||||
}
|
||||
|
||||
/// Under roots a command nobody classified is refused; without roots it isn't this table's business.
|
||||
#[test]
|
||||
fn an_unclassified_command_fails_closed() {
|
||||
let base = std::env::temp_dir().join(format!("cc-commands-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let roots = AutomationRoots::new(Some(&base), None).unwrap();
|
||||
assert_eq!(refusal("made.up"), None);
|
||||
confine(roots.as_ref(), || {
|
||||
assert!(refusal("made.up").unwrap().contains("not classified"));
|
||||
assert!(refusal("drawingrecovery").unwrap().contains("autosave"));
|
||||
assert!(refusal("blocklibraries").unwrap().contains("settings folder"));
|
||||
assert_eq!(refusal("open"), None);
|
||||
assert_eq!(refusal("line"), None);
|
||||
});
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ pub mod blockedit;
|
||||
pub mod capped_read;
|
||||
pub mod cmd;
|
||||
pub mod doc_path;
|
||||
pub mod file_access;
|
||||
mod finite;
|
||||
pub mod grip_dims;
|
||||
pub mod grips;
|
||||
|
||||
@@ -13,6 +13,7 @@ pub struct LispFile {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// LISP `open`: a file handle, or nil when the file can't be opened or the automation roots refuse it.
|
||||
pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 3)?;
|
||||
let path = string(&a[0])?.to_string();
|
||||
@@ -38,7 +39,7 @@ pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError>
|
||||
}
|
||||
None => return Ok(Flow::Value(Value::Nil)),
|
||||
}
|
||||
} else if !can_write(&path) {
|
||||
} else if crate::file_access::check_write(&path).is_err() || !can_write(&path) {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let id = ctx.env.next_file;
|
||||
@@ -83,6 +84,7 @@ pub fn read_text_file(path: impl AsRef<std::path::Path>) -> Option<String> {
|
||||
// Read through a byte-limited, regular-file-only reader so a path naming an endless device
|
||||
// cannot exhaust memory before the 64 MiB cap is enforced (CWE-400).
|
||||
const MAX: usize = 64 * 1024 * 1024;
|
||||
crate::file_access::check_read(path.as_ref()).ok()?;
|
||||
let bytes = crate::capped_read::read_capped(path.as_ref(), MAX).ok()?;
|
||||
Some(String::from_utf8_lossy(&bytes).into_owned())
|
||||
}
|
||||
@@ -103,9 +105,13 @@ fn can_write(_path: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Write or append `text`, doing nothing when the automation roots refuse the path.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_text_file(path: &str, text: &str, append: bool) {
|
||||
use std::io::Write;
|
||||
if crate::file_access::check_write(path).is_err() {
|
||||
return;
|
||||
}
|
||||
// Opened without blocking and without truncating, so a FIFO with no reader fails at once
|
||||
// instead of stalling the interpreter; only a regular file is then truncated and written.
|
||||
let mut o = std::fs::OpenOptions::new();
|
||||
@@ -127,10 +133,11 @@ fn write_text_file(path: &str, text: &str, append: bool) {
|
||||
fn write_text_file(_path: &str, _text: &str, _append: bool) {}
|
||||
|
||||
/// A file or a folder: routines test whether a module is installed with `(findfile "module/.")`.
|
||||
/// Outside the automation roots the answer is no.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn file_exists(path: &str) -> bool {
|
||||
let p = std::path::Path::new(path);
|
||||
p.is_file() || p.is_dir()
|
||||
crate::file_access::check_read(p).is_ok() && (p.is_file() || p.is_dir())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -64,7 +64,11 @@ pub(super) fn list(a: &[Value]) -> R {
|
||||
pub(super) fn append(a: &[Value]) -> R {
|
||||
let mut items = Vec::new();
|
||||
for v in a {
|
||||
items.extend(list_arg(v)?);
|
||||
let l = list_arg(v)?;
|
||||
// Check the result's cells before holding them: the same long list given many times
|
||||
// would otherwise grow far past the cell cap inside this one call (#1930).
|
||||
super::super::value::check_new_cells(items.len().saturating_add(l.len()))?;
|
||||
items.extend(l);
|
||||
}
|
||||
Ok(Value::list(items))
|
||||
}
|
||||
|
||||
@@ -1228,10 +1228,23 @@ pub fn load_source(s: &Session, name: &str) -> Option<String> {
|
||||
}
|
||||
let candidates =
|
||||
if std::path::Path::new(name).extension().is_none() { vec![format!("{name}.lsp"), name.to_string()] } else { vec![name.to_string()] };
|
||||
// As given (a path, or relative to the working folder), then in the support folder.
|
||||
let support =
|
||||
s.lisp_support_dir().map(|d| candidates.iter().map(|c| d.join(c).to_string_lossy().into_owned()).collect::<Vec<_>>()).unwrap_or_default();
|
||||
candidates.iter().chain(&support).find_map(super::builtins::read_text_file)
|
||||
// An absolute path is read as given. A relative name is looked up in the support folder only,
|
||||
// never in the process working folder: that can be the folder of a drawing just opened from a
|
||||
// file manager, and a `tools.lsp` shipped beside it must not answer a startup file's
|
||||
// `(load "tools")` (#1927). Without a support folder (the command-line tool, which has no
|
||||
// startup files) a relative name is read as given.
|
||||
let dir = match s.lisp_support_dir() {
|
||||
Some(d) if !std::path::Path::new(name).is_absolute() => d,
|
||||
_ => return candidates.iter().find_map(super::builtins::read_text_file),
|
||||
};
|
||||
// A relative name stays inside the support folder: plain folder and file names only. `..` would
|
||||
// climb out of it, and on Windows a rooted name (`\tools`) or a drive-relative one (`C:tools`,
|
||||
// the working folder of drive C) is not absolute, yet joined to the folder it replaces it.
|
||||
use std::path::Component;
|
||||
if !std::path::Path::new(name).components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) {
|
||||
return None;
|
||||
}
|
||||
candidates.iter().find_map(|c| super::builtins::read_text_file(dir.join(c)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1480,3 +1480,74 @@ fn atof_out_of_range_exponent_reads_whole_token() {
|
||||
assert_eq!(ok(&mut s, "(< (atof \"-1e400\") -1e300)"), "T");
|
||||
assert_eq!(ok(&mut s, "(= (atof \"1e-400\") 0.0)"), "T");
|
||||
}
|
||||
|
||||
/// #1927: with a support folder, a relative `load` name is found there, never through the
|
||||
/// process working folder; an absolute path is still read as given.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn relative_load_uses_the_support_folder_not_the_working_folder() {
|
||||
let base = std::env::temp_dir().join(format!("cadcraft-lisp-loadpath-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let (support, other) = (base.join("support"), base.join("other"));
|
||||
std::fs::create_dir_all(&support).unwrap();
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
std::fs::write(support.join("tools.lsp"), "(setq which \"support\")").unwrap();
|
||||
std::fs::write(other.join("tools.lsp"), "(setq which \"other\")").unwrap();
|
||||
std::fs::write(other.join("only.lsp"), "(setq only 1)").unwrap();
|
||||
// `other/…` as a path relative to the working folder.
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let up = "../".repeat(cwd.components().count().saturating_sub(1));
|
||||
let rel = |f: &str| format!("{up}{}", other.join(f).to_string_lossy().trim_start_matches('/'));
|
||||
|
||||
let mut s = session();
|
||||
s.set_lisp_support_dir(Some(support.clone()));
|
||||
assert_eq!(ok(&mut s, "(load \"tools\") which"), "\"support\"");
|
||||
let r = eval(&mut s, &format!("(load \"{}\") only", rel("only.lsp")));
|
||||
assert!(!matches!(r.as_deref(), Ok("1")), "not read through the working folder: {r:?}");
|
||||
assert_eq!(ok(&mut s, &format!("(load \"{}\") which", other.join("tools.lsp").to_string_lossy())), "\"other\"");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// #1927 on Windows: a rooted name (`\folder\tools.lsp`, no drive) or a drive-relative one
|
||||
/// (`C:tools`) is not absolute, but joined to the support folder it replaces that folder; such a
|
||||
/// name is refused rather than read from outside the support folder.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn rooted_and_drive_relative_load_names_stay_in_the_support_folder() {
|
||||
let base = std::env::temp_dir().join(format!("cadcraft-lisp-rooted-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let (support, other) = (base.join("support"), base.join("other"));
|
||||
std::fs::create_dir_all(&support).unwrap();
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
let outside = other.join("only.lsp");
|
||||
std::fs::write(&outside, "(setq only 1)").unwrap();
|
||||
// The same file without its drive (`\Users\...\other\only.lsp`), escaped for a LISP string.
|
||||
let full = outside.to_string_lossy().into_owned();
|
||||
let rooted = full.get(full.find('\\').unwrap()..).unwrap().replace('\\', "\\\\");
|
||||
let drive = full.get(..2).unwrap().to_string();
|
||||
|
||||
let mut s = session();
|
||||
s.set_lisp_support_dir(Some(support.clone()));
|
||||
let r = eval(&mut s, &format!("(load \"{rooted}\") only"));
|
||||
assert!(!matches!(r.as_deref(), Ok("1")), "a rooted name is not read outside the support folder: {r:?}");
|
||||
let r = eval(&mut s, &format!("(load \"{drive}only\") only"));
|
||||
assert!(!matches!(r.as_deref(), Ok("1")), "a drive-relative name is refused: {r:?}");
|
||||
std::fs::write(support.join("only.lsp"), "(setq only 2)").unwrap();
|
||||
assert_eq!(ok(&mut s, "(load \".\\\\only\") only"), "2", "a plain relative name is still read from the support folder");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// #1930: `append` over many references to one long list is refused before it builds the
|
||||
/// result, not after it has filled memory.
|
||||
#[test]
|
||||
fn append_checks_the_cell_cap_before_building_its_result() {
|
||||
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = session();
|
||||
s.lisp.limits.cells = 50_000;
|
||||
let before = super::value::live_cells();
|
||||
let e =
|
||||
eval(&mut s, "(setq l nil) (repeat 10000 (setq l (cons 1 l))) (setq m nil) (repeat 1000 (setq m (cons l m))) (apply 'append m)").unwrap_err();
|
||||
assert!(e.contains("too many list cells"), "{e}");
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -76,6 +76,12 @@ pub fn check_cells() -> Result<(), LispError> {
|
||||
if live_cells() > CELL_LIMIT.with(Cell::get) { Err(LispError::quit("out of memory: too many list cells")) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// `n` more cons cells would exceed the cap: checked before a built-in allocates a result many
|
||||
/// times the size of its arguments (`append` over the same long list, #1930).
|
||||
pub fn check_new_cells(n: usize) -> Result<(), LispError> {
|
||||
if live_cells().saturating_add(n) > CELL_LIMIT.with(Cell::get) { Err(LispError::quit("out of memory: too many list cells")) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Start a slice of a run on this thread: it has made `used` bytes of its `budget`.
|
||||
pub fn set_string_budget(used: u64, budget: u64) {
|
||||
STRING_BYTES.with(|c| c.set((used, budget)));
|
||||
|
||||
@@ -31,7 +31,7 @@ impl Accept {
|
||||
/// [Truecolor/COlorbook] <BYLAYER>:". A prompt asking for something else besides its keywords has
|
||||
/// it: "Enter block name or [?]:", "Specify insertion base point or [Basepoint/…]:". Read from
|
||||
/// AutoCAD's command line over measured runs, where no prompt was written both ways.
|
||||
const NO_OR: &[&str] = &[
|
||||
const NO_OR: [&str; 28] = [
|
||||
"Bring to front",
|
||||
"Calculate rectangle dimensions based on",
|
||||
"Choose mode for selected object conversion",
|
||||
@@ -50,7 +50,6 @@ const NO_OR: &[&str] = &[
|
||||
"Enter option",
|
||||
"Enter polyline linetype generation option",
|
||||
"Enter property to change",
|
||||
"Enter states to change",
|
||||
"Enter the type of array",
|
||||
"Enter type of unused objects to purge",
|
||||
"Enter viewport arrangement",
|
||||
|
||||
@@ -24,8 +24,12 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a command by id, unless the automation roots, its own state or the block editor refuse it.
|
||||
fn execute_guarded(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||
if let Some(why) = crate::file_access::commands::refusal(spec.id) {
|
||||
return Err(EngineError::Disabled(spec.id.into(), why));
|
||||
}
|
||||
(spec.enabled)(self).map_err(|m| EngineError::Disabled(spec.id.into(), m))?;
|
||||
if let Some(why) = cmd::blocks::bedit::refused_in_editor(self, spec.id) {
|
||||
return Err(EngineError::Disabled(spec.id.into(), why));
|
||||
|
||||
@@ -79,6 +79,9 @@ impl Session {
|
||||
}
|
||||
return Err(EngineError::UnknownCommand(typed.to_string()));
|
||||
};
|
||||
if let Some(why) = crate::file_access::commands::refusal(spec.id) {
|
||||
return Err(EngineError::Disabled(spec.id.into(), why));
|
||||
}
|
||||
if transparent && spec.transparent && self.running.is_some() {
|
||||
// Transparent commands (zoom, pan…) run without cancelling the active one.
|
||||
if spec.interactive.is_none() {
|
||||
|
||||
@@ -27,10 +27,6 @@ pub struct Settings {
|
||||
pub measureinit: bool,
|
||||
/// -VIEW sEttings > Layer snapshot: named views save the layer settings with them.
|
||||
pub view_layer_snapshot: bool,
|
||||
/// -LAYER stAte Save: the properties a new layer state restores (its mask), as the last Save
|
||||
/// left them. AutoCAD 2024 keeps these toggles in the registry from one Save to the next
|
||||
/// (measured); Edit doesn't change them.
|
||||
pub layer_state_mask: u32,
|
||||
pub dynmode: bool,
|
||||
/// DYNDIGRIP: which dimensions grip dimensional input shows while a grip is stretched (bits:
|
||||
/// 1 resulting length, 2 length change, 4 absolute angle, 8 angle change, 16 radius); read
|
||||
@@ -152,7 +148,6 @@ impl Default for Settings {
|
||||
zoomfactor: 60,
|
||||
measureinit: false,
|
||||
view_layer_snapshot: true,
|
||||
layer_state_mask: cadcraft_doc::LayerState::ALL,
|
||||
dynmode: true,
|
||||
dyndigrip: 31,
|
||||
dyndivis: 1,
|
||||
|
||||
@@ -291,6 +291,7 @@ pub fn format_angle_list(angles: &[f64]) -> String {
|
||||
angles.iter().map(|a| format!("{}", (a.to_degrees() * 1e6).round() / 1e6)).collect::<Vec<_>>().join(";")
|
||||
}
|
||||
|
||||
/// 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();
|
||||
if is_read_only(&n) {
|
||||
@@ -387,6 +388,10 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
|
||||
"SAVETIME" => crate::autosave::set_savetime(
|
||||
as_f64(v).filter(|m| *m >= 0.0 && *m <= f64::from(crate::autosave::MAX_SAVETIME)).ok_or_else(bad)?.round() as u32,
|
||||
),
|
||||
// A folder autosave and recovery would use without any further check.
|
||||
"SAVEFILEPATH" if crate::file_access::current().is_some() => {
|
||||
return Err(EngineError::Other("SAVEFILEPATH cannot be changed under the automation roots".into()));
|
||||
}
|
||||
"SAVEFILEPATH" => crate::autosave::set_savefilepath(v.as_str().ok_or_else(bad)?),
|
||||
"ISAVEBAK" => crate::autosave::set_isavebak(as_bool(v).ok_or_else(bad)?),
|
||||
// A number is in degrees; text is an angle typed in AUNITS (SETVAR at the command line).
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
//! process-wide, so these tests run one at a time.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::MAX_ALIASES;
|
||||
use cadcraft_engine::cmd::resolve_alias;
|
||||
use serde_json::json;
|
||||
|
||||
@@ -26,6 +28,10 @@ ZZBAD, *NOSUCHCOMMAND
|
||||
LINE, *CIRCLE
|
||||
";
|
||||
|
||||
fn alias_prefix(count: usize) -> String {
|
||||
(0..count).map(|i| format!("ZZP{i:05},*LINE\n")).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alias_file_adds_and_overrides_aliases() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
@@ -61,17 +67,148 @@ fn an_alias_file_adds_and_overrides_aliases() {
|
||||
fn reinit_reads_the_alias_file_again() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let dir = TempDir::new("aliases");
|
||||
let file = dir.file("mine.pgp", "ZZR, *RECTANG\n");
|
||||
let file = dir.file("mine.pgp", "ZZR, *LINE\nzzr, *RECTANG\n");
|
||||
let mut s = Session::new();
|
||||
s.execute("aliasedit", &json!({ "file": file })).unwrap();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
let r = s.execute("aliasedit", &json!({ "file": file })).unwrap();
|
||||
assert_eq!(r["loaded"], json!(1));
|
||||
assert_eq!(r["file"], json!(file));
|
||||
assert_eq!(r["warnings"], json!([]));
|
||||
assert_eq!(resolve_alias("zzr"), "rectang");
|
||||
|
||||
std::fs::write(&file, "ZZR, *CIRCLE\n").unwrap();
|
||||
std::fs::write(&file, "ZZR, *MOVE\nzzr, *CIRCLE\n").unwrap();
|
||||
s.cmdline("reinit").unwrap();
|
||||
assert_eq!(resolve_alias("zzr"), "circle");
|
||||
assert!(s.log.iter().any(|l| l.contains("1 command alias")), "{:?}", s.log);
|
||||
let r = s.execute("reinit", &json!({ "text": "ZZS, *SCALE\n" })).unwrap();
|
||||
let r = s.execute("aliasedit", &json!({})).unwrap();
|
||||
assert_eq!(r["file"], json!(file));
|
||||
assert_eq!(r["aliases"], json!({ "zzr": "circle" }));
|
||||
let r = s.execute("reinit", &json!({ "text": "ZZS, *LINE\nzzs, *SCALE\n" })).unwrap();
|
||||
assert_eq!(r["aliases"], json!({ "zzs": "scale" }));
|
||||
assert_eq!(r["loaded"], json!(1));
|
||||
assert_eq!(r["warnings"], json!([]));
|
||||
assert_eq!(r["file"], json!(file), "reloading text keeps the remembered file");
|
||||
let r = s.execute("reinit", &json!({})).unwrap();
|
||||
assert_eq!(r["aliases"], json!({ "zzr": "circle" }));
|
||||
assert_eq!(r["loaded"], json!(1));
|
||||
assert_eq!(r["file"], json!(file));
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_redefinitions_win_and_the_listing_stays_sorted() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
let text = "ZZZ,*LINE\nZza,*LINE\nzzz,*CIRCLE\nZZA,*NO_SUCH_1933\nLINE,*CIRCLE\n";
|
||||
let r = s.execute("aliasedit", &json!({ "text": text })).unwrap();
|
||||
let aliases = json!({ "zza": "line", "zzz": "circle" });
|
||||
assert_eq!(r["aliases"], aliases);
|
||||
assert_eq!(r["loaded"], json!(2), "loaded counts unique aliases, not definitions");
|
||||
assert_eq!(r["file"], json!(null));
|
||||
assert_eq!(
|
||||
r["warnings"],
|
||||
json!(["line 4: ZZA: unknown command *NO_SUCH_1933; skipped", "line 5: LINE is a command name; it stays the command; skipped"])
|
||||
);
|
||||
assert_eq!(resolve_alias("ZZZ"), "circle");
|
||||
assert_eq!(resolve_alias("zza"), "line", "an invalid redefinition keeps the previous target");
|
||||
assert_eq!(resolve_alias("line"), "line");
|
||||
assert_eq!(serde_json::to_string(&r["aliases"]).unwrap(), r#"{"zza":"line","zzz":"circle"}"#);
|
||||
let listing = s.execute("aliasedit", &json!({})).unwrap();
|
||||
assert_eq!(listing, json!({ "aliases": aliases, "file": null, "loaded": 0, "warnings": [] }));
|
||||
|
||||
let empty = s.execute("aliasedit", &json!({ "text": "" })).unwrap();
|
||||
assert_eq!(empty, json!({ "aliases": {}, "file": null, "loaded": 0, "warnings": [] }));
|
||||
assert_eq!(resolve_alias("zza"), "zza", "an empty import replaces the old set");
|
||||
assert_eq!(resolve_alias("zzz"), "zzz");
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicates_below_the_limit_leave_room_for_another_alias() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
let mut text = alias_prefix(MAX_ALIASES - 1);
|
||||
for _ in 0..16 {
|
||||
text.push_str("ZZP00000,*MOVE\nzzp00001,*CIRCLE\n");
|
||||
}
|
||||
let r = s.execute("aliasedit", &json!({ "text": text })).unwrap();
|
||||
assert_eq!(r["loaded"], json!(MAX_ALIASES - 1));
|
||||
assert_eq!(r["aliases"].as_object().unwrap().len(), MAX_ALIASES - 1);
|
||||
assert_eq!(r["warnings"], json!([]));
|
||||
for i in 0..MAX_ALIASES - 1 {
|
||||
let expected = match i {
|
||||
0 => "move",
|
||||
1 => "circle",
|
||||
_ => "line",
|
||||
};
|
||||
assert_eq!(r["aliases"][format!("zzp{i:05}")], json!(expected));
|
||||
}
|
||||
|
||||
text.push_str("ZZNEW,*PLINE\n");
|
||||
let r = s.execute("aliasedit", &json!({ "text": text })).unwrap();
|
||||
assert_eq!(r["loaded"], json!(MAX_ALIASES));
|
||||
assert_eq!(r["aliases"].as_object().unwrap().len(), MAX_ALIASES);
|
||||
assert_eq!(r["aliases"]["zznew"], json!("pline"));
|
||||
assert_eq!(r["aliases"]["zzp00000"], json!("move"));
|
||||
assert_eq!(r["aliases"]["zzp00001"], json!("circle"));
|
||||
assert_eq!(r["warnings"], json!([]), "duplicate definitions do not use up the alias limit");
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_file_validates_lines_before_stopping_at_the_next_valid_definition() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
let mut text = alias_prefix(MAX_ALIASES);
|
||||
text.push_str("; comment\nZZP00000,*NO_SUCH_1933\nLINE,*CIRCLE\nZZEXTERNAL, START NOTHING\nmalformed\nZZP00000,*MOVE\nZZAFTER,*CIRCLE\nanother malformed sentinel\n");
|
||||
let params = json!({ "text": text });
|
||||
let start = Instant::now();
|
||||
let result = s.execute("aliasedit", ¶ms);
|
||||
let elapsed = start.elapsed();
|
||||
let r = result.unwrap();
|
||||
assert_eq!(r["loaded"], json!(MAX_ALIASES));
|
||||
assert_eq!(r["aliases"].as_object().unwrap().len(), MAX_ALIASES);
|
||||
assert_eq!(r["aliases"]["zzp00000"], json!("line"), "the cap stops even a valid duplicate replacement");
|
||||
assert!(r["aliases"].get("zzafter").is_none(), "the remainder of the file is skipped");
|
||||
assert_eq!(
|
||||
r["warnings"],
|
||||
json!([
|
||||
format!("line {}: ZZP00000: unknown command *NO_SUCH_1933; skipped", MAX_ALIASES + 2),
|
||||
format!("line {}: LINE is a command name; it stays the command; skipped", MAX_ALIASES + 3),
|
||||
format!("line {}: ZZEXTERNAL is an external command; CADCraft doesn't run programs from alias files", MAX_ALIASES + 4),
|
||||
format!("line {}: `malformed` is not ALIAS, *COMMAND; skipped", MAX_ALIASES + 5),
|
||||
format!("line {}: more than {MAX_ALIASES} aliases; the rest are skipped", MAX_ALIASES + 6)
|
||||
])
|
||||
);
|
||||
|
||||
// Setting one existing alias through JSON has a different rule from importing a full file.
|
||||
let r = s.execute("aliasedit", &json!({ "set": { "ZZP00000": "move" } })).unwrap();
|
||||
assert_eq!(r["aliases"]["zzp00000"], json!("move"));
|
||||
assert_eq!(r["loaded"], json!(1));
|
||||
assert!(s.execute("aliasedit", &json!({ "set": { "ZZNEW": "line" } })).is_err());
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
// A generous responsiveness guard, not a benchmark or a timeout for a hung import.
|
||||
assert!(elapsed < Duration::from_secs(5), "importing {MAX_ALIASES} aliases took {elapsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_warning_limit_does_not_stop_a_later_valid_redefinition() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
let mut text = String::from("ZZW,*LINE\n");
|
||||
for _ in 0..101 {
|
||||
text.push_str("ZZW,*NO_SUCH_1933\n");
|
||||
}
|
||||
text.push_str("zzw,*CIRCLE\n");
|
||||
let r = s.execute("aliasedit", &json!({ "text": text })).unwrap();
|
||||
assert_eq!(r["aliases"], json!({ "zzw": "circle" }));
|
||||
assert_eq!(r["loaded"], json!(1));
|
||||
let warnings: Vec<_> = (2..=101).map(|no| format!("line {no}: ZZW: unknown command *NO_SUCH_1933; skipped")).collect();
|
||||
assert_eq!(r["warnings"], json!(warnings), "only the first 100 warnings are returned");
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -285,6 +285,7 @@ fn oops_brings_back_what_it_erased_where_it_was() {
|
||||
assert_eq!(order, [a, b, c]);
|
||||
}
|
||||
|
||||
/// A refused -WBLOCK leaves OOPS as it was.
|
||||
#[test]
|
||||
fn a_dash_wblock_refused_during_refedit_leaves_oops_as_it_was() {
|
||||
let (mut s, a, b, c) = drawing();
|
||||
@@ -301,3 +302,27 @@ fn a_dash_wblock_refused_during_refedit_leaves_oops_as_it_was() {
|
||||
s.execute("oops", &json!({})).unwrap();
|
||||
assert!(alive(&s, c));
|
||||
}
|
||||
|
||||
/// Outside the automation roots the prompt doesn't say whether a file is there.
|
||||
#[test]
|
||||
fn the_replace_prompt_says_nothing_about_a_file_outside_the_roots() {
|
||||
let (mut s, ..) = drawing();
|
||||
let dir = TempDir::new("dash-wblock-roots");
|
||||
for d in ["in", "out", "outside"] {
|
||||
std::fs::create_dir(dir.join(d)).unwrap();
|
||||
}
|
||||
let there = dir.join("outside/there.dwg");
|
||||
std::fs::write(&there, "old").unwrap();
|
||||
// Without roots the same file gets the prompt, so its absence below is the check's doing.
|
||||
let (mut free, ..) = drawing();
|
||||
free.cmdline("-wblock").unwrap();
|
||||
free.cmdline(&there.display().to_string()).unwrap();
|
||||
assert!(free.prompt_text().contains("already exists"), "{}", free.prompt_text());
|
||||
let write = dir.join("out");
|
||||
let roots = cadcraft_engine::file_access::AutomationRoots::new(Some(&dir.join("in")), Some(&write)).unwrap();
|
||||
cadcraft_engine::file_access::confine(roots.as_ref(), || {
|
||||
s.cmdline("-wblock").unwrap();
|
||||
s.cmdline(&there.display().to_string()).unwrap();
|
||||
assert!(!s.prompt_text().contains("already exists"), "{}", s.prompt_text());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,202 +0,0 @@
|
||||
//! The Key point option of a base point: ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (Base point and
|
||||
//! REPlace) take the source objects' key point (an end point, midpoint, centre…) nearest the
|
||||
//! picked point as the base point; the JSON forms take `keyPoint`.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{ArrayKind, ArrayParams, EntityKind, Handle};
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use serde_json::json;
|
||||
|
||||
fn source_line(s: &mut Session) -> String {
|
||||
let r = s.execute("line", &json!({"points": [[0, 0], [2, 1]]})).unwrap();
|
||||
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string()
|
||||
}
|
||||
|
||||
fn handle(v: &serde_json::Value) -> Handle {
|
||||
Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The array's insertion point (its base point) and parameters.
|
||||
fn array(s: &Session, h: Handle) -> (Vec2, ArrayParams) {
|
||||
let d = s.doc().unwrap();
|
||||
let e = d.entity(h).unwrap();
|
||||
let EntityKind::Insert(i) = &e.kind else { panic!("not an array") };
|
||||
(i.insert.xy(), d.array_params(e).unwrap())
|
||||
}
|
||||
|
||||
fn only_array(s: &Session) -> Handle {
|
||||
let d = s.doc().unwrap();
|
||||
let arrays: Vec<Handle> = d.model.iter().filter(|e| d.array_params(e).is_some()).map(|e| e.handle).collect();
|
||||
assert_eq!(arrays.len(), 1);
|
||||
arrays[0]
|
||||
}
|
||||
|
||||
fn typed(s: &mut Session, inputs: &[&str]) {
|
||||
for t in inputs {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrayrect_and_arraypolar_take_a_key_point_as_the_base_point() {
|
||||
let mut s = Session::new();
|
||||
let l = source_line(&mut s);
|
||||
let r = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "keyPoint": [1.9, 1.05]})).unwrap();
|
||||
assert!(array(&s, handle(&r)).0.near(Vec2::new(2.0, 1.0), 1e-9));
|
||||
let mut s = Session::new();
|
||||
let l = source_line(&mut s);
|
||||
let r = s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 4, "keyPoint": [1.1, 0.4]})).unwrap();
|
||||
assert!(array(&s, handle(&r)).0.near(Vec2::new(1.0, 0.5), 1e-9), "the line's midpoint");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_key_points_at_arrayrect_and_arraypolar() {
|
||||
let mut s = Session::new();
|
||||
source_line(&mut s);
|
||||
typed(&mut s, &["arrayrect", "l", "", "b", "k", "1.9,0.95", "x"]);
|
||||
assert!(array(&s, only_array(&s)).0.near(Vec2::new(2.0, 1.0), 1e-9));
|
||||
// Enter at the key point prompt goes back to the base point prompt.
|
||||
let mut s = Session::new();
|
||||
source_line(&mut s);
|
||||
typed(&mut s, &["arraypolar", "l", "", "b", "k"]);
|
||||
assert!(s.current_prompt().unwrap().message.contains("key point"));
|
||||
typed(&mut s, &[""]);
|
||||
assert!(s.current_prompt().unwrap().message.contains("base point"));
|
||||
typed(&mut s, &["k", "0.1,0.1", "-10,0", "x"]);
|
||||
assert!(array(&s, only_array(&s)).0.near(Vec2::new(0.0, 0.0), 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrayedit_moves_the_base_point_to_a_key_point_of_an_item() {
|
||||
let mut s = Session::new();
|
||||
let l = source_line(&mut s);
|
||||
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
|
||||
// Near the start of the third item: the base point goes to (10, 0), the items stay.
|
||||
s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [10.2, 0.05]})).unwrap();
|
||||
let (at, p) = array(&s, h);
|
||||
assert!(at.near(Vec2::new(10.0, 0.0), 1e-9), "{at:?}");
|
||||
assert!(matches!(p.kind, ArrayKind::Rect(r) if r.cols == 3 && r.col_spacing == 5.0));
|
||||
let items = s.execute("explode", &json!({"handles": [h.hex()]})).unwrap();
|
||||
assert!(items.to_string().len() > 2);
|
||||
let d = s.doc().unwrap();
|
||||
let mut starts: Vec<(i64, i64)> = d
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::Line(l) => Some(((l.a.x * 10.0).round() as i64, (l.a.y * 10.0).round() as i64)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
starts.sort();
|
||||
assert_eq!(starts, [(0, 0), (50, 0), (100, 0)]);
|
||||
// Not on an item: refused.
|
||||
let mut s = Session::new();
|
||||
let l = source_line(&mut s);
|
||||
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
|
||||
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [3.5, 40]})).is_err());
|
||||
assert!(array(&s, h).0.near(Vec2::ZERO, 1e-9));
|
||||
// Typed: Base point, Key point, a point on the second item near its end.
|
||||
s.set_selection(vec![h]);
|
||||
typed(&mut s, &["arrayedit", "b", "k", "6.9,0.9", "x"]);
|
||||
assert!(array(&s, h).0.near(Vec2::new(7.0, 1.0), 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacement_objects_take_a_key_point_as_their_base_point() {
|
||||
let mut s = Session::new();
|
||||
let l = source_line(&mut s);
|
||||
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
|
||||
let c = s.execute("circle", &json!({"center": [50, 50], "radius": 1})).unwrap()["handle"].clone();
|
||||
// The circle's right quadrant is the base point: on item 1 (at x = 5) its centre is at x = 4.
|
||||
s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [c], "keyPoint": [51.2, 50.1], "items": [[1, 0, 0]]}})).unwrap();
|
||||
s.execute("explode", &json!({"handles": [h.hex()]})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
// The replaced item stays a reference to the replacement block.
|
||||
let centres: Vec<Vec2> = d
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::Insert(i) => d.block(&i.block).map(|b| (i.transform(b.base.xy()), b)),
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(|(m, b)| {
|
||||
b.entities
|
||||
.iter()
|
||||
.filter_map(move |e| match &e.kind {
|
||||
EntityKind::Circle(c) => Some(m.apply(c.center.xy())),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
assert!(centres.iter().any(|c| c.near(Vec2::new(4.0, 0.0), 1e-9)), "{centres:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_key_points_never_panic() {
|
||||
let mut s = Session::new();
|
||||
let l = source_line(&mut s);
|
||||
for kp in [json!(["a", 1]), json!([1e308, -1e308]), json!([]), json!("x"), json!(null)] {
|
||||
let _ = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "keyPoint": kp}));
|
||||
let _ = s.execute("arraypolar", &json!({"handles": [l], "center": [5, 5], "count": 3, "keyPoint": kp}));
|
||||
}
|
||||
let mut s = Session::new();
|
||||
let l = source_line(&mut s);
|
||||
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
|
||||
for kp in [json!([1e308, 1e308]), json!([-1e308, 0]), json!(["x"]), json!([0.5, 0.25])] {
|
||||
let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": kp}));
|
||||
let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [], "keyPoint": kp, "items": [[0, 0, 0]]}}));
|
||||
}
|
||||
// Typed key points far away or on nothing are refused without leaving the command broken.
|
||||
s.set_selection(vec![h]);
|
||||
typed(&mut s, &["arrayedit", "b", "k"]);
|
||||
assert!(s.cmdline("1e300,1e300").is_err() || s.running.is_some());
|
||||
s.cancel();
|
||||
}
|
||||
|
||||
/// A `keyPoint` that is there but isn't a point is refused, not taken as no key point (which
|
||||
/// would make the array at another base point).
|
||||
#[test]
|
||||
fn a_key_point_that_is_not_a_point_is_refused() {
|
||||
let mut s = Session::new();
|
||||
let l = source_line(&mut s);
|
||||
assert!(s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "keyPoint": ["bad", 1]})).is_err());
|
||||
assert!(s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 3, "keyPoint": "x"})).is_err());
|
||||
assert!(s.doc().unwrap().model.iter().all(|e| s.doc().unwrap().array_params(e).is_none()), "no array made");
|
||||
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
|
||||
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [1]})).is_err());
|
||||
let c = s.execute("circle", &json!({"center": [50, 50], "radius": 1})).unwrap()["handle"].clone();
|
||||
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [c], "keyPoint": {}, "items": [[1, 0, 0]]}})).is_err());
|
||||
}
|
||||
|
||||
/// More objects than the key point search takes are refused rather than searched in part, which
|
||||
/// could miss the nearest key point.
|
||||
#[test]
|
||||
fn a_key_point_of_too_many_objects_is_refused() {
|
||||
let mut s = Session::new();
|
||||
// 10,001 lines; the last one ends nearest the key point.
|
||||
let pts: Vec<[f64; 2]> = (0..10_002).map(|i| [f64::from(i), 0.0]).collect();
|
||||
let r = s.execute("line", &json!({ "points": pts })).unwrap();
|
||||
let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
|
||||
assert_eq!(hs.len(), 10_001, "{r}");
|
||||
let e = s.execute("arraypolar", &json!({"handles": hs, "center": [0, -50], "count": 2, "keyPoint": [10_001.2, 0]})).unwrap_err();
|
||||
assert!(e.to_string().contains("10000"), "{e}");
|
||||
}
|
||||
|
||||
/// ARRAYEDIT with a new base point (`base` or `keyPoint`) and a polar `center` in one call puts the
|
||||
/// centre where asked: the base point moves the array's insertion point, so the centre is read in
|
||||
/// the array's placement after that move.
|
||||
#[test]
|
||||
fn arrayedit_center_with_a_new_base_point_lands_where_asked() {
|
||||
for (key, at) in [("base", json!([2, 1])), ("keyPoint", json!([1.95, 0.99]))] {
|
||||
let mut s = Session::new();
|
||||
let l = source_line(&mut s);
|
||||
let h = handle(&s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 4, "base": [0, 0]})).unwrap());
|
||||
s.execute("arrayedit", &json!({"handle": h.hex(), key: at, "center": [5, 0]})).unwrap();
|
||||
let (ins, p) = array(&s, h);
|
||||
let ArrayKind::Polar(k) = p.kind else { panic!("not polar") };
|
||||
assert!(ins.near(Vec2::new(2.0, 1.0), 1e-9), "{key}: {ins:?}");
|
||||
// The centre is kept relative to the insertion point.
|
||||
assert!((ins + k.center).near(Vec2::new(5.0, 0.0), 1e-9), "{key}: centre at {:?}", ins + k.center);
|
||||
}
|
||||
}
|
||||
@@ -83,22 +83,14 @@ fn dash_attedit_one_at_a_time_edits_the_selected_attributes() {
|
||||
let mut s = with_block();
|
||||
let h = handle(&insert(&mut s, 100.0, json!({"T": "abc"})));
|
||||
type_lines(&mut s, &["-attedit", "y", "", "T", "", "105,0", ""]);
|
||||
assert!(s.prompt_text().contains("[Value/Position/Height/Angle/Style/Layer/Color/Next] <N>"), "{}", s.prompt_text());
|
||||
// Edit Position, Height, Angle, and Style
|
||||
type_lines(&mut s, &["p", "10,20", "h", "2.5", "a", "45", "s", "Standard"]);
|
||||
// Edit Value: change and replace
|
||||
assert!(s.prompt_text().contains("[Value/Layer/Color/Next] <N>"), "{}", s.prompt_text());
|
||||
// Unsupported options say so and keep the prompt.
|
||||
s.cmdline("p").unwrap();
|
||||
assert!(s.log.iter().any(|l| l.contains("Position is not available yet")), "{:?}", s.log);
|
||||
type_lines(&mut s, &["v", "c", "b", "B", "v", "r", "replaced value", "n"]);
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(value(&s, h, "T"), "replaced value");
|
||||
assert_eq!(value(&s, h, "U"), "u");
|
||||
|
||||
let EntityKind::Insert(ins) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
|
||||
let att = ins.attribs.iter().find(|a| a.tag == "T").unwrap();
|
||||
assert!((att.text.insert.x - 10.0).abs() < 1e-6);
|
||||
assert!((att.text.insert.y - 20.0).abs() < 1e-6);
|
||||
assert!((att.text.height - 2.5).abs() < 1e-6);
|
||||
assert!((att.text.rotation.to_degrees() - 45.0).abs() < 1e-4);
|
||||
assert_eq!(att.text.style, "Standard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -117,34 +109,3 @@ fn attribute_tags_match_in_any_case_and_unknown_tags_are_reported() {
|
||||
let r = s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "four"}})).unwrap();
|
||||
assert_eq!(r, json!({"changed": 1}));
|
||||
}
|
||||
|
||||
/// -ATTEDIT Position moves an aligned or fit attribute without losing its baseline: both of its
|
||||
/// points move by the same offset (setting both to the picked point would leave no direction or
|
||||
/// length to fit the text between).
|
||||
#[test]
|
||||
fn dash_attedit_position_keeps_an_aligned_attributes_baseline() {
|
||||
use cadcraft_doc::HAlign;
|
||||
use cadcraft_geom::Vec3;
|
||||
for halign in [HAlign::Aligned, HAlign::Fit] {
|
||||
let mut s = with_block();
|
||||
let h = handle(&insert(&mut s, 100.0, json!({"T": "abc"})));
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let EntityKind::Insert(i) = &mut e.kind {
|
||||
for a in i.attribs.iter_mut().filter(|a| a.tag == "T") {
|
||||
a.text.halign = halign;
|
||||
a.text.insert = Vec3::new(100.0, 1.0, 0.0);
|
||||
a.text.align_pt = Some(Vec3::new(104.0, 1.0, 0.0));
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
type_lines(&mut s, &["-attedit", "y", "", "T", "", "105,0", "", "p", "10,20", "n"]);
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let EntityKind::Insert(ins) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
|
||||
let t = &ins.attribs.iter().find(|a| a.tag == "T").unwrap().text;
|
||||
assert!(t.insert.xy().near(cadcraft_geom::Vec2::new(10.0, 20.0), 1e-9), "{halign:?}: {:?}", t.insert);
|
||||
assert!(t.align_pt.is_some_and(|p| p.xy().near(cadcraft_geom::Vec2::new(14.0, 20.0), 1e-9)), "{halign:?}: {:?}", t.align_pt);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ fn dash_attedit_sets_layer_and_colour_of_one_attribute() {
|
||||
for t in ["-attedit", "y", "", "T", "", "105,0", ""] {
|
||||
s.cmdline(t).unwrap();
|
||||
}
|
||||
assert!(s.prompt_text().contains("[Value/Position/Height/Angle/Style/Layer/Color/Next] <N>"), "{}", s.prompt_text());
|
||||
assert!(s.prompt_text().contains("[Value/Layer/Color/Next] <N>"), "{}", s.prompt_text());
|
||||
s.cmdline("l").unwrap();
|
||||
assert!(s.prompt_text().contains("Enter new layer name <0>"), "{}", s.prompt_text());
|
||||
// An unknown layer is refused and asked again.
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
//! -LAYER stAte: AutoCAD 2024's layer state prompts and messages (measured with accoreconsole on a
|
||||
//! drawing with layers A, red, and B), and the `layerstate.*` commands they run.
|
||||
|
||||
use cadcraft_engine::doc::LayerState;
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
const LABELS: [&str; 10] = ["On", "Frozen", "Lock", "Plot", "Newvpfreeze", "Color", "lineType", "lineWeight", "Transparency", "plotStyle"];
|
||||
|
||||
/// The toggles AutoCAD lists before "Enter states to change", with `no` the ones set to No.
|
||||
fn table(no: &[&str]) -> Vec<String> {
|
||||
let mut v = vec!["States".to_string()];
|
||||
v.extend(LABELS.iter().map(|l| format!("{l:<20}{}", if no.contains(l) { "No" } else { "Yes" })));
|
||||
v
|
||||
}
|
||||
|
||||
/// Layers A (red) and B; the current layer stays 0.
|
||||
fn drawing() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.script("-LAYER N A,B C 1 A\n\n").unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Run `script` to its end and return what it wrote besides the commands' names and -LAYER's
|
||||
/// "Current layer" line.
|
||||
fn run(s: &mut Session, script: &str) -> Vec<String> {
|
||||
let at = s.log.len();
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script:?} ends at: {}", s.prompt_text());
|
||||
s.log[at..].iter().filter(|l| !l.starts_with("Command: ") && !l.starts_with("Current layer:")).cloned().collect()
|
||||
}
|
||||
|
||||
fn states(s: &Session) -> Vec<(String, u32)> {
|
||||
s.doc().unwrap().layer_states.iter().map(|st| (st.name.clone(), st.mask)).collect()
|
||||
}
|
||||
|
||||
fn state(name: &str, mask: u32) -> (String, u32) {
|
||||
(name.to_string(), mask)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_asks_the_states_and_remembers_them_for_the_next_save() {
|
||||
let mut s = drawing();
|
||||
// Each toggle lists the states again; On off is AutoCAD's 2046.
|
||||
let out = run(&mut s, "-LAYER A S S6 ON\n\n\n\nLINE 0,0 1,0\n\n");
|
||||
assert_eq!(out, [table(&[]), table(&["On"])].concat());
|
||||
assert_eq!(states(&s), [state("S6", 2046)]);
|
||||
assert_eq!(s.doc().unwrap().model.len(), 1, "the next command runs");
|
||||
// The next Save starts from the toggles the last one left: On alone is 513, then every
|
||||
// toggle once more is 2046 (AutoCAD's S7 and S8).
|
||||
let out = run(&mut s, "-LAYER A S S7 ON F L P N C T W TR S\n\n\n\n");
|
||||
assert_eq!(out[..11], table(&["On"]));
|
||||
assert_eq!(
|
||||
out[out.len() - 11..],
|
||||
table(&["Frozen", "Lock", "Plot", "Newvpfreeze", "Color", "lineType", "lineWeight", "Transparency", "plotStyle"])
|
||||
);
|
||||
run(&mut s, "-LAYER A S S8 ON F L P N C T W TR S\n\n\n\n");
|
||||
run(&mut s, "-LAYER A S S9 ON\n\n\n\n");
|
||||
assert_eq!(states(&s)[1..], [state("S7", 513), state("S8", 2046), state("S9", LayerState::ALL)]);
|
||||
// Edit lists and changes the state's own mask (found in any case), not the next Save's
|
||||
// toggles (AutoCAD: Edit S1 to 2015, then S2 is 2047).
|
||||
let out = run(&mut s, "-LAYER A E s6 ON C\n\n\n\n");
|
||||
assert_eq!(out, [table(&["On"]), table(&[]), table(&["Color"])].concat());
|
||||
run(&mut s, "-LAYER A S S10\n\n\n\n");
|
||||
assert_eq!(states(&s)[0], state("S6", 2015));
|
||||
assert_eq!(states(&s)[4], state("S10", LayerState::ALL));
|
||||
// Each -LAYER is one undo step.
|
||||
s.undo().unwrap();
|
||||
assert_eq!(states(&s).len(), 4);
|
||||
s.undo().unwrap();
|
||||
assert_eq!(states(&s)[0], state("S6", 2046));
|
||||
// A state from AutoCAD after a restore (mask 67583 = 2047 + 65536) named as AutoCAD names a
|
||||
// state renamed to "*X": `?` lists it, and Edit keeps the bit no toggle reaches.
|
||||
s.doc_mut().unwrap().layer_states.push(LayerState { name: "*A1".into(), mask: 67583, ..LayerState::default() });
|
||||
assert_eq!(
|
||||
run(
|
||||
&mut s,
|
||||
"-LAYER A ?
|
||||
|
||||
|
||||
"
|
||||
)[2],
|
||||
"*A1"
|
||||
);
|
||||
run(
|
||||
&mut s,
|
||||
"-LAYER A E *a1 C
|
||||
|
||||
|
||||
|
||||
",
|
||||
);
|
||||
assert_eq!(states(&s)[4], state("*A1", 67583 - 32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_follow_autocads_rules_and_messages() {
|
||||
let mut s = drawing();
|
||||
run(&mut s, "-LAYER A S S1\n\n\n\n");
|
||||
// A saved name in another case is refused and asked again.
|
||||
let out = run(&mut s, "-LAYER A S s1 S2\n\n\n\n");
|
||||
assert_eq!(out, [vec!["Layer state \"s1\" already exists.".to_string()], table(&[])].concat());
|
||||
// The layer name characters, and more than 255 characters, are refused; Enter goes back.
|
||||
let long = "y".repeat(256);
|
||||
let out = run(&mut s, &format!("-LAYER A S *X a<b a,b {long}\n\n\n\n"));
|
||||
assert_eq!(
|
||||
out,
|
||||
[
|
||||
"\"*X\" is an invalid layer state name.",
|
||||
"\"a<b\" is an invalid layer state name.",
|
||||
"\"a,b\" is an invalid layer state name.",
|
||||
&format!("\"{long}\" is an invalid layer state name.")
|
||||
]
|
||||
);
|
||||
run(&mut s, &format!("-LAYER A S {}\n\n\n\n", "x".repeat(255)));
|
||||
assert_eq!(states(&s).len(), 3);
|
||||
run(&mut s, &format!("-LAYER A D {}\n\n\n", "x".repeat(255)));
|
||||
// `?` lists by name without regard to case.
|
||||
run(&mut s, "-LAYER A S b\n\n\n\n");
|
||||
let list = ["Layer state", "-----------------------------", "b", "S1", "S2"];
|
||||
assert_eq!(run(&mut s, "-LAYER A ?\n\n\n"), list);
|
||||
// Each name prompt lists on `?`, says an unknown name and asks again, and Enter goes back.
|
||||
let out = run(&mut s, "-LAYER A R ? NOSUCH\n\nE NOSUCH\n\nN NOSUCH\n\nD NOSUCH\n\n\n\n");
|
||||
assert_eq!(out[..5], list);
|
||||
assert_eq!(out[5..], ["Unknown layer state name."; 4]);
|
||||
// Unknown options, Import and EXport.
|
||||
let out = run(&mut s, "-LAYER A XYZ I EX\n\n\n");
|
||||
assert_eq!(out, ["Invalid option keyword.", "-LAYER stAte Import is not available yet.", "-LAYER stAte EXport is not available yet."]);
|
||||
let out = run(&mut s, "-LAYER A S T1 XYZ\n\n\n\n");
|
||||
assert_eq!(out, [table(&[]), vec!["Invalid option keyword.".to_string()]].concat());
|
||||
assert_eq!(states(&s).len(), 4, "T1 is saved after the invalid toggle");
|
||||
run(&mut s, "-LAYER A D T1\n\n\n");
|
||||
// Name: a name some state has in any case, the state's own too, is refused with two lines.
|
||||
assert_eq!(run(&mut s, "-LAYER A N S1 S2\n\n\n"), ["Layer state could not be renamed.", "S2 already exists."]);
|
||||
assert_eq!(run(&mut s, "-LAYER A N S1 s1\n\n\n"), ["Layer state could not be renamed.", "s1 already exists."]);
|
||||
// A name with a refused character leaves the state as it is, with no message; Enter too.
|
||||
assert!(run(&mut s, "-LAYER A N S1 a,b\n\n\n").is_empty());
|
||||
assert!(run(&mut s, "-LAYER A N S1\n\n\n\n").is_empty());
|
||||
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S1", "S2", "b"]);
|
||||
// The old name in another case.
|
||||
assert!(run(&mut s, "-LAYER A N s1 S9\n\n\n").is_empty());
|
||||
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S9", "S2", "b"]);
|
||||
assert!(run(&mut s, "-LAYER A D s9\n\n\n").is_empty());
|
||||
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S2", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn esc_drops_the_state_being_saved_and_undo_takes_back_name_and_delete() {
|
||||
let mut s = drawing();
|
||||
run(
|
||||
&mut s,
|
||||
"-LAYER A S S1
|
||||
|
||||
|
||||
|
||||
",
|
||||
);
|
||||
// Esc at the toggles: that state isn't saved and the next Save's toggles stay as they were;
|
||||
// what the same -LAYER did before Esc stays, as for the other -LAYER options.
|
||||
s.script(
|
||||
"-LAYER A S S2
|
||||
|
||||
S S3 C ON
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
// AutoCAD 2024 asks for the toggles without "or" before them.
|
||||
assert_eq!(
|
||||
s.current_prompt().unwrap().display(),
|
||||
"Enter states to change [On/Frozen/Lock/Plot/Newvpfreeze/Color/lineType/lineWeight/TRansparency/plotStyle]:"
|
||||
);
|
||||
s.input(Input::Cancel).unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(states(&s), [state("S1", LayerState::ALL), state("S2", LayerState::ALL)]);
|
||||
assert_eq!(s.settings.layer_state_mask, LayerState::ALL);
|
||||
// Name and Delete are one undo step each, like Save.
|
||||
run(
|
||||
&mut s,
|
||||
"-LAYER A N S1 S9
|
||||
|
||||
|
||||
",
|
||||
);
|
||||
run(
|
||||
&mut s,
|
||||
"-LAYER A D S2
|
||||
|
||||
|
||||
",
|
||||
);
|
||||
assert_eq!(states(&s), [state("S9", LayerState::ALL)]);
|
||||
s.undo().unwrap();
|
||||
assert_eq!(states(&s), [state("S9", LayerState::ALL), state("S2", LayerState::ALL)]);
|
||||
s.undo().unwrap();
|
||||
assert_eq!(states(&s), [state("S1", LayerState::ALL), state("S2", LayerState::ALL)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_finds_the_state_in_any_case() {
|
||||
let mut s = drawing();
|
||||
run(&mut s, "-LAYER A S S1\n\n\n\n");
|
||||
run(&mut s, "-LAYER C 3 A M C\n\n");
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!((d.layer("A").unwrap().color, d.header.str("CLAYER", "0")), (cadcraft_color::Color::Index(3), "C".to_string()));
|
||||
assert!(run(&mut s, "-LAYER A R s1\n\n\n").is_empty());
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!((d.layer("A").unwrap().color, d.header.str("CLAYER", "0")), (cadcraft_color::Color::Index(1), "0".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_layer_states_take_a_mask_and_find_names_in_any_case() {
|
||||
let mut s = drawing();
|
||||
s.execute("layerstate.save", &json!({ "name": "M" })).unwrap();
|
||||
s.execute("layerstate.save", &json!({ "name": "On", "mask": LayerState::ON })).unwrap();
|
||||
for bad in [json!(4096), json!(-1), json!(1.5), json!("1")] {
|
||||
assert!(s.execute("layerstate.save", &json!({ "name": "X", "mask": bad })).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(states(&s), [state("M", LayerState::ALL), state("On", 513)]);
|
||||
// Restore, Rename and Delete find a name in another case; a name another state has in any
|
||||
// case is refused, the state's own in another case too.
|
||||
s.execute("layer.set", &json!({ "name": "A", "color": "3" })).unwrap();
|
||||
s.execute("layerstate.restore", &json!({ "name": "m" })).unwrap();
|
||||
assert_eq!(s.doc().unwrap().layer("A").unwrap().color, cadcraft_color::Color::Index(1));
|
||||
assert!(s.execute("layerstate.rename", &json!({ "from": "m", "to": "ON" })).is_err());
|
||||
assert!(s.execute("layerstate.rename", &json!({ "from": "m", "to": "m" })).is_err());
|
||||
s.execute("layerstate.rename", &json!({ "from": "m", "to": "M2" })).unwrap();
|
||||
s.execute("layerstate.delete", &json!({ "name": "on" })).unwrap();
|
||||
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
|
||||
// A name -LAYER stAte Save refuses is refused here too, and nothing is saved.
|
||||
let long = "x".repeat(256);
|
||||
for name in ["", " ", "a<b", "a\nb", long.as_str()] {
|
||||
assert!(s.execute("layerstate.save", &json!({ "name": name })).is_err(), "{name:?}");
|
||||
}
|
||||
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
|
||||
// Save onto a name another state has in another case replaces that state, as one spelled the
|
||||
// same: AutoCAD 2024 keeps one state per name in any case.
|
||||
s.execute("layerstate.save", &json!({ "name": "m2", "mask": LayerState::ON })).unwrap();
|
||||
assert_eq!(states(&s), [state("m2", 513)]);
|
||||
// Names that differ only in case (CADCraft's own record keeps the second of them, which AutoCAD
|
||||
// 2024 doesn't see): Save and Delete take the one spelled so, though the other comes first, and
|
||||
// leave the other.
|
||||
s.doc_mut().unwrap().layer_states.insert(0, LayerState::new("M2", Vec::new(), ""));
|
||||
s.execute("layerstate.save", &json!({ "name": "m2", "mask": LayerState::ON | LayerState::FROZEN })).unwrap();
|
||||
assert_eq!(states(&s), [state("M2", LayerState::ALL), state("m2", 515)]);
|
||||
s.execute("layerstate.delete", &json!({ "name": "m2" })).unwrap();
|
||||
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
|
||||
}
|
||||
@@ -4,7 +4,6 @@ mod annotate_options;
|
||||
mod annotative;
|
||||
mod arc_ctrl_direction;
|
||||
mod array_commands;
|
||||
mod array_key_point;
|
||||
mod assoc_array;
|
||||
mod attdef_command;
|
||||
mod attdisp_attsync;
|
||||
@@ -79,7 +78,6 @@ mod join_close;
|
||||
mod json_param_validation;
|
||||
mod layer_cmdline;
|
||||
mod layer_merge_delete;
|
||||
mod layer_state_cmdline;
|
||||
mod layoff_repeat;
|
||||
mod layout_prompts;
|
||||
mod leader_command;
|
||||
|
||||
@@ -76,135 +76,13 @@ fn rename_prompts_type_old_and_new_name() {
|
||||
assert!(d.block("Pump").is_some() && d.layer("New").is_some() && d.layer("Old").is_none(), "{:?}", s.log);
|
||||
assert_eq!(insert_targets(d), ["Assy", "Pump", "Pump", "Pump"]);
|
||||
assert_eq!(d.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 1);
|
||||
// A type CADCraft lacks reads both names and reports.
|
||||
let n = s.log.len();
|
||||
s.script("-RENAME M a b\nLINE 0,0 2,0\n\n").unwrap();
|
||||
// An unknown old name re-prompts; a type CADCraft lacks reads both names and reports.
|
||||
s.script("-RENAME LA Missing\nNew\nNewer\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(s.log[n..].iter().any(|l| l.contains("Renaming a material is not available yet.")), "{:?}", &s.log[n..]);
|
||||
assert!(s.doc().unwrap().layer("Newer").is_some());
|
||||
let n = s.log.len();
|
||||
s.script("-RENAME VP a b\nLINE 0,0 2,0\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(s.log[n..].iter().any(|l| l.contains("not available yet")), "{:?}", &s.log[n..]);
|
||||
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 2);
|
||||
}
|
||||
|
||||
/// What `script` adds to the log; the command has ended.
|
||||
fn said(s: &mut Session, script: &str) -> Vec<String> {
|
||||
let n = s.log.len();
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
s.log[n..].to_vec()
|
||||
}
|
||||
|
||||
fn says(log: &[String], text: &str) -> bool {
|
||||
log.iter().any(|l| l.contains(text))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_ends_on_a_name_it_cannot_take_with_autocads_messages() {
|
||||
// AutoCAD 2024 (accoreconsole, measured, the same for blocks, dimension styles, layers,
|
||||
// linetypes, text styles, UCSs and views): `Cannot find layer "X".` for an old name that
|
||||
// doesn't exist, `A layer named "X" already exists.` and `*Invalid*` for a new name that does,
|
||||
// `Invalid layer name.` for one it can't take; each ends the command.
|
||||
let mut s = drawing();
|
||||
for name in ["A1", "A2"] {
|
||||
s.execute("layer.new", &json!({ "name": name })).unwrap();
|
||||
}
|
||||
let log = said(&mut s, "-RENAME LA NOSUCH\nLINE 0,0 3,0\n\n");
|
||||
assert!(says(&log, "Cannot find layer \"NOSUCH\"."), "{log:?}");
|
||||
// The command ended there: the next input started LINE.
|
||||
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 1);
|
||||
let log = said(&mut s, "-RENAME LA A1 A2\n");
|
||||
assert!(says(&log, "A layer named \"A2\" already exists.") && says(&log, "*Invalid*"), "{log:?}");
|
||||
let log = said(&mut s, "-RENAME LA A1 X<Y\n");
|
||||
assert!(says(&log, "Invalid layer name."), "{log:?}");
|
||||
// No new name at all is an invalid one too.
|
||||
s.cmdline("-RENAME LA A1").unwrap();
|
||||
let n = s.log.len();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none() && says(&s.log[n..], "Invalid layer name."), "{:?}", &s.log[n..]);
|
||||
assert!(s.doc().unwrap().layer("A1").is_some());
|
||||
said(&mut s, "-RENAME LA A1 B1\n");
|
||||
assert!(s.doc().unwrap().layer("B1").is_some() && s.doc().unwrap().layer("A1").is_none());
|
||||
// The old name in another case than stored, and the new name as typed: a rename to that case
|
||||
// (AutoCAD 2024, measured: LAY1 typed lay1, new name lay1, gives lay1).
|
||||
said(&mut s, "-RENAME LA b1 b1\n");
|
||||
assert!(s.doc().unwrap().layers.iter().any(|l| l.name == "b1"));
|
||||
// Old names AutoCAD 2024 won't rename (measured), each ending the command before the new name.
|
||||
let lines = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
|
||||
for (script, message) in [
|
||||
("-RENAME LA 0\n", "Cannot rename layer \"0\"."),
|
||||
("-RENAME LT continuous\n", "Cannot rename linetype \"continuous\"."),
|
||||
("-RENAME LT ByLayer\n", "Invalid linetype name."),
|
||||
("-RENAME LT byblock\n", "Invalid linetype name."),
|
||||
("-RENAME LT CONTINUOUS\n", "Cannot rename linetype \"CONTINUOUS\"."),
|
||||
("-RENAME B *Model_Space\n", "Invalid block name."),
|
||||
("-RENAME B *U1\n", "Invalid block name."),
|
||||
] {
|
||||
let n = lines(&s);
|
||||
let log = said(&mut s, &format!("{script}LINE 0,0 4,0\n\n"));
|
||||
assert!(says(&log, message), "{script}: {log:?}");
|
||||
assert_eq!(says(&log, "*Invalid*"), message.starts_with("Cannot"), "{script}: {log:?}");
|
||||
assert_eq!(lines(&s), n + 1, "{script}: the next input starts a command");
|
||||
}
|
||||
// A UCS is "ucs" in the prompts and in "A ucs named", "UCS" in the other two.
|
||||
for name in ["U1", "U2"] {
|
||||
let ucs = cadcraft_engine::doc::Ucs { name: name.into(), origin: Default::default(), x_axis: Default::default(), y_axis: Default::default() };
|
||||
s.doc_mut().unwrap().ucss.push(ucs);
|
||||
}
|
||||
s.cmdline("-RENAME U").unwrap();
|
||||
assert!(s.prompt_text().contains("Enter old ucs name"), "{}", s.prompt_text());
|
||||
s.cancel();
|
||||
assert!(says(&said(&mut s, "-RENAME U NOSUCH\n"), "Cannot find UCS \"NOSUCH\"."));
|
||||
assert!(says(&said(&mut s, "-RENAME U U1 U2\n"), "A ucs named \"U2\" already exists."));
|
||||
assert!(says(&said(&mut s, "-RENAME U U1 X<Y\n"), "Invalid UCS name."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_takes_a_saved_viewport_configuration() {
|
||||
// AutoCAD 2024 (measured): -RENAME VPort renames a saved configuration, every tile of it, old
|
||||
// name in any case, and to another case of its own name; "*ACTIVE" (old or new), names with
|
||||
// characters AutoCAD refuses and names already used are refused as for the other types.
|
||||
let mut s = Session::new();
|
||||
s.execute("-vports", &json!({ "option": "2", "arrangement": "vertical" })).unwrap();
|
||||
s.execute("-vports", &json!({ "option": "save", "name": "CFG1" })).unwrap();
|
||||
s.execute("-vports", &json!({ "option": "save", "name": "CFG3" })).unwrap();
|
||||
let names = |s: &Session| -> Vec<(String, usize)> { s.doc().unwrap().vports.iter().map(|v| (v.name.clone(), v.tiles.len())).collect() };
|
||||
said(&mut s, "-RENAME VP cfg1 CFG2\n");
|
||||
assert_eq!(names(&s), [("*Active".to_string(), 2), ("CFG2".to_string(), 2), ("CFG3".to_string(), 2)]);
|
||||
for (script, message) in [
|
||||
// A refused old name ends the command before the new name is asked.
|
||||
("-RENAME VP NOSUCH\n", "Cannot find viewport configuration \"NOSUCH\"."),
|
||||
("-RENAME VP *ACTIVE\n", "Invalid viewport configuration name."),
|
||||
("-RENAME VP CFG2 *ACTIVE\n", "Invalid viewport configuration name."),
|
||||
("-RENAME VP CFG2 A<B\n", "Invalid viewport configuration name."),
|
||||
("-RENAME VP CFG2 CFG3\n", "A viewport configuration named \"CFG3\" already exists."),
|
||||
] {
|
||||
let log = said(&mut s, script);
|
||||
assert!(says(&log, message), "{script}: {log:?}");
|
||||
// "*Invalid*" follows a name already used only.
|
||||
assert_eq!(says(&log, "*Invalid*"), message.ends_with("already exists."), "{script}: {log:?}");
|
||||
}
|
||||
// No new name at all is an invalid one too (measured: CFG1, then Enter).
|
||||
s.cmdline("-RENAME VP CFG2").unwrap();
|
||||
let n = s.log.len();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none() && says(&s.log[n..], "Invalid viewport configuration name."), "{:?}", &s.log[n..]);
|
||||
assert_eq!(names(&s), [("*Active".to_string(), 2), ("CFG2".to_string(), 2), ("CFG3".to_string(), 2)]);
|
||||
said(&mut s, "-RENAME VP CFG2 cfg2\n");
|
||||
assert_eq!(names(&s), [("*Active".to_string(), 2), ("cfg2".to_string(), 2), ("CFG3".to_string(), 2)]);
|
||||
// The new name is compared with the stored one, not with the old name as typed (measured:
|
||||
// CFG1 typed cfg1 to cfg1 gives cfg1; typed cfg1 to CFG1 changes nothing).
|
||||
said(&mut s, "-RENAME VP CFG2 CFG2\n");
|
||||
assert_eq!(names(&s)[1].0, "CFG2");
|
||||
said(&mut s, "-RENAME VP cfg2 CFG2\n");
|
||||
assert_eq!(names(&s)[1].0, "CFG2");
|
||||
said(&mut s, "-RENAME VP cfg2 cfg2\n");
|
||||
assert_eq!(names(&s)[1].0, "cfg2");
|
||||
// The JSON form too, which never takes the configuration shown, and refuses a name already
|
||||
// used (in any case) or with a character AutoCAD refuses, as for the other tables.
|
||||
s.execute("rename", &json!({ "table": "vport", "from": "CFG3", "to": "Pair" })).unwrap();
|
||||
assert_eq!(names(&s)[2].0, "Pair");
|
||||
for to in ["Shown", "CFG2", "A<B"] {
|
||||
let from = if to == "Shown" { "*Active" } else { "Pair" };
|
||||
assert!(s.execute("rename", &json!({ "table": "vport", "from": from, "to": to })).is_err(), "{from} to {to}");
|
||||
}
|
||||
s.execute("rename", &json!({ "table": "vport", "from": "pair", "to": "PAIR" })).unwrap();
|
||||
assert_eq!(names(&s), [("*Active".to_string(), 2), ("cfg2".to_string(), 2), ("PAIR".to_string(), 2)]);
|
||||
}
|
||||
|
||||
@@ -41,8 +41,8 @@ use cadcraft_geom::Vec2;
|
||||
use craft_shx::Record;
|
||||
pub use craft_shx::{ShxError, ShxKind, compile};
|
||||
pub use table::{
|
||||
FontProvider, add_drawing_dir, clear_registered, drawing_dirs, find, font_map, generation, installed, register, search_path, set_font_dirs,
|
||||
set_font_map, set_provider, set_search_path,
|
||||
FontProvider, OpenGuard, add_drawing_dir, add_drawing_dir_guarded, clear_registered, drawing_dirs, find, font_map, generation, installed,
|
||||
register, search_path, set_font_dirs, set_font_map, set_provider, set_search_path,
|
||||
};
|
||||
pub use text::ShxText;
|
||||
pub(crate) use text::{shape, width};
|
||||
|
||||
+108
-19
@@ -20,14 +20,23 @@ use super::{ShxError, ShxFont};
|
||||
/// app's own font folder). Called with the normalised file name (`romans.shx`); returns the
|
||||
/// file's bytes. Called without the font table's lock held.
|
||||
pub trait FontProvider: Send + Sync {
|
||||
/// The bytes of the font file `file_name`, or `None` when this provider has none by that name.
|
||||
fn load(&self, file_name: &str) -> Option<Vec<u8>>;
|
||||
}
|
||||
|
||||
/// Decides whether the file at a path may be opened by the font search; asked of every candidate in
|
||||
/// a folder, before anything opens it.
|
||||
pub type OpenGuard = Arc<dyn Fn(&Path) -> bool + Send + Sync>;
|
||||
|
||||
/// Most fonts kept loaded, and their total bytes.
|
||||
const MAX_FONTS: usize = 128;
|
||||
const MAX_LOADED_BYTES: usize = 256 << 20;
|
||||
/// Most drawing folders and search path entries remembered.
|
||||
const MAX_DIRS: usize = 32;
|
||||
/// Most folders whose guards are kept.
|
||||
const MAX_GUARDED_DIRS: usize = 1024;
|
||||
/// Most guards kept past [`MAX_GUARDED_DIRS`], each applying to every folder searched.
|
||||
const MAX_OVERFLOW_GUARDS: usize = 4096;
|
||||
/// Most font map entries.
|
||||
const MAX_MAP: usize = 1024;
|
||||
|
||||
@@ -38,6 +47,12 @@ struct Table {
|
||||
loaded_bytes: usize,
|
||||
provider: Option<Arc<dyn FontProvider>>,
|
||||
drawing_dirs: Vec<PathBuf>,
|
||||
/// The guards of the drawing folders that have any, by the owner that gave each one.
|
||||
drawing_guards: HashMap<PathBuf, Vec<(String, OpenGuard)>>,
|
||||
/// Guards given once [`MAX_GUARDED_DIRS`] folders had one: they apply to every folder searched.
|
||||
overflow_guards: Vec<(String, OpenGuard)>,
|
||||
/// The overflow guards ran out: every file is refused from then on.
|
||||
overflow_closed: bool,
|
||||
font_dirs: Vec<PathBuf>,
|
||||
search_path: Vec<PathBuf>,
|
||||
map: Vec<(String, String)>,
|
||||
@@ -118,16 +133,55 @@ pub fn set_provider(provider: Option<Arc<dyn FontProvider>>) {
|
||||
/// Search the folder of a drawing being opened for the fonts its styles name (most recent
|
||||
/// first).
|
||||
pub fn add_drawing_dir(dir: &Path) {
|
||||
add_dir(dir, None);
|
||||
}
|
||||
|
||||
/// Like [`add_drawing_dir`], with every file the search would open in `dir` put to `guard` first,
|
||||
/// whatever its name and however it is found in the folder: a font the guard refuses is skipped.
|
||||
///
|
||||
/// The table is shared by the whole process, so a folder keeps the guard of every `owner` that gave
|
||||
/// one (an owner giving it again replaces its own) and a font is opened only when all of them allow
|
||||
/// it. Adding the folder without a guard never removes one. Fonts found are kept for every caller,
|
||||
/// so owners with different rules shouldn't share a process.
|
||||
pub fn add_drawing_dir_guarded(dir: &Path, owner: &str, guard: OpenGuard) {
|
||||
add_dir(dir, Some((owner, guard)));
|
||||
}
|
||||
|
||||
/// Remember `dir`, most recent first, with the guard it is searched under, if any. The folder's
|
||||
/// guards are kept after it drops off the list of drawing folders.
|
||||
fn add_dir(dir: &Path, guard: Option<(&str, OpenGuard)>) {
|
||||
if dir.as_os_str().is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut t = table();
|
||||
if t.drawing_dirs.first().is_some_and(|d| d == dir) {
|
||||
if guard.is_none() && t.drawing_dirs.first().is_some_and(|d| d == dir) {
|
||||
return;
|
||||
}
|
||||
// Guards outlive the drawing list: a folder dropped from it can still be reached as a font
|
||||
// folder or on the search path. When there is no room for another folder's guards, they apply to
|
||||
// every folder searched from then on, so nothing is left unguarded.
|
||||
let no_room = !t.drawing_guards.contains_key(dir) && t.drawing_guards.len() >= MAX_GUARDED_DIRS;
|
||||
t.drawing_dirs.retain(|d| d != dir);
|
||||
t.drawing_dirs.insert(0, dir.to_path_buf());
|
||||
t.drawing_dirs.truncate(MAX_DIRS);
|
||||
if let Some((owner, guard)) = guard {
|
||||
if no_room {
|
||||
// Every overflow guard stays: none may be replaced by another folder's. When even these
|
||||
// run out, everything is refused from then on.
|
||||
let kept = &mut t.overflow_guards;
|
||||
if !kept.iter().any(|(_, g)| Arc::ptr_eq(g, &guard)) {
|
||||
if kept.len() < MAX_OVERFLOW_GUARDS {
|
||||
kept.push((owner.to_string(), guard));
|
||||
} else {
|
||||
t.overflow_closed = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let guards = t.drawing_guards.entry(dir.to_path_buf()).or_default();
|
||||
guards.retain(|(o, _)| o != owner);
|
||||
guards.push((owner.to_string(), guard));
|
||||
}
|
||||
}
|
||||
t.changed();
|
||||
}
|
||||
|
||||
@@ -194,7 +248,7 @@ pub fn generation() -> u64 {
|
||||
/// The SHX font file a style or linetype names, if CADCraft can find and read it.
|
||||
pub fn find(name: &str) -> Option<Arc<ShxFont>> {
|
||||
let mut k = key(name)?;
|
||||
let (provider, dirs, generation) = {
|
||||
let (provider, folders, (guarded, overflow), generation) = {
|
||||
let t = table();
|
||||
// The font map renames once (a map can't loop).
|
||||
if let Some(to) = t.map.iter().find(|(from, _)| *from == k).and_then(|(_, to)| key(to)) {
|
||||
@@ -206,9 +260,29 @@ pub fn find(name: &str) -> Option<Arc<ShxFont>> {
|
||||
if let Some(r) = t.resolved.get(&k) {
|
||||
return r.clone();
|
||||
}
|
||||
let dirs: Vec<PathBuf> = t.drawing_dirs.iter().chain(t.font_dirs.iter()).chain(t.search_path.iter()).cloned().collect();
|
||||
(t.provider.clone(), dirs, t.generation)
|
||||
let folders: Vec<PathBuf> = t.drawing_dirs.iter().chain(t.font_dirs.iter()).chain(t.search_path.iter()).cloned().collect();
|
||||
let guarded: Vec<(PathBuf, Vec<OpenGuard>)> =
|
||||
t.drawing_guards.iter().map(|(d, g)| (d.clone(), g.iter().map(|(_, g)| g.clone()).collect())).collect();
|
||||
let mut overflow: Vec<OpenGuard> = t.overflow_guards.iter().map(|(_, g)| g.clone()).collect();
|
||||
if t.overflow_closed {
|
||||
overflow.push(Arc::new(|_: &Path| false));
|
||||
}
|
||||
(t.provider.clone(), folders, (guarded, overflow), t.generation)
|
||||
};
|
||||
// A guard belongs to the folder, however the search reaches it: a font folder or the search path
|
||||
// naming the same folder as a drawing's is held to the same guards.
|
||||
// Each folder is resolved once per lookup (spelled, and as the file system has it).
|
||||
let resolved = |d: &Path| std::fs::canonicalize(d).ok();
|
||||
let guarded: Vec<(PathBuf, Option<PathBuf>, Vec<OpenGuard>)> = guarded.into_iter().map(|(d, g)| (d.clone(), resolved(&d), g)).collect();
|
||||
let dirs: Vec<(PathBuf, Vec<OpenGuard>)> = folders
|
||||
.into_iter()
|
||||
.map(|d| {
|
||||
let real = resolved(&d);
|
||||
let own = guarded.iter().filter(|(g, r, _)| *g == d || (real.is_some() && *r == real)).flat_map(|(_, _, g)| g.iter().cloned());
|
||||
let guards = own.chain(overflow.iter().cloned()).collect();
|
||||
(d, guards)
|
||||
})
|
||||
.collect();
|
||||
let font = provider
|
||||
.and_then(|p| p.load(&k))
|
||||
.or_else(|| read_from(&dirs, &k))
|
||||
@@ -266,24 +340,24 @@ pub fn installed() -> Vec<String> {
|
||||
|
||||
/// The file `name` (a lower-case key) in the first of `dirs` that has it, whatever the case of
|
||||
/// its name: lower-case, upper-case, else any other case found in the directory (`Simplex.shx`
|
||||
/// on a case-sensitive file system).
|
||||
/// on a case-sensitive file system). Each of a folder's guards is asked about each candidate before
|
||||
/// anything opens it, so a link is judged by where it leads.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_from(dirs: &[PathBuf], name: &str) -> Option<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
let read = |file: &Path| -> Option<Vec<u8>> {
|
||||
let meta = std::fs::metadata(file).ok()?;
|
||||
if !meta.is_file() || meta.len() > MAX_FILE_BYTES as u64 {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
let limit = u64::try_from(MAX_FILE_BYTES).unwrap_or(u64::MAX).saturating_add(1);
|
||||
std::fs::File::open(file).and_then(|f| f.take(limit).read_to_end(&mut bytes)).ok()?;
|
||||
Some(bytes)
|
||||
};
|
||||
for d in dirs {
|
||||
fn read_from(dirs: &[(PathBuf, Vec<OpenGuard>)], name: &str) -> Option<Vec<u8>> {
|
||||
for (d, guards) in dirs {
|
||||
let read = |file: &Path| -> Option<Vec<u8>> {
|
||||
if !guards.iter().all(|g| g(file)) {
|
||||
return None;
|
||||
}
|
||||
read_file(file)
|
||||
};
|
||||
if let Some(b) = [d.join(name), d.join(name.to_ascii_uppercase())].iter().find_map(|f| read(f)) {
|
||||
return Some(b);
|
||||
}
|
||||
// The folder is listed only when its guards allow the folder itself.
|
||||
if !guards.iter().all(|g| g(d)) {
|
||||
continue;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(d) else { continue };
|
||||
let found = entries
|
||||
.take(MAX_DIR_ENTRIES)
|
||||
@@ -297,7 +371,22 @@ fn read_from(dirs: &[PathBuf], name: &str) -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The bytes of the SHX file at `file`, when it is a file of a sensible size.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_file(file: &Path) -> Option<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
let meta = std::fs::metadata(file).ok()?;
|
||||
if !meta.is_file() || meta.len() > MAX_FILE_BYTES as u64 {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
let limit = u64::try_from(MAX_FILE_BYTES).unwrap_or(u64::MAX).saturating_add(1);
|
||||
std::fs::File::open(file).and_then(|f| f.take(limit).read_to_end(&mut bytes)).ok()?;
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
/// On the web there are no folders to search.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn read_from(_dirs: &[PathBuf], _name: &str) -> Option<Vec<u8>> {
|
||||
fn read_from(_dirs: &[(PathBuf, Vec<OpenGuard>)], _name: &str) -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
//! A guarded drawing folder: the font search asks the guard about every file it would open there,
|
||||
//! before opening it (the automation roots use this to keep a font link from leading out of them).
|
||||
// Integration tests: unwrapping on failure is fine here, unlike in shipped code (AGENTS.md).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use cadcraft_fonts::shx;
|
||||
|
||||
const FONT: &str = "*0,4,guard\n6,2,0,0\n*65,7,UCA\n1,064,040,06C,2,020,0\n";
|
||||
|
||||
/// A folder of this test's own, made here so nothing else put it there first, and removed when the
|
||||
/// test ends, also when it fails.
|
||||
struct TestDir(std::path::PathBuf);
|
||||
|
||||
impl Drop for TestDir {
|
||||
/// Removes the folder and all it holds.
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new folder for `tag`: creating it must not find one already there.
|
||||
fn fresh_dir(tag: &str) -> TestDir {
|
||||
let mut n = 0u32;
|
||||
loop {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-shx-{tag}-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => return TestDir(dir),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1,
|
||||
Err(e) => panic!("{}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lower-case file name of `file`, so a guard never reads the test folder's own name.
|
||||
fn name(file: &Path) -> String {
|
||||
file.file_name().map(|n| n.to_string_lossy().to_ascii_lowercase()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Every candidate the search opens in a guarded folder goes to the guard first, whatever its name
|
||||
/// or how the search finds it, and a font the guard refuses is skipped while the others are used.
|
||||
#[test]
|
||||
fn every_file_the_search_opens_goes_to_the_guard_first() {
|
||||
let bytes = shx::compile(FONT).unwrap();
|
||||
let owner = fresh_dir("guard");
|
||||
let dir = owner.0.clone();
|
||||
std::fs::write(dir.join("cadcraft-guard-ok.shx"), &bytes).unwrap();
|
||||
std::fs::write(dir.join("cadcraft-guard-bad.shx"), &bytes).unwrap();
|
||||
// Found only by looking through the folder, as a link under another spelling would be.
|
||||
std::fs::write(dir.join("CadCraft-Guard-Mixed.SHX"), &bytes).unwrap();
|
||||
std::fs::write(dir.join("CadCraft-Guard-Badmixed.SHX"), &bytes).unwrap();
|
||||
let asked: Arc<Mutex<Vec<PathBuf>>> = Arc::default();
|
||||
let log = asked.clone();
|
||||
shx::add_drawing_dir_guarded(
|
||||
&dir,
|
||||
"first",
|
||||
Arc::new(move |file: &Path| {
|
||||
log.lock().unwrap().push(file.to_path_buf());
|
||||
!name(file).contains("bad")
|
||||
}),
|
||||
);
|
||||
assert!(shx::find("cadcraft-guard-ok.shx").is_some());
|
||||
assert!(shx::find("cadcraft-guard-mixed.shx").is_some(), "a name found by looking through the folder");
|
||||
assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "a font the guard refuses is skipped");
|
||||
assert!(shx::find("cadcraft-guard-badmixed.shx").is_none(), "also one found by looking through the folder");
|
||||
let asked = asked.lock().unwrap();
|
||||
// The guard saw each font's file under the spelling the search tried (a file system that
|
||||
// ignores case answers the first one, so only the letters are compared).
|
||||
for file in ["cadcraft-guard-ok.shx", "cadcraft-guard-bad.shx", "cadcraft-guard-mixed.shx", "cadcraft-guard-badmixed.shx"] {
|
||||
let want = dir.join(file).to_string_lossy().to_ascii_lowercase();
|
||||
assert!(asked.iter().any(|a| a.to_string_lossy().to_ascii_lowercase() == want), "the guard was asked about {file}: {asked:?}");
|
||||
}
|
||||
drop(asked);
|
||||
// The folder added again without a guard (another session in the process) keeps its guard.
|
||||
shx::add_drawing_dir(&dir);
|
||||
assert!(shx::find("cadcraft-guard-bad.shx").is_none());
|
||||
// Another owner's guard is required as well: a font is opened only when every owner allows it.
|
||||
shx::add_drawing_dir_guarded(&dir, "second", Arc::new(|file: &Path| !name(file).contains("ok")));
|
||||
assert!(shx::find("cadcraft-guard-ok.shx").is_none(), "refused by the second owner");
|
||||
assert!(shx::find("cadcraft-guard-mixed.shx").is_some(), "allowed by both");
|
||||
// An owner giving its guard again replaces its own, and the other's stays.
|
||||
shx::add_drawing_dir_guarded(&dir, "second", Arc::new(|_: &Path| true));
|
||||
assert!(shx::find("cadcraft-guard-ok.shx").is_some());
|
||||
assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "the first owner's guard still holds");
|
||||
// The same folder named as a font folder or on the search path is held to its guards too.
|
||||
shx::set_font_dirs(vec![dir.clone()]);
|
||||
shx::set_search_path(&dir.to_string_lossy());
|
||||
assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "a font folder or the search path doesn't lift the guard");
|
||||
assert!(shx::find("cadcraft-guard-ok.shx").is_some());
|
||||
// The folder falling off the list of drawing folders (the list is short) keeps its guards while a
|
||||
// font folder or the search path still reaches it.
|
||||
for n in 0..40 {
|
||||
shx::add_drawing_dir(&dir.join(format!("other-{n}")));
|
||||
}
|
||||
assert!(!shx::drawing_dirs().contains(&dir));
|
||||
assert!(shx::find("cadcraft-guard-bad.shx").is_none(), "the outside font stays rejected after the eviction");
|
||||
assert!(shx::find("cadcraft-guard-ok.shx").is_some());
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! When even the overflow guards run out, every font is refused, whatever name the owners gave.
|
||||
// Integration tests: unwrapping on failure is fine here, unlike in shipped code (AGENTS.md).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_fonts::shx;
|
||||
|
||||
const FONT: &str = "*0,4,closed\n6,2,0,0\n*65,7,UCA\n1,064,040,06C,2,020,0\n";
|
||||
|
||||
/// A folder of this test's own, made here so nothing else put it there first, and removed when the
|
||||
/// test ends, also when it fails.
|
||||
struct TestDir(std::path::PathBuf);
|
||||
|
||||
impl Drop for TestDir {
|
||||
/// Removes the folder and all it holds.
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new folder for `tag`: creating it must not find one already there.
|
||||
fn fresh_dir(tag: &str) -> TestDir {
|
||||
let mut n = 0u32;
|
||||
loop {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-shx-{tag}-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => return TestDir(dir),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1,
|
||||
Err(e) => panic!("{}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Past every limit, a font that no guard objects to is still refused, also when an owner is called
|
||||
/// `closed`.
|
||||
#[test]
|
||||
fn guards_that_ran_out_refuse_every_font() {
|
||||
let bytes = shx::compile(FONT).unwrap();
|
||||
let owner = fresh_dir("closed");
|
||||
let dir = owner.0.clone();
|
||||
std::fs::write(dir.join("cadcraft-closed-ok.shx"), &bytes).unwrap();
|
||||
shx::set_font_dirs(vec![dir.clone()]);
|
||||
assert!(shx::find("cadcraft-closed-ok.shx").is_some(), "found while nothing guards the folder");
|
||||
for n in 0..6000 {
|
||||
shx::add_drawing_dir_guarded(&dir.join(format!("drawings-{n}")), "closed", Arc::new(|_: &Path| true));
|
||||
}
|
||||
assert!(shx::find("cadcraft-closed-ok.shx").is_none(), "refused once the guards ran out");
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! A guarded folder is listed only when its guards allow the folder itself, so a folder outside the
|
||||
//! automation roots isn't read even for the names in it.
|
||||
// Integration tests: unwrapping on failure is fine here, unlike in shipped code (AGENTS.md).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use cadcraft_fonts::shx;
|
||||
|
||||
/// A folder of this test's own, made here so nothing else put it there first, and removed when the
|
||||
/// test ends, also when it fails.
|
||||
struct TestDir(PathBuf);
|
||||
|
||||
impl Drop for TestDir {
|
||||
/// Removes the folder and all it holds.
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new folder: creating it must not find one already there.
|
||||
fn fresh_dir() -> TestDir {
|
||||
let mut n = 0u32;
|
||||
loop {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-shx-listing-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => return TestDir(dir),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1,
|
||||
Err(e) => panic!("{}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Looking for a font that isn't there makes the search list the folder, and the guard is asked
|
||||
/// about the folder itself first; a guard that refuses it ends the search there.
|
||||
#[test]
|
||||
fn the_folder_itself_goes_to_the_guard_before_it_is_listed() {
|
||||
let owner = fresh_dir();
|
||||
let dir = owner.0.clone();
|
||||
let asked: Arc<Mutex<Vec<PathBuf>>> = Arc::default();
|
||||
let log = asked.clone();
|
||||
let folder = dir.clone();
|
||||
shx::add_drawing_dir_guarded(
|
||||
&dir,
|
||||
"listing",
|
||||
Arc::new(move |path: &Path| {
|
||||
log.lock().unwrap().push(path.to_path_buf());
|
||||
path != folder
|
||||
}),
|
||||
);
|
||||
assert!(shx::find("cadcraft-listing-missing.shx").is_none());
|
||||
let seen = asked.lock().unwrap().clone();
|
||||
assert!(seen.contains(&dir), "the guard was asked about the folder: {seen:?}");
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! Past the number of guarded folders kept, a new folder's guards apply to every folder searched, so
|
||||
//! no font folder or search path entry is left unguarded.
|
||||
// Integration tests: unwrapping on failure is fine here, unlike in shipped code (AGENTS.md).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_fonts::shx;
|
||||
|
||||
const FONT: &str = "*0,4,overflow\n6,2,0,0\n*65,7,UCA\n1,064,040,06C,2,020,0\n";
|
||||
|
||||
/// A folder of this test's own, made here so nothing else put it there first, and removed when the
|
||||
/// test ends, also when it fails.
|
||||
struct TestDir(std::path::PathBuf);
|
||||
|
||||
impl Drop for TestDir {
|
||||
/// Removes the folder and all it holds.
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new folder for `tag`: creating it must not find one already there.
|
||||
fn fresh_dir(tag: &str) -> TestDir {
|
||||
let mut n = 0u32;
|
||||
loop {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-shx-{tag}-{}-{n}", std::process::id()));
|
||||
match std::fs::create_dir(&dir) {
|
||||
Ok(()) => return TestDir(dir),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1,
|
||||
Err(e) => panic!("{}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// With far more guarded folders than are kept, a font folder holding a font the guards refuse still
|
||||
/// has it refused, and one the guards allow is still found.
|
||||
#[test]
|
||||
fn guards_past_the_limit_apply_to_every_folder() {
|
||||
let bytes = shx::compile(FONT).unwrap();
|
||||
let owner = fresh_dir("overflow");
|
||||
let dir = owner.0.clone();
|
||||
std::fs::write(dir.join("cadcraft-overflow-bad.shx"), &bytes).unwrap();
|
||||
std::fs::write(dir.join("cadcraft-overflow-ok.shx"), &bytes).unwrap();
|
||||
for n in 0..1100 {
|
||||
let folder = dir.join(format!("drawings-{n}"));
|
||||
shx::add_drawing_dir_guarded(
|
||||
&folder,
|
||||
"session",
|
||||
Arc::new(|file: &Path| !file.file_name().is_some_and(|n| n.to_string_lossy().contains("bad"))),
|
||||
);
|
||||
}
|
||||
// A later folder with the same owner and a guard that allows everything doesn't lift the others.
|
||||
shx::add_drawing_dir_guarded(&dir.join("last-drawings"), "session", Arc::new(|_: &Path| true));
|
||||
shx::set_font_dirs(vec![dir.clone()]);
|
||||
assert!(shx::find("cadcraft-overflow-bad.shx").is_none(), "refused by a guard given past the limit");
|
||||
assert!(shx::find("cadcraft-overflow-ok.shx").is_some());
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::{Drawing, EntityKind, EntityStore, Handle, Image};
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
use craft_dxf::{Section, Tag};
|
||||
use craft_dxf::{SectionRef, Tag};
|
||||
|
||||
/// Most clip boundary vertices kept per image (hostile files).
|
||||
const MAX_CLIP: usize = 100_000;
|
||||
@@ -79,14 +79,14 @@ fn has_images(store: &EntityStore) -> bool {
|
||||
}
|
||||
|
||||
/// Fill in each image's definition (path, name, pixel size) from the IMAGEDEF it points to.
|
||||
pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) {
|
||||
pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
if !has_images(&d.model) && !d.layouts.iter().any(|l| has_images(&l.entities)) && !d.blocks.values().any(|b| has_images(&b.entities)) {
|
||||
return;
|
||||
}
|
||||
// IMAGE handle → IMAGEDEF handle.
|
||||
let mut refs: HashMap<Handle, String> = HashMap::new();
|
||||
for s in secs.iter().filter(|s| s.name == "ENTITIES" || s.name == "BLOCKS") {
|
||||
each_record(&s.tags, |kind, tags| {
|
||||
each_record(s.tags, |kind, tags| {
|
||||
if kind != "IMAGE" {
|
||||
return;
|
||||
}
|
||||
@@ -101,7 +101,7 @@ pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) {
|
||||
let mut defs: HashMap<String, Def> = HashMap::new();
|
||||
let mut names: HashMap<String, String> = HashMap::new();
|
||||
for s in secs.iter().filter(|s| s.name == "OBJECTS") {
|
||||
each_record(&s.tags, |kind, tags| match kind {
|
||||
each_record(s.tags, |kind, tags| match kind {
|
||||
"IMAGEDEF" => {
|
||||
let Some(h) = tags.iter().find(|t| t.code == 5).map(|t| key(&t.str())) else { return };
|
||||
let start = tags.iter().position(|t| t.code == 100 && t.str() == "AcDbRasterImageDef").unwrap_or(0);
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
//! Saved layer states as AutoCAD keeps them: the LAYER table's extension dictionary holds an
|
||||
//! `ACAD_LAYERSTATES` dictionary of one XRECORD per state. Measured in AutoCAD 2024 (DXFOUT of
|
||||
//! states saved with -LAYER stAte), an XRECORD holds `280 1`, the mask (91), a text (301: empty
|
||||
//! as -LAYER saves it; AutoCAD keeps one a file holds through restore and DXFOUT), `290 0` and
|
||||
//! the current layer's name (302), then for each layer its LAYER handle (330),
|
||||
//! flags (90: 1 off, 2 frozen, 4 locked, 8 plotted, 16 frozen in new viewports), colour index
|
||||
//! (62), lineweight (370), for a layer of an xref 93 (0 for a newly attached one; a file can hold
|
||||
//! 1, whose meaning isn't measured), LTYPE handle (331), plot style (in a drawing of colour-dependent
|
||||
//! plot styles the name `Color_N` in group 1, N its colour index; of named ones the handle of its
|
||||
//! placeholder object in group 390), transparency (440: 0 opaque, else `0x02000000 | alpha`) and,
|
||||
//! for a true colour, 92 (`0xC2RRGGBB`).
|
||||
//!
|
||||
//! States AutoCAD's dictionary can't hold stay in CADCraft's own record (`CADCRAFT_LAYERSTATES`):
|
||||
//! the view layer snapshots (`*VIEW name`), and a name that repeats an earlier one in another
|
||||
//! case: AutoCAD 2024 opens the entries `S` and `s` of one dictionary as one state, named as the
|
||||
//! first entry and holding the last one's record (measured), and so does the reader here.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use cadcraft_color::{Color, Rgb};
|
||||
use cadcraft_doc::{Layer, LayerState, Lineweight};
|
||||
use craft_dxf::Tag;
|
||||
|
||||
use crate::dxf_ext::{transparency_from_dxf, transparency_to_dxf};
|
||||
|
||||
/// The key of the states dictionary in the LAYER table's extension dictionary.
|
||||
pub(crate) const KEY: &str = "ACAD_LAYERSTATES";
|
||||
|
||||
/// The prefix of a true colour in group 92.
|
||||
const TRUE_COLOR: u32 = 0xC200_0000;
|
||||
|
||||
/// The bytes of layers the states of one file may copy (CWE-400). Each entry of a state is a copy
|
||||
/// of the drawing's layer, its names and description included, so without a bound a small file
|
||||
/// naming one layer with a long description in a great many entries would take gigabytes.
|
||||
pub(crate) const MAX_COPIED_BYTES: usize = 256 << 20;
|
||||
|
||||
/// Which of `states` go into AutoCAD's dictionary (the others into CADCraft's record).
|
||||
pub(crate) fn in_acad(states: &[LayerState]) -> Vec<bool> {
|
||||
let mut seen: HashSet<String> = HashSet::with_capacity(states.len());
|
||||
states.iter().map(|st| !st.name.trim().is_empty() && !st.name.starts_with('*') && seen.insert(st.name.to_lowercase())).collect()
|
||||
}
|
||||
|
||||
/// The states CADCraft's own record keeps (those [`in_acad`] leaves out).
|
||||
pub(crate) fn own(states: &[LayerState]) -> Vec<LayerState> {
|
||||
states.iter().zip(in_acad(states)).filter(|(_, acad)| !acad).map(|(st, _)| st.clone()).collect()
|
||||
}
|
||||
|
||||
/// Handles of the objects that hold the drawing's states in AutoCAD's form.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Plan {
|
||||
/// The LAYER table, which owns the extension dictionary.
|
||||
pub table: String,
|
||||
/// The LAYER table's extension dictionary.
|
||||
pub xdict: String,
|
||||
/// The `ACAD_LAYERSTATES` dictionary.
|
||||
dict: String,
|
||||
/// (index in the drawing's states, XRECORD handle).
|
||||
records: Vec<(usize, String)>,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
pub fn new(states: &[LayerState], mut handle: impl FnMut() -> String) -> Self {
|
||||
let acad = in_acad(states);
|
||||
if !acad.contains(&true) {
|
||||
return Plan::default();
|
||||
}
|
||||
let xdict = handle();
|
||||
let dict = handle();
|
||||
let records = acad.iter().enumerate().filter(|(_, a)| **a).map(|(i, _)| (i, handle())).collect();
|
||||
Plan { table: String::new(), xdict, dict, records }
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.records.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the state objects need from the rest of the file.
|
||||
pub(crate) struct Refs<'a> {
|
||||
/// Upper-case layer name → LAYER record handle.
|
||||
pub layers: &'a HashMap<String, String>,
|
||||
/// Upper-case linetype name → LTYPE record handle.
|
||||
pub ltypes: &'a HashMap<String, String>,
|
||||
/// Upper-case plot style name → its placeholder object's handle.
|
||||
pub pstyles: &'a HashMap<String, String>,
|
||||
/// Plot styles by colour (`$PSTYLEMODE` 1): the plot style name is `Color_N`.
|
||||
pub colour_dependent: bool,
|
||||
}
|
||||
|
||||
/// The objects of plan `p`: the extension dictionary, the `ACAD_LAYERSTATES` dictionary and one
|
||||
/// XRECORD per state. Layers the drawing no longer has are left out of a state (AutoCAD names
|
||||
/// layers by handle).
|
||||
pub(crate) fn objects(p: &Plan, states: &[LayerState], refs: &Refs) -> Vec<Tag> {
|
||||
let mut t = Vec::new();
|
||||
if p.is_empty() {
|
||||
return t;
|
||||
}
|
||||
t.extend([Tag::s(0, "DICTIONARY"), Tag::s(5, &p.xdict), Tag::s(330, &p.table), Tag::s(100, "AcDbDictionary"), Tag::i(280, 1), Tag::i(281, 1)]);
|
||||
t.extend([Tag::s(3, KEY), Tag::s(360, &p.dict)]);
|
||||
t.extend([Tag::s(0, "DICTIONARY"), Tag::s(5, &p.dict), Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, &p.xdict), Tag::s(102, "}")]);
|
||||
t.extend([Tag::s(330, &p.xdict), Tag::s(100, "AcDbDictionary"), Tag::i(281, 1)]);
|
||||
let planned = || p.records.iter().filter_map(|(i, h)| Some((states.get(*i)?, h)));
|
||||
for (st, h) in planned() {
|
||||
t.extend([Tag::s(3, &st.name), Tag::s(350, h)]);
|
||||
}
|
||||
for (st, h) in planned() {
|
||||
t.extend([Tag::s(0, "XRECORD"), Tag::s(5, h), Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, &p.dict), Tag::s(102, "}"), Tag::s(330, &p.dict)]);
|
||||
t.extend([Tag::s(100, "AcDbXrecord"), Tag::i(280, 1), Tag::i(91, i64::from(st.mask)), Tag::s(301, &st.description), Tag::i(290, 0)]);
|
||||
t.push(Tag::s(302, &st.current));
|
||||
for l in &st.layers {
|
||||
if let Some(lh) = refs.layers.get(&l.name.to_ascii_uppercase()) {
|
||||
layer(&mut t, l, lh, refs);
|
||||
}
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// One layer of a state's XRECORD.
|
||||
fn layer(t: &mut Vec<Tag>, l: &Layer, handle: &str, refs: &Refs) {
|
||||
let flags = i64::from(!l.on) | i64::from(l.frozen) << 1 | i64::from(l.locked) << 2 | i64::from(l.plot) << 3 | i64::from(l.vp_freeze_new) << 4;
|
||||
let aci = match l.color {
|
||||
Color::True(rgb) => i64::from(cadcraft_color::nearest_aci(rgb)),
|
||||
c => i64::from(c.to_aci()).clamp(1, 255),
|
||||
};
|
||||
t.extend([Tag::s(330, handle), Tag::i(90, flags), Tag::i(62, aci), Tag::i(370, i64::from(l.lineweight.to_dxf()))]);
|
||||
if crate::dxf_xref::dependent(&l.name) {
|
||||
t.push(Tag::i(93, 0));
|
||||
}
|
||||
// A linetype the drawing no longer has: Continuous, which every drawing has.
|
||||
if let Some(lt) = refs.ltypes.get(&l.linetype.to_ascii_uppercase()).or_else(|| refs.ltypes.get("CONTINUOUS")) {
|
||||
t.push(Tag::s(331, lt));
|
||||
}
|
||||
if refs.colour_dependent {
|
||||
t.push(Tag::s(1, format!("Color_{aci}")));
|
||||
} else if let Some(ps) = refs.pstyles.get(&l.plot_style.trim().to_ascii_uppercase()).or_else(|| refs.pstyles.get("NORMAL")) {
|
||||
t.push(Tag::s(390, ps));
|
||||
}
|
||||
t.push(Tag::i(440, if l.transparency == 0 { 0 } else { transparency_to_dxf(l.transparency) }));
|
||||
if let Color::True(rgb) = l.color {
|
||||
t.push(Tag::i(92, i64::from(i32::from_be_bytes((TRUE_COLOR | rgb.to_u32()).to_be_bytes()))));
|
||||
}
|
||||
}
|
||||
|
||||
/// What a state's handles name in the drawing being read.
|
||||
pub(crate) struct Lookup<'a> {
|
||||
/// The drawing's layer a LAYER handle names: a state's layer starts as a copy of it (what the
|
||||
/// state doesn't hold, such as the description, is the drawing's).
|
||||
pub layer: &'a dyn Fn(&str) -> Option<Layer>,
|
||||
/// The linetype an LTYPE handle names.
|
||||
pub ltype: &'a dyn Fn(&str) -> Option<String>,
|
||||
/// The plot style a placeholder handle names.
|
||||
pub pstyle: &'a dyn Fn(&str) -> Option<String>,
|
||||
/// Plot styles by colour: group 1 (`Color_N`) says nothing the layer's colour doesn't.
|
||||
pub colour_dependent: bool,
|
||||
}
|
||||
|
||||
/// The state `name` from its XRECORD's groups. A layer whose record is gone (AutoCAD keeps a
|
||||
/// purged layer's entry, measured) is skipped. A layer named in two entries is in the state once,
|
||||
/// the later entry's groups over the earlier one's, as restoring both in turn did: AutoCAD 2024
|
||||
/// restores the later one (measured with entries that each set every property). Each copy of a
|
||||
/// layer is charged to `budget`, the file's [`MAX_COPIED_BYTES`]; once it is spent, the entries
|
||||
/// left are left out.
|
||||
pub(crate) fn read(name: &str, tags: &[Tag], lookup: &Lookup, budget: &mut usize) -> LayerState {
|
||||
let mut st = LayerState { name: name.to_string(), ..LayerState::default() };
|
||||
// The data follows the subclass marker (an XRECORD without one holds none).
|
||||
let start = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbXrecord").map_or(tags.len(), |i| i + 1);
|
||||
let body = tags.get(start..).unwrap_or_default();
|
||||
let first = body.iter().position(|t| t.code == 330).unwrap_or(body.len());
|
||||
for t in body.get(..first).unwrap_or_default() {
|
||||
match t.code {
|
||||
91 => st.mask = t.str().trim().parse::<u32>().unwrap_or(LayerState::ALL),
|
||||
301 => st.description = t.str(),
|
||||
302 => st.current = t.str(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let rest = body.get(first..).unwrap_or_default();
|
||||
// The index in the state of each layer by its LAYER handle.
|
||||
let mut index: HashMap<String, usize> = HashMap::new();
|
||||
let mut at = 0;
|
||||
while let Some(group) = rest.get(at..) {
|
||||
let Some(head) = group.first() else { break };
|
||||
let len = group.iter().skip(1).position(|t| t.code == 330).map_or(group.len(), |n| n + 1);
|
||||
at += len;
|
||||
let groups = group.get(1..len).unwrap_or_default();
|
||||
let key = head.str().trim().to_ascii_uppercase();
|
||||
if let Some(slot) = index.get(&key).and_then(|&i| st.layers.get_mut(i)) {
|
||||
entry(slot, groups, lookup);
|
||||
} else if let Some(mut l) = (lookup.layer)(&head.str()) {
|
||||
let Some(left) = budget.checked_sub(cost(&l)) else { break };
|
||||
*budget = left;
|
||||
entry(&mut l, groups, lookup);
|
||||
index.insert(key, st.layers.len());
|
||||
st.layers.push(l);
|
||||
}
|
||||
}
|
||||
st
|
||||
}
|
||||
|
||||
/// The bytes a copy of layer `l` takes.
|
||||
fn cost(l: &Layer) -> usize {
|
||||
std::mem::size_of::<Layer>() + l.name.len() + l.linetype.len() + l.description.len() + l.plot_style.len()
|
||||
}
|
||||
|
||||
/// A layer's properties from the groups after its handle.
|
||||
fn entry(l: &mut Layer, groups: &[Tag], lookup: &Lookup) {
|
||||
let int = |t: &Tag| t.str().trim().parse::<i64>().ok();
|
||||
let mut true_color = None;
|
||||
for t in groups {
|
||||
match t.code {
|
||||
90 => {
|
||||
if let Some(f) = int(t) {
|
||||
(l.on, l.frozen, l.locked, l.plot, l.vp_freeze_new) = (f & 1 == 0, f & 2 != 0, f & 4 != 0, f & 8 != 0, f & 16 != 0);
|
||||
}
|
||||
}
|
||||
62 => {
|
||||
if let Some(c) = int(t).map(i64::abs).and_then(|c| u8::try_from(c).ok()).filter(|c| *c >= 1) {
|
||||
l.color = Color::Index(c);
|
||||
}
|
||||
}
|
||||
92 => true_color = int(t).and_then(|v| u32::try_from(v & 0xFFFF_FFFF).ok()).filter(|v| v & 0xFF00_0000 == TRUE_COLOR),
|
||||
370 => {
|
||||
if let Some(w) = int(t).and_then(|w| i16::try_from(w).ok()) {
|
||||
l.lineweight = Lineweight::from_dxf(w);
|
||||
}
|
||||
}
|
||||
331 => {
|
||||
if let Some(lt) = (lookup.ltype)(&t.str()) {
|
||||
l.linetype = lt;
|
||||
}
|
||||
}
|
||||
390 => {
|
||||
if let Some(ps) = (lookup.pstyle)(&t.str()) {
|
||||
l.plot_style = ps;
|
||||
}
|
||||
}
|
||||
1 if !lookup.colour_dependent => l.plot_style = t.str(),
|
||||
440 => {
|
||||
if let Some(v) = int(t) {
|
||||
l.transparency = transparency_from_dxf(v).unwrap_or(0);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(v) = true_color {
|
||||
l.color = Color::True(Rgb::from_u32(v & 0x00FF_FFFF));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A state's XRECORD groups with an entry per (layer handle, colour index).
|
||||
fn tags(entries: &[(&str, i64)]) -> Vec<Tag> {
|
||||
let mut t = vec![Tag::s(100, "AcDbXrecord"), Tag::i(280, 1), Tag::i(91, 2047), Tag::s(302, "0")];
|
||||
for (h, aci) in entries {
|
||||
t.extend([Tag::s(330, *h), Tag::i(90, 8)]);
|
||||
// 0: no colour group.
|
||||
if *aci != 0 {
|
||||
t.push(Tag::i(62, *aci));
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_named_twice_takes_its_last_entry_and_copies_stop_at_the_budget() {
|
||||
let layer = |h: &str| match h {
|
||||
"A1" => Some(Layer::new("A")),
|
||||
"B1" => Some(Layer::new("B")),
|
||||
_ => None,
|
||||
};
|
||||
let none = |_: &str| None::<String>;
|
||||
let lookup = Lookup { layer: &layer, ltype: &none, pstyle: &none, colour_dependent: true };
|
||||
let colours = |st: &LayerState| st.layers.iter().map(|l| (l.name.clone(), l.color)).collect::<Vec<_>>();
|
||||
// AutoCAD 2024 restores the last of two entries of one layer (measured: green, then blue,
|
||||
// restores blue); it stays in the first one's place. A later entry without a colour keeps
|
||||
// the earlier one's, as restoring both in turn did.
|
||||
let mut budget = MAX_COPIED_BYTES;
|
||||
let st = read("S", &tags(&[("A1", 3), ("B1", 2), ("A1", 5), ("B1", 0)]), &lookup, &mut budget);
|
||||
assert_eq!(colours(&st), [("A".to_string(), Color::Index(5)), ("B".to_string(), Color::Index(2))]);
|
||||
// Each new copy is charged (a repeated entry copies nothing); past the budget the rest of
|
||||
// the entries, and of the file's states, are left out.
|
||||
let one = cost(&Layer::new("A"));
|
||||
let mut budget = one;
|
||||
let st = read("S", &tags(&[("A1", 3), ("A1", 4), ("B1", 5)]), &lookup, &mut budget);
|
||||
assert_eq!((colours(&st), budget), (vec![("A".to_string(), Color::Index(4))], 0));
|
||||
let st = read("T", &tags(&[("B1", 2)]), &lookup, &mut budget);
|
||||
assert!(st.layers.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ use cadcraft_doc::{
|
||||
MLineJust, MLineStyle, MLineVertex, STANDARD_MLINE_STYLE,
|
||||
};
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
use craft_dxf::{Section, Tag};
|
||||
use craft_dxf::{SectionRef, Tag};
|
||||
|
||||
/// Most groups 41 kept per element and vertex (start, then break pairs).
|
||||
const MAX_PARAMS: usize = 2 * MAX_MLINE_CUTS + 2;
|
||||
@@ -333,10 +333,10 @@ fn has_mlines(store: &EntityStore) -> bool {
|
||||
}
|
||||
|
||||
/// Read the multiline styles, then give every multiline its style's elements, caps and fill.
|
||||
pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) {
|
||||
pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
let mut styles: Vec<MLineStyle> = Vec::new();
|
||||
for s in secs.iter().filter(|s| s.name == "OBJECTS") {
|
||||
each_record(&s.tags, |kind, tags| {
|
||||
each_record(s.tags, |kind, tags| {
|
||||
if kind == "MLINESTYLE"
|
||||
&& styles.len() < MAX_STYLES
|
||||
&& let Some(st) = read_style(tags)
|
||||
|
||||
+25
-81
@@ -18,7 +18,7 @@ use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
|
||||
use craft_dxf::{Section, Tag};
|
||||
use craft_dxf::{SectionRef, Tag};
|
||||
|
||||
/// Named object dictionary entries CADCraft writes itself from its model (plus every key that
|
||||
/// starts with `CADCRAFT`): they are read into the model, not kept raw. A change that starts
|
||||
@@ -36,11 +36,10 @@ const MODELLED_KEYS: &[&str] = &[
|
||||
"ACAD_IMAGE_VARS",
|
||||
];
|
||||
|
||||
/// Extension dictionary entries not kept raw: dimension associativity and the LAYER table's layer
|
||||
/// states (CADCraft reads and rewrites them), draw order and annotation scale contexts (written
|
||||
/// from their own models by the changes that model them; stale copies would contradict the
|
||||
/// drawing).
|
||||
const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_LAYERSTATES", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"];
|
||||
/// Extension dictionary entries not kept raw: dimension associativity (CADCraft reads and
|
||||
/// rewrites it), draw order and annotation scale contexts (written from their own models by the
|
||||
/// changes that model them; stale copies would contradict the drawing).
|
||||
const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"];
|
||||
|
||||
/// Applications whose xdata CADCraft reads and writes itself. `ACAD` holds dimension overrides
|
||||
/// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept.
|
||||
@@ -323,8 +322,8 @@ fn put_xdata(d: &mut Drawing, mut xdata: HashMap<Handle, Vec<RawTag>>) {
|
||||
}
|
||||
|
||||
/// Keep what `secs` holds that the reader did not model in `d.foreign`.
|
||||
pub(crate) fn read(secs: &[Section], d: &mut Drawing) {
|
||||
let get = |name: &str| secs.iter().find(|s| s.name == name).map(|s| split(&s.tags)).unwrap_or_default();
|
||||
pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
let get = |name: &str| secs.iter().find(|s| s.name == name).map(|s| split(s.tags)).unwrap_or_default();
|
||||
let (classes, tables, blocks, entities, objects) = (get("CLASSES"), get("TABLES"), get("BLOCKS"), get("ENTITIES"), get("OBJECTS"));
|
||||
// The drawing's entities by handle: whether each is of a type CADCraft doesn't model.
|
||||
let ents = entity_types(d);
|
||||
@@ -466,7 +465,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) {
|
||||
|
||||
/// The `$ACADVER` the file's own HEADER section declares, if it does. Not the drawing's: a new
|
||||
/// drawing starts as AC1032, and a file without the variable would leave that default there.
|
||||
fn file_version(secs: &[Section]) -> Option<String> {
|
||||
fn file_version(secs: &[SectionRef<'_>]) -> Option<String> {
|
||||
let header = secs.iter().find(|s| s.name.eq_ignore_ascii_case("HEADER"))?;
|
||||
let at = header.tags.iter().position(|t| t.code == 9 && t.str().trim().eq_ignore_ascii_case("$ACADVER"))?;
|
||||
let value = header.tags.get(at + 1).filter(|t| t.code != 9)?.str();
|
||||
@@ -990,7 +989,20 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
let root = objects.first().filter(|(k, _, _)| is_dictionary(k)).map(|(_, s, _)| *s);
|
||||
let root_keys: HashSet<String> =
|
||||
objects.iter().find(|(_, s, _)| Some(*s) == root).map(|(_, _, t)| entries(t).into_iter().map(|(k, _)| up(&k)).collect()).unwrap_or_default();
|
||||
let (mut attached, merged) = kept_dictionaries(f, &xd, &recs, tags);
|
||||
// Extension dictionaries that go on a written record (one without its own).
|
||||
let mut block = String::new();
|
||||
let mut attached: HashSet<String> = HashSet::new();
|
||||
for r in &recs {
|
||||
if r.kind == "BLOCK" {
|
||||
block = up(&val(body(r), 2).unwrap_or_default());
|
||||
}
|
||||
if let Some(x) = extra_for(f, &xd, r, body(r), &block)
|
||||
&& let Some(xd) = x.xdict
|
||||
&& head(body(r)).xdict.is_none()
|
||||
{
|
||||
attached.insert(xd.hex());
|
||||
}
|
||||
}
|
||||
for (_, t) in planned.values().flatten() {
|
||||
let x = head(t.get(1..).unwrap_or(&[])).handle.and_then(|h| handle(&h)).and_then(|h| entity_extra(f, &xd, h));
|
||||
attached.extend(x.and_then(|x| x.xdict).map(Handle::hex));
|
||||
@@ -1038,7 +1050,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
if nod.contains(&owner) {
|
||||
break dict_entries.get(&cur).is_some_and(|k| !root_keys.contains(&up(k))) && root.is_some();
|
||||
}
|
||||
if attached.contains(&cur) || merged.contains_key(&cur) {
|
||||
if attached.contains(&cur) {
|
||||
break true;
|
||||
}
|
||||
break unknown.contains(&owner) && written.contains(&owner);
|
||||
@@ -1056,13 +1068,6 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
alive.insert(o.handle.hex(), format!("{next:X}"));
|
||||
next = next.saturating_add(1);
|
||||
}
|
||||
// A merged dictionary is not written: what pointed at it points at the written one.
|
||||
for (kept, own) in &merged {
|
||||
if let Some(h) = alive.get_mut(kept) {
|
||||
h.clone_from(own);
|
||||
}
|
||||
}
|
||||
let merged_into: HashMap<String, &ForeignObject> = merged.iter().filter_map(|(kept, own)| Some((own.clone(), *objs.get(kept)?))).collect();
|
||||
let entities: HashSet<String> = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect();
|
||||
let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities };
|
||||
let mut out: Vec<Tag> = Vec::with_capacity(tags.len() + f.objects.iter().map(|o| o.tags.len() + 1).sum::<usize>());
|
||||
@@ -1076,7 +1081,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
continue;
|
||||
}
|
||||
if r.kind == "ENDSEC" && r.sec == "OBJECTS" {
|
||||
for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex()) && !merged.contains_key(&o.handle.hex())) {
|
||||
for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex())) {
|
||||
let number = is_proxy(&o.kind).then(|| renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str()))))).flatten();
|
||||
match number {
|
||||
Some(n) => {
|
||||
@@ -1100,15 +1105,11 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
}
|
||||
out.extend(tags.get(r.start).cloned());
|
||||
let x = extra_for(f, &xd, r, b, &block);
|
||||
let joined = joined_into(&merged_into, b);
|
||||
if x.is_none() && Some(r.start) != root && joined.is_none() {
|
||||
if x.is_none() && Some(r.start) != root {
|
||||
out.extend(b.iter().cloned());
|
||||
continue;
|
||||
}
|
||||
record(&map, r, b, x.as_deref(), None, Some(r.start) == root, &mut out);
|
||||
if let Some(kept) = joined {
|
||||
join_entries(&map, b, kept, &mut out);
|
||||
}
|
||||
}
|
||||
add_appids(&mut out);
|
||||
let top = max_handle(&out).saturating_add(1);
|
||||
@@ -1120,32 +1121,6 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
*tags = out;
|
||||
}
|
||||
|
||||
/// Kept extension dictionaries of written records: those that go on a record without its own,
|
||||
/// and those whose entries join the one the writer gave a table (the LAYER table's, holding the
|
||||
/// layer states) as kept dictionary → the written one.
|
||||
fn kept_dictionaries(f: &Foreign, xd: &XdataOf, recs: &[Rec], tags: &[Tag]) -> (HashSet<String>, HashMap<String, String>) {
|
||||
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
|
||||
let mut block = String::new();
|
||||
let mut attached: HashSet<String> = HashSet::new();
|
||||
let mut merged: HashMap<String, String> = HashMap::new();
|
||||
for r in recs {
|
||||
if r.kind == "BLOCK" {
|
||||
block = up(&val(body(r), 2).unwrap_or_default());
|
||||
}
|
||||
let Some(kept) = extra_for(f, xd, r, body(r), &block).and_then(|x| x.xdict) else { continue };
|
||||
match head(body(r)).xdict {
|
||||
None => {
|
||||
attached.insert(kept.hex());
|
||||
}
|
||||
Some(own) if r.sec == "TABLES" => {
|
||||
merged.insert(kept.hex(), own);
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
(attached, merged)
|
||||
}
|
||||
|
||||
/// Complete source tables keep positional identities even when names repeat.
|
||||
fn proxy_class_number(f: &Foreign, numbers: &HashMap<String, i64>, old: Option<i64>) -> Option<i64> {
|
||||
if f.complete_class_table {
|
||||
@@ -1377,37 +1352,6 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti
|
||||
}
|
||||
}
|
||||
|
||||
/// The kept dictionary whose entries join written dictionary `b`, if any.
|
||||
fn joined_into<'a>(merged_into: &HashMap<String, &'a ForeignObject>, b: &[Tag]) -> Option<&'a ForeignObject> {
|
||||
if merged_into.is_empty() {
|
||||
return None;
|
||||
}
|
||||
head(b).handle.and_then(|h| merged_into.get(&h).copied())
|
||||
}
|
||||
|
||||
/// The entries of kept dictionary `kept` that written dictionary `b` doesn't have (by key, without
|
||||
/// regard to case), appended to it with their handles remapped; entries whose object is gone are
|
||||
/// left out.
|
||||
fn join_entries(map: &Map, b: &[Tag], kept: &ForeignObject, out: &mut Vec<Tag>) {
|
||||
let has = |key: &str| b.iter().any(|t| t.code == 3 && up(&t.str()) == up(key));
|
||||
let mut key: Option<&str> = None;
|
||||
for t in kept.tags.iter().take_while(|t| t.code < 1000) {
|
||||
match t.code {
|
||||
3 => key = Some(t.value.as_str()),
|
||||
350 | 360 => {
|
||||
if let Some(k) = key.take()
|
||||
&& !has(k)
|
||||
&& let Some(h) = map.get(&t.value).filter(|h| h != "0")
|
||||
{
|
||||
out.push(Tag::s(3, k));
|
||||
out.push(Tag::s(t.code, h));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kept xdata of applications the record doesn't already carry, handles remapped.
|
||||
fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>) {
|
||||
let mut skip = false;
|
||||
|
||||
@@ -10,7 +10,7 @@ use cadcraft_doc::{
|
||||
RayLine, Solid, Table, TableCell, Text, TextStyle, Tolerance, Transparency, Ucs, Unknown, VAlign, Viewport, VportConfig, VportTile, Wipeout,
|
||||
};
|
||||
use cadcraft_geom::{PolyVertex, Spline, Vec2, Vec3};
|
||||
use craft_dxf::{Tag, records, sections};
|
||||
use craft_dxf::{Tag, record_slices, section_slices};
|
||||
|
||||
use crate::{IoError, Result};
|
||||
|
||||
@@ -85,7 +85,7 @@ type LayoutDef = (String, u32, String, PageSetup, Option<(Vec2, Vec2)>);
|
||||
/// Import DXF sections while sharing one materialized-table-cell budget across blocks and entity sections.
|
||||
fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result<Drawing> {
|
||||
let tags = craft_dxf::parse(bytes).map_err(|e| IoError::Format(e.to_string()))?;
|
||||
let secs = sections(&tags);
|
||||
let secs = section_slices(&tags);
|
||||
if secs.is_empty() {
|
||||
return Err(IoError::Format("no sections found".into()));
|
||||
}
|
||||
@@ -112,17 +112,17 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result<Drawing> {
|
||||
let mut skipped = std::collections::BTreeMap::new();
|
||||
count_skipped(&mut skipped, "(no section)", outside_sections(&tags));
|
||||
for s in &secs {
|
||||
match s.name.as_str() {
|
||||
"HEADER" => header(&s.tags, &mut d),
|
||||
"TABLES" => tables(&s.tags, &mut d, &mut rx),
|
||||
"BLOCKS" => blocks.extend(read_blocks(&s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped)),
|
||||
match s.name {
|
||||
"HEADER" => header(s.tags, &mut d),
|
||||
"TABLES" => tables(s.tags, &mut d, &mut rx),
|
||||
"BLOCKS" => blocks.extend(read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped)),
|
||||
// A damaged file may split its entities over several ENTITIES sections (#865).
|
||||
"ENTITIES" => {
|
||||
let mut n = 0;
|
||||
entities.extend(parse_entities(&records(&s.tags), &mut d, &mut rx, &mut n, &mut table_cells_left));
|
||||
entities.extend(parse_entities(&record_slices(s.tags), &mut d, &mut rx, &mut n, &mut table_cells_left));
|
||||
count_skipped(&mut skipped, "ENTITIES", n);
|
||||
}
|
||||
"OBJECTS" => read_objects(&s.tags, &mut objs, &mut layout_objs),
|
||||
"OBJECTS" => read_objects(s.tags, &mut objs, &mut layout_objs),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::common::T;
|
||||
use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity};
|
||||
use super::objects::{MAX_OBJECTS, Objects, page_setup};
|
||||
use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, Vec2, records};
|
||||
use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, Vec2, record_slices};
|
||||
|
||||
pub(super) fn parse_entities(
|
||||
recs: &[(String, Vec<Tag>)],
|
||||
recs: &[(String, &[Tag])],
|
||||
d: &mut Drawing,
|
||||
rx: &mut Rx,
|
||||
skipped: &mut usize,
|
||||
@@ -91,7 +91,7 @@ pub(super) fn read_blocks(
|
||||
table_cells_left: &mut usize,
|
||||
skipped: &mut std::collections::BTreeMap<String, usize>,
|
||||
) -> Vec<BlockDef> {
|
||||
let recs = records(tags);
|
||||
let recs = record_slices(tags);
|
||||
for (k, tg) in &recs {
|
||||
let t = T(tg);
|
||||
if k == "BLOCK" && t.i(70).unwrap_or(0) & 4 != 0 {
|
||||
@@ -133,8 +133,8 @@ pub(super) fn read_blocks(
|
||||
|
||||
/// Read the OBJECTS section into `objs`, and each LAYOUT into `layout_objs`.
|
||||
pub(super) fn read_objects(tags: &[Tag], objs: &mut Objects, layout_objs: &mut Vec<LayoutDef>) {
|
||||
for (k, tg) in records(tags) {
|
||||
objs.add(&k, &tg);
|
||||
for (k, tg) in record_slices(tags) {
|
||||
objs.add(&k, tg);
|
||||
if k == "LAYOUT" {
|
||||
// Fields after the AcDbLayout marker (AcDbPlotSettings also has a code 1).
|
||||
let start = tg.iter().position(|x| x.code == 100 && x.str() == "AcDbLayout").unwrap_or(0);
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::text::{attdef, attrib_modes, attrib_props, mtext_from, multiline_attr
|
||||
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, records,
|
||||
Vec3, Viewport, Wipeout, record_slices,
|
||||
};
|
||||
use cadcraft_doc::PolyfaceMesh;
|
||||
|
||||
@@ -420,10 +420,10 @@ pub(super) fn acad_table(tags: &[Tag], table_cells_left: &mut usize) -> Table {
|
||||
|
||||
/// The plot style names of a file: the entries of the `ACAD_PLOTSTYLENAME` dictionary of the
|
||||
/// named object dictionary (the first object), by placeholder handle.
|
||||
pub(super) fn plot_style_names(secs: &[craft_dxf::Section]) -> HashMap<String, String> {
|
||||
pub(super) fn plot_style_names(secs: &[craft_dxf::SectionRef<'_>]) -> HashMap<String, String> {
|
||||
let mut out = HashMap::new();
|
||||
let Some(objects) = secs.iter().find(|s| s.name == "OBJECTS") else { return out };
|
||||
let recs = records(&objects.tags);
|
||||
let recs = record_slices(objects.tags);
|
||||
let entries = |tags: &[Tag]| {
|
||||
let mut v: Vec<(String, String)> = Vec::new();
|
||||
let mut name: Option<String> = None;
|
||||
@@ -543,7 +543,7 @@ pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityK
|
||||
/// can't be placed are counted in `skipped`.
|
||||
/// The entity of a POLYLINE, with its mesh faces (advancing `i` past its VERTEX records). `None`
|
||||
/// for a mesh without faces.
|
||||
pub(super) fn polyline_entity(recs: &[(String, Vec<Tag>)], i: &mut usize, t: &T) -> Option<(Common, EntityKind, Vec<EntityKind>)> {
|
||||
pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -> Option<(Common, EntityKind, Vec<EntityKind>)> {
|
||||
let flags = t.i(70).unwrap_or(0);
|
||||
let mut pts: Vec<(Vec3, f64, f64, f64)> = Vec::new();
|
||||
// Polyface face records (VERTEX 70 bit 128 without 64): vertex indices 71–74.
|
||||
@@ -601,7 +601,7 @@ pub(super) fn polyline_entity(recs: &[(String, Vec<Tag>)], i: &mut usize, t: &T)
|
||||
}
|
||||
|
||||
/// The ATTRIB records after an INSERT, advancing `i` past them and their SEQEND.
|
||||
pub(super) fn insert_attribs(recs: &[(String, Vec<Tag>)], i: &mut usize, ins_layer: &str) -> Vec<Attrib> {
|
||||
pub(super) fn insert_attribs(recs: &[(String, &[Tag])], i: &mut usize, ins_layer: &str) -> Vec<Attrib> {
|
||||
let mut attribs = Vec::new();
|
||||
while let Some((k2, t2)) = recs.get(*i) {
|
||||
if k2 == "ATTRIB" {
|
||||
|
||||
@@ -8,14 +8,10 @@ use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup
|
||||
pub(super) struct Objects {
|
||||
/// Dictionary entry handle (upper case) → entry name.
|
||||
names: HashMap<String, String>,
|
||||
/// (dictionary handle, entry handle), both upper case, in the order the dictionaries list them.
|
||||
entry_order: Vec<(String, String)>,
|
||||
/// SCALE objects (the annotation scale list), in file order.
|
||||
scales: Vec<cadcraft_doc::AnnoScale>,
|
||||
/// XRECORD handle (upper case) → its groups.
|
||||
xrecords: HashMap<String, Vec<Tag>>,
|
||||
/// XRECORD handles in file order.
|
||||
xrecord_order: Vec<String>,
|
||||
/// TABLESTYLE objects: (handle, groups).
|
||||
table_styles: Vec<(String, Vec<Tag>)>,
|
||||
/// DIMASSOC objects.
|
||||
@@ -54,11 +50,7 @@ impl Objects {
|
||||
if let Some(n) = name.take()
|
||||
&& self.names.len() < MAX_OBJECTS
|
||||
{
|
||||
let entry = t.str().trim().to_ascii_uppercase();
|
||||
if self.entry_order.len() < MAX_OBJECTS {
|
||||
self.entry_order.push((h.clone(), entry.clone()));
|
||||
}
|
||||
self.names.insert(entry, n);
|
||||
self.names.insert(t.str().trim().to_ascii_uppercase(), n);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -66,9 +58,7 @@ impl Objects {
|
||||
}
|
||||
}
|
||||
"XRECORD" if self.xrecords.len() < MAX_OBJECTS => {
|
||||
if self.xrecords.insert(h.clone(), tags.to_vec()).is_none() {
|
||||
self.xrecord_order.push(h);
|
||||
}
|
||||
self.xrecords.insert(h, tags.to_vec());
|
||||
}
|
||||
"TABLESTYLE" if self.table_styles.len() < MAX_OBJECTS => self.table_styles.push((h, tags.to_vec())),
|
||||
"DIMASSOC" if self.dimassocs.len() < MAX_OBJECTS => self.dimassocs.push(tags.to_vec()),
|
||||
@@ -90,65 +80,6 @@ impl Objects {
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer states of the LAYER table's `ACAD_LAYERSTATES` dictionary (its XRECORDs, in file
|
||||
/// order), read with the drawing's layers and linetypes. Entries whose names differ only in case
|
||||
/// are one state, as AutoCAD 2024 opens them (measured with `S` and `s` in both orders): named as
|
||||
/// the first of them in the dictionary, holding the last one's record, where the first of their
|
||||
/// records comes in the file.
|
||||
fn acad_layer_states(&self, d: &Drawing, rx: &Rx) -> Vec<cadcraft_doc::LayerState> {
|
||||
let dicts: std::collections::HashSet<&str> =
|
||||
self.names.iter().filter(|(_, n)| n.eq_ignore_ascii_case(crate::dxf_layer_states::KEY)).map(|(h, _)| h.as_str()).collect();
|
||||
if dicts.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut by_name: HashMap<String, &cadcraft_doc::Layer> = HashMap::with_capacity(d.layers.len());
|
||||
for l in &d.layers {
|
||||
by_name.entry(l.name.to_ascii_lowercase()).or_insert(l);
|
||||
}
|
||||
let layer_of =
|
||||
|h: &str| rx.layers.get(&h.trim().to_ascii_uppercase()).and_then(|n| by_name.get(&n.to_ascii_lowercase())).map(|l| (*l).clone());
|
||||
let ltype_of = |h: &str| rx.ltypes.get(&h.trim().to_ascii_uppercase()).cloned();
|
||||
let pstyle_of = |h: &str| rx.pstyles.get(&h.trim().to_ascii_uppercase()).cloned();
|
||||
let lookup = crate::dxf_layer_states::Lookup {
|
||||
layer: &layer_of,
|
||||
ltype: <ype_of,
|
||||
pstyle: &pstyle_of,
|
||||
colour_dependent: d.header.i64("PSTYLEMODE", 1) != 0,
|
||||
};
|
||||
let ours = |tags: &[Tag]| owner(tags).is_some_and(|o| dicts.contains(o.as_str()));
|
||||
// By lower-case name: the first entry's name and the last entry's record, in dictionary order.
|
||||
let mut first: HashMap<String, &String> = HashMap::new();
|
||||
let mut last: HashMap<String, &Vec<Tag>> = HashMap::new();
|
||||
for (dict, h) in &self.entry_order {
|
||||
if dicts.contains(dict.as_str())
|
||||
&& let (Some(name), Some(tags)) = (self.names.get(h), self.xrecords.get(h))
|
||||
&& ours(tags)
|
||||
{
|
||||
first.entry(name.to_ascii_lowercase()).or_insert(name);
|
||||
last.insert(name.to_ascii_lowercase(), tags);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut taken = std::collections::HashSet::new();
|
||||
let mut budget = crate::dxf_layer_states::MAX_COPIED_BYTES;
|
||||
for h in &self.xrecord_order {
|
||||
let (Some(tags), Some(name)) = (self.xrecords.get(h), self.names.get(h)) else { continue };
|
||||
if out.len() >= crate::dxf_ext::MAX_LAYER_STATES {
|
||||
break;
|
||||
}
|
||||
if !ours(tags) {
|
||||
continue;
|
||||
}
|
||||
let key = name.to_ascii_lowercase();
|
||||
if taken.insert(key.clone()) {
|
||||
let name = first.get(&key).copied().unwrap_or(name);
|
||||
let tags = last.get(&key).copied().unwrap_or(tags);
|
||||
out.push(crate::dxf_layer_states::read(name, tags, &lookup, &mut budget));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The text of the CADCraft XRECORD stored under `key` in a dictionary (its 1/3 strings).
|
||||
pub(super) fn xrecord_text(&self, key: &str) -> Option<String> {
|
||||
let h = self.names.iter().find(|(_, n)| n.as_str() == key).map(|(h, _)| h)?;
|
||||
@@ -277,18 +208,10 @@ impl Objects {
|
||||
if let Some(p) = self.xrecord_text(crate::dxf_ext::ANNOTATION_KEY).and_then(|t| crate::dxf_ext::parse_anno(&t)) {
|
||||
crate::dxf_ext::apply_anno(d, p);
|
||||
}
|
||||
// Saved layer states: AutoCAD's, then those of CADCraft's own record (a file of an
|
||||
// earlier version keeps them all there) that AutoCAD's doesn't hold.
|
||||
let mut states = self.acad_layer_states(d, rx);
|
||||
if let Some(own) = self.xrecord_text(crate::dxf_ext::LAYER_STATES_KEY).and_then(|t| crate::dxf_ext::parse_layer_states(&t)) {
|
||||
let mut names: std::collections::HashSet<String> = states.iter().map(|s| s.name.clone()).collect();
|
||||
for st in own {
|
||||
if states.len() < crate::dxf_ext::MAX_LAYER_STATES && names.insert(st.name.clone()) {
|
||||
states.push(st);
|
||||
}
|
||||
}
|
||||
// Saved layer states.
|
||||
if let Some(states) = self.xrecord_text(crate::dxf_ext::LAYER_STATES_KEY).and_then(|t| crate::dxf_ext::parse_layer_states(&t)) {
|
||||
d.layer_states = states;
|
||||
}
|
||||
d.layer_states = states;
|
||||
// The drawing's plot style tables.
|
||||
if let Some(tables) = self.xrecord_text(crate::dxf_ext::PLOT_STYLES_KEY).and_then(|t| crate::dxf_ext::parse_plot_styles(&t)) {
|
||||
d.plot_style_tables = tables;
|
||||
@@ -308,20 +231,6 @@ impl Objects {
|
||||
}
|
||||
}
|
||||
|
||||
/// An object's owner (its first group 330 outside a `102` group), upper case.
|
||||
fn owner(tags: &[Tag]) -> Option<String> {
|
||||
let mut inside = false;
|
||||
for t in tags {
|
||||
match t.code {
|
||||
102 => inside = t.str().trim().starts_with('{'),
|
||||
330 if !inside => return Some(t.str().trim().to_ascii_uppercase()),
|
||||
100 => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Page setup from a LAYOUT object's AcDbPlotSettings fields (sizes and margins in mm).
|
||||
pub(super) fn page_setup(t: &T) -> PageSetup {
|
||||
let mut p = PageSetup::default();
|
||||
|
||||
@@ -2,7 +2,7 @@ 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, records,
|
||||
VportConfig, VportTile, record_slices,
|
||||
};
|
||||
use cadcraft_fonts::windows::windows_font;
|
||||
|
||||
@@ -92,7 +92,7 @@ fn style_font(tags: &[Tag], file: String) -> String {
|
||||
|
||||
/// Load symbol tables and resolve handle references, indexing layer names for case-insensitive updates.
|
||||
pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
let recs = records(tags);
|
||||
let recs = record_slices(tags);
|
||||
// STYLE handle → name, or the shape file of an unnamed shape style (linetype elements).
|
||||
let ltype_styles: HashMap<String, String> = recs
|
||||
.iter()
|
||||
@@ -114,7 +114,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
let mut linetype_names: std::collections::HashSet<String> = d.linetypes.iter().map(|l| l.name.to_ascii_lowercase()).collect();
|
||||
let mut style_index: HashMap<String, usize> = d.text_styles.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
|
||||
for (kind, tg) in recs {
|
||||
let t = T(&tg);
|
||||
let t = T(tg);
|
||||
match kind.as_str() {
|
||||
"LAYER" => {
|
||||
let name = t.s(2).unwrap_or_default();
|
||||
@@ -141,11 +141,11 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
if let Some(n) = t.s(390).and_then(|h| rx.pstyles.get(&h.trim().to_ascii_uppercase())) {
|
||||
l.plot_style = n.clone();
|
||||
}
|
||||
let alpha = crate::dxf_ext::xdata(&tg, crate::dxf_ext::LAYER_TRANSPARENCY_APP).iter().find(|x| x.code == 1071);
|
||||
let alpha = crate::dxf_ext::xdata(tg, crate::dxf_ext::LAYER_TRANSPARENCY_APP).iter().find(|x| x.code == 1071);
|
||||
if let Some(pct) = alpha.and_then(|x| crate::dxf_ext::transparency_from_dxf(x.i64())) {
|
||||
l.transparency = pct;
|
||||
}
|
||||
if let Some(desc) = crate::dxf_ext::xdata(&tg, crate::dxf_ext::LAYER_DESCRIPTION_APP).iter().filter(|x| x.code == 1000).nth(1) {
|
||||
if let Some(desc) = crate::dxf_ext::xdata(tg, crate::dxf_ext::LAYER_DESCRIPTION_APP).iter().filter(|x| x.code == 1000).nth(1) {
|
||||
l.description = desc.str();
|
||||
}
|
||||
match layer_index.get(&name.to_ascii_lowercase()) {
|
||||
@@ -166,7 +166,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
continue;
|
||||
}
|
||||
linetype_names.insert(name.to_ascii_lowercase());
|
||||
let pattern = ltype_pattern(&tg, <ype_styles);
|
||||
let pattern = ltype_pattern(tg, <ype_styles);
|
||||
d.linetypes.push(Linetype { name, description: t.s(3).unwrap_or_default(), pattern });
|
||||
}
|
||||
"STYLE" => {
|
||||
@@ -178,7 +178,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
let gen_flags = t.i(71).unwrap_or(0);
|
||||
let st = TextStyle {
|
||||
name: name.clone(),
|
||||
font: style_font(&tg, t.s(3).unwrap_or_default()),
|
||||
font: style_font(tg, t.s(3).unwrap_or_default()),
|
||||
big_font: t.s(4).unwrap_or_default(),
|
||||
height: t.fd(40, 0.0),
|
||||
width_factor: t.fd(41, 1.0),
|
||||
@@ -186,7 +186,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
backwards: gen_flags & 2 != 0,
|
||||
upside_down: gen_flags & 4 != 0,
|
||||
vertical: t.i(70).unwrap_or(0) & 4 != 0,
|
||||
annotative: annotative(&tg),
|
||||
annotative: annotative(tg),
|
||||
};
|
||||
match style_index.get(&name.to_ascii_lowercase()).and_then(|&i| d.text_styles.get_mut(i)) {
|
||||
Some(x) => *x = st,
|
||||
@@ -230,7 +230,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
if !(center.x.is_finite() && center.y.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let x = crate::dxf_ext::xdata(&tg, crate::dxf_ext::APP);
|
||||
let x = crate::dxf_ext::xdata(tg, crate::dxf_ext::APP);
|
||||
let field = |key: &str| {
|
||||
x.iter().position(|t| t.code == 1000 && t.str() == key).and_then(|i| x.get(i + 1)).filter(|t| t.code == 1000).map(Tag::str)
|
||||
};
|
||||
@@ -274,8 +274,8 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
fields.insert(field.to_string(), v);
|
||||
}
|
||||
}
|
||||
fields.extend(crate::dxf_ext::read_newer_dimvars(&tg, &rx.styles, &rx.brs, &rx.ltypes));
|
||||
let mut st = DimStyle { name: name.clone(), annotative: annotative(&tg), ..DimStyle::default() };
|
||||
fields.extend(crate::dxf_ext::read_newer_dimvars(tg, &rx.styles, &rx.brs, &rx.ltypes));
|
||||
let mut st = DimStyle { name: name.clone(), annotative: annotative(tg), ..DimStyle::default() };
|
||||
st.apply_fields(&fields);
|
||||
match d.dim_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(&name)) {
|
||||
Some(x) => *x = st,
|
||||
@@ -292,7 +292,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
d.vports.retain(|c| c.tiles.len() > usize::from(c.is_active()) || c.tiles.first().is_some_and(|t| t.twist != 0.0));
|
||||
}
|
||||
|
||||
fn index_table_handles(recs: &[(String, Vec<Tag>)], rx: &mut Rx) {
|
||||
fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
|
||||
for (kind, tags) in recs {
|
||||
let table = T(tags);
|
||||
let (Some(handle), Some(name)) = (table.s(5), table.s(2)) else { continue };
|
||||
|
||||
@@ -58,8 +58,6 @@ 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,
|
||||
/// Saved layer states in AutoCAD's form (the LAYER table's extension dictionary).
|
||||
pub(super) layer_states: crate::dxf_layer_states::Plan,
|
||||
}
|
||||
|
||||
impl Ctx {
|
||||
|
||||
@@ -143,18 +143,10 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) {
|
||||
}
|
||||
|
||||
pub(super) fn table_head(w: &mut W, name: &str, count: usize) -> String {
|
||||
table_head_x(w, name, count, None)
|
||||
}
|
||||
|
||||
/// A table's head, with its extension dictionary `xdict` when it has one.
|
||||
pub(super) fn table_head_x(w: &mut W, name: &str, count: usize, xdict: Option<&str>) -> String {
|
||||
let h = w.h();
|
||||
w.s(0, "TABLE");
|
||||
w.s(2, name);
|
||||
w.s(5, h.clone());
|
||||
if let Some(x) = xdict {
|
||||
w.group("ACAD_XDICTIONARY", 360, &[x]);
|
||||
}
|
||||
w.s(330, "0");
|
||||
w.s(100, "AcDbSymbolTable");
|
||||
w.i(70, count as i64);
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::common::annotative_xdata;
|
||||
use super::ctx::{AssocObj, Ctx};
|
||||
use super::entity::{entity, hatch_reactors};
|
||||
use super::header::{code_page, header_vars};
|
||||
use super::layout::{paper_views, record_head, sheet_first, table_head, table_head_x, vport_table};
|
||||
use super::layout::{paper_views, record_head, sheet_first, table_head, vport_table};
|
||||
use super::objects::{cadcraft_fonts_name, group_obj, mleader_style_obj, scale_list, table_style_obj};
|
||||
use super::{
|
||||
Block, Color, DimStyle, DimVal, Drawing, Entity, EntityKind, EntityStore, Group, HVal, Handle, HashMap, Layout, MLeaderStyle, PageSetup, Space,
|
||||
@@ -68,7 +68,7 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
|
||||
}
|
||||
}
|
||||
w.s(0, "ENDTAB");
|
||||
write_layer_table(w, d, &mut cx.layer_states);
|
||||
write_layer_table(w, d);
|
||||
// STYLE. Linetype shapes from a shape file that isn't a text style get an unnamed shape
|
||||
// style record (70 bit 1) naming the file.
|
||||
let mut shape_files: Vec<String> = Vec::new();
|
||||
@@ -185,12 +185,8 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
|
||||
ltype_handles
|
||||
}
|
||||
|
||||
/// The LAYER table; when the drawing has layer states AutoCAD can hold, the table's extension
|
||||
/// dictionary holds them (written with the objects, [`crate::dxf_layer_states`]).
|
||||
fn write_layer_table(w: &mut W, d: &Drawing, states: &mut crate::dxf_layer_states::Plan) {
|
||||
let xdict = (!states.is_empty()).then(|| states.xdict.clone());
|
||||
let th = table_head_x(w, "LAYER", d.layers.len(), xdict.as_deref());
|
||||
states.table.clone_from(&th);
|
||||
fn write_layer_table(w: &mut W, d: &Drawing) {
|
||||
let th = table_head(w, "LAYER", d.layers.len());
|
||||
for l in &d.layers {
|
||||
let lh = record_head(w, "LAYER", &th, "AcDbLayerTableRecord");
|
||||
w.layers.insert(l.name.to_ascii_uppercase(), lh);
|
||||
@@ -753,16 +749,6 @@ fn write_objects(w: &mut W, plan: ObjectWritePlan<'_>) {
|
||||
write_root_group_objects(w, &plan, &groups, &group_owner, &written, &mleader_dict);
|
||||
write_style_objects(w, &plan, &mleader_dict, &mleader_handles);
|
||||
write_named_objects(w, &plan);
|
||||
let layer_states = {
|
||||
let refs = crate::dxf_layer_states::Refs {
|
||||
layers: &w.layers,
|
||||
ltypes: &plan.cx.ltypes,
|
||||
pstyles: &w.pstyles,
|
||||
colour_dependent: plan.d.header.i64("PSTYLEMODE", 1) != 0,
|
||||
};
|
||||
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_layout_objects(w, &plan);
|
||||
// Raster image definitions.
|
||||
@@ -993,9 +979,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
if let Some(chunks) = dxf_ext::constraint_chunks(&d.constraints, &d.parametric) {
|
||||
xrecords.push((dxf_ext::CONSTRAINTS_KEY, w.h(), chunks));
|
||||
}
|
||||
// Saved layer states: AutoCAD's dictionary holds those it can, CADCraft's record the others.
|
||||
cx.layer_states = crate::dxf_layer_states::Plan::new(&d.layer_states, || w.h());
|
||||
if let Some(chunks) = dxf_ext::layer_state_chunks(&crate::dxf_layer_states::own(&d.layer_states)) {
|
||||
if let Some(chunks) = dxf_ext::layer_state_chunks(&d.layer_states) {
|
||||
xrecords.push((dxf_ext::LAYER_STATES_KEY, w.h(), chunks));
|
||||
}
|
||||
if let Some(chunks) = dxf_ext::plot_style_chunks(&d.plot_style_tables) {
|
||||
@@ -1007,19 +991,14 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
// The annotation scale list: the ACAD_SCALELIST dictionary of SCALE objects.
|
||||
let scale_dict = w.h();
|
||||
let scales: Vec<(&cadcraft_doc::AnnoScale, String)> = d.scales.iter().filter(|s| s.is_valid()).map(|s| (s, w.h())).collect();
|
||||
// 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.
|
||||
// Plot style names used by layers and objects (Normal always), each a placeholder object.
|
||||
let pstyle_dict = w.h();
|
||||
let mut pstyle_names: Vec<String> = vec![cadcraft_doc::NORMAL_STYLE.to_string()];
|
||||
let mut seen: std::collections::HashSet<String> = pstyle_names.iter().map(|n| n.to_ascii_uppercase()).collect();
|
||||
let named_styles = d.header.i64("PSTYLEMODE", 1) == 0;
|
||||
let in_states = d.layer_states.iter().filter(|_| named_styles).flat_map(|s| s.layers.iter());
|
||||
let named = d.layers.iter().chain(in_states).map(|l| l.plot_style.as_str()).chain(every.iter().map(|e| e.common.plot_style.as_str()));
|
||||
let named = d.layers.iter().map(|l| l.plot_style.as_str()).chain(every.iter().map(|e| e.common.plot_style.as_str()));
|
||||
for n in named {
|
||||
let n = n.trim();
|
||||
let logical = n.is_empty() || n.eq_ignore_ascii_case("bylayer") || n.eq_ignore_ascii_case("byblock");
|
||||
if !logical && pstyle_names.len() < dxf_ext::MAX_PLOT_STYLE_NAMES && seen.insert(n.to_ascii_uppercase()) {
|
||||
if !logical && pstyle_names.len() < dxf_ext::MAX_PLOT_STYLE_NAMES && !pstyle_names.iter().any(|x| x.eq_ignore_ascii_case(n)) {
|
||||
pstyle_names.push(n.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ mod dxf_raw;
|
||||
mod dxf_clip;
|
||||
mod dxf_ext;
|
||||
mod dxf_image;
|
||||
mod dxf_layer_states;
|
||||
mod dxf_mleader;
|
||||
mod dxf_read;
|
||||
mod dxf_table;
|
||||
|
||||
@@ -65,8 +65,8 @@ pub fn census(dxf: &[u8]) -> Option<Census> {
|
||||
_ => {}
|
||||
}
|
||||
};
|
||||
for s in craft_dxf::sections(&tags) {
|
||||
let records = craft_dxf::records(&s.tags);
|
||||
for s in craft_dxf::section_slices(&tags) {
|
||||
let records = craft_dxf::record_slices(s.tags);
|
||||
match s.name.trim().to_ascii_uppercase().as_str() {
|
||||
"ENTITIES" => {
|
||||
for (t, g) in &records {
|
||||
|
||||
+5
-17
@@ -1856,24 +1856,22 @@ fn layer_states_roundtrip_next_to_constraints() {
|
||||
description: "walls \\ hidden".into(),
|
||||
..Layer::default()
|
||||
});
|
||||
d.layer_states.push(LayerState::new("Plot", d.layers.clone(), "Wände"));
|
||||
d.layer_states.push(LayerState { name: "Plot".into(), layers: d.layers.clone() });
|
||||
let mut off = d.layers.clone();
|
||||
for l in &mut off {
|
||||
(l.on, l.frozen, l.locked, l.plot) = (false, true, true, false);
|
||||
}
|
||||
d.layer_states.push(LayerState::new("All off", off, ""));
|
||||
d.layer_states.push(LayerState { name: "All off".into(), layers: off });
|
||||
let text = write_dxf(&d);
|
||||
// AutoCAD's dictionary holds both states; CADCraft's record isn't needed.
|
||||
assert!(text.contains("ACAD_LAYERSTATES") && !text.contains("CADCRAFT_LAYERSTATES"));
|
||||
assert!(text.contains("CADCRAFT_LAYERSTATES"));
|
||||
let back = read_dxf(text.as_bytes()).unwrap();
|
||||
assert_eq!(back.layer_states, d.layer_states);
|
||||
assert_eq!(back.constraints, constraints);
|
||||
assert_eq!(roundtrip(&back).layer_states, d.layer_states);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
assert_eq!(read(&write(&d, "x.dwg").unwrap(), "x.dwg").unwrap().layer_states, d.layer_states);
|
||||
// Drawings without saved layer states carry neither.
|
||||
let none = write_dxf(&Drawing::new_imperial());
|
||||
assert!(!none.contains("CADCRAFT_LAYERSTATES") && !none.contains("ACAD_LAYERSTATES"));
|
||||
// Drawings without saved layer states carry no record.
|
||||
assert!(!write_dxf(&Drawing::new_imperial()).contains("CADCRAFT_LAYERSTATES"));
|
||||
}
|
||||
|
||||
fn table_sample() -> Table {
|
||||
@@ -3715,13 +3713,3 @@ fn solid_hatch_keeps_angle_scale_and_double_flag() {
|
||||
assert!(f("41").is_some_and(|s| (s - 2.0).abs() < 1e-12), "{h:?}");
|
||||
assert_eq!(group(h, "77"), Some("0"), "{h:?}");
|
||||
}
|
||||
|
||||
/// A layer state of CADCraft's own record from before states had a mask, a current layer and a
|
||||
/// description (its JSON holds only the name and the layers) restores every property and names no
|
||||
/// current layer.
|
||||
#[test]
|
||||
fn a_layer_state_saved_before_masks_restores_everything() {
|
||||
let states = crate::dxf_ext::parse_layer_states(r#"{"version":1,"states":[{"name":"S","layers":[]}]}"#).unwrap();
|
||||
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, "", "")]);
|
||||
}
|
||||
|
||||
@@ -1,451 +0,0 @@
|
||||
//! Saved layer states in AutoCAD's form: the LAYER table's extension dictionary holds an
|
||||
//! `ACAD_LAYERSTATES` dictionary of one XRECORD per state. The groups below are copied from
|
||||
//! AutoCAD 2024's own DXFOUT of states saved with -LAYER stAte on a self-built drawing.
|
||||
|
||||
use cadcraft_color::{Color, Rgb};
|
||||
use cadcraft_doc::{Drawing, Layer, LayerState, Lineweight};
|
||||
use cadcraft_io::{read, write_dxf};
|
||||
|
||||
/// `(code, value)` pairs of a DXF, trimmed.
|
||||
fn pairs(dxf: &str) -> Vec<(String, String)> {
|
||||
let lines: Vec<&str> = dxf.lines().collect();
|
||||
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
|
||||
}
|
||||
|
||||
fn join(p: &[(String, String)]) -> String {
|
||||
p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
|
||||
}
|
||||
|
||||
fn g(c: &str, v: &str) -> (String, String) {
|
||||
(c.to_string(), v.to_string())
|
||||
}
|
||||
|
||||
/// The records of a DXF: (type, groups after the `0`).
|
||||
fn records(p: &[(String, String)]) -> Vec<(String, Vec<(String, String)>)> {
|
||||
let mut out: Vec<(String, Vec<(String, String)>)> = Vec::new();
|
||||
for (c, v) in p {
|
||||
if c == "0" {
|
||||
out.push((v.clone(), Vec::new()));
|
||||
} else if let Some(last) = out.last_mut() {
|
||||
last.1.push((c.clone(), v.clone()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn value<'a>(groups: &'a [(String, String)], code: &str) -> Option<&'a str> {
|
||||
groups.iter().find(|(c, _)| c == code).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// The handle of table record `kind` named `name`.
|
||||
fn record_handle(p: &[(String, String)], kind: &str, name: &str) -> String {
|
||||
let recs = records(p);
|
||||
let (_, groups) = recs.iter().find(|(k, gs)| k == kind && value(gs, "2").is_some_and(|n| n.eq_ignore_ascii_case(name))).unwrap();
|
||||
value(groups, "5").unwrap().to_string()
|
||||
}
|
||||
|
||||
/// A handle above every handle of the file, plus `k`.
|
||||
fn fresh(p: &[(String, String)], k: u64) -> String {
|
||||
let top = p.iter().filter(|(c, _)| c == "5" || c == "105").filter_map(|(_, v)| u64::from_str_radix(v, 16).ok()).max().unwrap();
|
||||
format!("{:X}", top + 0x100 + k)
|
||||
}
|
||||
|
||||
/// `dxf` with the LAYER table given extension dictionary `xdict` and `objects` added at the end
|
||||
/// of OBJECTS.
|
||||
fn inject(dxf: &str, xdict: &str, objects: Vec<(String, String)>) -> String {
|
||||
let mut p = pairs(dxf);
|
||||
let table = p.iter().enumerate().position(|(i, (c, v))| c == "0" && v == "TABLE" && p.get(i + 1).is_some_and(|n| n.1 == "LAYER")).unwrap();
|
||||
let at = table + p[table..].iter().position(|(c, _)| c == "5").unwrap() + 1;
|
||||
p.splice(at..at, [g("102", "{ACAD_XDICTIONARY"), g("360", xdict), g("102", "}")]);
|
||||
let objs = p.iter().position(|(c, v)| c == "2" && v == "OBJECTS").unwrap();
|
||||
let end = objs + p[objs..].iter().position(|(c, v)| c == "0" && v == "ENDSEC").unwrap();
|
||||
p.splice(end..end, objects);
|
||||
join(&p)
|
||||
}
|
||||
|
||||
/// Layers A (red) and B, and the DASHED linetype.
|
||||
fn drawing() -> Drawing {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.layers.push(Layer { color: Color::Index(1), ..Layer::new("A") });
|
||||
d.layers.push(Layer::new("B"));
|
||||
d.linetypes.push(cadcraft_doc::library::standard_linetypes().into_iter().find(|l| l.name == "DASHED").unwrap());
|
||||
d
|
||||
}
|
||||
|
||||
/// State S2 as AutoCAD 2024 wrote it after -LAYER: A true colour 10,20,30 (nearest index 168),
|
||||
/// 50% transparent, 0.35 mm, DASHED, not plotted; B locked and frozen in new viewports. Then the
|
||||
/// entry of a layer purged since (AutoCAD keeps it, pointing at handles that are gone).
|
||||
fn s2(p: &[(String, String)], rec: &str, dict: &str) -> Vec<(String, String)> {
|
||||
let (a, b, zero) = (record_handle(p, "LAYER", "A"), record_handle(p, "LAYER", "B"), record_handle(p, "LAYER", "0"));
|
||||
let (cont, dashed) = (record_handle(p, "LTYPE", "Continuous"), record_handle(p, "LTYPE", "DASHED"));
|
||||
let gone = fresh(p, 0x50);
|
||||
let mut v =
|
||||
vec![g("0", "XRECORD"), g("5", rec), g("102", "{ACAD_REACTORS"), g("330", dict), g("102", "}"), g("330", dict), g("100", "AcDbXrecord")];
|
||||
v.extend([g("280", "1"), g("91", "2047"), g("301", ""), g("290", "0"), g("302", "0")]);
|
||||
for (h, flags, aci, lw, lt, ps, tr) in [
|
||||
(b.as_str(), "28", "7", "-3", cont.as_str(), "Color_7", "0"),
|
||||
(a.as_str(), "0", "168", "35", dashed.as_str(), "Color_168", "33554559"),
|
||||
(zero.as_str(), "8", "7", "-3", cont.as_str(), "Color_7", "0"),
|
||||
(gone.as_str(), "8", "7", "-3", gone.as_str(), "Color_7", "0"),
|
||||
] {
|
||||
v.extend([g("330", h), g("90", flags), g("62", aci), g("370", lw), g("331", lt), g("1", ps), g("440", tr)]);
|
||||
if h == a {
|
||||
v.push(g("92", "-1039526882"));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// State S7, saved with only On and restored once (AutoCAD then sets bit 65536), current layer A.
|
||||
fn s7(p: &[(String, String)], rec: &str, dict: &str) -> Vec<(String, String)> {
|
||||
let (a, b) = (record_handle(p, "LAYER", "A"), record_handle(p, "LAYER", "B"));
|
||||
let cont = record_handle(p, "LTYPE", "Continuous");
|
||||
let mut v =
|
||||
vec![g("0", "XRECORD"), g("5", rec), g("102", "{ACAD_REACTORS"), g("330", dict), g("102", "}"), g("330", dict), g("100", "AcDbXrecord")];
|
||||
v.extend([g("280", "1"), g("91", "66049"), g("301", "only on"), g("290", "0"), g("302", "A")]);
|
||||
for (h, aci) in [(b.as_str(), "7"), (a.as_str(), "1")] {
|
||||
v.extend([g("330", h), g("90", "8"), g("62", aci), g("370", "-3"), g("331", &cont), g("1", &format!("Color_{aci}")), g("440", "0")]);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The extension dictionary of the LAYER table and the states dictionary, with `extra` entries in
|
||||
/// the extension dictionary.
|
||||
fn dictionaries(p: &[(String, String)], x: &str, y: &str, states: &[(&str, &str)], extra: &[(&str, &str)]) -> Vec<(String, String)> {
|
||||
let table = {
|
||||
let recs = records(p);
|
||||
let (_, gs) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
|
||||
value(gs, "5").unwrap().to_string()
|
||||
};
|
||||
let mut v = vec![g("0", "DICTIONARY"), g("5", x), g("330", &table), g("100", "AcDbDictionary"), g("280", "1"), g("281", "1")];
|
||||
for (k, h) in extra.iter().copied().chain([("ACAD_LAYERSTATES", y)]) {
|
||||
v.extend([g("3", k), g("360", h)]);
|
||||
}
|
||||
v.extend([
|
||||
g("0", "DICTIONARY"),
|
||||
g("5", y),
|
||||
g("102", "{ACAD_REACTORS"),
|
||||
g("330", x),
|
||||
g("102", "}"),
|
||||
g("330", x),
|
||||
g("100", "AcDbDictionary"),
|
||||
g("281", "1"),
|
||||
]);
|
||||
for (name, h) in states {
|
||||
v.extend([g("3", name), g("350", h)]);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn autocad_file() -> String {
|
||||
let base = write_dxf(&drawing());
|
||||
let p = pairs(&base);
|
||||
let h = |k| fresh(&p, k);
|
||||
let (x, y, r2, r7) = (h(1), h(2), h(3), h(4));
|
||||
let mut objects = dictionaries(&p, &x, &y, &[("S2", &r2), ("S7", &r7)], &[]);
|
||||
objects.extend(s2(&p, &r2, &y));
|
||||
objects.extend(s7(&p, &r7, &y));
|
||||
inject(&base, &x, objects)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_layer_states_autocad_writes() {
|
||||
let d = read(autocad_file().as_bytes(), "acad.dxf").unwrap();
|
||||
let names: Vec<&str> = d.layer_states.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names, ["S2", "S7"]);
|
||||
let s2 = &d.layer_states[0];
|
||||
assert_eq!((s2.mask, s2.current.as_str(), s2.description.as_str()), (2047, "0", ""));
|
||||
// The purged layer's entry is skipped.
|
||||
let layers: Vec<&str> = s2.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(layers, ["B", "A", "0"]);
|
||||
let a = &s2.layers[1];
|
||||
assert_eq!(a.color, Color::True(Rgb(10, 20, 30)));
|
||||
assert_eq!((a.transparency, a.lineweight, a.linetype.as_str()), (50, Lineweight::from_dxf(35), "DASHED"));
|
||||
assert!(a.on && !a.frozen && !a.locked && !a.plot && !a.vp_freeze_new);
|
||||
// A colour-dependent drawing: the plot style stays the layer's ("Color_168" is its colour's).
|
||||
assert_eq!(a.plot_style, "Normal");
|
||||
let b = &s2.layers[0];
|
||||
assert!(b.on && !b.frozen && b.locked && b.plot && b.vp_freeze_new, "{b:?}");
|
||||
assert_eq!((b.color, b.linetype.as_str(), b.transparency), (Color::Index(7), "Continuous", 0));
|
||||
let s7 = &d.layer_states[1];
|
||||
assert_eq!((s7.mask, s7.current.as_str(), s7.description.as_str()), (66049, "A", "only on"));
|
||||
assert_eq!(s7.layers.iter().find(|l| l.name == "A").unwrap().color, Color::Index(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autocads_layer_states_are_written_back_in_its_form() {
|
||||
let d = read(autocad_file().as_bytes(), "acad.dxf").unwrap();
|
||||
let text = write_dxf(&d);
|
||||
let p = pairs(&text);
|
||||
// One states dictionary, in the LAYER table's extension dictionary, and no CADCraft copy.
|
||||
assert_eq!(p.iter().filter(|(c, v)| c == "3" && v == "ACAD_LAYERSTATES").count(), 1);
|
||||
assert!(!text.contains("CADCRAFT_LAYERSTATES"));
|
||||
let recs = records(&p);
|
||||
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
|
||||
let x = table.windows(2).find(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).unwrap();
|
||||
let (_, xd) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(x.as_str())).unwrap();
|
||||
assert_eq!(value(xd, "330"), value(table, "5"));
|
||||
let back = read(text.as_bytes(), "back.dxf").unwrap();
|
||||
assert_eq!(back.layer_states, d.layer_states);
|
||||
// The XRECORD of S2 as AutoCAD writes it: B, then A.
|
||||
let (a_h, b_h) = (record_handle(&p, "LAYER", "A"), record_handle(&p, "LAYER", "B"));
|
||||
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
|
||||
let head = rec.iter().position(|(c, _)| c == "280").unwrap();
|
||||
assert_eq!(rec[head..head + 5], [("280", "1"), ("91", "2047"), ("301", ""), ("290", "0"), ("302", "0")].map(|(c, v)| g(c, v)));
|
||||
let cont = record_handle(&p, "LTYPE", "Continuous");
|
||||
let b = [("330", b_h.as_str()), ("90", "28"), ("62", "7"), ("370", "-3"), ("331", &cont), ("1", "Color_7"), ("440", "0")];
|
||||
assert_eq!(rec[head + 5..head + 12], b.map(|(c, v)| g(c, v)));
|
||||
let from = rec.iter().position(|(c, v)| c == "330" && *v == a_h).unwrap();
|
||||
let a: Vec<(String, String)> = rec[from..from + 9].to_vec();
|
||||
let dashed = record_handle(&p, "LTYPE", "DASHED");
|
||||
let want = [
|
||||
("330", a_h.as_str()),
|
||||
("90", "0"),
|
||||
("62", "168"),
|
||||
("370", "35"),
|
||||
("331", &dashed),
|
||||
("1", "Color_168"),
|
||||
("440", "33554559"),
|
||||
("92", "-1039526882"),
|
||||
];
|
||||
assert_eq!(a[..8], want.map(|(c, v)| g(c, v)), "{a:?}");
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
|
||||
assert_eq!(read(&dwg, "x.dwg").unwrap().layer_states, d.layer_states);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_filters_next_to_the_states_are_kept() {
|
||||
// The LAYER table's extension dictionary of a drawing with layer filters holds them next to
|
||||
// the states (ACAD_LAYERFILTERS, ACLYDICTIONARY): they stay, in the dictionary CADCraft writes.
|
||||
let base = write_dxf(&drawing());
|
||||
let p = pairs(&base);
|
||||
let h = |k| fresh(&p, k);
|
||||
let (x, y, r2, f, fr, gone) = (h(1), h(2), h(3), h(4), h(5), h(6));
|
||||
// Two entries whose objects the file doesn't have (a handle of nothing, and a null one): they
|
||||
// aren't written into the table's dictionary.
|
||||
let extra = [("ACAD_LAYERFILTERS", f.as_str()), ("OTHER_GONE", gone.as_str()), ("OTHER_NULL", "0")];
|
||||
let mut objects = dictionaries(&p, &x, &y, &[("S2", &r2)], &extra);
|
||||
objects.extend(s2(&p, &r2, &y));
|
||||
objects.extend([g("0", "DICTIONARY"), g("5", &f), g("102", "{ACAD_REACTORS"), g("330", &x), g("102", "}"), g("330", &x)]);
|
||||
objects.extend([g("100", "AcDbDictionary"), g("281", "1"), g("3", "Walls"), g("350", &fr)]);
|
||||
objects.extend([g("0", "XRECORD"), g("5", &fr), g("102", "{ACAD_REACTORS"), g("330", &f), g("102", "}"), g("330", &f), g("100", "AcDbXrecord")]);
|
||||
objects.extend([g("280", "1"), g("1", "A*")]);
|
||||
let file = inject(&base, &x, objects);
|
||||
let mut text = file;
|
||||
for round in 0..2 {
|
||||
let d = read(text.as_bytes(), "f.dxf").unwrap();
|
||||
assert_eq!(d.layer_states.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["S2"], "round {round}");
|
||||
text = write_dxf(&d);
|
||||
let p = pairs(&text);
|
||||
let recs = records(&p);
|
||||
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
|
||||
let xdicts: Vec<String> = table.windows(2).filter(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).collect();
|
||||
assert_eq!(xdicts.len(), 1, "round {round}");
|
||||
let xd = &xdicts[0];
|
||||
let (_, dict) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(xd.as_str())).unwrap();
|
||||
let keys: Vec<&str> = dict.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.as_str()).collect();
|
||||
assert_eq!(keys, ["ACAD_LAYERSTATES", "ACAD_LAYERFILTERS"], "round {round}");
|
||||
// The filters dictionary is owned by the written one, and so is its filter by it.
|
||||
let fh = dict.windows(2).find(|w| w[0] == g("3", "ACAD_LAYERFILTERS")).map(|w| w[1].1.clone()).unwrap();
|
||||
let (_, fd) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(fh.as_str())).unwrap();
|
||||
let owner = fd.iter().filter(|(c, _)| c == "330").map(|(_, v)| v.as_str()).collect::<Vec<_>>();
|
||||
assert_eq!(owner, [xd.as_str(), xd.as_str()], "round {round}: reactor and owner");
|
||||
let walls = value(fd, "350").unwrap();
|
||||
let (_, wr) = recs.iter().find(|(k, gs)| k == "XRECORD" && value(gs, "5") == Some(walls)).unwrap();
|
||||
assert!(wr.contains(&g("330", &fh)) && wr.contains(&g("1", "A*")), "round {round}");
|
||||
// The kept dictionary itself is not written a second time.
|
||||
assert_eq!(recs.iter().filter(|(k, gs)| k == "DICTIONARY" && gs.iter().any(|(c, v)| c == "3" && v == "ACAD_LAYERFILTERS")).count(), 1);
|
||||
}
|
||||
// With every state deleted the filters stay, in the table's own dictionary, and AutoCAD's states
|
||||
// don't come back.
|
||||
let mut d = read(text.as_bytes(), "f.dxf").unwrap();
|
||||
d.layer_states.clear();
|
||||
let text = write_dxf(&d);
|
||||
assert!(!text.contains("ACAD_LAYERSTATES"));
|
||||
let p = pairs(&text);
|
||||
let recs = records(&p);
|
||||
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
|
||||
let xd = table.windows(2).find(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).unwrap();
|
||||
let (_, dict) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(xd.as_str())).unwrap();
|
||||
assert_eq!(dict.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.as_str()).collect::<Vec<_>>(), ["ACAD_LAYERFILTERS"]);
|
||||
assert!(read(text.as_bytes(), "g.dxf").unwrap().layer_states.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_whose_names_differ_only_in_case_open_as_one_state() {
|
||||
// AutoCAD 2024 opens the entries `S` and `s` of one ACAD_LAYERSTATES dictionary as one state:
|
||||
// named as the first entry in the dictionary and holding the last entry's record (measured with
|
||||
// the records in one file order and the entries in both dictionary orders, so the first entry's
|
||||
// record came first in the file once and last once). Here S2's record (mask 2047) comes first in
|
||||
// the file, then state T's, then S7's (66049); the merged state stays where S2's record is.
|
||||
let base = write_dxf(&drawing());
|
||||
let p = pairs(&base);
|
||||
let h = |k| fresh(&p, k);
|
||||
let (x, y, r2, r7, rt) = (h(1), h(2), h(3), h(4), h(5));
|
||||
let states = |d: &Drawing| d.layer_states.iter().map(|s| (s.name.clone(), s.mask)).collect::<Vec<_>>();
|
||||
for (pair, name, mask) in [([("S", r2.as_str()), ("s", r7.as_str())], "S", 66049), ([("s", r7.as_str()), ("S", r2.as_str())], "s", 2047)] {
|
||||
let entries = [pair[0], ("T", rt.as_str()), pair[1]];
|
||||
let mut objects = dictionaries(&p, &x, &y, &entries, &[]);
|
||||
objects.extend(s2(&p, &r2, &y));
|
||||
objects.extend(s7(&p, &rt, &y));
|
||||
objects.extend(s7(&p, &r7, &y));
|
||||
let d = read(inject(&base, &x, objects).as_bytes(), "case.dxf").unwrap();
|
||||
let want = [(name.to_string(), mask), ("T".to_string(), 66049)];
|
||||
assert_eq!(states(&d), want, "{entries:?}");
|
||||
// Written back, they are the states AutoCAD opened.
|
||||
let back = read(write_dxf(&d).as_bytes(), "back.dxf").unwrap();
|
||||
assert_eq!(states(&back), want, "{entries:?}");
|
||||
}
|
||||
// A record the dictionary lists as `s` but another object owns isn't a state, and doesn't stand
|
||||
// in for S's record either.
|
||||
let mut objects = dictionaries(&p, &x, &y, &[("S", r2.as_str()), ("s", r7.as_str())], &[]);
|
||||
objects.extend(s2(&p, &r2, &y));
|
||||
objects.extend(s7(&p, &r7, &x));
|
||||
let d = read(inject(&base, &x, objects).as_bytes(), "stray.dxf").unwrap();
|
||||
assert_eq!(states(&d), [("S".to_string(), 2047)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_snapshots_and_names_twice_in_another_case_stay_in_cadcrafts_record() {
|
||||
let mut d = drawing();
|
||||
for name in ["Plan", "*VIEW Front", "PLAN", "Wände", "WÄNDE", "", " "] {
|
||||
d.layer_states.push(LayerState::new(name, d.layers.clone(), "A"));
|
||||
}
|
||||
let text = write_dxf(&d);
|
||||
let p = pairs(&text);
|
||||
let recs = records(&p);
|
||||
let (_, states) =
|
||||
recs.iter().find(|(k, gs)| k == "DICTIONARY" && gs.contains(&g("281", "1")) && gs.iter().any(|(c, v)| c == "3" && v == "Plan")).unwrap();
|
||||
// (The DXF writes "ä" as \U+00E4.)
|
||||
let keys: Vec<String> = states.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.replace("\\U+00E4", "ä")).collect();
|
||||
assert_eq!(keys, ["Plan", "Wände"], "AutoCAD's dictionary holds the first of each name");
|
||||
assert!(text.contains("CADCRAFT_LAYERSTATES"));
|
||||
let back = read(text.as_bytes(), "v.dxf").unwrap();
|
||||
// AutoCAD's states first, then CADCraft's own.
|
||||
// (A blank name can't be a key of AutoCAD's dictionary: those stay in CADCraft's record too.)
|
||||
let want: Vec<LayerState> = [0, 3, 1, 2, 4, 5, 6].iter().map(|&i| d.layer_states[i].clone()).collect();
|
||||
assert_eq!(back.layer_states, want);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let dwg = cadcraft_io::write(&d, "v.dwg").unwrap();
|
||||
assert_eq!(read(&dwg, "v.dwg").unwrap().layer_states, want);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_of_an_xref_gets_group_93() {
|
||||
// AutoCAD 2024 writes 93 (0 for a newly attached xref) after the lineweight of an xref's layer
|
||||
// only (measured with a self-built xref).
|
||||
let mut d = drawing();
|
||||
d.layers.push(Layer::new("XR|L1"));
|
||||
d.layer_states.push(LayerState::new("X", d.layers.clone(), "0"));
|
||||
let p = pairs(&write_dxf(&d));
|
||||
let recs = records(&p);
|
||||
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
|
||||
let start = rec.iter().position(|(c, _)| c == "302").unwrap() + 1;
|
||||
let mut with_93 = Vec::new();
|
||||
let mut layer = String::new();
|
||||
for (i, (c, v)) in rec.iter().enumerate().skip(start) {
|
||||
match c.as_str() {
|
||||
"330" => layer.clone_from(v),
|
||||
"93" => {
|
||||
assert_eq!((v.as_str(), rec[i - 1].0.as_str(), rec[i + 1].0.as_str()), ("0", "370", "331"));
|
||||
with_93.push(layer.clone());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(with_93, [record_handle(&p, "LAYER", "XR|L1")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_plot_styles_are_written_by_placeholder() {
|
||||
// In a drawing of named plot styles AutoCAD 2024 writes a layer's plot style as group 390, the
|
||||
// handle of the style's placeholder object (measured); CADCraft reads it back by that handle.
|
||||
let mut d = drawing();
|
||||
d.header.set_i64("PSTYLEMODE", 0);
|
||||
let a = d.layers.iter().position(|l| l.name == "A").unwrap();
|
||||
d.layers[a].plot_style = "Thick".into();
|
||||
d.layer_states.push(LayerState::new("N", d.layers.clone(), "0"));
|
||||
// No layer uses Thick any more: its placeholder is written for the state.
|
||||
d.layers[a].plot_style = "Normal".into();
|
||||
let text = write_dxf(&d);
|
||||
let p = pairs(&text);
|
||||
let recs = records(&p);
|
||||
let (_, names) = recs.iter().find(|(k, _)| k == "ACDBDICTIONARYWDFLT").unwrap();
|
||||
let thick = names.windows(2).find(|w| w[0] == g("3", "Thick")).map(|w| w[1].1.clone()).unwrap();
|
||||
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
|
||||
assert!(rec.contains(&g("390", &thick)) && !rec.iter().any(|(c, _)| c == "1"), "{rec:?}");
|
||||
let back = read(text.as_bytes(), "n.dxf").unwrap();
|
||||
assert_eq!(back.layer_states[0].layers.iter().find(|l| l.name == "A").unwrap().plot_style, "Thick");
|
||||
assert_eq!(back.layer_states, d.layer_states);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let dwg = cadcraft_io::write(&d, "n.dwg").unwrap();
|
||||
assert_eq!(read(&dwg, "n.dwg").unwrap().layer_states, d.layer_states);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_state_in_both_records_is_read_from_autocads() {
|
||||
// A file of an earlier CADCraft keeps its states in CADCraft's record; AutoCAD then saves a state
|
||||
// of the same name in its own dictionary: AutoCAD's is the one read.
|
||||
let mut d = drawing();
|
||||
d.layer_states.push(LayerState::new("S", d.layers.clone(), "A"));
|
||||
d.layer_states.push(LayerState::new("*VIEW S", d.layers.clone(), "B"));
|
||||
let text = write_dxf(&d);
|
||||
assert!(text.contains("*VIEW S"));
|
||||
let text = text.replace("*VIEW S", "S");
|
||||
let back = read(text.as_bytes(), "both.dxf").unwrap();
|
||||
assert_eq!(back.layer_states.iter().map(|s| (s.name.as_str(), s.current.as_str())).collect::<Vec<_>>(), [("S", "A")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn states_past_the_limit_are_left_out_and_the_rest_come_in_file_order() {
|
||||
// A hostile file with one state more than the reader keeps (100 000): the last one in the file
|
||||
// is left out, and the others come in file order, here the reverse of their names' order.
|
||||
const LIMIT: u64 = 100_000;
|
||||
let base = write_dxf(&drawing());
|
||||
let p = pairs(&base);
|
||||
let first = u64::from_str_radix(&fresh(&p, 0), 16).unwrap();
|
||||
let h = |k: u64| format!("{:X}", first + k);
|
||||
let (x, y) = (h(1), h(2));
|
||||
let names: Vec<String> = (0..=LIMIT).map(|i| format!("S{:06}", LIMIT + 1 - i)).collect();
|
||||
let records: Vec<String> = (0..=LIMIT).map(|i| h(3 + i)).collect();
|
||||
let entries: Vec<(&str, &str)> = names.iter().map(String::as_str).zip(records.iter().map(String::as_str)).collect();
|
||||
let mut objects = dictionaries(&p, &x, &y, &entries, &[]);
|
||||
for r in &records {
|
||||
objects.extend([g("0", "XRECORD"), g("5", r), g("330", &y), g("100", "AcDbXrecord")]);
|
||||
objects.extend([g("280", "1"), g("91", "2047"), g("301", ""), g("290", "0"), g("302", "0")]);
|
||||
}
|
||||
let d = read(inject(&base, &x, objects).as_bytes(), "many.dxf").unwrap();
|
||||
let names: Vec<&str> = d.layer_states.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names.len(), 100_000);
|
||||
assert_eq!((names.first().copied(), names.get(1).copied(), names.last().copied()), (Some("S100001"), Some("S100000"), Some("S000002")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_twice_in_a_file_is_one_state() {
|
||||
// A damaged file can hold an object twice under one handle: one state.
|
||||
let base = write_dxf(&drawing());
|
||||
let p = pairs(&base);
|
||||
let h = |k| fresh(&p, k);
|
||||
let (x, y, r7) = (h(1), h(2), h(4));
|
||||
let mut objects = dictionaries(&p, &x, &y, &[("S7", &r7)], &[]);
|
||||
objects.extend(s7(&p, &r7, &y));
|
||||
objects.extend(s7(&p, &r7, &y));
|
||||
let d = read(inject(&base, &x, objects).as_bytes(), "twice.dxf").unwrap();
|
||||
assert_eq!(d.layer_states.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["S7"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_92_without_the_true_colour_prefix_is_not_a_true_colour() {
|
||||
// AutoCAD 2024 writes 92 only for a true colour, 0xC2RRGGBB (measured); a value with another
|
||||
// high byte (not seen from AutoCAD) leaves the colour index of group 62.
|
||||
let text = autocad_file().replace("92\n-1039526882", "92\n-1023410175");
|
||||
let d = read(text.as_bytes(), "c3.dxf").unwrap();
|
||||
assert_eq!(d.layer_states[0].layers.iter().find(|l| l.name == "A").unwrap().color, Color::Index(168));
|
||||
}
|
||||
@@ -32,7 +32,6 @@ mod groups_roundtrip;
|
||||
mod hatch_assoc_roundtrip;
|
||||
mod hatch_pattern_def;
|
||||
mod helix_roundtrip;
|
||||
mod layer_states_acad;
|
||||
mod layout_limits_roundtrip;
|
||||
mod layout_paper_units;
|
||||
mod layout_plot_window;
|
||||
|
||||
@@ -185,7 +185,7 @@ pub(super) fn layer_states() -> Case {
|
||||
layer.on = false;
|
||||
layer.locked = true;
|
||||
}
|
||||
drawing.layer_states.push(LayerState::new("Saved", layers, "0"));
|
||||
drawing.layer_states.push(LayerState { name: "Saved".into(), layers });
|
||||
Case { name: "drawing/layer-state".into(), drawing }
|
||||
}
|
||||
|
||||
|
||||
@@ -492,16 +492,11 @@ const OBJECTS: &str = "
|
||||
330 61
|
||||
100 AcDbXrecord
|
||||
280 1
|
||||
91 2047
|
||||
91 0
|
||||
301 Plan
|
||||
290 0
|
||||
302 0
|
||||
330 11
|
||||
90 8
|
||||
8 WALLS
|
||||
90 0
|
||||
62 1
|
||||
370 -3
|
||||
1 Normal
|
||||
440 0
|
||||
0 DICTIONARY
|
||||
5 63
|
||||
330 10
|
||||
@@ -808,19 +803,14 @@ fn ucs_layer_states_and_block_descriptions_are_kept() {
|
||||
assert_eq!((u.origin.x, u.origin.y, u.origin.z), (1.0, 2.0, 3.0));
|
||||
assert_eq!((u.x_axis.y, u.y_axis.x), (1.0, -1.0));
|
||||
assert_eq!(d.block("DOOR").map(|b| b.description.as_str()), Some("A door leaf"));
|
||||
let states: Vec<(&str, Vec<&str>)> =
|
||||
d.layer_states.iter().map(|s| (s.name.as_str(), s.layers.iter().map(|l| l.name.as_str()).collect())).collect();
|
||||
assert_eq!(states, [("Plan", vec!["WALLS"])]);
|
||||
for o in [&a, &b] {
|
||||
// Layer states live in the LAYER table's extension dictionary, each layer named by its
|
||||
// handle (as AutoCAD 2024 writes them; CADCraft reads and rewrites them).
|
||||
// Layer states live in the LAYER table's extension dictionary.
|
||||
let table = o.of("TABLE").into_iter().find(|t| s(t, 2) == "LAYER").expect("LAYER table");
|
||||
let [xd] = group(table, "ACAD_XDICTIONARY").try_into().expect("LAYER table extension dictionary");
|
||||
let (_, dict) = o.handle(&xd).expect("dictionary");
|
||||
let (_, states) = o.entry(dict, "ACAD_LAYERSTATES").expect("ACAD_LAYERSTATES");
|
||||
let (_, plan) = o.entry(states, "Plan").expect("layer state Plan");
|
||||
let layers = plan.iter().skip_while(|t| t.code != 302).filter(|t| t.code == 330).map(Tag::str).collect::<Vec<_>>();
|
||||
assert_eq!((s(plan, 301), layers), ("Plan".into(), vec![h(o.named("LAYER", "WALLS"))]));
|
||||
assert_eq!((s(plan, 301), s(plan, 8)), ("Plan".into(), "WALLS".into()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpStream, ToSocketAddrs};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::file_access::{self, AutomationRoots};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Something that answers control-channel methods (`engine.execute`, `cmdline.input`,
|
||||
@@ -298,6 +300,7 @@ impl Backend for Remote {
|
||||
fn has_ui(&self) -> bool {
|
||||
true
|
||||
}
|
||||
/// What this backend talks to, for messages.
|
||||
fn describe(&self) -> String {
|
||||
format!("connected to CADCraft at {}", self.addr)
|
||||
}
|
||||
@@ -321,13 +324,19 @@ const HEADLESS_METHODS: &[(&str, &str, &str)] = &[
|
||||
];
|
||||
|
||||
/// An in-process headless session (no window).
|
||||
#[derive(Default)]
|
||||
pub struct Headless {
|
||||
pub session: Session,
|
||||
/// The folders its methods may read and write (`--automation-read-root`,
|
||||
/// `--automation-write-root`); `None`: anywhere.
|
||||
roots: Option<Arc<AutomationRoots>>,
|
||||
}
|
||||
|
||||
impl Default for Headless {
|
||||
fn default() -> Self {
|
||||
Headless { session: Session::new() }
|
||||
impl Headless {
|
||||
/// Confine the files every method reads and writes to `roots` ([`file_access`]).
|
||||
pub fn with_automation_roots(mut self, roots: Option<Arc<AutomationRoots>>) -> Self {
|
||||
self.roots = roots;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,8 +355,9 @@ fn state(s: &Session) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
impl Backend for Headless {
|
||||
fn call(&mut self, method: &str, p: Value) -> Result<Value, String> {
|
||||
impl Headless {
|
||||
/// The reply to one control method; the caller holds it to the roots.
|
||||
fn answer(&mut self, method: &str, p: &Value) -> Result<Value, String> {
|
||||
let s = &mut self.session;
|
||||
let str_p = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string);
|
||||
match method {
|
||||
@@ -407,14 +417,14 @@ impl Backend for Headless {
|
||||
"engine.commands" => {
|
||||
Ok(Value::Array(cadcraft_engine::command_specs().iter().map(|c| serde_json::to_value(c.info(s)).unwrap_or_default()).collect()))
|
||||
}
|
||||
"drawing.inspect" | "document.inspect" => s.execute("drawing.inspect", &p).map_err(|e| e.to_string()),
|
||||
"drawing.inspect" | "document.inspect" => s.execute("drawing.inspect", p).map_err(|e| e.to_string()),
|
||||
"ui.render" => {
|
||||
let w = p.get("width").and_then(Value::as_f64).unwrap_or(1600.0).clamp(16.0, 8192.0) as u32;
|
||||
let h = p.get("height").and_then(Value::as_f64).unwrap_or(1000.0).clamp(16.0, 8192.0) as u32;
|
||||
let st = s.state().map_err(|e| e.to_string())?;
|
||||
let window = render_window(&p);
|
||||
let window = render_window(p);
|
||||
// `background` and `plot_style` (#803), read as the app reads them.
|
||||
let look = cadcraft_engine::render_look::RenderLook::from_params(&st.doc, &p)?;
|
||||
let look = cadcraft_engine::render_look::RenderLook::from_params(&st.doc, p)?;
|
||||
let opts = cadcraft_render::Options {
|
||||
view: window,
|
||||
transparency: s.settings.transparency_display,
|
||||
@@ -437,6 +447,7 @@ impl Backend for Headless {
|
||||
let mut r =
|
||||
json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "truncated": list.truncated});
|
||||
if let Some(path) = str_p("path") {
|
||||
file_access::check_write(&path)?;
|
||||
let file = std::path::Path::new(&path);
|
||||
let folder = cadcraft_engine::atomic_write::missing_folder(file);
|
||||
cadcraft_engine::atomic_write::write_atomic_making_folders(file, &png).map_err(|e| format!("{path}: {e}"))?;
|
||||
@@ -452,7 +463,7 @@ impl Backend for Headless {
|
||||
}
|
||||
"app.save" => {
|
||||
let id = if p.get("path").is_some() { "saveas" } else { "qsave" };
|
||||
s.execute(id, &p).map_err(|e| e.to_string())
|
||||
s.execute(id, p).map_err(|e| e.to_string())
|
||||
}
|
||||
"ui.screenshot" => Err("no UI in headless mode; use render".into()),
|
||||
"control.methods" => Ok(HEADLESS_METHODS
|
||||
@@ -463,9 +474,18 @@ impl Backend for Headless {
|
||||
other => Err(format!("unknown method `{other}`; `control.methods` lists them (docs/control-protocol.md)")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for Headless {
|
||||
/// Run one control method inside the roots, if any.
|
||||
fn call(&mut self, method: &str, p: Value) -> Result<Value, String> {
|
||||
let roots = self.roots.clone();
|
||||
file_access::confine(roots.as_ref(), || self.answer(method, &p))
|
||||
}
|
||||
fn has_ui(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// What this backend talks to, for messages.
|
||||
fn describe(&self) -> String {
|
||||
"headless CADCraft session".into()
|
||||
}
|
||||
|
||||
@@ -412,3 +412,39 @@ fn legacy_protocol_routing_and_version_negotiation() {
|
||||
json!([{"jsonrpc":"2.0","id":[1],"result":{}},{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"missing `method`"}}])
|
||||
);
|
||||
}
|
||||
|
||||
/// With a read root and no write root (the read-only use #1931 asks for), an agent still draws,
|
||||
/// reads and renders, but no route writes a file outside: the save tool, `execute` of the
|
||||
/// writers, a save hidden mid-line at the command line and one in a script. Carried from #1973's
|
||||
/// read-only mode tests.
|
||||
#[test]
|
||||
fn a_read_root_alone_still_draws_but_writes_nothing() {
|
||||
let base = std::env::temp_dir().join(format!("cc-mcp-readonly-{}", std::process::id()));
|
||||
let (inside, outside) = (base.join("in"), base.join("outside"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let roots = cadcraft_engine::file_access::AutomationRoots::new(Some(&inside), None).unwrap();
|
||||
let mut s = Server::new(Box::new(Headless::default().with_automation_roots(roots)));
|
||||
let _ = call(&mut s, 1, "initialize", json!({"protocolVersion": "2025-06-18"}));
|
||||
let _ = s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
|
||||
|
||||
tool(&mut s, "command_line", json!({"text": "rectang 0,0 100,60"}));
|
||||
tool(&mut s, "execute", json!({"command": "circle", "params": {"center": [10, 10], "radius": 4}}));
|
||||
assert_eq!(tool(&mut s, "inspect_drawing", json!({}))["entityCount"], 2, "drawing edits are allowed");
|
||||
assert_eq!(tool(&mut s, "render", json!({}))["type"], json!("image"), "a render without `path` writes nothing");
|
||||
|
||||
let out = |n: &str| outside.join(n).to_string_lossy().into_owned();
|
||||
let refused = |s: &mut Server, name: &str, args: Value| {
|
||||
let r = call(s, 98, "tools/call", json!({"name": name, "arguments": args}));
|
||||
assert_eq!(r["result"]["isError"], json!(true), "{name} was not refused: {r}");
|
||||
};
|
||||
refused(&mut s, "save", json!({"path": out("a.dxf")}));
|
||||
refused(&mut s, "execute", json!({"command": "saveas", "params": {"path": out("b.dxf")}}));
|
||||
refused(&mut s, "execute", json!({"command": "wblock", "params": {"path": out("c.dxf")}}));
|
||||
refused(&mut s, "render", json!({"path": out("d.png")}));
|
||||
let _ = call(&mut s, 97, "tools/call", json!({"name": "command_line", "arguments": {"text": format!("zoom e save {}", out("e.dxf"))}}));
|
||||
let _ = call(&mut s, 96, "tools/call", json!({"name": "script", "arguments": {"text": format!("circle 0,0 1\nsave {}\n", out("f.dxf"))}}));
|
||||
let written: Vec<_> = std::fs::read_dir(&outside).unwrap().filter_map(Result::ok).map(|e| e.file_name()).collect();
|
||||
assert!(written.is_empty(), "nothing is written outside the roots: {written:?}");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
+69
@@ -32,6 +32,75 @@ Example client configuration (Claude Code / Claude Desktop):
|
||||
{ "mcpServers": { "cadcraft": { "command": "cadcraft-cli", "args": ["mcp"] } } }
|
||||
```
|
||||
|
||||
## Confining file access
|
||||
|
||||
```sh
|
||||
cadcraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project/out
|
||||
```
|
||||
|
||||
The two flags (PhotoCraft, VectorCraft and the other Craft apps take the same ones, so one client
|
||||
configuration works across the suite) keep the agent to the folders you give it:
|
||||
|
||||
- Every file a command **reads** must lie inside the **read root or the write root**: `open`,
|
||||
`recover`, `compare`, `script`, `import`, `insert`, `xattach` and every xref it loads, `new`
|
||||
templates, `appload` and LISP `load`/`open`, support files (`linetype`, `hatch.patterns`,
|
||||
`aliasedit`, `reinit`), data links, plot style and plotter configuration files named by a path,
|
||||
and the shared plotter settings folder.
|
||||
- Every file a command **writes** must lie inside the **write root**: `save`/`qsave`/`saveas`
|
||||
(including the temporary file and `.bak` written beside the destination), `export`, `plot`, `publish`,
|
||||
`pdfbook`, `wblock`, data extraction, table export, plot style and plotter saves, the shared
|
||||
plotter settings folder, and `render {path}`. The write root itself is refused: a save's
|
||||
temporary file would sit beside it, outside the root.
|
||||
- Give the same folder twice for both. A root left out grants none of its *own* access: a read
|
||||
root allows no writes, while a write root still allows reads inside it (files the agent wrote it
|
||||
can read back). Without either flag nothing changes.
|
||||
- A path is made absolute against the server's working directory, then its links are followed: a
|
||||
file or folder link that leads out of a root is outside it. For a file that doesn't exist yet,
|
||||
its nearest existing folder's links are followed and the rest must be plain names, so `..` below
|
||||
a folder that doesn't exist is refused, as is a link that leads nowhere. The result is compared
|
||||
with the root by whole folder names, exactly: `/work2/x` is not inside `/work`, and on Windows
|
||||
a folder's own case comes from the file system, so a case-sensitive folder's `Root` is not
|
||||
`root`. On Windows a UNC path (`\\server\share`, `\\?\UNC\...`, including `\\host@SSL\...`) is
|
||||
refused before it is opened unless a root is on that same server and share. A device path
|
||||
(`\\.\...`) is refused unless a root uses the same device, and a verbatim path that isn't a
|
||||
disk is refused unless a root uses the same prefix. Device names (`CON`, `NUL`, `COM1`,
|
||||
`LPT¹`…) are refused too.
|
||||
- A path you write must also stand under the write root: a link outside it pointing in is refused,
|
||||
because a drawing's `.bak` goes beside the link and a delete removes the link.
|
||||
- A refused path in a tool other than `command_line` is an ordinary tool error with `isError: true`
|
||||
that the agent can read and correct, for example `automation path rejected: outside the write root
|
||||
/work/project/out: /etc/x.png`, `automation path rejected: outside the read root (or the write
|
||||
root): /etc/x.png`, `automation path rejected: the write root itself cannot be written:
|
||||
/work/project/out`, `automation path rejected: UNC paths are refused unless a root is on the
|
||||
same server and share: \\203.0.113.5\s\x.dwg`, or `automation filesystem access is not granted:
|
||||
write authority is absent: /work/project/out/x.png`.
|
||||
- A refused path in a `command_line` line is not a tool error: the reply is an ordinary result, with
|
||||
the refusal in its `error` field (and echoed in `output`) and without `isError`. A client that
|
||||
drives `command_line` has to read `error`.
|
||||
- A file a drawing names is held to the roots too: an image or xref saved with a path outside them is
|
||||
not loaded from there, and the answer doesn't say whether the file exists. As without roots, a file
|
||||
of the same name beside the host drawing is tried next, so when one is there and inside the roots
|
||||
it is loaded in its place: check what a reference loaded when it matters.
|
||||
- A command runs under the roots only if it is classified (`crates/engine/src/file_access/commands.rs`):
|
||||
one nobody classified is refused, whatever it does. `drawingrecovery` is refused, and SAVEFILEPATH
|
||||
can't be changed, because both work on the server's autosave folder.
|
||||
- SHX fonts beside an opened drawing are searched, and each file the search would open there is
|
||||
checked against the roots first, whatever its name: a font that is a link leading out of the
|
||||
roots is skipped, and the rest of the folder is still used.
|
||||
- The server itself still reads the system's fonts, from the system font folders and
|
||||
`CADCRAFT_SHXPATH`. Their paths come from the server's setup, never from the agent, but a font file
|
||||
named by a drawing can decide which of them is read.
|
||||
- The roots must be existing folders; a missing one stops the server with an error. Each flag is
|
||||
given once (`--flag <dir>` or `--flag=<dir>`).
|
||||
|
||||
The flags confine the headless server. `--connect` with them is an error, since the server would
|
||||
otherwise talk to an app that isn't confined; the app's control channel does not take them yet
|
||||
(#1585). Without `--connect` the server writes the files itself, so every check happens here.
|
||||
|
||||
A path is checked, then opened: another program on the computer that swaps in a link between the two
|
||||
can still win that race, and a hard link can't be told from a file. Use the operating system's
|
||||
sandbox as well if other programs can change these folders.
|
||||
|
||||
## Tools
|
||||
|
||||
| Tool | What it does |
|
||||
|
||||
Reference in New Issue
Block a user