mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-28 08:45:12 -06:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f526120996 | ||
|
|
8eb26836e3 |
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1408289866,
|
||||
"producer_workflow_id": 429719786,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
|
||||
@@ -34,26 +34,12 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
with:
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
app-name: cadcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the release environment and export its keys; that environment must
|
||||
# admit nightly-signer alongside release before the first dispatch.
|
||||
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
with:
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
app-name: cadcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
|
||||
@@ -72,8 +72,6 @@ Layout:
|
||||
|
||||
Checks for the crates you changed: `cargo test -p <crate>`, `cargo clippy -p <crate> --all-targets -- -D warnings`, `cargo xtask layers`, `cargo xtask assets`, `cargo xtask wasm`, `cargo xtask parity` (regenerates `docs/parity-checklist.md`).
|
||||
|
||||
Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a covered menu item `headless: yes` because its command is in the engine registry that `cadcraft-cli` and the MCP server load. An uncovered item takes `no`/`partial` and a `reach` (`window`, `os`, `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs` (a path ending in ` > ` covers its submenu), or reads `unknown`. Never write `yes` there. A covered leaf is `yes` whatever its marks say, so a submenu mark stays while any leaf under it is uncovered; drop a mark only once commands cover every leaf it matches (the check then fails on it as stale).
|
||||
|
||||
Paths and conventions:
|
||||
|
||||
- No crate allows `unsafe` (`unsafe_code = "forbid"` in the workspace).
|
||||
|
||||
Generated
+12
@@ -887,9 +887,11 @@ dependencies = [
|
||||
"craft-jsonrpc",
|
||||
"craft-mcp",
|
||||
"getrandom 0.4.3",
|
||||
"hmac",
|
||||
"libc",
|
||||
"log",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tiny-skia",
|
||||
]
|
||||
|
||||
@@ -2065,6 +2067,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3230,6 +3233,15 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
|
||||
+2
-2
@@ -16,7 +16,7 @@ CADCraft treats these as untrusted, and a way past these defences is a vulnerabi
|
||||
|
||||
- **Drawing files.** Opening a DXF, DWG or other file must not run code, write outside the paths the user chose, or crash the app. Panics are bugs too, but memory exhaustion or a decoder abort on a crafted file is the more serious case.
|
||||
- **AutoLISP in a drawing's folder.** A drawing must not run code that the user didn't choose to load.
|
||||
- **The control channel.** It listens on loopback only and needs the session token from an owner-only file on every request. Another local account reaching it without that token is a vulnerability.
|
||||
- **The control channel.** It listens on loopback only and needs the session token from an owner-only file on every request. Another local account reaching it without that token is a vulnerability. The MCP bridge sends requests only to a server that proves it holds the token, so a program listening on the port in the app's place gets none.
|
||||
- **Temporary and autosave files.** Autosave files are unsaved drawings: another account must not be able to read them or redirect a write through them.
|
||||
- **Updates.** A release must not be replaceable by someone other than the project.
|
||||
|
||||
@@ -25,7 +25,7 @@ CADCraft treats these as untrusted, and a way past these defences is a vulnerabi
|
||||
These are known and being worked on, so they don't need a report:
|
||||
|
||||
- Agents connected through MCP or the control channel can read and write any path the user can. There are no workspace roots yet.
|
||||
- A local process can make the control channel buffer up to 512 MiB before its token is checked. The total is capped, so this can slow the app but not exhaust memory without limit.
|
||||
- A local process without the token can hold the control channel's 16 connections for up to 10 seconds at a time, with at most 64 KiB of request line each, so it can keep an agent from reaching the app while it keeps reconnecting. It can't make the app run anything.
|
||||
- The DWG worker process has no memory limit of its own yet, so a crafted file can use a lot of memory before it stops. It ends that one open or save, not the app.
|
||||
- The web build has no autosave yet.
|
||||
|
||||
|
||||
@@ -60,10 +60,19 @@ fn no_connect_still_serves_headless() {
|
||||
fn connect_with_address_routes_to_that_endpoint() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback");
|
||||
let addr = listener.local_addr().expect("local addr").to_string();
|
||||
let port = listener.local_addr().expect("local addr").port();
|
||||
// As the app does: write the session token, and prove holding it when the bridge says hello.
|
||||
let token = cadcraft_mcp::control_token::issue(port).expect("issue token");
|
||||
let server = std::thread::spawn(move || {
|
||||
let (conn, _) = listener.accept().expect("accept");
|
||||
let mut reader = BufReader::new(conn.try_clone().expect("clone"));
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).expect("read hello");
|
||||
let hello: Value = serde_json::from_str(&line).expect("json hello");
|
||||
assert_eq!(hello["method"], "hello", "the bridge says hello first: {line}");
|
||||
let proof = cadcraft_mcp::control_token::server_proof(&token, hello["params"]["nonce"].as_str().unwrap_or_default());
|
||||
writeln!(&conn, "{}", json!({"id": hello["id"], "ok": true, "result": {"proof": proof}})).expect("write proof");
|
||||
line.clear();
|
||||
reader.read_line(&mut line).expect("read request");
|
||||
let req: Value = serde_json::from_str(&line).expect("json request");
|
||||
let reply = json!({"id": req["id"], "ok": true, "result": {"fixture": "loopback"}});
|
||||
@@ -75,6 +84,7 @@ fn connect_with_address_routes_to_that_endpoint() {
|
||||
let out = mcp(&["--connect", &addr], &format!("{INIT}\n{call}\n"));
|
||||
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
|
||||
let req = server.join().expect("server thread");
|
||||
cadcraft_mcp::control_token::revoke(port);
|
||||
assert_eq!(req["method"], "ui.inspect");
|
||||
let r = replies(&out);
|
||||
let instructions = r.iter().find(|v| v["id"] == 1).and_then(|v| v["result"]["instructions"].as_str()).unwrap_or_default();
|
||||
|
||||
@@ -5,15 +5,19 @@
|
||||
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
|
||||
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
|
||||
//! ([`Limits`]): simultaneous connections, request line length (shorter until a request on the
|
||||
//! connection has carried the token), queued requests, and how long a socket may sit idle or
|
||||
//! blocked on a write.
|
||||
//! connection has carried the token), queued requests, how long a connection may stay open before
|
||||
//! it has shown the token, and how long a socket may sit idle or blocked on a write.
|
||||
//!
|
||||
//! A `hello` with a nonce is answered before the token check with a proof that the server holds
|
||||
//! the token ([`cadcraft_mcp::control_token::server_proof`]), so a client can tell the app from
|
||||
//! another program on the port before it sends anything else (#1925).
|
||||
|
||||
use std::io::{BufRead, BufReader, ErrorKind, Write};
|
||||
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use cadcraft_ui_egui::ControlRequest;
|
||||
use serde_json::{Value, json};
|
||||
@@ -33,6 +37,9 @@ struct Limits {
|
||||
total_bytes: usize,
|
||||
/// Requests waiting for the app at once; more are answered `busy`.
|
||||
queue: usize,
|
||||
/// How long a connection may stay open before a request on it has carried the right token; it
|
||||
/// is closed then, so peers without the token can't hold the connection slots (#1925).
|
||||
preauth_time: Duration,
|
||||
/// How long a connection may go without sending a byte before it is closed.
|
||||
idle_timeout: Duration,
|
||||
/// How long a reply write may block before the connection is closed.
|
||||
@@ -51,6 +58,7 @@ impl Default for Limits {
|
||||
// Room for one maximal request plus smaller ones, not `max_clients` maximal ones.
|
||||
total_bytes: 512 * 1024 * 1024,
|
||||
queue: 64,
|
||||
preauth_time: cadcraft_mcp::control_token::MAX_UNAUTHENTICATED_TIME,
|
||||
idle_timeout: Duration::from_secs(600),
|
||||
write_timeout: Duration::from_secs(30),
|
||||
reply_timeout: Duration::from_secs(60),
|
||||
@@ -338,6 +346,47 @@ fn is_http_request_line(text: &str) -> bool {
|
||||
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
|
||||
}
|
||||
|
||||
/// The method a client sends, before any request with the token, to have the server prove it holds
|
||||
/// the token.
|
||||
const HELLO: &str = "hello";
|
||||
|
||||
/// `hello`'s parameters.
|
||||
#[derive(serde::Deserialize)]
|
||||
struct HelloParams {
|
||||
nonce: String,
|
||||
}
|
||||
|
||||
/// The proof answering a `hello` with `params`, or the error that closes the connection.
|
||||
fn hello_proof(params: Option<&serde_json::value::RawValue>, token: &str) -> Result<String, String> {
|
||||
let nonce = params.and_then(|p| serde_json::from_str::<HelloParams>(p.get()).ok()).map(|p| p.nonce).unwrap_or_default();
|
||||
if !cadcraft_mcp::control_token::valid_nonce(&nonce) {
|
||||
let digits = &cadcraft_mcp::control_token::NONCE_DIGITS;
|
||||
return Err(format!("`hello` needs a `nonce` of {} to {} hexadecimal digits; closing the connection", digits.start(), digits.end()));
|
||||
}
|
||||
Ok(cadcraft_mcp::control_token::server_proof(token, &nonce))
|
||||
}
|
||||
|
||||
/// A connection's read side. Until `until` (the end of [`Limits::preauth_time`]), each read waits
|
||||
/// at most until then, however the bytes trickle in; after it, reads fail as timed out.
|
||||
struct Timed {
|
||||
stream: TcpStream,
|
||||
idle: Duration,
|
||||
until: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Read for Timed {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
if let Some(until) = self.until {
|
||||
let left = until.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Err(std::io::Error::new(ErrorKind::TimedOut, "no request with the control token in time"));
|
||||
}
|
||||
self.stream.set_read_timeout(Some(left.min(self.idle)))?;
|
||||
}
|
||||
self.stream.read(buf)
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve bounded JSON lines, authenticating each request before enqueueing it for the UI.
|
||||
/// Invalid credentials close the connection; queue and reply limits report whether a request ran.
|
||||
fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context, limits: Limits, token: &str, budget: Budget) {
|
||||
@@ -346,7 +395,8 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
|
||||
}
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let mut out = stream;
|
||||
let mut reader = BufReader::new(read);
|
||||
let until = Instant::now().checked_add(limits.preauth_time);
|
||||
let mut reader = BufReader::new(Timed { stream: read, idle: limits.idle_timeout, until });
|
||||
let mut buf = Vec::new();
|
||||
let mut held = Held::new(budget);
|
||||
// The token is checked only after the whole line is read, so until a request here has carried
|
||||
@@ -368,6 +418,17 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
|
||||
Ok(true) => match parse_line(&buf) {
|
||||
Line::Blank => continue,
|
||||
Line::Reject(e) => e,
|
||||
// Answered without the token and without authenticating the connection: the proof
|
||||
// shows the token is known here, not that the peer knows it.
|
||||
Line::Request { id, method, params, .. } if method == HELLO => match hello_proof(params, token) {
|
||||
Ok(proof) => {
|
||||
if writeln!(out, "{}", json!({"id": id, "ok": true, "result": {"proof": proof}})).is_err() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Line::Request { id, method, params, token: given } => {
|
||||
// Authenticate the peer before dispatching: loopback TCP does not identify the
|
||||
// OS user, so only a client holding the owner-only session token may drive the
|
||||
@@ -380,7 +441,14 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
|
||||
let _ = writeln!(out, "{r}");
|
||||
break;
|
||||
}
|
||||
authenticated = true;
|
||||
if !authenticated {
|
||||
authenticated = true;
|
||||
let timed = reader.get_mut();
|
||||
timed.until = None;
|
||||
if timed.stream.set_read_timeout(Some(limits.idle_timeout)).is_err() {
|
||||
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())) {
|
||||
@@ -744,6 +812,87 @@ mod tests {
|
||||
assert_eq!((v["ok"].as_bool(), v["method"].as_str()), (Some(true), Some("ping")), "{line}");
|
||||
}
|
||||
|
||||
/// A `hello` line with `nonce` and no token.
|
||||
fn hello_line(nonce: &str) -> String {
|
||||
json!({"id": "h", "method": "hello", "params": {"nonce": nonce}}).to_string() + "\n"
|
||||
}
|
||||
|
||||
/// A `hello` is answered with a proof of the token before any token has been shown, and the
|
||||
/// connection stays open for requests; the `hello` itself authenticates nothing.
|
||||
#[test]
|
||||
fn a_hello_is_answered_with_a_proof_of_the_token() {
|
||||
let addr = serve_echo_with(preauth());
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut r = BufReader::new(c.try_clone().unwrap());
|
||||
let nonce = cadcraft_mcp::control_token::new_nonce().unwrap();
|
||||
c.write_all(hello_line(&nonce).as_bytes()).unwrap();
|
||||
let mut line = String::new();
|
||||
r.read_line(&mut line).unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(v["id"], "h", "{line}");
|
||||
let proof = v["result"]["proof"].as_str().unwrap();
|
||||
assert!(cadcraft_mcp::control_token::verify_server_proof(TEST_TOKEN, &nonce, proof), "{line}");
|
||||
assert!(!line.contains(TEST_TOKEN), "the token itself is never sent");
|
||||
// Still unauthenticated: a line past the preauth bound is refused…
|
||||
let refused = exchange(addr, format!("{}{}", hello_line(&nonce), long_req_line(1, 2000)).as_bytes());
|
||||
assert_eq!(refused.len(), 2, "{refused:?}");
|
||||
assert!(refused[1]["error"].as_str().unwrap().contains("longer than 1000 bytes"), "{refused:?}");
|
||||
// …and a request with the token after the hello goes through on the same connection.
|
||||
c.write_all(req_line(2, "ping").as_bytes()).unwrap();
|
||||
line.clear();
|
||||
r.read_line(&mut line).unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!((v["id"].as_i64(), v["method"].as_str()), (Some(2), Some("ping")), "{line}");
|
||||
}
|
||||
|
||||
/// A `hello` without a usable nonce gets an error and the connection is closed.
|
||||
#[test]
|
||||
fn a_hello_without_a_usable_nonce_closes_the_connection() {
|
||||
let addr = serve_echo();
|
||||
for bad in [r#"{"method":"hello"}"#.to_string(), hello_line("abc").trim_end().to_string(), hello_line(&"z".repeat(64)).trim_end().to_string()]
|
||||
{
|
||||
let replies = exchange(addr, format!("{bad}\n{}", req_line(1, "ping")).as_bytes());
|
||||
assert_eq!(replies.len(), 1, "{bad}: {replies:?}");
|
||||
assert!(replies[0]["error"].as_str().unwrap().contains("`nonce`"), "{bad}: {replies:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection that doesn't show the token within `preauth_time` is closed even while it keeps
|
||||
/// sending (a byte at a time, or `hello`s), so peers without the token can't hold the slots;
|
||||
/// one that has shown it stays open past that time.
|
||||
#[test]
|
||||
fn a_connection_that_never_shows_the_token_is_closed_in_time() {
|
||||
let limits = Limits { preauth_time: Duration::from_millis(400), idle_timeout: Duration::from_secs(5), ..short() };
|
||||
let addr = serve_echo_with(limits);
|
||||
let nonce = cadcraft_mcp::control_token::new_nonce().unwrap();
|
||||
for trickle in [b"{".to_vec(), hello_line(&nonce).into_bytes()] {
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let reader = std::thread::spawn({
|
||||
let c = c.try_clone().unwrap();
|
||||
move || BufReader::new(c).lines().count()
|
||||
});
|
||||
let t = std::time::Instant::now();
|
||||
while c.write_all(&trickle).is_ok() && t.elapsed() < Duration::from_secs(4) && !reader.is_finished() {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
assert!(reader.is_finished() && t.elapsed() < Duration::from_secs(3), "still open after {:?}", t.elapsed());
|
||||
let _ = reader.join();
|
||||
}
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut r = BufReader::new(c.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
c.write_all(req_line(1, "ping").as_bytes()).unwrap();
|
||||
r.read_line(&mut line).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(700));
|
||||
c.write_all(req_line(2, "pong").as_bytes()).unwrap();
|
||||
line.clear();
|
||||
r.read_line(&mut line).unwrap();
|
||||
assert!(line.contains("pong"), "an authenticated connection outlives the preauth time: {line:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_connections_are_refused() {
|
||||
let addr = serve_echo();
|
||||
|
||||
@@ -185,56 +185,11 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recognise the shared portable data namespace in both the supplied and resolved path.
|
||||
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
|
||||
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
|
||||
@@ -335,8 +290,6 @@ const EFRAME_APP_ID: &str = "ai.storyteller.cadcraft";
|
||||
/// The subfolder autosave and Drawing Recovery write ([`crate::main`], `<settings>/autosave`).
|
||||
pub const AUTOSAVE: &str = "autosave";
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 6] = [AUTOSAVE, "logs", "support", "single-instance", "plotters", "crash-reports"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -521,31 +474,6 @@ mod tests {
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data");
|
||||
for name in [AUTOSAVE, "logs", "support", "single-instance", "plotters", "crash-reports"] {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
|
||||
let mut fixture = Fixture::new();
|
||||
|
||||
@@ -399,9 +399,7 @@ impl EntityKind {
|
||||
t3(p);
|
||||
}
|
||||
if let DimKind::Linear { rotation } = &mut d.kind {
|
||||
// A mirror reflects the dimension line's direction about the mirror line:
|
||||
// `rot` is twice the mirror line's angle, so `a` lands at `rot - a`.
|
||||
*rotation = cadcraft_geom::norm_angle(if mirror { rot - *rotation } else { *rotation + rot });
|
||||
*rotation = cadcraft_geom::norm_angle(*rotation + rot);
|
||||
}
|
||||
d.marks.transform(&t3, rot, s, mirror);
|
||||
d.block = None;
|
||||
|
||||
@@ -100,9 +100,7 @@ impl DimMarks {
|
||||
/// Transform the points and angles (part of [`super::EntityKind::transform`]).
|
||||
pub(super) fn transform(&mut self, t3: &dyn Fn(&mut Vec3), rot: f64, s: f64, mirror: bool) {
|
||||
if let Some(a) = &mut self.oblique {
|
||||
// A mirror reflects a direction about the mirror line: `rot` is the transformed X
|
||||
// axis (twice the mirror line's angle), so a direction `a` lands at `rot - a`.
|
||||
*a = cadcraft_geom::norm_angle(if mirror { rot - *a } else { *a + rot });
|
||||
*a = cadcraft_geom::norm_angle(if mirror { rot - (*a - rot) } else { *a + rot });
|
||||
}
|
||||
if let Some(j) = &mut self.jog_line {
|
||||
t3(j);
|
||||
|
||||
@@ -112,8 +112,7 @@ pub struct Drawing {
|
||||
/// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name.
|
||||
pub dim_styles: NamedList<DimStyle>,
|
||||
pub mleader_styles: Vec<MLeaderStyle>,
|
||||
/// Table styles in table order; looked up by name with [`NamedList::by_name`].
|
||||
pub table_styles: NamedList<TableStyle>,
|
||||
pub table_styles: Vec<TableStyle>,
|
||||
/// Multiline styles (MLSTYLE); STANDARD is always there.
|
||||
pub mline_styles: Vec<MLineStyle>,
|
||||
/// Block definitions by name; [`Drawing::block`] looks them up.
|
||||
@@ -196,7 +195,7 @@ impl Drawing {
|
||||
d.scales = metric_scales();
|
||||
d.dim_styles.push(DimStyle::iso25());
|
||||
d.mleader_styles = vec![MLeaderStyle::metric()];
|
||||
d.table_styles = vec![TableStyle::metric()].into();
|
||||
d.table_styles = vec![TableStyle::metric()];
|
||||
d.header.set_str("DIMSTYLE", "ISO-25");
|
||||
d
|
||||
}
|
||||
@@ -214,7 +213,7 @@ impl Drawing {
|
||||
text_styles: vec![TextStyle::default()].into(),
|
||||
dim_styles: vec![DimStyle::default()].into(),
|
||||
mleader_styles: vec![MLeaderStyle::default()],
|
||||
table_styles: vec![TableStyle::default()].into(),
|
||||
table_styles: vec![TableStyle::default()],
|
||||
mline_styles: vec![MLineStyle::default()],
|
||||
blocks: NamedMap::default(),
|
||||
model: EntityStore::new(),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles,
|
||||
//! table styles and layouts), whose names are looked up without case through an index instead of a
|
||||
//! scan once a table is large and looked up often.
|
||||
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles
|
||||
//! and layouts), whose names are looked up without case through an index instead of a scan once a
|
||||
//! table is large and looked up often.
|
||||
//!
|
||||
//! [`Drawing::layer`](crate::Drawing::layer), [`Drawing::block`](crate::Drawing::block) and the
|
||||
//! other lookups by name run for every entity while a drawing is read, measured and drawn, and
|
||||
@@ -117,11 +117,11 @@ macro_rules! named_by_field {
|
||||
}
|
||||
)*};
|
||||
}
|
||||
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::TableStyle, crate::Layout);
|
||||
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::Layout);
|
||||
|
||||
/// A list of named entries in their own order (the drawing's layers, linetypes, text styles,
|
||||
/// dimension styles, table styles and layouts). It reads and changes as a `Vec`;
|
||||
/// [`NamedList::by_name`] finds the first entry of a name without case.
|
||||
/// dimension styles and layouts). It reads and changes as a `Vec`; [`NamedList::by_name`] finds the
|
||||
/// first entry of a name without case.
|
||||
pub struct NamedList<T> {
|
||||
list: Vec<T>,
|
||||
index: Lazy<usize>,
|
||||
|
||||
+1
-41
@@ -29,7 +29,7 @@ fn new_metric_drawing_has_metric_multileader_and_table_styles() {
|
||||
|
||||
let i = Drawing::new_imperial();
|
||||
assert_eq!(i.mleader_styles, vec![MLeaderStyle::default()]);
|
||||
assert_eq!(*i.table_styles, vec![TableStyle::default()]);
|
||||
assert_eq!(i.table_styles, vec![TableStyle::default()]);
|
||||
assert_eq!((i.mleader_styles[0].text_height, i.table_styles[0].text_height), (0.18, 0.18));
|
||||
}
|
||||
|
||||
@@ -271,46 +271,6 @@ fn transform_arc_mirror_keeps_shape() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirroring_a_rotated_dimension_reflects_its_direction() {
|
||||
let dim = |kind: DimKind, marks: DimMarks| {
|
||||
EntityKind::Dimension(Dimension {
|
||||
kind,
|
||||
defpt: Vec3::ZERO,
|
||||
text_mid: Vec3::ZERO,
|
||||
p13: Vec3::ZERO,
|
||||
p14: Vec3::new(7.071_067_811_865_475, 7.071_067_811_865_475, 0.0),
|
||||
p15: Vec3::ZERO,
|
||||
p16: Vec3::ZERO,
|
||||
text: String::new(),
|
||||
style: "Standard".into(),
|
||||
measurement: 10.0,
|
||||
text_rotation: 0.0,
|
||||
user_text_pos: false,
|
||||
block: None,
|
||||
insertion_point: Vec3::ZERO,
|
||||
overrides: Default::default(),
|
||||
assoc: vec![],
|
||||
marks,
|
||||
})
|
||||
};
|
||||
// A dimension line at 45° mirrored across the X axis runs at -45° (315°) and still measures 10.
|
||||
let mut k = dim(DimKind::Linear { rotation: std::f64::consts::FRAC_PI_4 }, DimMarks::default());
|
||||
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::X));
|
||||
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
|
||||
let DimKind::Linear { rotation } = d.kind else { panic!("a linear dimension") };
|
||||
assert!((rotation - 7.0 * std::f64::consts::FRAC_PI_4).abs() < 1e-9, "{rotation}");
|
||||
let p2 = Vec2::new(7.071_067_811_865_475, -7.071_067_811_865_475);
|
||||
assert!((p2.dot(Vec2::from_angle(rotation)).abs() - 10.0).abs() < 1e-9, "the mirrored measurement");
|
||||
|
||||
// Oblique extension lines reflect about the mirror line too (a 45° line here) instead of
|
||||
// being double-reflected (120° rather than 30°).
|
||||
let mut k = dim(DimKind::Aligned, DimMarks { oblique: Some(std::f64::consts::FRAC_PI_3), ..DimMarks::default() });
|
||||
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::new(1.0, 1.0)));
|
||||
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
|
||||
assert!((d.marks.oblique.unwrap_or(0.0) - (std::f64::consts::FRAC_PI_2 - std::f64::consts::FRAC_PI_3)).abs() < 1e-9, "{:?}", d.marks.oblique);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_bounds_with_cyclic_block_terminate() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! that contain themselves lose the reference that closes the loop, and objects sharing a handle
|
||||
//! get new ones.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::{Block, DimStyle, Drawing, Entity, EntityKind, EntityStore, Handle, Layer, Linetype, MLeaderStyle, TableStyle, TextStyle};
|
||||
@@ -425,9 +425,6 @@ fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
|
||||
let all = all_handles(d);
|
||||
let ok_text = |d: &Drawing, n: &str| d.text_style(n).is_some();
|
||||
let ok_dim = |d: &Drawing, n: &str| d.dim_style(n).is_some();
|
||||
// Multileader style names, lower-cased, built once: a scan per multileader made a file of N of
|
||||
// them naming styles among N quadratic to audit (#1924).
|
||||
let mleader_styles: BTreeSet<String> = d.mleader_styles.iter().map(|s| s.name.to_ascii_lowercase()).collect();
|
||||
// Missing names, counted: (what, name) → (objects, first location).
|
||||
let mut counts: BTreeMap<(&'static str, String), (usize, String)> = BTreeMap::new();
|
||||
missing_layers(d, out);
|
||||
@@ -465,12 +462,12 @@ fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
|
||||
if let Some(t) = &mut m.text {
|
||||
text_style(&mut t.style);
|
||||
}
|
||||
if !mleader_styles.contains(&m.style.to_ascii_lowercase()) {
|
||||
if !has_name(&d.mleader_styles, &m.style, |s| &s.name) {
|
||||
note("multileader style", &m.style);
|
||||
m.style = "Standard".into();
|
||||
}
|
||||
}
|
||||
EntityKind::Table(t) if d.table_styles.by_name(&t.style).is_none() => {
|
||||
EntityKind::Table(t) if !has_name(&d.table_styles, &t.style, |s| &s.name) => {
|
||||
note("table style", &t.style);
|
||||
t.style = "Standard".into();
|
||||
}
|
||||
|
||||
@@ -270,7 +270,7 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
|
||||
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name).into();
|
||||
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name).into();
|
||||
d.mleader_styles = pick(&src.mleader_styles, &used.mleader_styles, |t| &t.name);
|
||||
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name).into();
|
||||
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name);
|
||||
d.blocks = src.blocks.iter().filter(|(k, _)| used.blocks.contains(&up(k))).map(|(k, b)| (k.clone(), b.clone())).collect();
|
||||
d.layouts.clear();
|
||||
d
|
||||
|
||||
@@ -26,10 +26,6 @@ fn default_max_arc_len(s: &Session, min: f64) -> f64 {
|
||||
s.doc().ok().map_or(min, |d| d.header.f64("CADCRAFT_REVCLOUDMAXARCLEN", min)).max(min)
|
||||
}
|
||||
|
||||
/// The bulge of every arc of a revision cloud (an arc of about 110°). Readers that check
|
||||
/// `RevcloudProps` xdata and bulge accept a closed polyline whose bulges are within 0.02 of this.
|
||||
const CLOUD_BULGE: f64 = 0.520567050552;
|
||||
|
||||
/// Bulged closed polyline vertices for a revision cloud around `boundary`.
|
||||
pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, reverse: bool) -> Option<Vec<PolyVertex>> {
|
||||
let mut pts: Vec<Vec2> = Vec::new();
|
||||
@@ -73,7 +69,7 @@ pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, re
|
||||
out.extend(chain.at_length_in(&ends, perim * j as f64 / k as f64).map(|x| x.0));
|
||||
}
|
||||
}
|
||||
let b = if reverse { -CLOUD_BULGE } else { CLOUD_BULGE };
|
||||
let b = if reverse { -0.5 } else { 0.5 };
|
||||
Some(out.into_iter().map(|p| PolyVertex::with_bulge(p, b)).collect())
|
||||
}
|
||||
|
||||
|
||||
@@ -258,7 +258,7 @@ fn run_cellstyle_use(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(v) => v.as_str().map(|x| x.trim().to_string()).ok_or_else(|| bad(id, "`style` must be a cell style name"))?,
|
||||
None => return Err(bad(id, "`style` (cell style name) is required")),
|
||||
};
|
||||
let styles: Vec<TableStyle> = s.doc()?.table_styles.to_vec();
|
||||
let styles: Vec<TableStyle> = s.doc()?.table_styles.clone();
|
||||
edit(s, p, id, |t| {
|
||||
let st = styles.iter().find(|x| x.name.eq_ignore_ascii_case(&t.style)).cloned().unwrap_or_default();
|
||||
if !name.is_empty() && !st.has_cell_style(&name) {
|
||||
|
||||
@@ -224,54 +224,6 @@ fn audit_at_the_command_line_asks_before_fixing() {
|
||||
assert_eq!(s.execute("audit", &json!({})).unwrap()["errors"], 0);
|
||||
}
|
||||
|
||||
/// Many multileaders and tables naming styles the drawing lacks, among many styles, are audited in
|
||||
/// linear time (#1924). As before, each is set to Standard, and one naming a style in other case is
|
||||
/// left as it is. The names share their first 200 bytes, so comparing two costs about that.
|
||||
#[test]
|
||||
fn many_objects_naming_missing_styles_audit_quickly() {
|
||||
use cadcraft_engine::doc::{MLeader, MLeaderStyle, Table, TableStyle};
|
||||
const N: usize = 10_000;
|
||||
let name = |kind: char, i: usize| format!("{kind}{}{i:06}", "x".repeat(199));
|
||||
let missing = |kind: char| format!("{kind}{}z{:05}", "x".repeat(199), 0);
|
||||
let mleader = |style: String| {
|
||||
EntityKind::MLeader(MLeader {
|
||||
leaders: vec![vec![Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0)]],
|
||||
landing: Vec3::new(2.0, 1.0, 0.0),
|
||||
dogleg: 0.5,
|
||||
text: None,
|
||||
style,
|
||||
arrow_size: 1.0,
|
||||
spline: false,
|
||||
block: None,
|
||||
})
|
||||
};
|
||||
let table = |style: String| EntityKind::Table(Table { style, ..Table::default() });
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.mleader_styles.extend((0..N).map(|i| MLeaderStyle { name: name('M', i), ..MLeaderStyle::default() }));
|
||||
d.table_styles.extend((0..N).map(|i| TableStyle { name: name('T', i), ..TableStyle::default() }));
|
||||
for _ in 0..N {
|
||||
raw(&mut d, &Space::Model, Common::default(), mleader(missing('M')));
|
||||
raw(&mut d, &Space::Model, Common::default(), table(missing('T')));
|
||||
}
|
||||
raw(&mut d, &Space::Model, Common::default(), mleader(name('M', N - 1).to_ascii_uppercase()));
|
||||
raw(&mut d, &Space::Model, Common::default(), table(name('T', N - 1).to_ascii_uppercase()));
|
||||
let started = std::time::Instant::now();
|
||||
cadcraft_engine::audit::repair(&mut d);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
let styles: Vec<&str> = d
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::MLeader(m) => Some(m.style.as_str()),
|
||||
EntityKind::Table(t) => Some(t.style.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(styles.len(), 2 * N + 2);
|
||||
assert!(styles[..2 * N].iter().all(|s| *s == "Standard"), "a missing style is set to Standard");
|
||||
assert_eq!(styles[2 * N..], [name('M', N - 1).to_ascii_uppercase(), name('T', N - 1).to_ascii_uppercase()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_standard_entries_and_layer_zero_are_recreated() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -157,7 +157,6 @@ mod rectang_polygon_order;
|
||||
mod refedit;
|
||||
mod region;
|
||||
mod rename_cmdline;
|
||||
mod revcloud_recognised;
|
||||
mod rotate_reference;
|
||||
mod rotation_grip_input;
|
||||
mod scale_offset_z;
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
//! Readers recognise a saved revision cloud (#1570): a closed polyline with `RevcloudProps`
|
||||
//! xdata whose every arc has bulge 0.520567 (they accept 0.02 either way; 0.5 was just outside).
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Drawing, EntityKind, Handle, RawTag};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const BULGE: f64 = 0.520567050552;
|
||||
|
||||
fn h(v: &Value) -> Handle {
|
||||
v["handle"].as_str().and_then(Handle::parse_hex).unwrap()
|
||||
}
|
||||
|
||||
fn last(s: &Session) -> Handle {
|
||||
s.doc().unwrap().model.iter().last().map(|e| e.handle).unwrap()
|
||||
}
|
||||
|
||||
/// Types `lines` at the command line and returns the one entity that run created. The prompt
|
||||
/// sequence must have finished: a stale script leaves a prompt waiting, and `last` would then be
|
||||
/// the previous entity, whose XDATA this test would wrongly accept. Counts new handles, not
|
||||
/// entities: Object mode erases the picked shape as it adds the cloud.
|
||||
fn typed_cloud(s: &mut Session, lines: &[&str]) -> Handle {
|
||||
let before: Vec<Handle> = s.doc().unwrap().model.iter().map(|e| e.handle).collect();
|
||||
for l in lines {
|
||||
s.cmdline(l).unwrap();
|
||||
}
|
||||
assert!(!s.prompting(), "{lines:?} left a prompt waiting: {}", s.prompt_text());
|
||||
let new: Vec<Handle> = s.doc().unwrap().model.iter().map(|e| e.handle).filter(|h| !before.contains(h)).collect();
|
||||
assert_eq!(new.len(), 1, "{lines:?} must create exactly one entity, got {new:?}");
|
||||
assert_eq!(last(s), new[0], "{lines:?}: the new cloud must be the last entity");
|
||||
new[0]
|
||||
}
|
||||
|
||||
fn props(xdata: &[RawTag]) -> Vec<(i32, String)> {
|
||||
let start = xdata.iter().position(|t| t.code == 1001 && t.value == "RevcloudProps").expect("RevcloudProps xdata");
|
||||
xdata[start..].iter().take_while(|t| t.code != 1001 || t.value == "RevcloudProps").map(|t| (t.code, t.value.trim().to_string())).collect()
|
||||
}
|
||||
|
||||
/// The cloud `h` is what readers take for a cloud: closed, cloud bulges, `RevcloudProps`.
|
||||
fn assert_cloud(d: &Drawing, h: Handle, arc_len: f64) {
|
||||
let e = d.entity(h).unwrap();
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
|
||||
assert!(p.closed);
|
||||
assert!(p.vertices.iter().all(|v| (v.bulge.abs() - BULGE).abs() < 1e-9), "{:?}", p.vertices);
|
||||
let x = props(&e.common.xdata);
|
||||
assert_eq!(x.len(), 3, "{x:?}");
|
||||
assert_eq!(x[1], (1070, "0".to_string()));
|
||||
assert_eq!(x[2].0, 1040);
|
||||
assert!((x[2].1.parse::<f64>().unwrap() - arc_len).abs() < 1e-12, "{x:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_way_of_drawing_a_cloud_is_recognised() {
|
||||
let mut s = Session::new();
|
||||
let rect = h(&s.execute("revcloud", &json!({"p1": [0, 0], "p2": [100, 50], "arcLength": 15})).unwrap());
|
||||
let poly = h(&s.execute("revcloud.polygonal", &json!({"points": [[0, 0], [0, 30], [30, 0]], "arcLength": 5})).unwrap());
|
||||
let rev = h(&s.execute("revcloud.freehand", &json!({"freehand": [[0, 0], [50, 0], [50, 50]], "arcLength": 10, "reverse": true})).unwrap());
|
||||
let circle = h(&s.execute("circle", &json!({"center": [200, 0], "radius": 20})).unwrap());
|
||||
let obj = h(&s.execute("revcloud", &json!({"handle": circle, "arcLength": 4})).unwrap());
|
||||
// Arc length asks the minimum and then the maximum (#1714).
|
||||
let typed = typed_cloud(&mut s, &["revcloud a 2 2", "300,0 320,10"]);
|
||||
s.execute("rectang", &json!({"p1": [400, 0], "p2": [420, 20]})).unwrap();
|
||||
// Object then asks "Reverse direction" after the pick.
|
||||
let picked = typed_cloud(&mut s, &["revcloud a 3 3 o 400,10 n"]);
|
||||
let d = s.doc().unwrap();
|
||||
for (h, a) in [(rect, 15.0), (poly, 5.0), (rev, 10.0), (obj, 4.0), (typed, 2.0), (picked, 3.0)] {
|
||||
assert_cloud(d, h, a);
|
||||
}
|
||||
let EntityKind::LwPolyline(p) = &d.entity(rev).unwrap().kind else { panic!() };
|
||||
assert!(p.vertices.iter().all(|v| v.bulge < 0.0), "a reversed cloud keeps its arcs turned inward");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_cloud_reads_back_as_a_cloud() {
|
||||
let mut s = Session::new();
|
||||
s.execute("revcloud", &json!({"p1": [0, 0], "p2": [100, 50], "arcLength": 15})).unwrap();
|
||||
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let appid = lines.windows(2).any(|w| w[0] == "0" && w[1] == "APPID")
|
||||
&& lines.windows(4).any(|w| w[0] == "AcDbRegAppTableRecord" && w[1] == "2" && w[2] == "RevcloudProps");
|
||||
assert!(appid, "RevcloudProps is a registered application");
|
||||
let read = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
let cloud = read.model.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
|
||||
assert_cloud(&read, cloud, 15.0);
|
||||
}
|
||||
@@ -101,40 +101,6 @@ impl<'a> UcsNames<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries of a list (a table's records, a drawing's styles), by name with its ASCII letters
|
||||
/// lower-cased, each name at the position of its first entry. A later record of a name replaces
|
||||
/// the first, which keeps its place and takes the later record's name. Each record or lookup is
|
||||
/// then a map lookup, not a scan of the list: a file of N records, or of N objects each naming one
|
||||
/// of N styles, cost N² name comparisons (#1924). Ordered by name rather than hashed, so its cost
|
||||
/// does not depend on hash keys.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ByName(std::collections::BTreeMap<String, usize>);
|
||||
|
||||
impl ByName {
|
||||
/// The entries the list starts with; the first of a name is the one kept.
|
||||
pub(crate) fn new<T>(list: &[T], name: impl Fn(&T) -> &str) -> Self {
|
||||
ByName(list.iter().enumerate().rev().map(|(i, t)| (name(t).to_ascii_lowercase(), i)).collect())
|
||||
}
|
||||
|
||||
/// Put `item`, named `name`, in place of the first entry of that name, else at the end.
|
||||
pub(crate) fn put<T>(&mut self, list: &mut Vec<T>, name: &str, item: T) {
|
||||
let key = name.to_ascii_lowercase();
|
||||
match self.0.get(&key).and_then(|&i| list.get_mut(i)) {
|
||||
Some(x) => *x = item,
|
||||
None => {
|
||||
self.0.insert(key, list.len());
|
||||
list.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The position of the first entry named `name` (ignoring ASCII case), while the list has
|
||||
/// changed only through [`ByName::put`] since [`ByName::new`].
|
||||
pub(crate) fn position(&self, name: &str) -> Option<usize> {
|
||||
self.0.get(&name.to_ascii_lowercase()).copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `x` and `y` can be a UCS's axes: finite, not zero and not along each other (relative
|
||||
/// to their lengths, so short but square axes are fine). Read and written by the same rule.
|
||||
pub(crate) fn usable_axes(x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool {
|
||||
|
||||
@@ -453,12 +453,9 @@ fn attribs(d: &Drawing, ins: &Insert, values: &[(String, String)]) -> Vec<Attrib
|
||||
}
|
||||
|
||||
/// What a MULTILEADER record points at in the file being written.
|
||||
pub(crate) struct Refs<'a> {
|
||||
pub(crate) struct Refs {
|
||||
/// MLEADERSTYLE handle.
|
||||
pub style: String,
|
||||
/// The drawing's style of the multileader's style name (the first of that name, ignoring
|
||||
/// case), when it has one.
|
||||
pub style_def: Option<&'a MLeaderStyle>,
|
||||
/// STYLE record handle of the text.
|
||||
pub text_style: Option<String>,
|
||||
/// BLOCK_RECORD handle of the content block.
|
||||
@@ -466,7 +463,7 @@ pub(crate) struct Refs<'a> {
|
||||
}
|
||||
|
||||
/// The groups of a MULTILEADER record after its `AcDbMLeader` marker.
|
||||
pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs<'_>) -> Vec<Tag> {
|
||||
pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec<Tag> {
|
||||
let mut t: Vec<Tag> = Vec::new();
|
||||
let s = |t: &mut Vec<Tag>, c: i32, v: &str| t.push(Tag::s(c, v));
|
||||
let f = |t: &mut Vec<Tag>, c: i32, v: f64| t.push(Tag::f(c, v));
|
||||
@@ -476,7 +473,7 @@ pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs<'_>) -> Vec<Tag> {
|
||||
t.push(Tag::f(c + 10, v.y));
|
||||
t.push(Tag::f(c + 20, v.z));
|
||||
};
|
||||
let style = r.style_def.cloned().unwrap_or_default();
|
||||
let style = d.mleader_styles.iter().find(|x| x.name.eq_ignore_ascii_case(&m.style)).cloned().unwrap_or_default();
|
||||
// Block content wins over text when an entity has both (DXF has one content type).
|
||||
let block = m.block.as_ref().zip(r.block.as_ref());
|
||||
let text = if block.is_some() { None } else { m.text.as_ref() };
|
||||
|
||||
@@ -286,9 +286,7 @@ fn read_style(tags: &[Tag]) -> Option<MLineStyle> {
|
||||
let mut fill = Color::ByLayer;
|
||||
for t in body {
|
||||
match t.code {
|
||||
// Trimmed, as the writer writes it and as multilines look it up: a padded name kept
|
||||
// as read was missed by its multilines' lookup, so a save wrote a second style of it.
|
||||
2 => st.name = t.str().trim().to_string(),
|
||||
2 => st.name = t.str(),
|
||||
3 => st.description = t.str(),
|
||||
70 => flags = t.i64(),
|
||||
51 => st.start_caps.angle = t.f64().to_radians(),
|
||||
@@ -347,11 +345,11 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
}
|
||||
});
|
||||
}
|
||||
// A later style of a name replaces the first.
|
||||
let mut names = crate::dxf_ext::ByName::new(&d.mline_styles, |s| &s.name);
|
||||
for st in styles {
|
||||
let name = st.name.clone();
|
||||
names.put(&mut d.mline_styles, &name, st);
|
||||
match d.mline_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&st.name)) {
|
||||
Some(x) => *x = st,
|
||||
None => d.mline_styles.push(st),
|
||||
}
|
||||
}
|
||||
let by_name: HashMap<String, MLineStyle> = d.mline_styles.iter().map(|s| (key(&s.name), s.clone())).collect();
|
||||
fill(&mut d.model, &by_name);
|
||||
@@ -386,14 +384,12 @@ pub(crate) struct Plan {
|
||||
pub dict: String,
|
||||
/// Each style and its MLINESTYLE handle.
|
||||
styles: Vec<(MLineStyle, String)>,
|
||||
/// The positions of the styles by name.
|
||||
names: crate::dxf_ext::ByName,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
/// The MLINESTYLE handle of style `name` (STANDARD's when it is missing).
|
||||
pub fn handle(&self, name: &str) -> String {
|
||||
let find = |n: &str| self.names.position(n.trim()).and_then(|i| self.styles.get(i)).map(|(_, h)| h.clone());
|
||||
let find = |n: &str| self.styles.iter().find(|(s, _)| s.name.eq_ignore_ascii_case(n.trim())).map(|(_, h)| h.clone());
|
||||
find(name).or_else(|| find(STANDARD_MLINE_STYLE)).unwrap_or_else(|| "0".into())
|
||||
}
|
||||
}
|
||||
@@ -404,18 +400,15 @@ pub(crate) fn plan<'a>(d: &Drawing, every: impl Iterator<Item = &'a Entity>, mut
|
||||
if !list.iter().any(|s| s.name.eq_ignore_ascii_case(STANDARD_MLINE_STYLE)) {
|
||||
list.insert(0, MLineStyle::default());
|
||||
}
|
||||
let mut names = crate::dxf_ext::ByName::new(&list, |s| &s.name);
|
||||
for e in every {
|
||||
if let EntityKind::MLine(m) = &e.kind
|
||||
&& names.position(m.style.trim()).is_none()
|
||||
&& !list.iter().any(|s| s.name.eq_ignore_ascii_case(m.style.trim()))
|
||||
{
|
||||
names.put(&mut list, m.style.trim(), MLineStyle { name: m.style.trim().to_string(), ..m.def.clone() });
|
||||
list.push(MLineStyle { name: m.style.trim().to_string(), ..m.def.clone() });
|
||||
}
|
||||
}
|
||||
let dict = new_handle();
|
||||
let styles: Vec<(MLineStyle, String)> = list.into_iter().filter(|s| !s.name.trim().is_empty()).map(|s| (s, new_handle())).collect();
|
||||
let names = crate::dxf_ext::ByName::new(&styles, |(s, _)| &s.name);
|
||||
Plan { dict, styles, names }
|
||||
Plan { dict, styles: list.into_iter().filter(|s| !s.name.trim().is_empty()).map(|s| (s, new_handle())).collect() }
|
||||
}
|
||||
|
||||
/// The `ACAD_MLINESTYLE` dictionary (owned by the root dictionary `root`) and its styles.
|
||||
|
||||
@@ -2,7 +2,6 @@ use super::common::T;
|
||||
use super::dimassoc::dimassoc;
|
||||
use super::document::sortents_table;
|
||||
use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup, Rx, Tag, Ucs, Vec2, Vec3};
|
||||
use crate::dxf_ext::ByName;
|
||||
|
||||
/// Non-graphical objects applied once every entity is placed.
|
||||
#[derive(Default)]
|
||||
@@ -219,13 +218,14 @@ impl Objects {
|
||||
}
|
||||
|
||||
fn apply_table_styles(&self, d: &mut Drawing) {
|
||||
// Table styles (named by their ACAD_TABLESTYLE dictionary entries); a later style of a
|
||||
// name replaces the first.
|
||||
let mut by_name = ByName::new(&d.table_styles, |s| &s.name);
|
||||
// Table styles (named by their ACAD_TABLESTYLE dictionary entries).
|
||||
for (h, tags) in &self.table_styles {
|
||||
let Some(name) = self.names.get(h).filter(|n| !n.is_empty()) else { continue };
|
||||
let st = crate::dxf_table::read_table_style(name, tags);
|
||||
by_name.put(&mut d.table_styles, name, st);
|
||||
match d.table_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(name)) {
|
||||
Some(x) => *x = st,
|
||||
None => d.table_styles.push(st),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,7 +236,10 @@ impl Objects {
|
||||
// style's, so every cell style height applies as it is.
|
||||
let height = {
|
||||
let style = name.as_deref().unwrap_or("Standard");
|
||||
d.table_styles.by_name(style).map_or(cadcraft_doc::TableStyle::default().text_height, |s| s.text_height)
|
||||
d.table_styles
|
||||
.iter()
|
||||
.find(|s| s.name.eq_ignore_ascii_case(style))
|
||||
.map_or(cadcraft_doc::TableStyle::default().text_height, |s| s.text_height)
|
||||
};
|
||||
let _ = d.modify_entity(*h, |e| {
|
||||
if let EntityKind::Table(t) = &mut e.kind {
|
||||
@@ -250,9 +253,7 @@ impl Objects {
|
||||
}
|
||||
|
||||
fn apply_mleader_styles(&self, d: &mut Drawing, rx: &Rx) {
|
||||
// Multileader styles (named by their ACAD_MLEADERSTYLE dictionary entries); a later style
|
||||
// of a name replaces the first.
|
||||
let mut by_name = ByName::new(&d.mleader_styles, |s| &s.name);
|
||||
// Multileader styles (named by their ACAD_MLEADERSTYLE dictionary entries).
|
||||
for (h, tags) in &self.mleader_styles {
|
||||
let Some(name) = self.names.get(h).filter(|n| !n.is_empty()) else { continue };
|
||||
let t = T(tags);
|
||||
@@ -268,7 +269,10 @@ impl Objects {
|
||||
text_style: text_style.unwrap_or(def.text_style),
|
||||
annotative: t.i(296).unwrap_or(0) != 0,
|
||||
};
|
||||
by_name.put(&mut d.mleader_styles, name, st);
|
||||
match d.mleader_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(name)) {
|
||||
Some(x) => *x = st,
|
||||
None => d.mleader_styles.push(st),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ use super::{
|
||||
Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, Vec3,
|
||||
VportConfig, VportTile, record_slices,
|
||||
};
|
||||
use crate::dxf_ext::ByName;
|
||||
use cadcraft_fonts::windows::windows_font;
|
||||
use craft_dxf::lin_pat::MAX_LINETYPE_ELEMENTS;
|
||||
|
||||
@@ -115,12 +114,10 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
// The same for linetypes (first definition wins) and text styles (last definition wins).
|
||||
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();
|
||||
// And for dimension styles, views and UCSs (a later record replaces the first of its name),
|
||||
// and viewport configurations (a record adds a tile to the first of its name).
|
||||
// And for dimension styles, views and UCSs (a later record replaces the first of its name).
|
||||
let mut dim_style_names = ByName::new(&d.dim_styles, |s| &s.name);
|
||||
let mut view_names = ByName::new(&d.views, |v| &v.name);
|
||||
let mut ucs_names = ByName::new(&d.ucss, |u| &u.name);
|
||||
let mut vport_names = ByName::new(&d.vports, |c| &c.name);
|
||||
for (kind, tg) in recs {
|
||||
let t = T(tg);
|
||||
match kind.as_str() {
|
||||
@@ -208,7 +205,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
// The first *ACTIVE viewport holds the current snap/grid settings.
|
||||
"VPORT" if !active_vport && t.s(2).is_some_and(|n| n.trim().eq_ignore_ascii_case("*ACTIVE")) => {
|
||||
active_vport = true;
|
||||
vport_record(d, &mut vport_names, &t, true);
|
||||
vport_record(d, &t, true);
|
||||
for (name, code) in [("SNAPUNIT", 14), ("GRIDUNIT", 15)] {
|
||||
if let (Some(x), Some(y)) = (t.f(code), t.f(code + 10)) {
|
||||
let p = Vec2::new(x, y);
|
||||
@@ -283,7 +280,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
|
||||
st.apply_fields(&fields);
|
||||
dim_style_names.put(&mut d.dim_styles, &name, st);
|
||||
}
|
||||
"VPORT" => vport_record(d, &mut vport_names, &t, false),
|
||||
"VPORT" => vport_record(d, &t, false),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -293,6 +290,32 @@ 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));
|
||||
}
|
||||
|
||||
/// The records of one table read so far, by name with its ASCII letters lower-cased. A later
|
||||
/// record of a name replaces the first, which keeps its place and takes the later record's name.
|
||||
/// Each record is then a map lookup, not a scan of the records before it: a file of N records cost
|
||||
/// N² name comparisons (#1924). Ordered by name rather than hashed, so its cost does not depend on
|
||||
/// hash keys.
|
||||
struct ByName(std::collections::BTreeMap<String, usize>);
|
||||
|
||||
impl ByName {
|
||||
/// The entries the table starts with; the first of a name is the one kept.
|
||||
fn new<T>(list: &[T], name: impl Fn(&T) -> &str) -> Self {
|
||||
ByName(list.iter().enumerate().rev().map(|(i, t)| (name(t).to_ascii_lowercase(), i)).collect())
|
||||
}
|
||||
|
||||
/// Put `item`, named `name`, in place of the first entry of that name, else at the end.
|
||||
fn put<T>(&mut self, list: &mut Vec<T>, name: &str, item: T) {
|
||||
let key = name.to_ascii_lowercase();
|
||||
match self.0.get(&key).and_then(|&i| list.get_mut(i)) {
|
||||
Some(x) => *x = item,
|
||||
None => {
|
||||
self.0.insert(key, list.len());
|
||||
list.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
|
||||
for (kind, tags) in recs {
|
||||
let table = T(tags);
|
||||
@@ -352,9 +375,8 @@ const MAX_VPORT_TILES: usize = 64;
|
||||
|
||||
/// A VPORT record: one tile of the configuration it names (`*ACTIVE` the one shown). Corners
|
||||
/// are fractions of the drawing area; unusable tiles are skipped. `first_active`: this is the
|
||||
/// file's first `*ACTIVE` record, the one whose view is the drawing's saved view. `names`: the
|
||||
/// configurations read so far by name.
|
||||
fn vport_record(d: &mut Drawing, names: &mut ByName, t: &T, first_active: bool) {
|
||||
/// file's first `*ACTIVE` record, the one whose view is the drawing's saved view.
|
||||
fn vport_record(d: &mut Drawing, t: &T, first_active: bool) {
|
||||
let name = t.s(2).map(|n| n.trim().to_string()).unwrap_or_default();
|
||||
// View twist (group 51, degrees).
|
||||
let twist = t.f(51).map_or(0.0, |a| cadcraft_geom::norm_angle(a.to_radians()));
|
||||
@@ -391,13 +413,10 @@ fn vport_record(d: &mut Drawing, names: &mut ByName, t: &T, first_active: bool)
|
||||
let tile = VportTile { min: clamp(min), max: clamp(max), center, height, aspect, twist };
|
||||
let name = if name.eq_ignore_ascii_case(VportConfig::ACTIVE) { VportConfig::ACTIVE.to_string() } else { name };
|
||||
let room = d.vports.len() < MAX_OBJECTS;
|
||||
match names.position(&name).and_then(|i| d.vports.get_mut(i)) {
|
||||
match d.vports.iter_mut().find(|c| c.name.eq_ignore_ascii_case(&name)) {
|
||||
Some(c) if c.tiles.len() < MAX_VPORT_TILES => c.tiles.push(tile),
|
||||
Some(_) => {}
|
||||
None if room => {
|
||||
let config = VportConfig { name: name.clone(), tiles: vec![tile] };
|
||||
names.put(&mut d.vports, &name, config);
|
||||
}
|
||||
None if room => d.vports.push(VportConfig { name, tiles: vec![tile] }),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use super::{DimVal, Handle, HashMap, K, Vec3, Version, dxf_ext};
|
||||
use crate::dxf_ext::ByName;
|
||||
|
||||
/// The `DIMASSOC` object of an associative dimension (stored in the dimension's extension
|
||||
/// dictionary under `ACAD_DIMASSOC`).
|
||||
@@ -45,14 +44,8 @@ pub(super) struct Ctx {
|
||||
pub(super) tables: HashMap<Handle, (String, String)>,
|
||||
/// Table style name → TABLESTYLE handle (the first is the fallback).
|
||||
pub(super) table_styles: Vec<(String, String)>,
|
||||
/// The positions of [`Ctx::table_styles`] by name.
|
||||
pub(super) table_style_names: ByName,
|
||||
/// Multileader style name → MLEADERSTYLE handle (the first is the fallback): the drawing's
|
||||
/// multileader styles in order, or Standard alone when it has none.
|
||||
/// Multileader style name → MLEADERSTYLE handle (the first is the fallback).
|
||||
pub(super) mleader_styles: Vec<(String, String)>,
|
||||
/// The positions of [`Ctx::mleader_styles`] by name: those of the drawing's multileader styles
|
||||
/// too, when it has any.
|
||||
pub(super) mleader_style_names: ByName,
|
||||
/// Upper-case block name → BLOCK_RECORD handle (multileader block content).
|
||||
pub(super) block_records: HashMap<String, String>,
|
||||
/// Raster images' IMAGEDEF, IMAGEDEF_REACTOR and dictionary handles.
|
||||
@@ -83,23 +76,14 @@ impl Ctx {
|
||||
self.arrows.get(&name.trim().to_ascii_uppercase()).cloned()
|
||||
}
|
||||
pub(super) fn table_style(&self, name: &str) -> String {
|
||||
Self::named(&self.table_styles, &self.table_style_names, name)
|
||||
Self::named(&self.table_styles, name)
|
||||
}
|
||||
pub(super) fn mleader_style(&self, name: &str) -> String {
|
||||
Self::named(&self.mleader_styles, &self.mleader_style_names, name)
|
||||
Self::named(&self.mleader_styles, name)
|
||||
}
|
||||
/// The drawing's multileader style named `name` (the first of that name, ignoring case).
|
||||
pub(super) fn mleader_style_def<'d>(&self, d: &'d cadcraft_doc::Drawing, name: &str) -> Option<&'d cadcraft_doc::MLeaderStyle> {
|
||||
if self.mleader_styles.is_empty() {
|
||||
// No styles planned (one entity's groups, for AutoLISP): look in the drawing.
|
||||
return d.mleader_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name));
|
||||
}
|
||||
self.mleader_style_names.position(name).and_then(|i| d.mleader_styles.get(i))
|
||||
}
|
||||
/// The handle of the style `name` in `styles` (the first of that name, ignoring case, found
|
||||
/// through `names`, their positions by name), or of the first one.
|
||||
fn named(styles: &[(String, String)], names: &ByName, name: &str) -> String {
|
||||
names.position(name).and_then(|i| styles.get(i)).or_else(|| styles.first()).map(|(_, h)| h.clone()).unwrap_or_else(|| "0".into())
|
||||
/// The handle of the style `name` in `styles`, or of the first one.
|
||||
fn named(styles: &[(String, String)], name: &str) -> String {
|
||||
styles.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).or_else(|| styles.first()).map(|(_, h)| h.clone()).unwrap_or_else(|| "0".into())
|
||||
}
|
||||
/// A dimension variable encoded with this file's handles; integers outside the 16-bit
|
||||
/// range of their groups are dropped.
|
||||
|
||||
@@ -599,7 +599,6 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap
|
||||
common(w, e, owner, paper, "AcDbMLeader");
|
||||
let refs = crate::dxf_mleader::Refs {
|
||||
style: cx.mleader_style(&m.style),
|
||||
style_def: cx.mleader_style_def(d, &m.style),
|
||||
text_style: m.text.as_ref().and_then(|t| cx.style(&t.style)),
|
||||
block: m.block.as_ref().and_then(|b| cx.block_records.get(&b.block.to_ascii_uppercase()).cloned()),
|
||||
};
|
||||
|
||||
@@ -1135,11 +1135,9 @@ pub(super) fn tags_kept_for(
|
||||
let default_table_style = [TableStyle::default()];
|
||||
let table_styles: &[TableStyle] = if d.table_styles.is_empty() { &default_table_style } else { &d.table_styles };
|
||||
cx.table_styles = table_styles.iter().map(|s| (s.name.clone(), w.h())).collect();
|
||||
cx.table_style_names = crate::dxf_ext::ByName::new(&cx.table_styles, |(n, _)| n);
|
||||
let default_mleader_style = [MLeaderStyle::default()];
|
||||
let mleader_styles: &[MLeaderStyle] = if d.mleader_styles.is_empty() { &default_mleader_style } else { &d.mleader_styles };
|
||||
cx.mleader_styles = mleader_styles.iter().map(|s| (s.name.clone(), w.h())).collect();
|
||||
cx.mleader_style_names = crate::dxf_ext::ByName::new(&cx.mleader_styles, |(n, _)| n);
|
||||
let root_dict = w.h();
|
||||
let group_dict = w.h();
|
||||
let layout_dict = w.h();
|
||||
|
||||
@@ -506,315 +506,6 @@ fn a_layouts_named_ucs_is_the_first_of_its_name_with_its_frame() {
|
||||
assert_eq!(names.named("front", Vec3::new(1.0, 0.0, 0.0), x, y).map(|u| u.name.as_str()), Some("FRONT"));
|
||||
}
|
||||
|
||||
/// Many distinct table and multileader style names read in linear time, with the duplicate rule
|
||||
/// kept: a later style of a name in other case replaces the first, which keeps its place and takes
|
||||
/// the later style's name, also the Standard style a drawing starts with (#1924). The names share
|
||||
/// their first 200 bytes, so comparing two costs about that.
|
||||
#[test]
|
||||
fn many_distinct_table_and_multileader_style_names_read_quickly() {
|
||||
const N: usize = 20_000;
|
||||
let name = |kind: char, i: usize| format!("{kind}{}{i:06}", "x".repeat(199));
|
||||
// Each style: a dictionary entry naming its handle, and the object (TABLESTYLE margin 40 or
|
||||
// MLEADERSTYLE arrow size 44 set to `v`).
|
||||
let mut entries = String::new();
|
||||
let mut objects = String::new();
|
||||
let mut h = 0x1000;
|
||||
let mut style = |kind: &str, n: &str, v: f64| {
|
||||
h += 1;
|
||||
entries.push_str(&format!("3\n{n}\n350\n{h:X}\n"));
|
||||
let own = if kind == "TABLESTYLE" { format!("100\nAcDbTableStyle\n40\n{v}\n") } else { format!("100\nAcDbMLeaderStyle\n44\n{v}\n") };
|
||||
objects.push_str(&format!("0\n{kind}\n5\n{h:X}\n{own}"));
|
||||
};
|
||||
for (kind, k) in [("TABLESTYLE", 'T'), ("MLEADERSTYLE", 'M')] {
|
||||
for i in 0..N {
|
||||
style(kind, &name(k, i), 1.0);
|
||||
}
|
||||
style(kind, &name(k, 0).to_ascii_uppercase(), 2.0);
|
||||
style(kind, "STANDARD", 3.0);
|
||||
}
|
||||
let t = format!("0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nA0\n100\nAcDbDictionary\n{entries}{objects}0\nENDSEC\n0\nEOF\n");
|
||||
let started = std::time::Instant::now();
|
||||
let d = read(t.as_bytes(), "many.dxf").unwrap();
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
let tables: Vec<(&str, f64)> = d.table_styles.iter().map(|s| (s.name.as_str(), s.margin)).collect();
|
||||
let mleaders: Vec<(&str, f64)> = d.mleader_styles.iter().map(|s| (s.name.as_str(), s.arrow_size)).collect();
|
||||
for (styles, k) in [(tables, 'T'), (mleaders, 'M')] {
|
||||
assert_eq!(styles.len(), N + 1);
|
||||
assert_eq!(styles.first(), Some(&("STANDARD", 3.0)));
|
||||
assert_eq!(styles.get(1), Some(&(name(k, 0).to_ascii_uppercase().as_str(), 2.0)));
|
||||
assert_eq!(styles.get(2), Some(&(name(k, 1).as_str(), 1.0)));
|
||||
}
|
||||
}
|
||||
|
||||
/// The most multiline styles a file can hold, with long names, read in linear time, with the
|
||||
/// duplicate rule kept: a later style of a name in other case replaces the first, which keeps its
|
||||
/// place and takes the later style's name, also the STANDARD style a drawing starts with (#1924).
|
||||
/// The names share their first 1 000 bytes, so comparing two costs about that.
|
||||
#[test]
|
||||
fn many_multiline_style_names_read_quickly() {
|
||||
const N: usize = 9_998;
|
||||
let name = |i: usize| format!("L{}{i:06}", "x".repeat(999));
|
||||
let style = |n: &str, description: &str| format!("0\nMLINESTYLE\n100\nAcDbMlineStyle\n2\n{n}\n70\n0\n3\n{description}\n71\n1\n49\n0\n");
|
||||
let mut t = String::from("0\nSECTION\n2\nOBJECTS\n");
|
||||
for i in 0..N {
|
||||
t.push_str(&style(&name(i), "first"));
|
||||
}
|
||||
t.push_str(&style(&name(0).to_ascii_uppercase(), "second"));
|
||||
t.push_str(&style("standard", "third"));
|
||||
t.push_str("0\nENDSEC\n0\nEOF\n");
|
||||
let started = std::time::Instant::now();
|
||||
let d = read(t.as_bytes(), "mlines.dxf").unwrap();
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
let styles: Vec<(&str, &str)> = d.mline_styles.iter().map(|s| (s.name.as_str(), s.description.as_str())).collect();
|
||||
assert_eq!(styles.len(), N + 1);
|
||||
assert_eq!(styles.first(), Some(&("standard", "third")));
|
||||
assert_eq!(styles.get(1), Some(&(name(0).to_ascii_uppercase().as_str(), "second")));
|
||||
assert_eq!(styles.get(2), Some(&(name(1).as_str(), "first")));
|
||||
}
|
||||
|
||||
/// Many viewport configurations read in linear time, with the rule kept: a record adds a tile to
|
||||
/// the first configuration of its name, in any case, which keeps its own name, also from a later
|
||||
/// TABLES section (#1924). The names share their first 200 bytes, so comparing two costs about
|
||||
/// that.
|
||||
#[test]
|
||||
fn many_viewport_configurations_read_quickly() {
|
||||
const N: usize = 20_000;
|
||||
let name = |i: usize| format!("V{}{i:06}", "x".repeat(199));
|
||||
let record = |n: &str, x: f64| format!("0\nVPORT\n2\n{n}\n70\n0\n10\n0\n20\n0\n11\n1\n21\n1\n12\n{x}\n22\n0\n40\n10\n41\n1\n");
|
||||
let mut t = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n");
|
||||
for i in 0..N {
|
||||
t.push_str(&record(&name(i), 1.0));
|
||||
}
|
||||
t.push_str(&record(&name(0).to_ascii_uppercase(), 2.0));
|
||||
t.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n");
|
||||
t.push_str(&record(&name(1).to_ascii_uppercase(), 3.0));
|
||||
t.push_str("0\nENDTAB\n0\nENDSEC\n0\nEOF\n");
|
||||
let started = std::time::Instant::now();
|
||||
let d = read(t.as_bytes(), "vports.dxf").unwrap();
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
let configs: Vec<(&str, Vec<f64>)> =
|
||||
d.vports.iter().filter(|c| c.name.starts_with('V')).map(|c| (c.name.as_str(), c.tiles.iter().map(|t| t.center.x).collect())).collect();
|
||||
assert_eq!(configs.len(), N);
|
||||
assert_eq!(configs.first(), Some(&(name(0).as_str(), vec![1.0, 2.0])));
|
||||
assert_eq!(configs.get(1), Some(&(name(1).as_str(), vec![1.0, 3.0])));
|
||||
assert_eq!(configs.get(2), Some(&(name(2).as_str(), vec![1.0])));
|
||||
}
|
||||
|
||||
/// The value of group `code` in each record of type `kind` (its first, if repeated), in file order.
|
||||
fn first_groups(p: &[(String, String)], kind: &str, code: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let (mut inside, mut found) = (false, false);
|
||||
for (c, v) in p {
|
||||
if c == "0" {
|
||||
(inside, found) = (v.trim() == kind, false);
|
||||
} else if inside && !found && c == code {
|
||||
out.push(v.trim().to_string());
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every dictionary entry: its handle to its name.
|
||||
fn entry_names(p: &[(String, String)]) -> std::collections::HashMap<String, String> {
|
||||
let mut out = std::collections::HashMap::new();
|
||||
let (mut inside, mut name) = (false, None);
|
||||
for (c, v) in p {
|
||||
match c.as_str() {
|
||||
"0" => (inside, name) = (v.trim() == "DICTIONARY", None),
|
||||
"3" if inside => name = Some(v.trim().to_string()),
|
||||
"350" | "360" if inside => {
|
||||
if let Some(n) = name.take() {
|
||||
out.insert(v.trim().to_string(), n);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Saving many multileaders among many multileader styles takes linear time (#1924), and each is
|
||||
/// written as before: pointing at the first style of its name (ignoring case), else at the
|
||||
/// drawing's first style, with the landing gap of the first style of its name, else the default
|
||||
/// one. The names share their first 200 bytes, so comparing two costs about that.
|
||||
#[test]
|
||||
fn many_multileaders_among_many_styles_save_quickly() {
|
||||
const N: usize = 10_000;
|
||||
let name = |i: usize| format!("M{}{i:06}", "x".repeat(199));
|
||||
let missing = |i: usize| format!("M{}z{i:05}", "x".repeat(199));
|
||||
let mut d = Drawing::new_imperial();
|
||||
if let Some(first) = d.mleader_styles.first_mut() {
|
||||
first.landing_gap = 0.25;
|
||||
}
|
||||
d.mleader_styles.extend((0..N).map(|i| MLeaderStyle { name: name(i), landing_gap: 0.5, ..MLeaderStyle::default() }));
|
||||
d.mleader_styles.push(MLeaderStyle { name: name(N - 1).to_ascii_uppercase(), landing_gap: 0.75, ..MLeaderStyle::default() });
|
||||
let mleader = |style: String, x: f64| {
|
||||
EntityKind::MLeader(MLeader {
|
||||
leaders: vec![vec![Vec3::new(x, 0.0, 0.0), Vec3::new(x + 1.0, 1.0, 0.0)]],
|
||||
landing: Vec3::new(x + 2.0, 1.0, 0.0),
|
||||
dogleg: 0.5,
|
||||
text: None,
|
||||
style,
|
||||
arrow_size: 1.0,
|
||||
spline: false,
|
||||
block: None,
|
||||
})
|
||||
};
|
||||
for i in 0..N {
|
||||
d.add(&Space::Model, Common::default(), mleader(missing(i), i as f64)).unwrap();
|
||||
}
|
||||
d.add(&Space::Model, Common::default(), mleader(name(N - 1).to_ascii_uppercase(), -1.0)).unwrap();
|
||||
// As a MULTILEADER (R2007 and later): older files get a LEADER and its content instead.
|
||||
let started = std::time::Instant::now();
|
||||
let saved = dxf_2018(&d);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
let p = pairs(&saved);
|
||||
let entries = entry_names(&p);
|
||||
let styles: Vec<&str> = first_groups(&p, "MULTILEADER", "340").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect();
|
||||
let gaps: Vec<f64> = first_groups(&p, "MULTILEADER", "145").iter().filter_map(|v| v.parse().ok()).collect();
|
||||
assert_eq!((styles.len(), gaps.len()), (N + 1, N + 1));
|
||||
let default_gap = MLeaderStyle::default().landing_gap;
|
||||
assert!(styles[..N].iter().all(|s| *s == "Standard"), "a missing style points at the first style");
|
||||
assert!(gaps[..N].iter().all(|g| *g == default_gap), "a missing style writes the default landing gap");
|
||||
assert_eq!((styles[N], gaps[N]), (name(N - 1).as_str(), 0.5), "the first style of the name");
|
||||
}
|
||||
|
||||
/// A multileader's own groups (AutoLISP's entity data) carry its style's landing gap, found
|
||||
/// without the styles a save plans.
|
||||
#[test]
|
||||
fn a_multileaders_entity_groups_have_its_styles_landing_gap() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.mleader_styles.push(MLeaderStyle { name: "Notes".into(), landing_gap: 0.5, ..MLeaderStyle::default() });
|
||||
let m = MLeader {
|
||||
leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0)]],
|
||||
landing: Vec3::new(2.0, 1.0, 0.0),
|
||||
dogleg: 0.5,
|
||||
text: None,
|
||||
style: "NOTES".into(),
|
||||
arrow_size: 1.0,
|
||||
spline: false,
|
||||
block: None,
|
||||
};
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::MLeader(m)).unwrap();
|
||||
let e = d.entity(h).unwrap().clone();
|
||||
let (kind, tags) = entity_groups(&d, &e);
|
||||
assert_eq!(kind, "MULTILEADER");
|
||||
assert_eq!(tags.iter().find(|t| t.code == 145).map(|t| t.f64()), Some(0.5));
|
||||
}
|
||||
|
||||
/// Many tables from another writer naming a table style the file lacks, among many table styles,
|
||||
/// read and save in linear time (#1924). Each table takes the text height of the style of its
|
||||
/// name (ignoring case), else the default one, as before, and is saved pointing at that style,
|
||||
/// else at the drawing's first one. The names share their first 200 bytes.
|
||||
#[test]
|
||||
fn many_tables_among_many_table_styles_read_and_save_quickly() {
|
||||
const N: usize = 10_000;
|
||||
let name = |i: usize| format!("T{}{i:06}", "x".repeat(199));
|
||||
let missing = format!("T{}z{:05}", "x".repeat(199), 0);
|
||||
let upper = name(N - 1).to_ascii_uppercase();
|
||||
// Tables whose style (342) is a dictionary entry with no TABLESTYLE: the missing name for the
|
||||
// first N, the last style's name in upper case for the last one.
|
||||
let mut t = String::from("0\nSECTION\n2\nENTITIES\n");
|
||||
for i in 0..=N {
|
||||
let style = if i < N { "F0000" } else { "F0001" };
|
||||
t.push_str(&format!(
|
||||
"0\nACAD_TABLE\n5\n{:X}\n100\nAcDbBlockReference\n10\n{i}\n20\n0\n30\n0\n100\nAcDbTable\n342\n{style}\n91\n1\n92\n1\n141\n1\n142\n1\n",
|
||||
0x100000 + i
|
||||
));
|
||||
}
|
||||
t.push_str(&format!(
|
||||
"0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nA0\n100\nAcDbDictionary\n3\n{missing}\n350\nF0000\n3\n{upper}\n350\nF0001\n"
|
||||
));
|
||||
for i in 0..N {
|
||||
t.push_str(&format!("3\n{}\n350\n{:X}\n", name(i), 0x10000 + i));
|
||||
}
|
||||
for i in 0..N {
|
||||
t.push_str(&format!("0\nTABLESTYLE\n5\n{:X}\n100\nAcDbTableStyle\n7\n\n140\n0.5\n", 0x10000 + i));
|
||||
}
|
||||
t.push_str("0\nENDSEC\n0\nEOF\n");
|
||||
let started = std::time::Instant::now();
|
||||
let d = read(t.as_bytes(), "tables.dxf").unwrap();
|
||||
let saved = write_dxf(&d);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
let tables: Vec<(&str, f64)> =
|
||||
d.model.iter().filter_map(|e| if let EntityKind::Table(t) = &e.kind { Some((t.style.as_str(), t.text_height)) } else { None }).collect();
|
||||
let default_height = TableStyle::default().text_height;
|
||||
assert_eq!(tables.len(), N + 1);
|
||||
assert!(tables[..N].iter().all(|t| *t == (missing.as_str(), default_height)), "a missing style gives the default height");
|
||||
assert_eq!(tables[N], (upper.as_str(), 0.5), "the style of the name in other case");
|
||||
let p = pairs(&saved);
|
||||
let entries = entry_names(&p);
|
||||
let styles: Vec<&str> = first_groups(&p, "ACAD_TABLE", "342").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect();
|
||||
assert_eq!(styles.len(), N + 1);
|
||||
assert!(styles[..N].iter().all(|s| *s == "Standard"), "a missing style points at the first style");
|
||||
assert_eq!(styles[N], name(N - 1));
|
||||
}
|
||||
|
||||
/// Saving many multilines that each name a style the drawing lacks takes linear time (#1924). As
|
||||
/// before, each missing style is written once, with the elements of the first multiline naming it,
|
||||
/// and each multiline points at the first style of its name, ignoring case and surrounding spaces,
|
||||
/// or at STANDARD when it names none.
|
||||
#[test]
|
||||
fn many_multilines_naming_missing_styles_save_quickly() {
|
||||
const N: usize = 10_000;
|
||||
let missing = |i: usize| format!("L{}{i:06}", "x".repeat(199));
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mline = |style: String, x: f64| {
|
||||
let def = MLineStyle { name: style.clone(), ..MLineStyle::default() };
|
||||
let vertex = |x: f64| MLineVertex { p: Vec3::new(x, 0.0, 0.0), cuts: Vec::new() };
|
||||
EntityKind::MLine(MLine {
|
||||
style,
|
||||
def,
|
||||
scale: 1.0,
|
||||
justification: MLineJust::default(),
|
||||
closed: false,
|
||||
no_start_caps: false,
|
||||
no_end_caps: false,
|
||||
vertices: vec![vertex(x), vertex(x + 1.0)],
|
||||
})
|
||||
};
|
||||
for i in 0..N {
|
||||
d.add(&Space::Model, Common::default(), mline(missing(i), i as f64)).unwrap();
|
||||
}
|
||||
d.add(&Space::Model, Common::default(), mline(missing(N - 1).to_ascii_uppercase(), -1.0)).unwrap();
|
||||
let mut padded = mline(format!(" {} ", missing(0)), -2.0);
|
||||
if let EntityKind::MLine(m) = &mut padded {
|
||||
m.def.elements = vec![MLineElement { offset: 0.25, ..MLineElement::default() }];
|
||||
}
|
||||
d.add(&Space::Model, Common::default(), padded).unwrap();
|
||||
d.add(&Space::Model, Common::default(), mline(" ".into(), -3.0)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
let saved = write_dxf(&d);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
let p = pairs(&saved);
|
||||
let entries = entry_names(&p);
|
||||
let styles: Vec<&str> = first_groups(&p, "MLINE", "340").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect();
|
||||
let want: Vec<String> = (0..N).map(missing).chain([missing(N - 1), missing(0), "STANDARD".into()]).collect();
|
||||
assert_eq!(styles, want);
|
||||
assert_eq!(first_groups(&p, "MLINESTYLE", "2").len(), N + 1, "STANDARD and each missing style once");
|
||||
let offsets: Vec<f64> = first_groups(&p, "MLINESTYLE", "49").iter().filter_map(|v| v.parse().ok()).collect();
|
||||
assert!(offsets.len() == N + 1 && !offsets.contains(&0.25), "a later multiline does not change the style");
|
||||
}
|
||||
|
||||
/// A multiline style whose name has spaces around it in the file is read with the name trimmed, so
|
||||
/// its multilines, whose lookup trims, find it: a save writes it once and points them at it.
|
||||
#[test]
|
||||
fn a_padded_multiline_style_name_is_saved_once() {
|
||||
let t = "0\nSECTION\n2\nENTITIES\n0\nMLINE\n5\n100\n100\nAcDbEntity\n8\n0\n100\nAcDbMline\n2\n Road \n40\n1\n70\n0\n71\n1\n72\n2\n73\n2\n\
|
||||
10\n0\n20\n0\n30\n0\n11\n0\n21\n0\n31\n0\n12\n1\n22\n0\n32\n0\n13\n0\n23\n1\n33\n0\n74\n2\n41\n0\n41\n0\n75\n0\n74\n2\n41\n0\n41\n0\n75\n0\n\
|
||||
11\n1\n21\n0\n31\n0\n12\n1\n22\n0\n32\n0\n13\n0\n23\n1\n33\n0\n74\n2\n41\n0\n41\n0\n75\n0\n74\n2\n41\n0\n41\n0\n75\n0\n\
|
||||
0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n0\nMLINESTYLE\n5\n200\n100\nAcDbMlineStyle\n2\n Road \n70\n0\n3\npadded\n71\n2\n\
|
||||
49\n0.25\n62\n256\n6\nBYLAYER\n49\n-0.25\n62\n256\n6\nBYLAYER\n0\nENDSEC\n0\nEOF\n";
|
||||
let d = read(t.as_bytes(), "padded.dxf").unwrap();
|
||||
assert_eq!(d.mline_styles.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["STANDARD", "Road"]);
|
||||
let p = pairs(&write_dxf(&d));
|
||||
let entries = entry_names(&p);
|
||||
assert_eq!(first_groups(&p, "MLINESTYLE", "2"), ["STANDARD", "Road"], "one Road style");
|
||||
let styles: Vec<&str> = first_groups(&p, "MLINE", "340").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect();
|
||||
assert_eq!(styles, ["Road"]);
|
||||
}
|
||||
|
||||
/// Many layouts with every paper-space object in one of the last of them read in linear time.
|
||||
/// Each object goes to the first layout of its exact name, as before: not to an earlier one whose
|
||||
/// name differs only in case, nor to a later one of the same name (#1924).
|
||||
|
||||
@@ -19,6 +19,9 @@ serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# Secure randomness for the per-session control token (MIT OR Apache-2.0).
|
||||
getrandom = "0.4"
|
||||
# The control server's proof that it holds the session token (MIT OR Apache-2.0).
|
||||
hmac = "0.12"
|
||||
sha2 = "0.10"
|
||||
|
||||
[dev-dependencies]
|
||||
# Reads the pixels of rendered PNGs in the tests.
|
||||
|
||||
+215
-33
@@ -3,7 +3,7 @@
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpStream, ToSocketAddrs};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::file_access::{self, AutomationRoots};
|
||||
@@ -35,6 +35,9 @@ pub struct Remote {
|
||||
authed: bool,
|
||||
/// Longest reply line accepted (`MAX_REPLY_LINE`; smaller in tests).
|
||||
max_reply: usize,
|
||||
/// When the current connection was opened: the server closes one that hasn't shown the token
|
||||
/// within `MAX_UNAUTHENTICATED_TIME`.
|
||||
opened: Option<Instant>,
|
||||
}
|
||||
|
||||
/// The port component of a `HOST:PORT` address, for locating the token file.
|
||||
@@ -50,6 +53,13 @@ const LAUNCH_WAIT: Duration = Duration::from_secs(30);
|
||||
/// can't make the client allocate without bound (#1925).
|
||||
const MAX_REPLY_LINE: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// Longest reply to a `hello` the client reads: it comes before the peer has proved anything.
|
||||
const MAX_HELLO_REPLY: usize = 4096;
|
||||
|
||||
/// How long before the server's `MAX_UNAUTHENTICATED_TIME` runs out an unauthenticated connection
|
||||
/// is replaced instead of used, so a request is never written to a connection about to close.
|
||||
const PREAUTH_MARGIN: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Read one `\n`-terminated reply of at most `max` bytes (newline excluded). `Ok(0)` is end of
|
||||
/// stream; a longer line is an `InvalidData` error and the rest of it stays unread.
|
||||
fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) -> std::io::Result<usize> {
|
||||
@@ -67,7 +77,7 @@ fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) ->
|
||||
impl Remote {
|
||||
/// Connect to a running control server; its session token is read lazily when the first request is sent.
|
||||
pub fn connect(addr: &str) -> std::io::Result<Self> {
|
||||
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None, authed: false, max_reply: MAX_REPLY_LINE };
|
||||
let mut r = Self::lazy(addr, false);
|
||||
r.reconnect()?;
|
||||
Ok(r)
|
||||
}
|
||||
@@ -75,12 +85,11 @@ impl Remote {
|
||||
/// the server before the app is open. With `launch`, a call that finds nothing at `addr`
|
||||
/// opens the app with that control port first (macOS) and waits for it.
|
||||
pub fn lazy(addr: &str, launch: bool) -> Self {
|
||||
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE }
|
||||
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE, opened: None }
|
||||
}
|
||||
|
||||
/// The per-session token for this port, read (and cached) from the owner-only token file. A
|
||||
/// missing file is not fatal here: the request is sent without a token and the server replies
|
||||
/// with an authentication error the user can act on.
|
||||
/// The per-session token for this port, read (and cached) from the owner-only token file
|
||||
/// (`None` when there is none; then nothing is sent, see [`Remote::prove_server`]).
|
||||
///
|
||||
/// The desktop app listens only on `127.0.0.1:PORT`, so the token goes only to that exact
|
||||
/// peer: a name that also resolves elsewhere (`localhost` → `::1`, where another local account
|
||||
@@ -134,15 +143,65 @@ impl Remote {
|
||||
s.set_read_timeout(Some(Duration::from_secs(90))).ok();
|
||||
let read = s.try_clone()?;
|
||||
self.conn = Some((BufReader::new(read), s));
|
||||
return Ok(());
|
||||
self.opened = Some(Instant::now());
|
||||
// A peer that can't prove it is the app gets nothing; another address may be.
|
||||
match self.prove_server() {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => {
|
||||
self.conn = None;
|
||||
last = e;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => last = e,
|
||||
}
|
||||
}
|
||||
Err(last)
|
||||
}
|
||||
/// Have the peer just connected to prove it holds this port's session token before anything
|
||||
/// else is sent to it: any program that listens on the port first would otherwise receive the
|
||||
/// requests and could answer them (#1925). The `hello` carries a fresh nonce and no token; the
|
||||
/// app answers with [`crate::control_token::server_proof`]. A proof made with another token is
|
||||
/// checked once more against the token file, which a restarted app has rewritten.
|
||||
fn prove_server(&mut self) -> std::io::Result<()> {
|
||||
let refused = |addr: &str, why: &str| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
format!(
|
||||
"the program listening at {addr} {why}, so nothing was sent to it; is CADCraft running with its control port under this account?"
|
||||
),
|
||||
)
|
||||
};
|
||||
if self.token().is_none() {
|
||||
return Err(refused(&self.addr, "is not a CADCraft session whose control token this account can read"));
|
||||
}
|
||||
let nonce = crate::control_token::new_nonce()?;
|
||||
let hello = json!({"method": "hello", "params": {"nonce": nonce}}).to_string();
|
||||
let reply = self.roundtrip_within(&hello, MAX_HELLO_REPLY).map_err(|(e, _)| e)?;
|
||||
let reply = serde_json::from_str::<Value>(&reply).unwrap_or_default();
|
||||
let Some(proof) = reply.pointer("/result/proof").and_then(Value::as_str) else {
|
||||
// The app refuses a connection past its limit before reading anything: say why.
|
||||
return Err(match reply.get("error").and_then(Value::as_str) {
|
||||
Some(e) => std::io::Error::other(e.to_string()),
|
||||
None => refused(&self.addr, "did not answer as CADCraft's control server does"),
|
||||
});
|
||||
};
|
||||
let holds = |token: Option<&str>| token.is_some_and(|t| crate::control_token::verify_server_proof(t, &nonce, proof));
|
||||
if holds(self.token.as_deref()) {
|
||||
return Ok(());
|
||||
}
|
||||
self.token = None;
|
||||
if holds(self.token()) {
|
||||
return Ok(());
|
||||
}
|
||||
Err(refused(&self.addr, "could not prove it holds this account's control token"))
|
||||
}
|
||||
/// On failure the flag says whether the request may already have reached the server.
|
||||
fn roundtrip(&mut self, line: &str) -> Result<String, (std::io::Error, bool)> {
|
||||
self.roundtrip_within(line, self.max_reply)
|
||||
}
|
||||
/// [`Remote::roundtrip`], reading a reply of at most `max` bytes.
|
||||
fn roundtrip_within(&mut self, line: &str, max: usize) -> Result<String, (std::io::Error, bool)> {
|
||||
if self.conn.is_none() {
|
||||
self.reach().map_err(|e| (e, false))?;
|
||||
}
|
||||
@@ -155,7 +214,7 @@ impl Remote {
|
||||
return Err((e, true));
|
||||
}
|
||||
let mut reply = String::new();
|
||||
match read_reply_line(reader, &mut reply, self.max_reply) {
|
||||
match read_reply_line(reader, &mut reply, max) {
|
||||
Ok(0) => {
|
||||
self.conn = None;
|
||||
Err((std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "connection closed"), true))
|
||||
@@ -225,6 +284,11 @@ impl Remote {
|
||||
/// passed the check (#1925), so a long request on a new connection goes after a `ping` with the
|
||||
/// token; when the `ping` is refused its reply comes back instead and the request isn't sent.
|
||||
fn sign_and_send(&mut self, req: &mut Value) -> Result<String, (std::io::Error, bool)> {
|
||||
// The app closes a connection that hasn't shown the token in time; a request written to it
|
||||
// then would be lost with its fate unknown, so such a connection is replaced first.
|
||||
if !self.authed && self.opened.is_some_and(|t| t.elapsed() + PREAUTH_MARGIN >= crate::control_token::MAX_UNAUTHENTICATED_TIME) {
|
||||
self.conn = None;
|
||||
}
|
||||
if self.conn.is_none() {
|
||||
self.reach().map_err(|e| (e, false))?;
|
||||
}
|
||||
@@ -528,15 +592,40 @@ mod tests {
|
||||
use std::net::TcpListener;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The app's reply to `req` when it is a `hello`: a proof made with the token in this port's
|
||||
/// file now (the app's own token).
|
||||
fn hello_reply(req: &Value, port: u16) -> Option<Value> {
|
||||
(req["method"] == "hello").then(|| {
|
||||
let token = crate::control_token::read(port).unwrap_or_default();
|
||||
let proof = crate::control_token::server_proof(&token, req["params"]["nonce"].as_str().unwrap_or_default());
|
||||
json!({"ok": true, "result": {"proof": proof}})
|
||||
})
|
||||
}
|
||||
|
||||
/// Answer the `hello` a client opens a connection with, as the app does; `false` when the
|
||||
/// client sent nothing.
|
||||
fn answer_hello(reader: &mut impl BufRead, out: &mut impl Write, port: u16) -> bool {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
return false;
|
||||
}
|
||||
let reply = hello_reply(&serde_json::from_str(&line).unwrap(), port).expect("a hello first");
|
||||
writeln!(out, "{reply}").is_ok()
|
||||
}
|
||||
|
||||
/// A peer squatting on the control port can't make the client buffer an endless reply line (#1925).
|
||||
#[test]
|
||||
fn an_overlong_reply_is_refused_without_buffering_it() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
crate::control_token::issue(port).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(conn.try_clone().unwrap());
|
||||
assert!(answer_hello(&mut reader, &mut conn, port));
|
||||
let mut line = String::new();
|
||||
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
// No newline: the reply never ends. A bounded client gives up after the limit.
|
||||
let _ = conn.write_all(&[b'x'; 4096]);
|
||||
let _ = conn.flush();
|
||||
@@ -549,6 +638,7 @@ mod tests {
|
||||
assert!(err.to_string().contains("longer than 100 bytes"), "{err}");
|
||||
assert!(remote.conn.is_none());
|
||||
server.join().unwrap();
|
||||
crate::control_token::revoke(port);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -563,13 +653,17 @@ mod tests {
|
||||
#[test]
|
||||
fn lost_reply_to_a_mutation_is_not_resent() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
crate::control_token::issue(port).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let mut requests = 0;
|
||||
listener.set_nonblocking(false).unwrap();
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(conn.try_clone().unwrap());
|
||||
assert!(answer_hello(&mut reader, &mut conn, port));
|
||||
let mut line = String::new();
|
||||
BufReader::new(conn).read_line(&mut line).unwrap();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
requests += 1;
|
||||
// Anything arriving on a second connection would be a resend.
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
@@ -582,6 +676,7 @@ mod tests {
|
||||
let err = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
|
||||
assert!(err.contains("may or may not have been applied"), "{err}");
|
||||
assert_eq!(server.join().unwrap(), 1);
|
||||
crate::control_token::revoke(port);
|
||||
assert!(remote.token.is_none());
|
||||
assert!(remote.conn.is_none());
|
||||
}
|
||||
@@ -591,18 +686,22 @@ mod tests {
|
||||
fn timeout_reply_says_whether_a_retry_is_safe() {
|
||||
for (state, want) in [("not-run", "safe to send again"), ("may-have-run", "Inspect the drawing first")] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
crate::control_token::issue(port).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let (mut out, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(out.try_clone().unwrap());
|
||||
assert!(answer_hello(&mut reader, &mut out, port));
|
||||
let mut line = String::new();
|
||||
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
let mut out = conn;
|
||||
reader.read_line(&mut line).unwrap();
|
||||
writeln!(out, "{}", json!({"id": 1, "ok": false, "error": "timeout", "state": state})).unwrap();
|
||||
});
|
||||
let mut remote = Remote::connect(&addr).unwrap();
|
||||
let err = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
|
||||
assert!(err.starts_with("timeout") && err.contains(want), "{err}");
|
||||
server.join().unwrap();
|
||||
crate::control_token::revoke(port);
|
||||
}
|
||||
}
|
||||
/// Retrying a read after a lost reply reloads the replacement server session token.
|
||||
@@ -612,17 +711,21 @@ mod tests {
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let old = crate::control_token::issue(addr.port()).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
let mut line = String::new();
|
||||
let mut reader = BufReader::new(conn);
|
||||
let mut reader = BufReader::new(conn.try_clone().unwrap());
|
||||
assert!(answer_hello(&mut reader, &mut conn, addr.port()));
|
||||
reader.read_line(&mut line).unwrap();
|
||||
let first: Value = serde_json::from_str(&line).unwrap();
|
||||
assert!(first["token"].as_str() == Some(old.as_str()));
|
||||
let fresh = crate::control_token::issue(addr.port()).unwrap();
|
||||
drop(reader);
|
||||
drop((reader, conn));
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
line.clear();
|
||||
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
let mut reader = BufReader::new(conn.try_clone().unwrap());
|
||||
// The new session proves itself with its new token, which the client reads again.
|
||||
assert!(answer_hello(&mut reader, &mut conn, addr.port()));
|
||||
reader.read_line(&mut line).unwrap();
|
||||
let retry: Value = serde_json::from_str(&line).unwrap();
|
||||
assert!(retry["token"].as_str() == Some(fresh.as_str()));
|
||||
writeln!(conn, "{}", json!({"ok": true, "result": "pong"})).unwrap();
|
||||
@@ -636,6 +739,7 @@ mod tests {
|
||||
/// and the connection number and says what to send back; the server closes after each reply.
|
||||
/// Returns how many requests arrived, waiting a short while for each next connection.
|
||||
fn fake_app(listener: TcpListener, reply: impl Fn(&Value, usize) -> Value + Send + 'static) -> std::thread::JoinHandle<usize> {
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
std::thread::spawn(move || {
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let mut seen = 0;
|
||||
@@ -648,11 +752,13 @@ mod tests {
|
||||
Err(_) => break None,
|
||||
}
|
||||
};
|
||||
let Some(conn) = conn else { return seen };
|
||||
conn.set_nonblocking(false).unwrap();
|
||||
let Some(mut out) = conn else { return seen };
|
||||
out.set_nonblocking(false).unwrap();
|
||||
let mut reader = BufReader::new(out.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
let mut out = conn;
|
||||
if !answer_hello(&mut reader, &mut out, port) || reader.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
continue;
|
||||
}
|
||||
writeln!(out, "{}", reply(&serde_json::from_str(&line).unwrap(), seen)).unwrap();
|
||||
seen += 1;
|
||||
}
|
||||
@@ -660,21 +766,84 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A listener on another loopback address with the desktop's port (here `::1`) never receives
|
||||
/// the desktop's token.
|
||||
/// the desktop's token, nor any request: the client can't check it is the app.
|
||||
#[test]
|
||||
fn token_is_not_sent_to_another_loopback_listener() {
|
||||
fn nothing_is_sent_to_another_loopback_listener() {
|
||||
let Ok(listener) = TcpListener::bind("[::1]:0") else { return };
|
||||
let addr = listener.local_addr().unwrap();
|
||||
crate::control_token::issue(addr.port()).unwrap();
|
||||
let server = fake_app(listener, move |req, _| {
|
||||
assert!(req.get("token").is_none(), "token leaked to {addr}");
|
||||
json!({"ok": true, "result": "x"})
|
||||
let server = std::thread::spawn(move || {
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let mut got = Vec::new();
|
||||
BufReader::new(conn).read_to_end(&mut got).unwrap();
|
||||
got
|
||||
});
|
||||
let mut remote = Remote::lazy(&addr.to_string(), false);
|
||||
let got = remote.call("ping", json!({}));
|
||||
drop(remote);
|
||||
crate::control_token::revoke(addr.port());
|
||||
assert_eq!(got, Ok(json!("x")));
|
||||
assert_eq!(server.join().unwrap(), 1);
|
||||
assert!(got.as_ref().is_err_and(|e| e.contains("nothing was sent")), "{got:?}");
|
||||
assert!(server.join().unwrap().is_empty(), "the listener received bytes");
|
||||
}
|
||||
|
||||
/// A program on the app's port that answers the `hello` without the token's proof (here it
|
||||
/// echoes the nonce back, or another session's proof) gets no request, whatever it replies.
|
||||
#[test]
|
||||
fn a_peer_that_cannot_prove_the_token_gets_no_request() {
|
||||
for forged in ["echo", "other session", "error"] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
crate::control_token::issue(addr.port()).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let mut lines = Vec::new();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let start = Instant::now();
|
||||
while start.elapsed() < Duration::from_millis(500) {
|
||||
let Ok((mut out, _)) = listener.accept() else {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
continue;
|
||||
};
|
||||
out.set_nonblocking(false).unwrap();
|
||||
for line in BufReader::new(out.try_clone().unwrap()).lines() {
|
||||
let req: Value = serde_json::from_str(&line.unwrap()).unwrap();
|
||||
let nonce = req["params"]["nonce"].as_str().unwrap_or_default().to_string();
|
||||
lines.push(req["method"].as_str().unwrap_or_default().to_string());
|
||||
let reply = match forged {
|
||||
"echo" => json!({"ok": true, "result": {"proof": nonce}}),
|
||||
"other session" => json!({"ok": true, "result": {"proof": crate::control_token::server_proof("another", &nonce)}}),
|
||||
_ => json!({"ok": false, "error": "pretend error"}),
|
||||
};
|
||||
let _ = writeln!(out, "{reply}");
|
||||
}
|
||||
}
|
||||
lines
|
||||
});
|
||||
let mut remote = Remote::lazy(&addr.to_string(), false);
|
||||
let got = remote.call("engine.execute", json!({"command": "circle", "params": {}}));
|
||||
drop(remote);
|
||||
let lines = server.join().unwrap();
|
||||
crate::control_token::revoke(addr.port());
|
||||
assert!(got.is_err(), "{forged}: {got:?}");
|
||||
assert!(lines.iter().all(|m| m == "hello"), "{forged}: {lines:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An unauthenticated connection about to reach the app's `MAX_UNAUTHENTICATED_TIME` is
|
||||
/// replaced before a request is written to it, so the request isn't lost when the app closes it.
|
||||
#[test]
|
||||
fn an_unauthenticated_connection_near_the_app_deadline_is_replaced() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
crate::control_token::issue(addr.port()).unwrap();
|
||||
let server = fake_app(listener, |_, n| json!({"ok": true, "result": n}));
|
||||
let mut remote = Remote::connect(&addr.to_string()).unwrap();
|
||||
remote.opened = Some(Instant::now() - crate::control_token::MAX_UNAUTHENTICATED_TIME);
|
||||
let got = remote.call("engine.execute", json!({"command": "circle", "params": {}}));
|
||||
drop(remote);
|
||||
let requests = server.join().unwrap();
|
||||
crate::control_token::revoke(addr.port());
|
||||
// The first connection only saw the `hello`; the request went on the second.
|
||||
assert_eq!((got, requests), (Ok(json!(0)), 1));
|
||||
}
|
||||
|
||||
/// `--launch` reads the token before it opens the app, so the first request carries the token
|
||||
@@ -714,7 +883,9 @@ mod tests {
|
||||
fn unauthorized_is_resent_at_most_once_and_only_when_not_run() {
|
||||
for (state, connections) in [(Some("not-run"), 2), (Some("may-have-run"), 1), (None, 1)] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
crate::control_token::issue(port).unwrap();
|
||||
let server = fake_app(listener, move |_, _| {
|
||||
let mut r = json!({"ok": false, "error": "unauthorized: missing or invalid control token"});
|
||||
if let (Some(o), Some(state)) = (r.as_object_mut(), state) {
|
||||
@@ -726,6 +897,7 @@ mod tests {
|
||||
let err = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
|
||||
assert!(err.starts_with("unauthorized"), "{err}");
|
||||
assert_eq!(server.join().unwrap(), connections, "{state:?}");
|
||||
crate::control_token::revoke(port);
|
||||
assert!(remote.token.is_none() && remote.conn.is_none());
|
||||
}
|
||||
}
|
||||
@@ -733,20 +905,25 @@ mod tests {
|
||||
#[test]
|
||||
fn failed_mutation_write_is_not_resent() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
let mut remote = Remote::connect(&addr).unwrap();
|
||||
remote.conn.as_ref().unwrap().1.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
crate::control_token::issue(port).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(conn.try_clone().unwrap());
|
||||
assert!(answer_hello(&mut reader, &mut conn, port));
|
||||
let mut line = String::new();
|
||||
assert_eq!(BufReader::new(conn).read_line(&mut line).unwrap(), 0);
|
||||
assert_eq!(reader.read_line(&mut line).unwrap(), 0);
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
listener.accept().is_ok()
|
||||
});
|
||||
let mut remote = Remote::connect(&addr).unwrap();
|
||||
remote.conn.as_ref().unwrap().1.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
let error = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
|
||||
assert!(error.contains("may or may not have been applied"));
|
||||
assert!(!server.join().unwrap(), "a failed mutation write was retried");
|
||||
crate::control_token::revoke(port);
|
||||
assert!(remote.token.is_none());
|
||||
}
|
||||
|
||||
@@ -761,6 +938,7 @@ mod tests {
|
||||
listener: TcpListener,
|
||||
mut valid: impl FnMut(usize) -> Result<String, Value> + Send + 'static,
|
||||
) -> std::thread::JoinHandle<Vec<(usize, String, usize)>> {
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
std::thread::spawn(move || {
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let mut seen = Vec::new();
|
||||
@@ -783,6 +961,10 @@ mod tests {
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
let len = line.trim_end().len();
|
||||
line.clear();
|
||||
if let Some(reply) = hello_reply(&req, port) {
|
||||
writeln!(out, "{reply}").unwrap();
|
||||
continue;
|
||||
}
|
||||
seen.push((conn_no, req["method"].as_str().unwrap_or_default().to_string(), len));
|
||||
let reply = if !authed && len > crate::control_token::MAX_UNAUTHENTICATED_LINE {
|
||||
json!({"ok": false, "error": "request line too long before a request with the control token"})
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
|
||||
/// Length of the token in bytes (256 bits), rendered as lowercase hex.
|
||||
const TOKEN_BYTES: usize = 32;
|
||||
|
||||
@@ -21,6 +24,68 @@ const TOKEN_BYTES: usize = 32;
|
||||
/// with the token has been answered on the same connection.
|
||||
pub const MAX_UNAUTHENTICATED_LINE: usize = 64 * 1024;
|
||||
|
||||
/// How long a connection may stay open before a request on it has carried the right token; the
|
||||
/// server closes it then, so peers without the token can't hold every connection slot until the
|
||||
/// idle timeout (#1925). A client that keeps an unauthenticated connection this long opens a new one.
|
||||
pub const MAX_UNAUTHENTICATED_TIME: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
/// Shortest and longest `hello` nonce, in hexadecimal digits.
|
||||
pub const NONCE_DIGITS: std::ops::RangeInclusive<usize> = 32..=128;
|
||||
|
||||
/// What the server's proof is computed over besides the nonce, so a proof is never a valid token or
|
||||
/// a MAC made for anything else.
|
||||
const PROOF_LABEL: &[u8] = b"cadcraft control server proof v1\n";
|
||||
|
||||
/// A fresh nonce for a `hello` (256 bits of operating-system randomness, hex).
|
||||
pub fn new_nonce() -> io::Result<String> {
|
||||
random_hex()
|
||||
}
|
||||
|
||||
/// Whether `nonce` is one the server answers: hexadecimal digits, [`NONCE_DIGITS`] long.
|
||||
pub fn valid_nonce(nonce: &str) -> bool {
|
||||
NONCE_DIGITS.contains(&nonce.len()) && nonce.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// HMAC-SHA-256 of the proof label and `nonce`, keyed with the session token (HMAC takes keys of
|
||||
/// any length, so it is always `Some`).
|
||||
fn proof_mac(token: &str, nonce: &str) -> Option<Hmac<Sha256>> {
|
||||
let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(token.as_bytes()).ok()?;
|
||||
mac.update(PROOF_LABEL);
|
||||
mac.update(nonce.as_bytes());
|
||||
Some(mac)
|
||||
}
|
||||
|
||||
/// The server's answer to a `hello` carrying `nonce`: it shows the server holds the session token
|
||||
/// without sending the token, so a client can tell the app from another program listening on its
|
||||
/// port before it sends a request (#1925).
|
||||
pub fn server_proof(token: &str, nonce: &str) -> String {
|
||||
proof_mac(token, nonce).map(|mac| hex(&mac.finalize().into_bytes())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether `proof` is [`server_proof`] for `token` and `nonce`, compared in constant time.
|
||||
pub fn verify_server_proof(token: &str, nonce: &str, proof: &str) -> bool {
|
||||
let (Some(bytes), Some(mac)) = (unhex(proof), proof_mac(token, nonce)) else { return false };
|
||||
mac.verify_slice(&bytes).is_ok()
|
||||
}
|
||||
|
||||
/// Lowercase hexadecimal.
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
use std::fmt::Write as _;
|
||||
let _ = write!(s, "{b:02x}");
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The bytes of an even-length hexadecimal string, or `None`.
|
||||
fn unhex(text: &str) -> Option<Vec<u8>> {
|
||||
if !text.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
text.as_bytes().chunks(2).map(|pair| std::str::from_utf8(pair).ok().and_then(|p| u8::from_str_radix(p, 16).ok())).collect()
|
||||
}
|
||||
|
||||
/// The file holding the control token for `port`, inside a per-user private directory.
|
||||
///
|
||||
/// On Unix the runtime dir (`XDG_RUNTIME_DIR`, already `0700` and per-user) is preferred, else the
|
||||
@@ -140,12 +205,7 @@ pub fn matches(expected: &str, given: &str) -> bool {
|
||||
fn random_hex() -> io::Result<String> {
|
||||
let mut bytes = [0u8; TOKEN_BYTES];
|
||||
getrandom::fill(&mut bytes).map_err(|e| io::Error::other(format!("no secure randomness: {e}")))?;
|
||||
let mut s = String::with_capacity(TOKEN_BYTES * 2);
|
||||
for b in bytes {
|
||||
use std::fmt::Write as _;
|
||||
let _ = write!(s, "{b:02x}");
|
||||
}
|
||||
Ok(s)
|
||||
Ok(hex(&bytes))
|
||||
}
|
||||
|
||||
/// Replace a stale token with an exclusively created file using Unix mode `0600`, then flush its bytes.
|
||||
@@ -175,6 +235,32 @@ fn write_private(path: &std::path::Path, bytes: &[u8]) -> io::Result<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A proof checks out only for the token and nonce it was made with, and is neither the token
|
||||
/// nor readable as one.
|
||||
#[test]
|
||||
fn a_server_proof_holds_only_for_its_token_and_nonce() {
|
||||
let (token, nonce) = (random_hex().unwrap(), new_nonce().unwrap());
|
||||
let proof = server_proof(&token, &nonce);
|
||||
assert!(verify_server_proof(&token, &nonce, &proof));
|
||||
assert!(!verify_server_proof(&random_hex().unwrap(), &nonce, &proof), "another token");
|
||||
assert!(!verify_server_proof(&token, &new_nonce().unwrap(), &proof), "another nonce");
|
||||
assert!(!matches(&token, &proof));
|
||||
let mut flipped = proof.clone().into_bytes();
|
||||
flipped[0] = if flipped[0] == b'0' { b'1' } else { b'0' };
|
||||
for bad in [String::from_utf8(flipped).unwrap(), proof[1..].to_string(), format!("{}zz", &proof[2..]), String::new()] {
|
||||
assert!(!verify_server_proof(&token, &nonce, &bad), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonces_are_hex_of_a_bounded_length() {
|
||||
let nonce = new_nonce().unwrap();
|
||||
assert!(valid_nonce(&nonce));
|
||||
for bad in ["", "abc", &"0".repeat(*NONCE_DIGITS.end() + 1), &format!("{}g", &nonce[1..])] {
|
||||
assert!(!valid_nonce(bad), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An issued token has the expected size, can be read back, and disappears after revocation.
|
||||
#[test]
|
||||
fn issue_then_read_round_trips() {
|
||||
|
||||
+11
-2
@@ -261,19 +261,28 @@ fn a_lazy_bridge_starts_without_the_app_and_says_how_to_open_it() {
|
||||
let msg = r["result"]["content"][0]["text"].as_str().unwrap();
|
||||
assert!(msg.contains("not answering") && msg.contains("--control"), "{msg}");
|
||||
|
||||
// Once the app listens, the next call reaches it.
|
||||
// Once the app listens (and has written its token), the next call reaches it.
|
||||
let listener = std::net::TcpListener::bind(&addr).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let token = crate::control_token::issue(port).unwrap();
|
||||
let app = std::thread::spawn(move || {
|
||||
use std::io::{BufRead, Write};
|
||||
let (sock, _) = listener.accept().unwrap();
|
||||
let mut reader = std::io::BufReader::new(sock.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
std::io::BufReader::new(sock.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
let hello = serde_json::from_str::<Value>(&line).unwrap();
|
||||
let proof = crate::control_token::server_proof(&token, hello["params"]["nonce"].as_str().unwrap());
|
||||
writeln!(&sock, "{}", json!({"ok": true, "result": {"proof": proof}})).unwrap();
|
||||
line.clear();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
let id = serde_json::from_str::<Value>(&line).unwrap()["id"].clone();
|
||||
writeln!(&sock, "{}", json!({"id": id, "ok": true, "result": {"prompt": "Command:"}})).unwrap();
|
||||
});
|
||||
let r = call(&mut s, 4, "tools/call", json!({"name": "command_line", "arguments": {"text": ""}}));
|
||||
assert_ne!(r["result"]["isError"], json!(true), "{r}");
|
||||
app.join().unwrap();
|
||||
crate::control_token::revoke(port);
|
||||
}
|
||||
|
||||
/// The pixels of a `render` tool result.
|
||||
|
||||
@@ -94,7 +94,7 @@ fn coverage(t: &Table) -> Result<Vec<Vec<bool>>, Vec<Vec<bool>>> {
|
||||
|
||||
/// The table style a table uses (Standard defaults when missing).
|
||||
pub fn table_style_of(d: &Drawing, t: &Table) -> TableStyle {
|
||||
d.table_styles.by_name(&t.style).cloned().unwrap_or_default()
|
||||
d.table_styles.iter().find(|s| s.name.eq_ignore_ascii_case(&t.style)).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The scale of a table relative to its style: SCALE changes the table's text height, and every
|
||||
|
||||
@@ -23,6 +23,22 @@ reply and the connection is closed. To send a longer request (a script, a drawin
|
||||
new connection, first send a short one with the token, such as `ping`, and wait for its reply.
|
||||
The MCP bridge does this too.
|
||||
|
||||
Any program can listen on the port while the app isn't, so a client can first ask the server to
|
||||
prove it is the app, before it sends anything else on the connection:
|
||||
|
||||
```json
|
||||
{"id": "h", "method": "hello", "params": {"nonce": "<32 to 128 hexadecimal digits>"}}
|
||||
{"id": "h", "ok": true, "result": {"proof": "<64 hexadecimal digits>"}}
|
||||
```
|
||||
|
||||
`hello` needs no token and doesn't count as showing it. The proof is HMAC-SHA-256 keyed with the
|
||||
session token, over the bytes `cadcraft control server proof v1` and a newline followed by the
|
||||
nonce, in lowercase hexadecimal. A client that computes the same value from the token file knows the
|
||||
server holds the token; use a fresh random nonce each time. A `hello` without a valid nonce gets an
|
||||
error and the connection is closed. The MCP bridge sends a `hello` on every new connection and
|
||||
sends nothing more to a server that can't prove it holds the token, or when it can't read a token
|
||||
for the port.
|
||||
|
||||
Errors come back as `{"id": …, "ok": false, "error": "message"}`. An unknown method's error points
|
||||
to `control.methods`, which lists the methods the server answers.
|
||||
|
||||
@@ -32,7 +48,8 @@ after it runs. Blank lines are skipped.
|
||||
|
||||
The server bounds what a client can hold: 16 connections at once (more get an error line and are
|
||||
closed), 256 MiB per request line (64 KiB until the connection has shown the token; longer closes
|
||||
the connection), 64 queued requests (more are
|
||||
the connection), 10 seconds from connecting to the first request with the token (then the
|
||||
connection is closed, whatever it has sent), 64 queued requests (more are
|
||||
answered `{"ok": false, "error": "busy: …", "state": "not-run"}`), and 10 minutes idle or 30 seconds
|
||||
per blocked reply write before the socket is closed.
|
||||
|
||||
|
||||
+199
-195
@@ -1,213 +1,217 @@
|
||||
# Parity checklist
|
||||
|
||||
> **Generated:** 2026-11-27 by `cargo xtask parity`. Do not edit by hand.
|
||||
> **Generated:** 2026-11-01 by `cargo xtask parity`. Do not edit by hand.
|
||||
|
||||
Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment.
|
||||
|
||||
**Menu breadth: 306 / 491 items (62%)** · 482 registered commands.
|
||||
**Menu breadth: 298 / 491 items (61%)** · 449 registered commands.
|
||||
|
||||
| Menu | Items | Covered | % |
|
||||
|---|---|---|---|
|
||||
| File | 22 | 13 | 59% |
|
||||
| Edit | 13 | 12 | 92% |
|
||||
| View | 75 | 38 | 51% |
|
||||
| View | 75 | 37 | 49% |
|
||||
| Insert | 11 | 5 | 45% |
|
||||
| Format | 27 | 26 | 96% |
|
||||
| Tools | 85 | 71 | 84% |
|
||||
| Draw | 87 | 56 | 64% |
|
||||
| Tools | 85 | 66 | 78% |
|
||||
| Draw | 87 | 55 | 63% |
|
||||
| Dimension | 28 | 28 | 100% |
|
||||
| Modify | 113 | 54 | 48% |
|
||||
| Modify | 113 | 53 | 47% |
|
||||
| Window | 22 | 3 | 14% |
|
||||
| Help | 8 | 0 | 0% |
|
||||
|
||||
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 306 yes, 185 no (window 32, os 6, engine-gap 147), 0 partial, 0 unknown.**
|
||||
|
||||
A covered item is `headless: yes`: the command that covers it is in the engine registry that `cadcraft-cli` and the MCP server load. An item not covered carries its hand mark from `HEADLESS` in `xtask/src/parity.rs`, or `unknown`.
|
||||
|
||||
## Not yet covered
|
||||
|
||||
- File > New Sheet Set...: headless: no, reach: engine-gap (sheet sets could be commands)
|
||||
- File > Open Sheet Set...: headless: no, reach: engine-gap (sheet sets could be commands)
|
||||
- File > Open Recent > Clear Menu: headless: no, reach: window (the desktop recent-files list)
|
||||
- File > Attach...: headless: no, reach: engine-gap (attaching a reference could be a command)
|
||||
- File > Export Layout to Model...: headless: no, reach: engine-gap (the export could be a command)
|
||||
- File > Package Drawing...: headless: no, reach: engine-gap (packaging a drawing could be a command)
|
||||
- File > DWG Compare...: headless: no, reach: engine-gap (comparing drawings could be a command)
|
||||
- File > Markup Import...: headless: no, reach: engine-gap (the import could be a command)
|
||||
- File > Share...: headless: no, reach: os (an online sharing service)
|
||||
- Edit > Undo Group of commands: headless: no, reach: engine-gap (undo groups could be a command)
|
||||
- View > Pan > Point: headless: no, reach: window (drags the desktop view)
|
||||
- View > Orbit > Constrained Orbit: headless: no, reach: window (drags the desktop view)
|
||||
- View > Orbit > Free Orbit: headless: no, reach: window (drags the desktop view)
|
||||
- View > Camera > Adjust Distance: headless: no, reach: engine-gap (cameras could be created by a command)
|
||||
- View > Camera > Swivel: headless: no, reach: engine-gap (cameras could be created by a command)
|
||||
- View > 3D Views > Viewpoint: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > 3D Views > Plan View > Current UCS: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > 3D Views > Plan View > World UCS: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > 3D Views > Plan View > Named UCS: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > 3D Views > Top: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > 3D Views > Bottom: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > 3D Views > Front: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > 3D Views > Back: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > 3D Views > SW Isometric: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > 3D Views > SE Isometric: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > 3D Views > NE Isometric: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > 3D Views > NW Isometric: headless: no, reach: engine-gap (a saved view direction could be set by a command)
|
||||
- View > Hide: headless: no, reach: engine-gap (hidden-line output could be a command)
|
||||
- View > Visual Styles > 2D Wireframe: headless: no, reach: engine-gap (a visual style could be set by a command)
|
||||
- View > Visual Styles > Wireframe: headless: no, reach: engine-gap (a visual style could be set by a command)
|
||||
- View > Visual Styles > Hidden: headless: no, reach: engine-gap (a visual style could be set by a command)
|
||||
- View > Visual Styles > Realistic: headless: no, reach: engine-gap (a visual style could be set by a command)
|
||||
- View > Visual Styles > Conceptual: headless: no, reach: engine-gap (a visual style could be set by a command)
|
||||
- View > Visual Styles > Shaded: headless: no, reach: engine-gap (a visual style could be set by a command)
|
||||
- View > Visual Styles > Shaded with Edges: headless: no, reach: engine-gap (a visual style could be set by a command)
|
||||
- View > Visual Styles > Shades of Gray: headless: no, reach: engine-gap (a visual style could be set by a command)
|
||||
- View > Visual Styles > Sketchy: headless: no, reach: engine-gap (a visual style could be set by a command)
|
||||
- View > Visual Styles > X-Ray: headless: no, reach: engine-gap (a visual style could be set by a command)
|
||||
- View > Render > Light > New Point Light: headless: no, reach: engine-gap (rendering could be a command)
|
||||
- View > Render > Light > New Spotlight: headless: no, reach: engine-gap (rendering could be a command)
|
||||
- View > Render > Light > New Distant Light: headless: no, reach: engine-gap (rendering could be a command)
|
||||
- View > Render > Light > Light Glyphs: headless: no, reach: engine-gap (rendering could be a command)
|
||||
- View > Render > Materials Browser: headless: no, reach: engine-gap (rendering could be a command)
|
||||
- View > UCS Icon > Properties...: headless: no, reach: window (a desktop view overlay)
|
||||
- View > ViewCube > Settings: headless: no, reach: window (a desktop view control)
|
||||
- View > Lights: headless: no, reach: engine-gap (lights could be created by a command)
|
||||
- View > Enter Full Screen: headless: no, reach: window (the desktop window)
|
||||
- Insert > PDF Underlay...: headless: no, reach: engine-gap (the underlay could be inserted by a command)
|
||||
- Insert > Raster Image Reference...: headless: no, reach: engine-gap (the reference could be inserted by a command)
|
||||
- Insert > Field...: headless: no, reach: engine-gap (fields could be inserted by a command)
|
||||
- Insert > Layout > Layout from Template...: headless: no, reach: engine-gap (layouts could be created by a command)
|
||||
- Insert > ACIS File...: headless: no, reach: engine-gap (the import could be a command)
|
||||
- Insert > Drawing Exchange Binary...: headless: no, reach: engine-gap (the import could be a command)
|
||||
- Format > Transparency: headless: no, reach: engine-gap (transparency could be set by a command)
|
||||
- Tools > Spelling: headless: no, reach: engine-gap (a spell check could be a command)
|
||||
- Tools > Update Fields: headless: no, reach: engine-gap (updating fields could be a command)
|
||||
- Tools > Edit Xref in Place: headless: no, reach: window (edits a reference in the desktop view)
|
||||
- Tools > New UCS > Face: headless: no, reach: engine-gap (a coordinate system could be set by a command)
|
||||
- Tools > New UCS > Z Axis Vector: headless: no, reach: engine-gap (a coordinate system could be set by a command)
|
||||
- Tools > New UCS > X: headless: no, reach: engine-gap (a coordinate system could be set by a command)
|
||||
- Tools > New UCS > Y: headless: no, reach: engine-gap (a coordinate system could be set by a command)
|
||||
- Tools > Named UCS...: headless: no, reach: engine-gap (named coordinate systems could be commands)
|
||||
- Tools > Customize > Interface (CUI)...: headless: no, reach: window (a desktop dialog)
|
||||
- Tools > Import Settings: headless: no, reach: engine-gap (importing settings could be a command)
|
||||
- Tools > Export Settings: headless: no, reach: engine-gap (exporting settings could be a command)
|
||||
- Tools > Express Tools > Super Hatch > Image...: headless: no, reach: engine-gap (image and reference hatches could be commands)
|
||||
- Tools > Express Tools > Super Hatch > Xref...: headless: no, reach: engine-gap (image and reference hatches could be commands)
|
||||
- Tools > Express Tools > Super Hatch > Select Existing Object: headless: no, reach: window (picks an object in the desktop view)
|
||||
- Draw > 3D Modeling > Polysolid: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Box: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Wedge: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Cone: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Sphere: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Cylinder: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Torus: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Pyramid: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Extrude: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Revolve: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Sweep: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Loft: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Section Plane: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Surfaces > Planar: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Surfaces > Network: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Surfaces > Patch: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Box: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Wedge: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Cone: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Sphere: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Cylinder: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Torus: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Pyramid: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Smooth Mesh: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > 3D Face: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Meshes, Revolved Surface: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Meshes, Tabulated Surface: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Meshes, Ruled Surface: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Meshes > Meshes, Edge Surface: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Setup > Drawing: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Draw > 3D Modeling > Setup > Profile: headless: no, reach: engine-gap (3D solid and surface creation could be commands)
|
||||
- Modify > Object > External Reference > Frame: headless: no, reach: engine-gap (the frame setting could be a command)
|
||||
- Modify > Object > Image > Adjust...: headless: no, reach: engine-gap (image settings could be commands)
|
||||
- Modify > Object > Image > Quality: headless: no, reach: engine-gap (image settings could be commands)
|
||||
- Modify > Object > Image > Transparency: headless: no, reach: engine-gap (image settings could be commands)
|
||||
- Modify > Object > Image > Frame: headless: no, reach: engine-gap (image settings could be commands)
|
||||
- Modify > Clip > Image: headless: no, reach: engine-gap (clipping an image could be a command)
|
||||
- Modify > 3D Operations > 3D Move: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > 3D Operations > 3D Rotate: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > 3D Operations > 3D Align: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > 3D Operations > 3D Mirror: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > 3D Operations > 3D Array: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > 3D Operations > Interference Checking: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > 3D Operations > Slice: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > 3D Operations > Thicken: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > 3D Operations > Convert to Solid: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > 3D Operations > Convert to Surface: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > 3D Operations > Extract Edges: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > 3D Operations > Extract Isolines: headless: no, reach: engine-gap (3D operations could be commands)
|
||||
- Modify > Solid Editing > Imprint Edges: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Fillet edges: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Chamfer edges: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Color edges: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Copy edges: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Extrude faces: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Move faces: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Offset faces: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Delete faces: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Rotate faces: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Taper faces: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Color faces: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Copy faces: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Clean: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Separate: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Shell: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Solid Editing > Check: headless: no, reach: engine-gap (solid editing could be commands)
|
||||
- Modify > Surface Editing > Untrim: headless: no, reach: engine-gap (surface editing could be commands)
|
||||
- Modify > Surface Editing > Sculpt: headless: no, reach: engine-gap (surface editing could be commands)
|
||||
- Modify > Surface Editing > Convert to NURBS: headless: no, reach: engine-gap (surface editing could be commands)
|
||||
- Modify > Surface Editing > Convert to Mesh: headless: no, reach: engine-gap (surface editing could be commands)
|
||||
- Modify > Surface Editing > NURBS Surface Editing > Show CV: headless: no, reach: engine-gap (surface editing could be commands)
|
||||
- Modify > Surface Editing > NURBS Surface Editing > Hide CV: headless: no, reach: engine-gap (surface editing could be commands)
|
||||
- Modify > Surface Editing > NURBS Surface Editing > Add CV: headless: no, reach: engine-gap (surface editing could be commands)
|
||||
- Modify > Surface Editing > NURBS Surface Editing > Remove CV: headless: no, reach: engine-gap (surface editing could be commands)
|
||||
- Modify > Surface Editing > NURBS Surface Editing > Rebuild: headless: no, reach: engine-gap (surface editing could be commands)
|
||||
- Modify > Mesh Editing > Smooth More: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Smooth Less: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Refine Mesh: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Crease: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Uncrease: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Split Face: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Extrude Face: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Merge Face: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Spin Triangle Face: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Close Hole: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Collapse Face or Edge: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Convert to Faceted Solid: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Convert to Faceted Surface: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Convert to Smooth Solid: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Modify > Mesh Editing > Convert to Smooth Surface: headless: no, reach: engine-gap (mesh editing could be commands)
|
||||
- Window > Minimize: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Minimize All: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Zoom: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Tool Bar: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > File Tab: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Tool Sets: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Status Bar: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Command Line: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Blocks: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Properties Inspector: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Traces: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Sheet Set Manager: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Materials Browser: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Activity Insights: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Geometry Cleanup: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Hide Palettes: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Reset Palettes: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Start: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Window > Drawing1.dwg: headless: no, reach: window (opens or arranges a desktop window or palette)
|
||||
- Help > AutoCAD Help: headless: no, reach: os (opens online help in the browser)
|
||||
- Help > Autodesk Assistant: headless: no, reach: os (an online assistant service)
|
||||
- Help > Download Offline Help: headless: no, reach: os (an online download)
|
||||
- Help > What's New: headless: no, reach: os (opens online help in the browser)
|
||||
- Help > Highlight New Features: headless: no, reach: window (a desktop help window or dialog)
|
||||
- Help > Recover Files: headless: no, reach: window (a desktop help window or dialog)
|
||||
- Help > Send Feedback: headless: no, reach: os (an online feedback service)
|
||||
- Help > Privacy Settings...: headless: no, reach: window (a desktop help window or dialog)
|
||||
- File > New Sheet Set...
|
||||
- File > Open Sheet Set...
|
||||
- File > Open Recent > Clear Menu
|
||||
- File > Attach...
|
||||
- File > Export Layout to Model...
|
||||
- File > Package Drawing...
|
||||
- File > DWG Compare...
|
||||
- File > Markup Import...
|
||||
- File > Share...
|
||||
- Edit > Undo Group of commands
|
||||
- View > Pan > Point
|
||||
- View > Orbit > Constrained Orbit
|
||||
- View > Orbit > Free Orbit
|
||||
- View > Camera > Adjust Distance
|
||||
- View > Camera > Swivel
|
||||
- View > 3D Views > Viewpoint
|
||||
- View > 3D Views > Plan View > Current UCS
|
||||
- View > 3D Views > Plan View > World UCS
|
||||
- View > 3D Views > Plan View > Named UCS
|
||||
- View > 3D Views > Top
|
||||
- View > 3D Views > Bottom
|
||||
- View > 3D Views > Front
|
||||
- View > 3D Views > Back
|
||||
- View > 3D Views > SW Isometric
|
||||
- View > 3D Views > SE Isometric
|
||||
- View > 3D Views > NE Isometric
|
||||
- View > 3D Views > NW Isometric
|
||||
- View > Hide
|
||||
- View > Visual Styles > 2D Wireframe
|
||||
- View > Visual Styles > Wireframe
|
||||
- View > Visual Styles > Hidden
|
||||
- View > Visual Styles > Realistic
|
||||
- View > Visual Styles > Conceptual
|
||||
- View > Visual Styles > Shaded
|
||||
- View > Visual Styles > Shaded with Edges
|
||||
- View > Visual Styles > Shades of Gray
|
||||
- View > Visual Styles > Sketchy
|
||||
- View > Visual Styles > X-Ray
|
||||
- View > Render > Light > New Point Light
|
||||
- View > Render > Light > New Spotlight
|
||||
- View > Render > Light > New Distant Light
|
||||
- View > Render > Light > Light Glyphs
|
||||
- View > Render > Materials Browser
|
||||
- View > UCS Icon > Origin
|
||||
- View > UCS Icon > Properties...
|
||||
- View > ViewCube > Settings
|
||||
- View > Lights
|
||||
- View > Enter Full Screen
|
||||
- Insert > PDF Underlay...
|
||||
- Insert > Raster Image Reference...
|
||||
- Insert > Field...
|
||||
- Insert > Layout > Layout from Template...
|
||||
- Insert > ACIS File...
|
||||
- Insert > Drawing Exchange Binary...
|
||||
- Format > Transparency
|
||||
- Tools > Spelling
|
||||
- Tools > Update Fields
|
||||
- Tools > Edit Xref in Place
|
||||
- Tools > New UCS > World
|
||||
- Tools > New UCS > Face
|
||||
- Tools > New UCS > View
|
||||
- Tools > New UCS > Origin
|
||||
- Tools > New UCS > Z Axis Vector
|
||||
- Tools > New UCS > 3 Point
|
||||
- Tools > New UCS > X
|
||||
- Tools > New UCS > Y
|
||||
- Tools > New UCS > Z
|
||||
- Tools > Named UCS...
|
||||
- Tools > Customize > Interface (CUI)...
|
||||
- Tools > Import Settings
|
||||
- Tools > Export Settings
|
||||
- Tools > Express Tools > Super Hatch > Image...
|
||||
- Tools > Express Tools > Super Hatch > Xref...
|
||||
- Tools > Express Tools > Super Hatch > Select Existing Object
|
||||
- Draw > 3D Modeling > Polysolid
|
||||
- Draw > 3D Modeling > Box
|
||||
- Draw > 3D Modeling > Wedge
|
||||
- Draw > 3D Modeling > Cone
|
||||
- Draw > 3D Modeling > Sphere
|
||||
- Draw > 3D Modeling > Cylinder
|
||||
- Draw > 3D Modeling > Torus
|
||||
- Draw > 3D Modeling > Pyramid
|
||||
- Draw > 3D Modeling > Extrude
|
||||
- Draw > 3D Modeling > Revolve
|
||||
- Draw > 3D Modeling > Sweep
|
||||
- Draw > 3D Modeling > Loft
|
||||
- Draw > 3D Modeling > Section Plane
|
||||
- Draw > 3D Modeling > Surfaces > Planar
|
||||
- Draw > 3D Modeling > Surfaces > Network
|
||||
- Draw > 3D Modeling > Surfaces > Patch
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Box
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Wedge
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Cone
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Sphere
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Cylinder
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Torus
|
||||
- Draw > 3D Modeling > Meshes > Primitives > Pyramid
|
||||
- Draw > 3D Modeling > Meshes > Smooth Mesh
|
||||
- Draw > 3D Modeling > Meshes > 3D Face
|
||||
- Draw > 3D Modeling > Meshes > Meshes, Revolved Surface
|
||||
- Draw > 3D Modeling > Meshes > Meshes, Tabulated Surface
|
||||
- Draw > 3D Modeling > Meshes > Meshes, Ruled Surface
|
||||
- Draw > 3D Modeling > Meshes > Meshes, Edge Surface
|
||||
- Draw > 3D Modeling > Setup > Drawing
|
||||
- Draw > 3D Modeling > Setup > View
|
||||
- Draw > 3D Modeling > Setup > Profile
|
||||
- Modify > Object > External Reference > Frame
|
||||
- Modify > Object > Image > Adjust...
|
||||
- Modify > Object > Image > Quality
|
||||
- Modify > Object > Image > Transparency
|
||||
- Modify > Object > Image > Frame
|
||||
- Modify > Clip > Image
|
||||
- Modify > Clip > Xref
|
||||
- Modify > 3D Operations > 3D Move
|
||||
- Modify > 3D Operations > 3D Rotate
|
||||
- Modify > 3D Operations > 3D Align
|
||||
- Modify > 3D Operations > 3D Mirror
|
||||
- Modify > 3D Operations > 3D Array
|
||||
- Modify > 3D Operations > Interference Checking
|
||||
- Modify > 3D Operations > Slice
|
||||
- Modify > 3D Operations > Thicken
|
||||
- Modify > 3D Operations > Convert to Solid
|
||||
- Modify > 3D Operations > Convert to Surface
|
||||
- Modify > 3D Operations > Extract Edges
|
||||
- Modify > 3D Operations > Extract Isolines
|
||||
- Modify > Solid Editing > Imprint Edges
|
||||
- Modify > Solid Editing > Fillet edges
|
||||
- Modify > Solid Editing > Chamfer edges
|
||||
- Modify > Solid Editing > Color edges
|
||||
- Modify > Solid Editing > Copy edges
|
||||
- Modify > Solid Editing > Extrude faces
|
||||
- Modify > Solid Editing > Move faces
|
||||
- Modify > Solid Editing > Offset faces
|
||||
- Modify > Solid Editing > Delete faces
|
||||
- Modify > Solid Editing > Rotate faces
|
||||
- Modify > Solid Editing > Taper faces
|
||||
- Modify > Solid Editing > Color faces
|
||||
- Modify > Solid Editing > Copy faces
|
||||
- Modify > Solid Editing > Clean
|
||||
- Modify > Solid Editing > Separate
|
||||
- Modify > Solid Editing > Shell
|
||||
- Modify > Solid Editing > Check
|
||||
- Modify > Surface Editing > Untrim
|
||||
- Modify > Surface Editing > Sculpt
|
||||
- Modify > Surface Editing > Convert to NURBS
|
||||
- Modify > Surface Editing > Convert to Mesh
|
||||
- Modify > Surface Editing > NURBS Surface Editing > Show CV
|
||||
- Modify > Surface Editing > NURBS Surface Editing > Hide CV
|
||||
- Modify > Surface Editing > NURBS Surface Editing > Add CV
|
||||
- Modify > Surface Editing > NURBS Surface Editing > Remove CV
|
||||
- Modify > Surface Editing > NURBS Surface Editing > Rebuild
|
||||
- Modify > Mesh Editing > Smooth More
|
||||
- Modify > Mesh Editing > Smooth Less
|
||||
- Modify > Mesh Editing > Refine Mesh
|
||||
- Modify > Mesh Editing > Crease
|
||||
- Modify > Mesh Editing > Uncrease
|
||||
- Modify > Mesh Editing > Split Face
|
||||
- Modify > Mesh Editing > Extrude Face
|
||||
- Modify > Mesh Editing > Merge Face
|
||||
- Modify > Mesh Editing > Spin Triangle Face
|
||||
- Modify > Mesh Editing > Close Hole
|
||||
- Modify > Mesh Editing > Collapse Face or Edge
|
||||
- Modify > Mesh Editing > Convert to Faceted Solid
|
||||
- Modify > Mesh Editing > Convert to Faceted Surface
|
||||
- Modify > Mesh Editing > Convert to Smooth Solid
|
||||
- Modify > Mesh Editing > Convert to Smooth Surface
|
||||
- Window > Minimize
|
||||
- Window > Minimize All
|
||||
- Window > Zoom
|
||||
- Window > Tool Bar
|
||||
- Window > File Tab
|
||||
- Window > Tool Sets
|
||||
- Window > Status Bar
|
||||
- Window > Command Line
|
||||
- Window > Blocks
|
||||
- Window > Properties Inspector
|
||||
- Window > Traces
|
||||
- Window > Sheet Set Manager
|
||||
- Window > Materials Browser
|
||||
- Window > Activity Insights
|
||||
- Window > Geometry Cleanup
|
||||
- Window > Hide Palettes
|
||||
- Window > Reset Palettes
|
||||
- Window > Start
|
||||
- Window > Drawing1.dwg
|
||||
- Help > AutoCAD Help
|
||||
- Help > Autodesk Assistant
|
||||
- Help > Download Offline Help
|
||||
- Help > What's New
|
||||
- Help > Highlight New Features
|
||||
- Help > Recover Files
|
||||
- Help > Send Feedback
|
||||
- Help > Privacy Settings...
|
||||
|
||||
@@ -33,12 +33,11 @@ OUTPUT="$DIST/cadcraft-$VERSION-macos-aarch64-nightly.zip"
|
||||
nightly_compile_gui
|
||||
|
||||
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/CADCraft"
|
||||
chmod 755 "$APP/Contents/MacOS/CADCraft"
|
||||
cp "$ROOT/assets/app-icon/cadcraft-nightly.icns" "$APP/Contents/Resources/cadcraft-nightly.icns"
|
||||
# Launcher admits notices under Resources/docs, not beside the icon.
|
||||
nightly_copy_notices "$APP/Contents/Resources/docs"
|
||||
nightly_copy_notices "$APP/Contents/Resources"
|
||||
# The private mktemp cwd is the helper authority root: stage the template inside it.
|
||||
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
|
||||
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
|
||||
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
|
||||
lipo) that log their arguments. The unsigned producer also runs with a stub GUI build. These
|
||||
check the scripts and bundle layout, not native signing, notarization or Mac execution."""
|
||||
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
|
||||
real signature, notarization or Mac run."""
|
||||
import base64
|
||||
import importlib.util
|
||||
import json
|
||||
@@ -27,8 +27,6 @@ COMMIT = "b" * 40
|
||||
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
|
||||
ASSET = f"cadcraft-{VERSION}-macos-aarch64-nightly.zip"
|
||||
APP = "CADCraft Nightly.app"
|
||||
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
|
||||
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
|
||||
TEAM = "ABCDE12345"
|
||||
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
|
||||
SECRETS = {
|
||||
@@ -185,50 +183,6 @@ class Fixture:
|
||||
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
|
||||
return self.input
|
||||
|
||||
def package(self, font_licences):
|
||||
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
|
||||
source = HERE.parents[1]
|
||||
checkout = self.root / "source"
|
||||
checkout.mkdir()
|
||||
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
|
||||
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
|
||||
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
|
||||
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
|
||||
"assets/app-icon/cadcraft-nightly.icns"):
|
||||
target = checkout / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source / relative, target)
|
||||
env = self.env(**dict.fromkeys(SECRETS))
|
||||
|
||||
def git(*args):
|
||||
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
|
||||
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
|
||||
|
||||
git("init", "-q")
|
||||
git("add", "--", ".")
|
||||
git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Packaging fixture")
|
||||
commit = git("rev-parse", "HEAD").strip()
|
||||
version = VERSION[:-12] + commit[:12]
|
||||
# Generated licence text exercises the copier without depending on a font checkout.
|
||||
fonts = self.root / "craft-fonts"
|
||||
for family, data in font_licences.items():
|
||||
licence = fonts / "fonts" / family / "OFL.txt"
|
||||
licence.parent.mkdir(parents=True)
|
||||
licence.write_bytes(data)
|
||||
# The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI.
|
||||
(self.bin / "cargo").write_text(
|
||||
'#!/bin/sh\nset -eu\n'
|
||||
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/cadcraft"\n'
|
||||
'mkdir -p "$(dirname "$gui")"\n'
|
||||
"printf \"#!/bin/sh\\necho 'CADCraft %s (nightly-v1)'\\n\" \"$CADCRAFT_VERSION\" >\"$gui\"\n",
|
||||
)
|
||||
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
|
||||
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts),
|
||||
CADCRAFT_BUILD_CHANNEL="nightly-v1", CADCRAFT_VERSION=version,
|
||||
CADCRAFT_BUILD_SHA=commit, CADCRAFT_BUILD_DATE="2026-11-23")
|
||||
assert result.returncode == 0, result.stdout
|
||||
return self.dist / ASSET.replace(VERSION, version)
|
||||
|
||||
def env(self, **changes):
|
||||
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
|
||||
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
|
||||
@@ -456,40 +410,6 @@ class Verify(unittest.TestCase):
|
||||
|
||||
|
||||
class Build(unittest.TestCase):
|
||||
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
|
||||
f = Fixture(self)
|
||||
fonts = {"fixture-one": b"generated font notice one", "fixture-two": b"generated font notice two"}
|
||||
archive = f.package(fonts)
|
||||
source = HERE.parents[1]
|
||||
resources = f"{APP}/Contents/Resources"
|
||||
icon = "cadcraft-nightly.icns"
|
||||
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
|
||||
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
|
||||
notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()})
|
||||
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
|
||||
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
|
||||
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
|
||||
contents = f"{APP}/Contents"
|
||||
gui = f"{contents}/MacOS/CADCraft"
|
||||
with zipfile.ZipFile(archive) as zipped:
|
||||
entries = zipped.infolist()
|
||||
names = {entry.filename for entry in entries}
|
||||
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
|
||||
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
|
||||
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
|
||||
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
|
||||
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
|
||||
for path, data in expected_files.items():
|
||||
with self.subTest(path=path):
|
||||
self.assertEqual(zipped.read(path), data)
|
||||
mode = zipped.getinfo(path).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode))
|
||||
self.assertFalse(mode & 0o111)
|
||||
mode = zipped.getinfo(gui).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
|
||||
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
|
||||
def test_compilation_refuses_signing_material_before_building(self):
|
||||
f = Fixture(self)
|
||||
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
|
||||
|
||||
@@ -118,9 +118,8 @@ mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
# Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile).
|
||||
cp "$WORK/bin/cadcraft" "$APP/Contents/MacOS/CADCraft"
|
||||
cp "$ROOT/assets/app-icon/cadcraft.icns" "$APP/Contents/Resources/CADCraft.icns"
|
||||
# The licences and the bundled dependency font notices are installed before the app is signed.
|
||||
cp "$ROOT/LICENSE-MIT" "$ROOT/LICENSE-APACHE" "$ROOT/NOTICE" "$ROOT/ATTRIBUTION.md" \
|
||||
"$APP/Contents/Resources/"
|
||||
# Bundled dependency font notices are installed before the app is signed.
|
||||
cp "$ROOT/NOTICE" "$ROOT/ATTRIBUTION.md" "$APP/Contents/Resources/"
|
||||
# Licences of the embedded craft-fonts fonts (only when built with CRAFT_FONTS_DIR).
|
||||
copy_font_licences "$APP/Contents/Resources"
|
||||
sed -e "s/@VERSION@/$VERSION/g" -e "s/@SHORT_VERSION@/$SHORT_VERSION/g" \
|
||||
|
||||
@@ -13,12 +13,6 @@ INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
|
||||
SIGNER_BRANCH = "nightly-signer"
|
||||
|
||||
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
|
||||
# The pinned shared registry enables Windows, Linux and macOS for CADCraft.
|
||||
SIGNER_SECRETS = {
|
||||
"AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT",
|
||||
"AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE",
|
||||
"APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD",
|
||||
}
|
||||
# Each platform's one trust field in policy v3, and the public stable identity it must name.
|
||||
NIGHTLY_TRUST = {
|
||||
"windows-x86_64": ("publisher_subject",
|
||||
@@ -52,49 +46,6 @@ def assert_nightly_serialization(source):
|
||||
raise ValueError("nightly serialization must use its stable group and no cancellation")
|
||||
|
||||
|
||||
def caller_entries(lines, indent):
|
||||
"""Split the callers' plain YAML block entries; refuse other forms at checked levels."""
|
||||
entries = {}
|
||||
children = None
|
||||
for line in lines:
|
||||
if children is not None and line.startswith(" " * (indent + 1)):
|
||||
children.append(line)
|
||||
continue
|
||||
row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line)
|
||||
if row is None or row[1] in entries:
|
||||
raise ValueError("malformed or duplicate caller mapping entry")
|
||||
children = []
|
||||
entries[row[1]] = row[2], children
|
||||
return entries
|
||||
|
||||
|
||||
def assert_caller_secrets(source, job_name, names):
|
||||
"""Check the actual caller's root, job and secret blocks without a YAML dependency."""
|
||||
lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")]
|
||||
root = caller_entries(lines, 0)
|
||||
job_marker, job_lines = root.pop("jobs", (None, []))
|
||||
jobs = caller_entries(job_lines, 2)
|
||||
if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None:
|
||||
raise ValueError("the caller must have one plain job block")
|
||||
job = caller_entries(jobs[job_name][1], 4)
|
||||
if "environment" in job or "environment" in root or "secrets" in root:
|
||||
raise ValueError("only the native callee may bind the environment")
|
||||
if names:
|
||||
if "secrets" not in job:
|
||||
raise ValueError("signer requires an explicit target-specific secret map")
|
||||
mode, secret_lines = job.pop("secrets")
|
||||
expected = {name: ("${{ secrets." + name + " }}", []) for name in names}
|
||||
if mode is not None or caller_entries(secret_lines, 6) != expected:
|
||||
raise ValueError("signer must forward exactly the reviewed same-name secret references")
|
||||
elif "secrets" in job:
|
||||
raise ValueError("unsigned caller must not pass secrets")
|
||||
for value, children in (*root.values(), *job.values()):
|
||||
outside_map = "\n".join([value or "", *children])
|
||||
# Scan all remaining text: quoted braces can appear before a secret reference.
|
||||
if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map):
|
||||
raise ValueError("secret bindings belong only in the signer map")
|
||||
|
||||
|
||||
def job_conditions(jobs):
|
||||
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read)."""
|
||||
lines = jobs.splitlines()
|
||||
@@ -231,49 +182,8 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
with self.subTest(workflow=name):
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
|
||||
|
||||
def test_signer_forwards_exactly_the_reviewed_secret_names(self):
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
assert_caller_secrets(signer, "release", SIGNER_SECRETS)
|
||||
|
||||
def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self):
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
header = " secrets:\n"
|
||||
linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n"
|
||||
self.assertIn(linux, signer)
|
||||
mutations = {
|
||||
"missing name": signer.replace(linux, ""),
|
||||
"extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n",
|
||||
"renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")),
|
||||
"duplicate name": signer.replace(linux, linux + linux),
|
||||
"duplicate map": signer + header + linux,
|
||||
"quoted duplicate map": signer + ' "secrets": inherit\n',
|
||||
"inherit": signer.split(header)[0] + " secrets: inherit\n",
|
||||
"yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"),
|
||||
"yaml merge": signer + " <<: *other\n",
|
||||
"environment": signer + " environment: release\n",
|
||||
"secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"),
|
||||
}
|
||||
for change, source in mutations.items():
|
||||
with self.subTest(change=change), self.assertRaises(ValueError):
|
||||
assert_caller_secrets(source, "release", SIGNER_SECRETS)
|
||||
|
||||
def test_unsigned_caller_has_no_secrets(self):
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
assert_caller_secrets(producer, "unsigned", set())
|
||||
for suffix in (" secrets: {}\n", " secrets: inherit\n",
|
||||
" secrets:\n EXTRA: ${{ secrets.EXTRA }}\n",
|
||||
" extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"):
|
||||
with self.subTest(suffix=suffix), self.assertRaises(ValueError):
|
||||
assert_caller_secrets(producer + suffix, "unsigned", set())
|
||||
|
||||
def test_unsigned_caller_refuses_secret_after_format_brace(self):
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
# This inert fixture is never dispatched; the brace is part of the format string.
|
||||
env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n"
|
||||
source = producer.replace("jobs:\n", env + "jobs:\n", 1)
|
||||
with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"):
|
||||
assert_caller_secrets(source, "unsigned", set())
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
|
||||
self.assertNotIn("secrets.", executable)
|
||||
|
||||
|
||||
class NightlyTrustAnchors(unittest.TestCase):
|
||||
|
||||
+1
-163
@@ -25,125 +25,6 @@ pub fn leaves(catalog: &str) -> Vec<String> {
|
||||
out
|
||||
}
|
||||
|
||||
/// RFC-0052 hand marks for menu leaves no engine command covers: `(path, headless, reach, why)`.
|
||||
/// A path ending in ` > ` marks every leaf under it; the longest matching path wins.
|
||||
///
|
||||
/// `headless` is `no` or `partial`; `reach` is `window` (needs a desktop window, dialog or pointer),
|
||||
/// `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be an engine
|
||||
/// command, isn't one yet). `yes` is never written here: a leaf is `yes` only when a command from
|
||||
/// `cadcraft-cli commands`, the engine registry the CLI and the MCP server load, covers it. An
|
||||
/// unmarked uncovered leaf is `unknown`. [`mark_errors`] rejects marks that match nothing or only
|
||||
/// hide a `yes`.
|
||||
pub const HEADLESS: &[(&str, &str, &str, &str)] = &[
|
||||
("Draw > 3D Modeling > ", "no", "engine-gap", "3D solid and surface creation could be commands"),
|
||||
("Modify > 3D Operations > ", "no", "engine-gap", "3D operations could be commands"),
|
||||
("Modify > Solid Editing > ", "no", "engine-gap", "solid editing could be commands"),
|
||||
("Modify > Mesh Editing > ", "no", "engine-gap", "mesh editing could be commands"),
|
||||
("Modify > Surface Editing > ", "no", "engine-gap", "surface editing could be commands"),
|
||||
("View > 3D Views > ", "no", "engine-gap", "a saved view direction could be set by a command"),
|
||||
("View > Visual Styles > ", "no", "engine-gap", "a visual style could be set by a command"),
|
||||
("View > Render > ", "no", "engine-gap", "rendering could be a command"),
|
||||
("View > Camera > ", "no", "engine-gap", "cameras could be created by a command"),
|
||||
("View > Lights", "no", "engine-gap", "lights could be created by a command"),
|
||||
("View > Hide", "no", "engine-gap", "hidden-line output could be a command"),
|
||||
("View > Orbit > ", "no", "window", "drags the desktop view"),
|
||||
("View > Pan > ", "no", "window", "drags the desktop view"),
|
||||
("View > ViewCube > ", "no", "window", "a desktop view control"),
|
||||
("View > UCS Icon > ", "no", "window", "a desktop view overlay"),
|
||||
("View > Enter Full Screen", "no", "window", "the desktop window"),
|
||||
("Tools > New UCS > ", "no", "engine-gap", "a coordinate system could be set by a command"),
|
||||
("Tools > Named UCS...", "no", "engine-gap", "named coordinate systems could be commands"),
|
||||
("Tools > Customize > ", "no", "window", "a desktop dialog"),
|
||||
("Window > ", "no", "window", "opens or arranges a desktop window or palette"),
|
||||
("Help > ", "no", "window", "a desktop help window or dialog"),
|
||||
("Help > AutoCAD Help", "no", "os", "opens online help in the browser"),
|
||||
("Help > What's New", "no", "os", "opens online help in the browser"),
|
||||
("Help > Send Feedback", "no", "os", "an online feedback service"),
|
||||
("Help > Download Offline Help", "no", "os", "an online download"),
|
||||
("Help > Autodesk Assistant", "no", "os", "an online assistant service"),
|
||||
("File > Share...", "no", "os", "an online sharing service"),
|
||||
("File > Open Recent > ", "no", "window", "the desktop recent-files list"),
|
||||
("File > New Sheet Set...", "no", "engine-gap", "sheet sets could be commands"),
|
||||
("File > Open Sheet Set...", "no", "engine-gap", "sheet sets could be commands"),
|
||||
("File > Package Drawing...", "no", "engine-gap", "packaging a drawing could be a command"),
|
||||
("File > Export Layout to Model...", "no", "engine-gap", "the export could be a command"),
|
||||
("File > DWG Compare...", "no", "engine-gap", "comparing drawings could be a command"),
|
||||
("File > Markup Import...", "no", "engine-gap", "the import could be a command"),
|
||||
("File > Attach...", "no", "engine-gap", "attaching a reference could be a command"),
|
||||
("Edit > Undo Group of commands", "no", "engine-gap", "undo groups could be a command"),
|
||||
("Insert > Raster Image Reference...", "no", "engine-gap", "the reference could be inserted by a command"),
|
||||
("Insert > PDF Underlay...", "no", "engine-gap", "the underlay could be inserted by a command"),
|
||||
("Insert > Layout > ", "no", "engine-gap", "layouts could be created by a command"),
|
||||
("Insert > Field...", "no", "engine-gap", "fields could be inserted by a command"),
|
||||
("Insert > Drawing Exchange Binary...", "no", "engine-gap", "the import could be a command"),
|
||||
("Insert > ACIS File...", "no", "engine-gap", "the import could be a command"),
|
||||
("Format > Transparency", "no", "engine-gap", "transparency could be set by a command"),
|
||||
("Tools > Spelling", "no", "engine-gap", "a spell check could be a command"),
|
||||
("Tools > Update Fields", "no", "engine-gap", "updating fields could be a command"),
|
||||
("Tools > Edit Xref in Place", "no", "window", "edits a reference in the desktop view"),
|
||||
("Tools > Import Settings", "no", "engine-gap", "importing settings could be a command"),
|
||||
("Tools > Export Settings", "no", "engine-gap", "exporting settings could be a command"),
|
||||
("Tools > Express Tools > Super Hatch > ", "no", "engine-gap", "image and reference hatches could be commands"),
|
||||
("Tools > Express Tools > Super Hatch > Select Existing Object", "no", "window", "picks an object in the desktop view"),
|
||||
("Modify > Object > External Reference > Frame", "no", "engine-gap", "the frame setting could be a command"),
|
||||
("Modify > Object > Image > ", "no", "engine-gap", "image settings could be commands"),
|
||||
("Modify > Clip > Image", "no", "engine-gap", "clipping an image could be a command"),
|
||||
];
|
||||
|
||||
/// Whether a `HEADLESS` path covers a leaf.
|
||||
fn mark_covers(mark: &str, leaf: &str) -> bool {
|
||||
mark == leaf || (mark.ends_with(" > ") && leaf.starts_with(mark))
|
||||
}
|
||||
|
||||
/// A leaf's RFC-0052 `(headless, reach, why)`: `yes` when an engine command covers it, else the
|
||||
/// longest mark that covers it, else `unknown`.
|
||||
pub fn headless_of<'a>(leaf: &str, covered: bool, marks: &[(&'a str, &'a str, &'a str, &'a str)]) -> (&'a str, Option<&'a str>, &'a str) {
|
||||
if covered {
|
||||
return ("yes", None, "");
|
||||
}
|
||||
marks.iter().filter(|m| mark_covers(m.0, leaf)).max_by_key(|m| m.0.len()).map_or(("unknown", None, ""), |m| (m.1, Some(m.2), m.3))
|
||||
}
|
||||
|
||||
/// Problems with `marks` against `leaves` (`(path, covered)`): bad values, repeats, a mark that
|
||||
/// matches no leaf, and a mark whose leaves are all covered (it would only hide a `yes`).
|
||||
pub fn mark_errors(marks: &[(&str, &str, &str, &str)], leaves: &[(String, bool)]) -> Vec<String> {
|
||||
let mut errs = Vec::new();
|
||||
for (i, (path, value, reach, _)) in marks.iter().enumerate() {
|
||||
if !matches!(*value, "no" | "partial") {
|
||||
errs.push(format!("headless mark `{path}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
|
||||
}
|
||||
if !matches!(*reach, "window" | "os" | "engine-gap") {
|
||||
errs.push(format!("headless mark `{path}`: reach `{reach}` is not window, os or engine-gap"));
|
||||
}
|
||||
if marks[..i].iter().any(|m| m.0 == *path) {
|
||||
errs.push(format!("headless mark `{path}` is written twice"));
|
||||
}
|
||||
let hits: Vec<bool> = leaves.iter().filter(|l| mark_covers(path, &l.0)).map(|l| l.1).collect();
|
||||
if hits.is_empty() {
|
||||
errs.push(format!("headless mark `{path}` matches no catalog leaf"));
|
||||
} else if hits.iter().all(|c| *c) {
|
||||
errs.push(format!("headless mark `{path}` is stale: a command covers every leaf it marks"));
|
||||
}
|
||||
}
|
||||
errs
|
||||
}
|
||||
|
||||
/// The RFC-0052 summary line for `values` (`(headless, reach)` per leaf).
|
||||
pub fn headless_summary(values: &[(&str, Option<&str>)]) -> String {
|
||||
let count = |v: &str| values.iter().filter(|h| h.0 == v).count();
|
||||
let no = |r: &str| values.iter().filter(|h| h.0 == "no" && h.1 == Some(r)).count();
|
||||
format!(
|
||||
"**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.**",
|
||||
count("yes"),
|
||||
count("no"),
|
||||
no("window"),
|
||||
no("os"),
|
||||
no("engine-gap"),
|
||||
count("partial"),
|
||||
count("unknown")
|
||||
)
|
||||
}
|
||||
|
||||
/// Where the generated checklist goes.
|
||||
pub const OUT: &str = "docs/parity-checklist.md";
|
||||
|
||||
@@ -204,14 +85,12 @@ pub fn run(root: &Path) -> Result<(), String> {
|
||||
let ls = leaves(&catalog);
|
||||
let mut by_menu: Vec<(String, usize, usize)> = Vec::new();
|
||||
let mut missing = Vec::new();
|
||||
let mut checked: Vec<(String, bool)> = Vec::new();
|
||||
let mut hit = 0;
|
||||
for l in &ls {
|
||||
let top = l.split(" > ").next().unwrap_or("").to_string();
|
||||
let lower = l.to_ascii_lowercase();
|
||||
let leaf = lower.rsplit(" > ").next().unwrap_or("").to_string();
|
||||
let ok = paths.contains(&lower) || labels.contains(&leaf);
|
||||
checked.push((l.clone(), ok));
|
||||
if ok {
|
||||
hit += 1;
|
||||
} else {
|
||||
@@ -225,11 +104,6 @@ pub fn run(root: &Path) -> Result<(), String> {
|
||||
None => by_menu.push((top, 1, usize::from(ok))),
|
||||
}
|
||||
}
|
||||
let errs = mark_errors(HEADLESS, &checked);
|
||||
if !errs.is_empty() {
|
||||
return Err(format!("RFC-0052 headless marks in xtask/src/parity.rs:\n {}", errs.join("\n ")));
|
||||
}
|
||||
let values: Vec<(&str, Option<&str>)> = checked.iter().map(|(l, ok)| headless_of(l, *ok, HEADLESS)).map(|h| (h.0, h.1)).collect();
|
||||
let pct = |a: usize, b: usize| if b == 0 { 0.0 } else { 100.0 * a as f64 / b as f64 };
|
||||
let mut md = format!(
|
||||
"# Parity checklist\n\n> **Generated:** {} by `cargo xtask parity`. Do not edit by hand.\n\nMenu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment.\n\n**Menu breadth: {hit} / {} items ({:.0}%)** · {} registered commands.\n\n| Menu | Items | Covered | % |\n|---|---|---|---|\n",
|
||||
@@ -241,15 +115,9 @@ pub fn run(root: &Path) -> Result<(), String> {
|
||||
for (m, n, k) in &by_menu {
|
||||
md += &format!("| {m} | {n} | {k} | {:.0}% |\n", pct(*k, *n));
|
||||
}
|
||||
md += &format!(
|
||||
"\n{}\n\nA covered item is `headless: yes`: the command that covers it is in the engine registry that `cadcraft-cli` and the MCP server load. An item not covered carries its hand mark from `HEADLESS` in `xtask/src/parity.rs`, or `unknown`.\n",
|
||||
headless_summary(&values)
|
||||
);
|
||||
md += "\n## Not yet covered\n\n";
|
||||
for m in &missing {
|
||||
let (value, reach, why) = headless_of(m, false, HEADLESS);
|
||||
let reach = reach.map(|r| format!(", reach: {r} ({why})")).unwrap_or_default();
|
||||
md += &format!("- {m}: headless: {value}{reach}\n");
|
||||
md += &format!("- {m}\n");
|
||||
}
|
||||
std::fs::write(root.join(OUT), md).map_err(|e| format!("{OUT}: {e}"))?;
|
||||
println!("parity: {hit}/{} menu items ({:.0}%) → {OUT}", ls.len(), pct(hit, ls.len()));
|
||||
@@ -277,36 +145,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_marks_pick_the_longest_path() {
|
||||
let marks = [("W > ", "no", "window", "a"), ("W > C > ", "no", "os", "b"), ("X", "partial", "engine-gap", "c")];
|
||||
assert_eq!(headless_of("W > C > M", false, &marks), ("no", Some("os"), "b"));
|
||||
assert_eq!(headless_of("W > Mix", false, &marks), ("no", Some("window"), "a"));
|
||||
assert_eq!(headless_of("W > Mix", true, &marks).0, "yes", "a covered leaf is yes whatever the mark says");
|
||||
assert_eq!(headless_of("WX", false, &marks).0, "unknown", "a prefix mark needs the separator");
|
||||
let s = headless_summary(&[("yes", None), ("no", Some("window")), ("no", Some("os")), ("unknown", None)]);
|
||||
assert!(s.contains("1 yes, 2 no (window 1, os 1, engine-gap 0), 0 partial, 1 unknown"), "{s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_headless_marks_are_refused() {
|
||||
let leaves = [("W > Mix".to_string(), false), ("X".to_string(), true)];
|
||||
let bad = [("W > ", "yes", "window", ""), ("W > ", "no", "desk", ""), ("X", "no", "os", ""), ("Z", "no", "os", "")];
|
||||
let errs = mark_errors(&bad, &leaves);
|
||||
for want in ["is not `no` or `partial`", "reach `desk`", "written twice", "`X` is stale", "`Z` matches no catalog leaf"] {
|
||||
assert!(errs.iter().any(|e| e.contains(want)), "{want}: {errs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checked_in_marks_name_catalog_leaves() {
|
||||
let catalog = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/data/menu-catalog.txt")).unwrap_or_default();
|
||||
let leaves: Vec<(String, bool)> = leaves(&catalog).into_iter().map(|l| (l, false)).collect();
|
||||
assert!(!leaves.is_empty());
|
||||
let errs = mark_errors(HEADLESS, &leaves);
|
||||
assert!(errs.is_empty(), "{errs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_with_paths() {
|
||||
let c = "Draw\n Line\n Circle\n 3 Points\n 2 Points\nModify\n Move\n";
|
||||
|
||||
Reference in New Issue
Block a user