mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-22 22:07:45 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe3b20a37a | ||
|
|
9746b6999a | ||
|
|
0ca0af9026 | ||
|
|
6971715295 | ||
|
|
8d3236c5a3 | ||
|
|
5bfba91aa8 | ||
|
|
080c96aa06 | ||
|
|
a2f732118f | ||
|
|
c2af11dfa7 | ||
|
|
f4d4a6e4e1 | ||
|
|
b1dcb46e08 | ||
|
|
c00bc59949 | ||
|
|
1b577e9eed | ||
|
|
29bf02b6ce | ||
|
|
1998da2643 | ||
|
|
28ed9c58a7 | ||
|
|
a3560a1442 | ||
|
|
80e9a97164 | ||
|
|
97dccaf9e7 | ||
|
|
b39170aded | ||
|
|
20d489f059 | ||
|
|
318d8d9de1 | ||
|
|
4076a71dee | ||
|
|
e5a7d38a67 | ||
|
|
46053d43c1 | ||
|
|
6aa64fb5ae | ||
|
|
543285778b | ||
|
|
fed8b0f4e4 | ||
|
|
50baa3cfae | ||
|
|
ef6df4dffa | ||
|
|
97c5670a0a | ||
|
|
ed294b3fb3 | ||
|
|
40ddd7baca | ||
|
|
ea4a59b662 | ||
|
|
9e645ba17a | ||
|
|
8da04230af | ||
|
|
af5c658a4b | ||
|
|
5d76e47342 | ||
|
|
3caad662a4 | ||
|
|
615fee3e12 | ||
|
|
92fe0a655d | ||
|
|
a62dd047a4 | ||
|
|
b4c325a36b | ||
|
|
1ad4fc7c91 | ||
|
|
8178a68f3e | ||
|
|
29a22f7955 | ||
|
|
48f0a590ab | ||
|
|
80f2b6838d | ||
|
|
70e55f21cc | ||
|
|
d3af2d5077 | ||
|
|
afcf5d3461 | ||
|
|
7ecf836de7 | ||
|
|
4b97a1a25e | ||
|
|
4683023d94 | ||
|
|
44e0e431ee | ||
|
|
0b454bb536 | ||
|
|
9f2cd4ca78 | ||
|
|
1d92bb275c | ||
|
|
c73b1487ea | ||
|
|
2dc136781b | ||
|
|
5c00b66572 | ||
|
|
0e0344be94 | ||
|
|
3ec1e1b210 | ||
|
|
3165d2735e | ||
|
|
d04d67f8c3 | ||
|
|
67cc9a28c3 | ||
|
|
73d1b65f3e | ||
|
|
dab89a38ed | ||
|
|
3c956c4ccf | ||
|
|
3ee12a8c62 | ||
|
|
b8f60e1e60 | ||
|
|
984596fead | ||
|
|
c40ff9603e | ||
|
|
5869cf91f9 | ||
|
|
8e2aa822f7 | ||
|
|
595ccf2b06 | ||
|
|
a34cf69439 | ||
|
|
6ec0f2400a | ||
|
|
203865064a | ||
|
|
18effe68b4 | ||
|
|
b325046f76 | ||
|
|
48bcb817ed | ||
|
|
467ab20ace | ||
|
|
275f989aa5 | ||
|
|
fd17a05b95 | ||
|
|
f7b3b68952 | ||
|
|
8acdceeb61 | ||
|
|
4ce72c668a | ||
|
|
ad6d3d12ca | ||
|
|
6412e9c99a | ||
|
|
f7c4c148a3 | ||
|
|
0bd4d54f4a | ||
|
|
11ee9f1f64 | ||
|
|
e928316c4d | ||
|
|
1a3d2f6015 | ||
|
|
a801739ea7 | ||
|
|
41f9e394b9 | ||
|
|
dc59a8e33c | ||
|
|
b17880ca89 | ||
|
|
72e82c59d0 | ||
|
|
72f8dd8076 | ||
|
|
cc74fe32ed | ||
|
|
55ec024e31 | ||
|
|
9a5f26d5aa | ||
|
|
f646452065 | ||
|
|
5ab29b4090 | ||
|
|
64cb95d8ec | ||
|
|
4a0063f5f6 | ||
|
|
b6cc1c29ee | ||
|
|
015fe2a18d | ||
|
|
bb95044b19 | ||
|
|
bee69e6f24 | ||
|
|
0bf230b14a | ||
|
|
f4f0702d08 | ||
|
|
98401d6de2 | ||
|
|
97fbaf7da4 | ||
|
|
90a239b410 | ||
|
|
0a23281d45 | ||
|
|
3f3ac1ded9 | ||
|
|
7f2e4bb817 | ||
|
|
c667151667 | ||
|
|
d2a1090357 | ||
|
|
24e5687c3d | ||
|
|
a35817eaea | ||
|
|
b49137f6dd | ||
|
|
5147aae2c2 | ||
|
|
b551acec8d | ||
|
|
fa4f997eed |
Generated
-12
@@ -661,7 +661,6 @@ dependencies = [
|
||||
"craft-window",
|
||||
"eframe",
|
||||
"egui",
|
||||
"fmv-macos-events",
|
||||
"hidapi",
|
||||
"log",
|
||||
"muda",
|
||||
@@ -2057,17 +2056,6 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
|
||||
|
||||
[[package]]
|
||||
name = "fmv-macos-events"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.1.5"
|
||||
|
||||
+15
-10
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: pre-alpha** · next: alpha, when the six rows of the [alpha gate](docs/roadmap.md#alpha-gate) pass (five fail today; the gate was revised on 2026-11-19 and its hours are not re-estimated yet)
|
||||
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-19 · **Change:** major (alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-20 · **Change:** minor (Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
|
||||
CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and
|
||||
plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a
|
||||
@@ -115,21 +115,23 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
|
||||
- The open findings of the security audit (#1919–#1935): check each against the input limits that
|
||||
landed on 2026-11-11, close what is fixed and fix the rest. A crafted handle that makes new entities
|
||||
overwrite existing ones (#1921) is fixed by #1276.
|
||||
- Hostile-input fixes waiting in pull requests (#2820, #2821, #2765).
|
||||
- A saved file that crashes AutoCAD 2021 (#3303) and dimension text lost on save (#3299).
|
||||
- Crashes and hangs with a reproduction: the web build on a large DXF (#1603), a DWG with 3D content
|
||||
(#2174), startup on older graphics hardware (#1724, #1631, #3222).
|
||||
|
||||
**2. Parity with AutoCAD: the alpha gate rows, then the beta checklist (apart from its items named under tier 3).**
|
||||
- It starts on common hardware (#1596, then an automatic fallback renderer).
|
||||
- It starts on common hardware: an automatic fallback renderer (`CADCRAFT_STENCIL=0` is the manual
|
||||
switch since #3336).
|
||||
- It opens the DWG and DXF files people already have: large files (#3102, #2633, #1088), layouts and
|
||||
paper units (#1672, #2836), and a corpus of real files run in CI.
|
||||
- Saving loses nothing and other CAD programs open the result (#2904, #1687, #3234, #2632).
|
||||
- Input feels like AutoCAD for Windows: clicks while the mouse moves (#1001, #2092), right-click and
|
||||
Space as Enter (#1387), double-click to edit text (#842).
|
||||
- The prompt options that still say "not available yet", and TRIM/EXTEND depth.
|
||||
- Layouts print at scale on a system printer, and the menu bar and panels can always be restored
|
||||
(#3216, #1240).
|
||||
- 714 pull requests are open (2026-11-19). About 230 are mergeable, pass CI and are small; they are
|
||||
- Input feels like AutoCAD for Windows: the fixes for clicks while the mouse moves, right-click and
|
||||
Space as Enter, and double-click text editing landed (#3307, #3345); waiting for the reporters to
|
||||
confirm, and table cells are left (#842).
|
||||
- The prompt options that still say "not available yet" (gaps F1).
|
||||
- Layouts print at scale on a system printer (#3216); the menu bar and panels can be restored since
|
||||
#3308.
|
||||
- 661 pull requests are open (2026-11-20; 714 the day before). About 230 were mergeable, passed CI and were small; they are
|
||||
reviewed and landed in this order, the longest-waiting authors first within a row.
|
||||
|
||||
**3. Lower priority: affects fewer people and nothing breaks without it.**
|
||||
@@ -139,7 +141,9 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
|
||||
but a file with 3D content must open safely (tier 1).
|
||||
- Menu breadth against AutoCAD for Mac as a headline number.
|
||||
|
||||
Done since the last ranking: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
|
||||
Done on 2026-11-19 and 2026-11-20: the hostile-input fixes #1276, #2820, #2821 and #2765 (#3304, #3305), clicks while the mouse moves and right-click or Space as Enter (#3307), the interface reset (#3308), paper units (#3309), the UCS command (#3310), -ATTEDIT, -RENAME and -LAYER options (#3311), TRIM/EXTEND depth (#3312), dimension values kept on save (#3335), the stencil switch (#3336), a typed OPEN path (#3343) and double-click text editing (#3345).
|
||||
|
||||
Done before that: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
|
||||
OFFSET, ROTATE, PLINE, SPLINE, MTEXT and MLEADER (#397, #408, #547), autosave, recovery, AUDIT and
|
||||
RECOVER on the desktop (#406, #416), xrefs (#525), groups (#417), the Block Editor (#824, #833, #885),
|
||||
REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the Dimension Style Manager
|
||||
@@ -166,6 +170,7 @@ REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the D
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | minor | Upcoming updated for the merges of 2026-11-19 and 2026-11-20 (security stacks, input, interface reset, paper units, UCS, prompt options, TRIM/EXTEND, text editing in place); pull-request count 714 → 661; percentages and hours not re-scored |
|
||||
| 2026-11-19 | major | Alpha gate revised from user reports (six rows, Windows first; block authoring, xref editing in place and exact curve geometry moved to beta); Upcoming re-ranked into three tiers: urgent (security, leaks, crashes, lost work), parity, lower priority; percentages and hours not re-scored |
|
||||
| 2026-10-24 | minor | Re-audit against main 41d9b5e95: language table, CI gate and open-PR count re-checked against main 41d9b5e95 |
|
||||
| 2026-10-21 | trivial | Progress log: proxy objects keep their class through a save (#1812) |
|
||||
|
||||
@@ -56,6 +56,8 @@ fn install_io() {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
}
|
||||
|
||||
/// `path` as text, for the engine and io calls that take a file name as a string.
|
||||
|
||||
@@ -130,6 +130,8 @@ mod web {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
let Some(canvas) = app_canvas() else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
|
||||
@@ -62,11 +62,6 @@ winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
|
||||
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
|
||||
# in Cargo.lock through eframe.
|
||||
pollster = "1"
|
||||
# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C
|
||||
# handler behind a safe API, without relaxing the workspace's unsafe-code lint.
|
||||
# Pinned exactly: review the implementation before bumping.
|
||||
fmv-macos-events = "=0.1.0"
|
||||
|
||||
# Rust HID backends: no proprietary SDK or C HID library.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
//! macOS open-documents and quit Apple events (#158).
|
||||
//!
|
||||
//! A Finder double-click, Open With, a drop on the Dock icon and `open -a CADCraft plan.dxf` don't
|
||||
//! put the path in argv: LaunchServices sends the running (or just-launched) app a
|
||||
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
|
||||
//! `NSApplicationDelegate`, so AppKit answered "CADCraft cannot open files in the Drawing Exchange
|
||||
//! Format format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which
|
||||
//! this workspace forbids. The pinned `fmv-macos-events` crate wraps exactly that, an
|
||||
//! `NSAppleEventManager` handler registered before Finder's
|
||||
//! launch event that leaves winit's delegate alone, behind a safe main-thread API.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use cadcraft_ui_egui::CadApp;
|
||||
#[cfg(target_os = "macos")]
|
||||
use fmv_macos_events::{Event, Inbox, Registration};
|
||||
|
||||
/// The shape of `fmv_macos_events::Event`, so [`dispatch`] and its tests also build and run where
|
||||
/// that crate is not compiled (PR CI runs on Linux). On macOS the crate's own type is used.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
enum Event {
|
||||
Open(Vec<PathBuf>),
|
||||
Quit,
|
||||
}
|
||||
|
||||
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub struct AppleEvents {
|
||||
_registration: Registration,
|
||||
inbox: Inbox,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl AppleEvents {
|
||||
/// Register the handlers. Call on the main thread before the event loop starts, so the event
|
||||
/// that launched the app (a Finder double-click) is caught too.
|
||||
pub fn install() -> Self {
|
||||
let (registration, inbox) = Registration::install();
|
||||
Self { _registration: registration, inbox }
|
||||
}
|
||||
|
||||
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
|
||||
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
|
||||
let ctx = ctx.clone();
|
||||
self.inbox.set_wake(move || ctx.request_repaint());
|
||||
self.inbox.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths to hand to OPEN: UTF-8 and non-empty, each once, in the order they arrived. A second
|
||||
/// copy of the same path (Finder sends one per selected item, and a drop can repeat) would open
|
||||
/// the drawing twice.
|
||||
fn openable(paths: impl IntoIterator<Item = PathBuf>) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for p in paths {
|
||||
if let Some(s) = p.to_str().filter(|s| !s.is_empty())
|
||||
&& !out.iter().any(|o| o == s)
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Dispatch a batch through the regular opening and unsaved-changes paths. Returns whether the
|
||||
/// window may close now; a queued quit must not bypass the Save / Don't Save / Cancel prompt.
|
||||
fn dispatch(events: impl IntoIterator<Item = Event>, app: &mut CadApp) -> bool {
|
||||
let mut quit = false;
|
||||
for e in events {
|
||||
match e {
|
||||
Event::Open(paths) => {
|
||||
for p in openable(paths) {
|
||||
app.open_path(std::path::Path::new(&p));
|
||||
}
|
||||
}
|
||||
Event::Quit => quit = true,
|
||||
}
|
||||
}
|
||||
quit && !app.request_quit()
|
||||
}
|
||||
|
||||
/// Drain the inbox each frame; a quit closes the window like Cmd+Q, prompting for unsaved drawings.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn poll(inbox: &Inbox, app: &mut CadApp, ctx: &egui::Context) {
|
||||
if dispatch(inbox.drain(), app) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Event, dispatch, openable};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::closing::Choice;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct TestDir(PathBuf);
|
||||
|
||||
impl TestDir {
|
||||
fn new() -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-apple-events-{}-{}", std::process::id(), NEXT_DIR.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn app() -> CadApp {
|
||||
crate::install_io();
|
||||
// The DWG written and read here is the test's own synthetic file; the app starts its DWG
|
||||
// worker in `main`, which a test does not run.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
CadApp::new(Session::new(), Services::default())
|
||||
}
|
||||
|
||||
fn settle(app: &mut CadApp) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while app.opening.busy() && Instant::now() < deadline {
|
||||
app.finish_opening();
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
app.finish_opening();
|
||||
assert!(!app.opening.busy(), "background opening completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_order_and_drops_duplicates_and_empty_paths() {
|
||||
let paths = ["/a/plan.dxf", "", "/b/site.dwg", "/a/plan.dxf"].map(PathBuf::from);
|
||||
assert_eq!(openable(paths), ["/a/plan.dxf", "/b/site.dwg"]);
|
||||
assert!(openable(Vec::new()).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn skips_paths_that_are_not_utf8() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let bad = PathBuf::from(std::ffi::OsString::from_vec(vec![b'/', 0xff, b'.', b'd', b'x', b'f']));
|
||||
assert_eq!(openable([bad, PathBuf::from("/ok.dxf")]), ["/ok.dxf"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_dwg_and_dxf_without_replacing_an_unsaved_drawing() {
|
||||
let dir = TestDir::new();
|
||||
let dxf = dir.0.join("planta com espaços.dxf");
|
||||
let dwg = dir.0.join("Documentac\u{327}a\u{303}o.dwg");
|
||||
let bytes = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n10\n0\nENDSEC\n0\nEOF\n";
|
||||
let drawing = cadcraft_io::read(bytes, "synthetic.dxf").unwrap();
|
||||
std::fs::write(&dxf, bytes).unwrap();
|
||||
std::fs::write(&dwg, cadcraft_io::write(&drawing, "synthetic.dwg").unwrap()).unwrap();
|
||||
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!dispatch([Event::Open(vec![dxf.clone(), dwg.clone(), dxf.clone(), PathBuf::new()])], &mut app));
|
||||
settle(&mut app);
|
||||
|
||||
assert_eq!(app.session.docs.len(), 3, "each file is opened once alongside the unsaved drawing");
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
for path in [&dxf, &dwg] {
|
||||
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == path.to_str()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_open_reports_the_path_and_keeps_existing_drawings() {
|
||||
let dir = TestDir::new();
|
||||
let missing = dir.0.join("missing drawing.dwg");
|
||||
let mut app = app();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(!dispatch([Event::Open(vec![missing.clone()])], &mut app));
|
||||
settle(&mut app);
|
||||
assert_eq!(app.session.docs.len(), 1);
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.log.iter().any(|line| line.contains(missing.to_str().unwrap())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_asks_before_closing_unsaved_work_and_can_be_cancelled() {
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
assert!(!dispatch([Event::Quit], &mut app), "must not issue a window close before the answer");
|
||||
assert!(app.close_prompt().is_some());
|
||||
assert!(!app.quit_confirmed);
|
||||
assert!(!app.quit_requested);
|
||||
app.answer_close(Choice::Cancel);
|
||||
assert!(app.close_prompt().is_none());
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!app.quit_requested);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_can_close_a_clean_session() {
|
||||
let mut app = app();
|
||||
assert!(dispatch([Event::Quit], &mut app));
|
||||
assert!(app.close_prompt().is_none());
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,6 @@
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
mod apple_events;
|
||||
mod control_server;
|
||||
mod desktop_theme;
|
||||
mod env;
|
||||
@@ -56,9 +54,6 @@ struct App {
|
||||
/// The `movable` flag last set on the main window.
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: Option<bool>,
|
||||
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: fmv_macos_events::Inbox,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -107,9 +102,6 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Drawings and quit requests from Finder, the Dock and `open -a` (macOS).
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events::poll(&self.apple_events, &mut self.cad, ctx);
|
||||
// Consume control/open/screenshot queues and time-based autosave, including hidden ticks.
|
||||
self.cad.guarded_logic(ctx);
|
||||
// Host frame work runs here, once per frame, and so also on a hidden logic-only tick (which
|
||||
@@ -182,6 +174,8 @@ pub fn install_io() {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
@@ -443,12 +437,6 @@ fn main() -> eframe::Result {
|
||||
b.with_close_requested_on_terminate(true);
|
||||
}));
|
||||
}
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = apple_events::AppleEvents::install();
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = &apple_events;
|
||||
eframe::run_native(
|
||||
"CADCraft",
|
||||
options,
|
||||
@@ -512,14 +500,6 @@ fn main() -> eframe::Result {
|
||||
for f in &files {
|
||||
app.open_path(f);
|
||||
}
|
||||
// Start reading any launch-time documents before the first frame. Later events use
|
||||
// this same inbox, including the normal unsaved-changes handling for quit requests.
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = {
|
||||
let inbox = apple_events.connect(&cc.egui_ctx);
|
||||
apple_events::poll(&inbox, &mut app, &cc.egui_ctx);
|
||||
inbox
|
||||
};
|
||||
if app.session.docs.is_empty() {
|
||||
// In the units the profile asks for (MEASUREINIT, restored above).
|
||||
let metric = app.session.settings.measureinit;
|
||||
@@ -547,8 +527,6 @@ fn main() -> eframe::Result {
|
||||
menus_in_window: vars.no_native_menu == Switch::On,
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: None,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -331,16 +331,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for one test, and its socket path.
|
||||
/// A fresh folder for one test, and its socket path. Both names stay short: a Windows socket path
|
||||
/// holds at most 107 bytes, and a long `%TEMP%` already uses most of them.
|
||||
#[cfg(windows)]
|
||||
fn socket_dir(test: &str) -> (Cleanup, PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-single-instance-{}-{test}", std::process::id()));
|
||||
let dir = std::env::temp_dir().join(format!("cc-si-{}-{test}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("instance-test.sock");
|
||||
let path = dir.join("t.sock");
|
||||
(Cleanup(dir), path)
|
||||
}
|
||||
|
||||
/// Whether a socket can be bound at `path` here. It can't when `%TEMP%` is too long or lives
|
||||
/// under a redirected `%LOCALAPPDATA%`; the socket tests then skip instead of failing.
|
||||
#[cfg(windows)]
|
||||
fn can_bind(path: &std::path::Path) -> bool {
|
||||
let bound = uds_windows::UnixListener::bind(path)
|
||||
.map(drop)
|
||||
.map_err(|e| {
|
||||
// Straight to stderr: the test harness hides `eprintln!` from a test that passes.
|
||||
use std::io::Write;
|
||||
let _ = writeln!(std::io::stderr(), "skipping: no AF_UNIX socket at {}: {e}", path.display());
|
||||
})
|
||||
.is_ok();
|
||||
let _ = std::fs::remove_file(path);
|
||||
bound
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_test_socket_path_stays_far_below_the_limit() {
|
||||
// Its own folder, with a name as long as the longest one used here: `socket_dir` empties the
|
||||
// folder, and the launches test may be using "together" at the same moment.
|
||||
let (_dir, path) = socket_dir("lengthck");
|
||||
let added = path.as_os_str().len() - std::env::temp_dir().as_os_str().len();
|
||||
assert!(added <= 40, "{added} bytes on top of %TEMP%");
|
||||
}
|
||||
|
||||
/// The whole exchange over a real socket: a stale socket file is taken over, a later launch
|
||||
/// hands its files to that listener, one that asked for its own window gets it, and a request
|
||||
/// naming a relative path is refused.
|
||||
@@ -348,6 +375,9 @@ mod tests {
|
||||
#[test]
|
||||
fn a_later_launch_hands_its_files_to_the_first() {
|
||||
let (dir, path) = socket_dir("handoff");
|
||||
if !can_bind(&path) {
|
||||
return;
|
||||
}
|
||||
drop(uds_windows::UnixListener::bind(&path).unwrap());
|
||||
assert!(path.exists(), "the stale socket file stays behind");
|
||||
|
||||
@@ -369,6 +399,9 @@ mod tests {
|
||||
fn launches_at_once_open_one_window() {
|
||||
const LAUNCHES: usize = 6;
|
||||
let (dir, path) = socket_dir("together");
|
||||
if !can_bind(&path) {
|
||||
return;
|
||||
}
|
||||
let start = Arc::new(std::sync::Barrier::new(LAUNCHES));
|
||||
let launches: Vec<_> = (0..LAUNCHES)
|
||||
.map(|i| {
|
||||
|
||||
@@ -85,6 +85,9 @@ pub struct Foreign {
|
||||
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
|
||||
/// later save must not take it for this one (#2471).
|
||||
pub version: Option<String>,
|
||||
/// The file's registered applications (APPID names as read, in file order). Saving writes
|
||||
/// them all back, whether or not any xdata still names them.
|
||||
pub appids: Vec<String>,
|
||||
}
|
||||
|
||||
impl Foreign {
|
||||
@@ -103,6 +106,7 @@ impl Foreign {
|
||||
&& self.targets.is_empty()
|
||||
&& self.class_order.is_empty()
|
||||
&& self.data_store.is_empty()
|
||||
&& self.appids.is_empty()
|
||||
}
|
||||
|
||||
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
|
||||
@@ -126,22 +130,89 @@ pub fn sat_text_acis(u: &crate::Unknown, handle: Handle, stored: &std::collectio
|
||||
["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && !stored.contains(&handle) && has_sat_text(&u.tags)
|
||||
}
|
||||
|
||||
/// Whether a solid modeler entity can't be written to a DXF of 2013 and later (`modern`: SAT text
|
||||
/// with no data store record, [`sat_text_acis`]) or of 2010 and earlier (geometry only in the data
|
||||
/// store, which those files don't have, and no SAT text to write instead) (#2334).
|
||||
pub fn acis_left_out(u: &crate::Unknown, handle: Handle, stored: &std::collections::BTreeSet<Handle>, modern: bool) -> bool {
|
||||
if modern {
|
||||
return sat_text_acis(u, handle, stored);
|
||||
}
|
||||
["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && stored.contains(&handle) && !has_sat_text(&u.tags)
|
||||
}
|
||||
|
||||
/// The entities a DXF of 2013 or later leaves out because they hold SAT-text ACIS data
|
||||
/// ([`sat_text_acis`]), counted by DXF type, across model space, layouts and block definitions.
|
||||
pub fn sat_text_dropped(d: &crate::Drawing) -> BTreeMap<String, usize> {
|
||||
acis_dropped(d, true)
|
||||
}
|
||||
|
||||
/// The entities a DXF leaves out by [`acis_left_out`], counted like [`sat_text_dropped`].
|
||||
pub fn acis_dropped(d: &crate::Drawing, modern: bool) -> BTreeMap<String, usize> {
|
||||
let stored = d.foreign.data_store_entities();
|
||||
let mut out = BTreeMap::new();
|
||||
// The writer saves xrefs as references: their blocks (and `xref|` ones) hold nothing in the file.
|
||||
for e in saved_entities(d) {
|
||||
if let crate::EntityKind::Unknown(u) = &e.kind
|
||||
&& acis_left_out(u, e.handle, &stored, modern)
|
||||
{
|
||||
count(&mut out, &u.dxf_type);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The entities a DXF file holds: model space, layouts and block definitions. The writer saves
|
||||
/// xrefs as references: their blocks (and `xref|` ones) hold nothing in the file.
|
||||
fn saved_entities(d: &crate::Drawing) -> impl Iterator<Item = &std::sync::Arc<crate::Entity>> {
|
||||
let own_blocks = d.blocks.values().filter(|b| b.xref_path.is_none() && !xref_dependent(&b.name));
|
||||
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(own_blocks.map(|b| &b.entities));
|
||||
for e in stores.flat_map(|s| s.iter()) {
|
||||
if let crate::EntityKind::Unknown(u) = &e.kind
|
||||
&& sat_text_acis(u, e.handle, &stored)
|
||||
{
|
||||
let n: &mut usize = out.entry(u.dxf_type.to_ascii_uppercase()).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
stores.flat_map(|s| s.iter())
|
||||
}
|
||||
|
||||
/// Add one record of DXF type `kind` to `out`.
|
||||
fn count(out: &mut BTreeMap<String, usize>, kind: &str) {
|
||||
let n: &mut usize = out.entry(kind.to_ascii_uppercase()).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
|
||||
/// Whether a DXF type is a proxy (ACAD_PROXY_OBJECT, ACAD_PROXY_ENTITY).
|
||||
pub fn is_proxy(kind: &str) -> bool {
|
||||
let k = kind.trim();
|
||||
k.eq_ignore_ascii_case("ACAD_PROXY_OBJECT") || k.eq_ignore_ascii_case("ACAD_PROXY_ENTITY")
|
||||
}
|
||||
|
||||
/// Whether a proxy's groups (after its type) give it a separate string stream: a size above 0 in
|
||||
/// group 96 (2007) or 162 (2010 and later) after the `AcDbProxy…` marker. Before 2007 a proxy's
|
||||
/// strings are part of its data, so a file of an earlier version has no form for one that keeps
|
||||
/// them apart (#3229).
|
||||
pub fn proxy_has_string_stream<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)>) -> bool {
|
||||
let mut own = false;
|
||||
for (code, value) in groups {
|
||||
let v = value.as_ref().trim();
|
||||
match code {
|
||||
100 => own = own || v.to_ascii_lowercase().starts_with("acdbproxy"),
|
||||
96 | 162 if own && v.parse::<i64>().is_ok_and(|n| n > 0) => return true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The proxies a DXF earlier than 2007 leaves out because they have a separate string stream
|
||||
/// ([`proxy_has_string_stream`]), counted by DXF type.
|
||||
pub fn proxies_dropped_before_2007(d: &crate::Drawing) -> BTreeMap<String, usize> {
|
||||
let mut out = BTreeMap::new();
|
||||
let has_strings = |tags: &[RawTag]| proxy_has_string_stream(tags.iter().map(|t| (t.code, t.value.as_str())));
|
||||
for e in saved_entities(d) {
|
||||
if let crate::EntityKind::Unknown(u) = &e.kind
|
||||
&& is_proxy(&u.dxf_type)
|
||||
&& has_strings(&u.tags)
|
||||
{
|
||||
count(&mut out, &u.dxf_type);
|
||||
}
|
||||
}
|
||||
for o in d.foreign.objects.iter().filter(|o| is_proxy(&o.kind) && has_strings(&o.tags)) {
|
||||
count(&mut out, &o.kind);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -164,6 +235,23 @@ pub fn data_store_records(tags: &[RawTag]) -> Vec<&[RawTag]> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The ACIS version a modeler entity's SAT text declares (the first number of its first line:
|
||||
/// 400, 700, 21800…), if it has SAT text.
|
||||
pub fn sat_version(tags: &[RawTag]) -> Option<u32> {
|
||||
let marked = tags.iter().take_while(|r| r.code < 1000).any(|r| r.code == 100);
|
||||
let mut in_modeler = !marked;
|
||||
for r in tags.iter().take_while(|r| r.code < 1000) {
|
||||
if r.code == 100 {
|
||||
in_modeler = r.value.trim().eq_ignore_ascii_case("AcDbModelerGeometry");
|
||||
} else if in_modeler && r.code == 1 {
|
||||
let first = r.value.split_whitespace().next()?;
|
||||
// DXF before 2013 encodes SAT text: each character but a space is 159 minus it ("hoo" is 700).
|
||||
return first.parse().ok().or_else(|| first.bytes().map(|b| char::from(159u8.wrapping_sub(b))).collect::<String>().parse().ok());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether an entity's groups hold SAT text: groups 1 and 3 inside its `AcDbModelerGeometry`
|
||||
/// subclass. A file of a version before the subclass markers has no `100` groups: all of its
|
||||
/// groups (before the extended data) are the entity's.
|
||||
|
||||
@@ -821,6 +821,18 @@ pub struct PageSetup {
|
||||
/// save keeps where the sheet sits; `None` for a page CADCraft made, written as 0,0 (#2109).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub image_origin: Option<Vec2>,
|
||||
/// The plot layout flags (DXF group 70 of AcDbPlotSettings) as the file had them. Saving keeps
|
||||
/// the bits CADCraft doesn't model (plot paper space last, plot with plot styles, standard
|
||||
/// scale and the rest) as read instead of forcing its defaults (#3227); `None` for page setups
|
||||
/// made in CADCraft.
|
||||
#[serde(skip)]
|
||||
pub file_plot_flags: Option<i64>,
|
||||
/// The standard scale the file chose (DXF group 75, such as 25 for 1:50) and the plot scale it
|
||||
/// was read with. While the scale is unchanged, saving keeps that choice and the standard scale
|
||||
/// flag instead of writing the scale as a custom one; `None` for a custom scale, scaled to
|
||||
/// fit, or a page setup made in CADCraft.
|
||||
#[serde(skip)]
|
||||
pub file_standard_scale: Option<(i64, f64)>,
|
||||
}
|
||||
|
||||
impl Default for PageSetup {
|
||||
@@ -844,6 +856,8 @@ impl Default for PageSetup {
|
||||
paper_mm: None,
|
||||
file_paper: None,
|
||||
image_origin: None,
|
||||
file_plot_flags: None,
|
||||
file_standard_scale: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::curves::KW;
|
||||
use super::super::file::{drops_unknown, new_folder, not_saved, not_saved_message, report_new_folder, report_not_saved};
|
||||
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
|
||||
use super::super::machines::{SelOutcome, SelectPhase};
|
||||
use super::super::modify::erase_kept;
|
||||
use super::super::{CommandSpec, bad, point_param, str_param, targets};
|
||||
@@ -44,13 +44,13 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
|
||||
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
|
||||
};
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
|
||||
None => {
|
||||
let hs = targets(s, p)?;
|
||||
@@ -76,16 +76,17 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Write `what` to `path` through the io hooks; the objects written, the file's size and what a
|
||||
/// DWG file left out, for the caller to report as a save does. The
|
||||
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
|
||||
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
|
||||
/// the version it was written at, for the caller to report as a save does. The
|
||||
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
|
||||
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
|
||||
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>)> {
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
|
||||
let src = s.doc()?;
|
||||
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
|
||||
// block's base point for a block.
|
||||
@@ -108,13 +109,15 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
|
||||
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
let lost = if drops_unknown(path) { not_saved(&d) } else { BTreeMap::new() };
|
||||
Ok((d.model.len(), bytes.len(), lost))
|
||||
// The written drawing's own version: the writer is given no other.
|
||||
let version = own_version(&d, path);
|
||||
let lost = lost_writing(&d, path, version);
|
||||
Ok((d.model.len(), bytes.len(), lost, version))
|
||||
}
|
||||
|
||||
/// Say on the command line what the written DWG file left out.
|
||||
fn echo_not_saved(s: &mut Session, lost: &BTreeMap<String, usize>) {
|
||||
if let Some(msg) = not_saved_message(lost) {
|
||||
/// Say on the command line what the file written at `path` and `version` left out.
|
||||
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
|
||||
if let Some(msg) = lost_message(path, version, lost) {
|
||||
s.echo(msg);
|
||||
}
|
||||
}
|
||||
@@ -335,7 +338,7 @@ impl DashWblockM {
|
||||
|
||||
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
|
||||
match write(s, "-wblock", &self.path, what) {
|
||||
Ok((.., lost)) => echo_not_saved(s, &lost),
|
||||
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
}
|
||||
Ok(Step::Done)
|
||||
@@ -346,8 +349,8 @@ impl DashWblockM {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
|
||||
Ok((.., lost)) => {
|
||||
echo_not_saved(s, &lost);
|
||||
Ok((.., lost, version)) => {
|
||||
echo_not_saved(s, &self.path, version, &lost);
|
||||
erase(s, hs)?;
|
||||
}
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
|
||||
@@ -343,6 +343,11 @@ fn eq_variants(o: &TanObj) -> Vec<Eq3> {
|
||||
|
||||
/// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations).
|
||||
pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
||||
ttt_where(objs, |_| true)
|
||||
}
|
||||
|
||||
/// [`ttt`] among the circles `ok` accepts.
|
||||
pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Option<Circle> {
|
||||
let [(o1, p1), (o2, p2), (o3, p3)] = objs;
|
||||
let mut starts: Vec<[f64; 3]> = Vec::new();
|
||||
let cen = (p1 + p2 + p3) / 3.0;
|
||||
@@ -379,6 +384,9 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
||||
continue;
|
||||
}
|
||||
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
|
||||
if !ok(&c) {
|
||||
continue;
|
||||
}
|
||||
let sc = score(&c, &objs);
|
||||
if best.is_none_or(|(b, _)| sc < b - 1e-12) {
|
||||
best = Some((sc, c));
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::{
|
||||
Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number,
|
||||
point_param, size_param,
|
||||
};
|
||||
use crate::snap;
|
||||
|
||||
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = if let Some(center) = point_param(p, "center") {
|
||||
@@ -51,6 +52,8 @@ pub(super) fn run_arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) struct CircleM {
|
||||
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
|
||||
pts: Vec<Vec2>,
|
||||
/// 3P: the circle or arc each point was picked on with a tangent snap, by point.
|
||||
tans: Vec<Option<snap::SnapCurve>>,
|
||||
diameter: bool,
|
||||
/// The `Ttr` option hands over to the tangent-circle machine.
|
||||
delegate: Option<Box<dyn Interactive>>,
|
||||
@@ -69,18 +72,22 @@ impl Interactive for CircleM {
|
||||
match (self.mode, n) {
|
||||
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
|
||||
(0, _) if self.diameter => {
|
||||
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance()
|
||||
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance().deferred()
|
||||
}
|
||||
(0, _) => {
|
||||
let p =
|
||||
Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER).kw(&["Diameter"]).base_opt(self.pts.first().copied()).distance();
|
||||
let p = Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER)
|
||||
.kw(&["Diameter"])
|
||||
.base_opt(self.pts.first().copied())
|
||||
.distance()
|
||||
.deferred();
|
||||
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
|
||||
}
|
||||
(1, k) => Prompt::new(
|
||||
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
|
||||
Accept::POINT,
|
||||
)
|
||||
.base_opt(self.pts.last().copied()),
|
||||
.base_opt(self.pts.last().copied())
|
||||
.deferred(),
|
||||
(2, k) => Prompt::new(
|
||||
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
|
||||
Accept::POINT,
|
||||
@@ -120,7 +127,14 @@ impl Interactive for CircleM {
|
||||
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
|
||||
Some(Circle::new(*c, r))
|
||||
}
|
||||
1 if self.pts.len() == 3 => Circle::from_3_points(self.pts[0], self.pts[1], self.pts[2]),
|
||||
1 if self.pts.len() == 3 => match self.three_points() {
|
||||
Some(c) => Some(c),
|
||||
None => {
|
||||
self.pts.pop();
|
||||
self.tans.truncate(self.pts.len());
|
||||
return Err(crate::EngineError::Other("Circle does not exist.".into()));
|
||||
}
|
||||
},
|
||||
2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])),
|
||||
_ => None,
|
||||
};
|
||||
@@ -130,6 +144,29 @@ impl Interactive for CircleM {
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
// 3P: a point picked with a tangent snap makes the circle tangent to that curve (#1512).
|
||||
Input::Deferred(d) if self.mode == 1 => {
|
||||
let tan = (d.mode == snap::mode::TAN && !matches!(d.curve, snap::SnapCurve::Line { .. })).then_some(d.curve);
|
||||
self.tans.resize(self.pts.len(), None);
|
||||
self.tans.push(tan);
|
||||
self.input(s, Input::Point(d.at))
|
||||
}
|
||||
// A tangent picked for the radius: the circle around the center that touches the
|
||||
// curve, on the side it was picked (#1512).
|
||||
Input::Deferred(d) if self.mode == 0 && self.pts.len() == 1 => {
|
||||
let Some(&c) = self.pts.first() else { return Ok(Step::Continue) };
|
||||
// Around the picked curve's own center the circle would lie on it, not touch it.
|
||||
let concentric =
|
||||
matches!(d.curve, snap::SnapCurve::Circle { center, .. } | snap::SnapCurve::Arc { center, .. } if center.near(c, 1e-9));
|
||||
let touch = d.curve.perpendiculars(c, d.at).into_iter().filter(|_| !concentric).min_by(|a, b| a.dist(d.at).total_cmp(&b.dist(d.at)));
|
||||
match touch.map(|t| c.dist(t)).filter(|r| *r > 1e-12 && r.is_finite()) {
|
||||
Some(r) => {
|
||||
finish_circle(s, Circle::new(c, r))?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
None => Err(crate::EngineError::Other("No circle around the center is tangent there.".into())),
|
||||
}
|
||||
}
|
||||
Input::Text(t) if self.mode == 0 && self.pts.len() == 1 => {
|
||||
let v = number(&t).ok_or_else(|| crate::EngineError::Other("Requires numeric distance or second point.".into()))?;
|
||||
let r = if self.diameter { v / 2.0 } else { v };
|
||||
@@ -174,6 +211,38 @@ impl Interactive for CircleM {
|
||||
}
|
||||
}
|
||||
|
||||
impl CircleM {
|
||||
/// The 3P circle: through the three points, or tangent to the curves picked with TAN.
|
||||
fn three_points(&self) -> Option<Circle> {
|
||||
let [a, b, c] = <[Vec2; 3]>::try_from(self.pts.as_slice()).ok()?;
|
||||
if self.tans.iter().all(Option::is_none) {
|
||||
return Circle::from_3_points(a, b, c);
|
||||
}
|
||||
let tan = |i: usize| self.tans.get(i).copied().flatten();
|
||||
// A plain point is a circle of radius zero to pass through; an arc is solved as its circle.
|
||||
let target = |i: usize, p: Vec2| {
|
||||
let circle = match tan(i) {
|
||||
Some(snap::SnapCurve::Circle { center, radius } | snap::SnapCurve::Arc { center, radius, .. }) => Circle::new(center, radius),
|
||||
_ => Circle::new(p, 0.0),
|
||||
};
|
||||
crate::cmd::curves::TanObj::Circle(circle)
|
||||
};
|
||||
let pts = [a, b, c];
|
||||
// The circle must touch an arc within its sweep, not elsewhere on the arc's circle, and
|
||||
// not be the picked circle itself (which lies on it rather than touching it).
|
||||
let touches = |found: &Circle| {
|
||||
pts.iter().enumerate().all(|(i, p)| {
|
||||
tan(i).is_none_or(|t| {
|
||||
let same = matches!(target(i, *p), crate::cmd::curves::TanObj::Circle(o)
|
||||
if o.center.dist(found.center) + (o.radius - found.radius).abs() <= 1e-9 * o.radius);
|
||||
!same && t.contains(target(i, *p).touch(found))
|
||||
})
|
||||
})
|
||||
};
|
||||
crate::cmd::curves::ttt_where([(target(0, a), a), (target(1, b), b), (target(2, c), c)], touches)
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_circle(s: &mut Session, c: Circle) -> Result<()> {
|
||||
s.add_entity(circle(c.center, c.radius))?;
|
||||
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
|
||||
|
||||
+130
-43
@@ -83,6 +83,31 @@ pub fn object_records() -> Option<ObjectRecords> {
|
||||
OBJECT_RECORDS.get().copied()
|
||||
}
|
||||
|
||||
/// What a DXF of a version before 2007 leaves out of a drawing because it has no form for a
|
||||
/// proxy's separate string stream, counted by DXF type (installed by the app with the DXF writer,
|
||||
/// a lower layer, which finds it by writing; see `cadcraft_io::proxies_lost`). Without it the
|
||||
/// proxies themselves are counted ([`cadcraft_doc::foreign::proxies_dropped_before_2007`]).
|
||||
pub type ProxiesLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
|
||||
|
||||
static PROXIES_LOST: OnceLock<ProxiesLost> = OnceLock::new();
|
||||
|
||||
pub fn set_proxies_lost(f: ProxiesLost) {
|
||||
let _ = PROXIES_LOST.set(f);
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
|
||||
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
|
||||
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
if version >= Version::R2007 {
|
||||
return Default::default();
|
||||
}
|
||||
let d = d.committed();
|
||||
match PROXIES_LOST.get() {
|
||||
Some(f) => f(&d, version),
|
||||
None => cadcraft_doc::foreign::proxies_dropped_before_2007(&d),
|
||||
}
|
||||
}
|
||||
|
||||
/// COMPARE (drawing comparison).
|
||||
pub mod compare;
|
||||
|
||||
@@ -792,15 +817,23 @@ fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The version a drawing is saved in at `path` when none is asked for: its `$ACADVER` (2018 by
|
||||
/// default), and for DWG at least 2004 (the io layer's rule: R2000 DWG has no true colours).
|
||||
fn drawing_version(s: &Session, path: &str) -> Version {
|
||||
let v = s
|
||||
.state()
|
||||
.ok()
|
||||
.and_then(|st| st.drawing().header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver))
|
||||
.unwrap_or_default();
|
||||
pub fn drawing_version(s: &Session, path: &str) -> Version {
|
||||
let v = s.state().ok().and_then(|st| acadver(st.drawing())).unwrap_or_default();
|
||||
if is_dxf(path) { v } else { v.max(Version::R2004) }
|
||||
}
|
||||
|
||||
/// The version `d` is saved in at `path` when none is asked for, as [`drawing_version`] says for
|
||||
/// the active drawing.
|
||||
pub(crate) fn own_version(d: &Drawing, path: &str) -> Version {
|
||||
let v = acadver(d).unwrap_or_default();
|
||||
if is_dxf(path) { v } else { v.max(Version::R2004) }
|
||||
}
|
||||
|
||||
/// The version `d`'s `$ACADVER` names.
|
||||
fn acadver(d: &Drawing) -> Option<Version> {
|
||||
d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver)
|
||||
}
|
||||
|
||||
/// `document.switch index`: require the index, cancel the running command, activate that drawing and bump the epoch even if it was already active (screenshot identity).
|
||||
fn run_switch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("document.switch", "`index` is required"))? as usize;
|
||||
@@ -826,8 +859,9 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
|
||||
if drops_unknown(format!("drawing.{fmt}")) {
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
} else if version >= Version::R2013 && is_dxf_file(format!("drawing.{fmt}")) {
|
||||
report_sat_text_dropped(s, &mut r);
|
||||
} else if is_dxf_file(format!("drawing.{fmt}")) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
@@ -862,10 +896,12 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
|
||||
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities));
|
||||
for e in stores.flat_map(|s| s.iter()) {
|
||||
if let cadcraft_doc::EntityKind::Unknown(u) = &e.kind {
|
||||
// A DWG before 2013 writes a solid's SAT text as it is; from 2013 the geometry has to be
|
||||
// in the data store, and SAT text alone is lost (#2334).
|
||||
// A DWG before 2013 keeps a solid's SAT text of ACIS 7.0 and later; from 2013 the geometry
|
||||
// has to be in the data store, and SAT text alone is lost. Older SAT (ACIS 4.0, as ZWCAD
|
||||
// writes to DXF 2000) reaches the DWG without usable geometry: ZWCAD 2025 opens such a
|
||||
// solid as a proxy or an empty body (#2334).
|
||||
if MODELER_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t))
|
||||
&& (stored.contains(&e.handle) || (version < Version::R2013 && cadcraft_doc::foreign::has_sat_text(&u.tags)))
|
||||
&& (stored.contains(&e.handle) || (version < Version::R2013 && cadcraft_doc::foreign::sat_version(&u.tags).is_some_and(|v| v >= 700)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -907,9 +943,8 @@ pub fn not_saved_message(lost: &std::collections::BTreeMap<String, usize>) -> Op
|
||||
/// reports the same list afterwards to callers that never get a dialog.
|
||||
pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap<String, usize> {
|
||||
let version = drawing_version(s, path);
|
||||
if is_dxf_file(path) && version >= Version::R2013 {
|
||||
// The drawing a file holds: the host while the Block Editor is open.
|
||||
return s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default();
|
||||
if is_dxf_file(path) {
|
||||
return host_dxf_lost(s, version);
|
||||
}
|
||||
if !drops_unknown(path) {
|
||||
return Default::default();
|
||||
@@ -917,16 +952,85 @@ pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap<Strin
|
||||
s.doc().map(|d| not_saved_as(d, version)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Report what the file `path`, just written at the drawing's own version, left out.
|
||||
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
|
||||
if is_dxf_file(path) {
|
||||
if drawing_version(s, path) >= Version::R2013 {
|
||||
report_sat_text_dropped(s, r);
|
||||
}
|
||||
} else {
|
||||
let lost = loss_on_save(s, path);
|
||||
report_not_saved(s, r, &lost);
|
||||
/// What a DXF of `version` leaves out of the drawing a save writes: the host while the Block
|
||||
/// Editor is open ([`dxf_lost`]).
|
||||
fn host_dxf_lost(s: &Session, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
s.state().map(|st| dxf_lost(st.drawing(), version)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of `d`: solid modeler entities whose ACIS geometry that
|
||||
/// version has no place for (#2334: SAT text alone from 2013, data store geometry alone before),
|
||||
/// and before 2007 proxies whose strings it can't hold, with the objects that go with them
|
||||
/// (#3229). The two never name the same record: a solid lost before 2013 is lost in 2007 too.
|
||||
fn dxf_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
let mut lost = cadcraft_doc::foreign::acis_dropped(d, version >= Version::R2013);
|
||||
for (kind, n) in proxies_lost(d, version) {
|
||||
let m = lost.entry(kind).or_insert(0);
|
||||
*m = m.saturating_add(n);
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
/// What a file at `path` leaves out of `d`, written at `version`: empty when it keeps everything.
|
||||
pub(crate) fn lost_writing(d: &Drawing, path: &str, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
if !is_dxf_file(path) {
|
||||
return if drops_unknown(path) { not_saved_as(d, version) } else { Default::default() };
|
||||
}
|
||||
dxf_lost(d, version)
|
||||
}
|
||||
|
||||
/// Report what the file `path`, just written from the active document (what EXPORT writes: the
|
||||
/// block while the Block Editor is open) at its own version, left out.
|
||||
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
|
||||
let Ok(d) = s.doc() else { return };
|
||||
let version = own_version(d, path);
|
||||
let lost = lost_writing(d, path, version);
|
||||
report_lost(s, r, path, version, &lost);
|
||||
}
|
||||
|
||||
/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`),
|
||||
/// in the words for that kind of file, and list it in the result's `notSaved`.
|
||||
pub(crate) fn report_lost(s: &mut Session, r: &mut Value, path: &str, version: Version, lost: &std::collections::BTreeMap<String, usize>) {
|
||||
match lost_message(path, version, lost) {
|
||||
Some(msg) => s.echo(msg),
|
||||
None => return,
|
||||
}
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("notSaved".into(), json!(lost));
|
||||
}
|
||||
}
|
||||
|
||||
/// The command-line warning for what a file at `path` written at `version` left out, or `None`
|
||||
/// when it kept everything.
|
||||
pub(crate) fn lost_message(path: &str, version: Version, lost: &std::collections::BTreeMap<String, usize>) -> Option<String> {
|
||||
if !is_dxf_file(path) {
|
||||
return not_saved_message(lost);
|
||||
}
|
||||
if lost.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Solids (#2334) and, before 2007, proxies and what goes with them (#3229), each with its reason.
|
||||
let list = |solids: bool| -> Vec<String> {
|
||||
lost.iter().filter(|(t, _)| MODELER_TYPES.iter().any(|m| t.eq_ignore_ascii_case(m)) == solids).map(|(t, n)| format!("{n} {t}")).collect()
|
||||
};
|
||||
let mut parts = Vec::new();
|
||||
let solids = list(true);
|
||||
if !solids.is_empty() {
|
||||
let why = if version >= Version::R2013 {
|
||||
"2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them"
|
||||
} else {
|
||||
"2010 and earlier have no data store, where these entities keep their ACIS geometry; save as 2013 or later to keep them"
|
||||
};
|
||||
parts.push(format!("Not saved in the DXF file ({why}): {}", solids.join(", ")));
|
||||
}
|
||||
let others = list(false);
|
||||
if !others.is_empty() {
|
||||
parts.push(format!(
|
||||
"Not saved in the DXF file (proxies that keep their strings apart from their data, which DXF before 2007 can't hold, and the objects that go with them; save as 2007 or later to keep them): {}",
|
||||
others.join(", ")
|
||||
));
|
||||
}
|
||||
Some(parts.join(" "))
|
||||
}
|
||||
|
||||
/// Whether saving to `path` leaves out the entities [`not_saved`] counts: DWG does (the DWG
|
||||
@@ -945,24 +1049,6 @@ fn is_dxf_file(path: impl AsRef<std::path::Path>) -> bool {
|
||||
Format::from_path(path) == Some(Format::Dxf)
|
||||
}
|
||||
|
||||
/// Say on the command line which solid modeler entities a DXF of 2013 or later left out because
|
||||
/// they hold SAT-text ACIS data, which such files keep in a data store instead (#2334).
|
||||
fn report_sat_text_dropped(s: &mut Session, r: &mut Value) {
|
||||
// The drawing a file holds: the host while the Block Editor is open.
|
||||
let lost = s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default();
|
||||
if lost.is_empty() {
|
||||
return;
|
||||
}
|
||||
let list: Vec<String> = lost.iter().map(|(t, n)| format!("{n} {t}")).collect();
|
||||
s.echo(format!(
|
||||
"Not saved in the DXF file (2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them): {}",
|
||||
list.join(", ")
|
||||
));
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("notSaved".into(), json!(lost));
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder a write to `path` has to create, asked before writing so it can be reported after.
|
||||
/// The web has no folders.
|
||||
pub(super) fn new_folder(path: &str) -> Option<String> {
|
||||
@@ -1006,8 +1092,9 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R
|
||||
report_new_folder(s, &mut r, folder);
|
||||
if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) {
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
} else if version >= Version::R2013 && r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
|
||||
report_sat_text_dropped(s, &mut r);
|
||||
} else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
}
|
||||
if r.get("path").and_then(Value::as_str).is_some_and(is_drawing_file) {
|
||||
report_fonts(s, &mut r);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
|
||||
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
|
||||
|
||||
mod patfile;
|
||||
pub(super) use edit::{set_pattern, takes_pattern};
|
||||
@@ -36,6 +37,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// Typed with nothing selected it asks for objects, as in AutoCAD, rather than converting none.
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("region", "REGION")))),
|
||||
CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], addPoints?: [[x,y]], addBoundary?: [hex], removeLoops?: [zero-based index] (geometry edits require one hatch), style?, origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))),
|
||||
CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
|
||||
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
|
||||
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
|
||||
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
|
||||
.enabled(has_doc)
|
||||
|
||||
@@ -29,6 +29,59 @@ fn hatches(s: &Session, p: &Value) -> Result<Vec<Handle>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Most polylines one HATCHGENERATEBOUNDARY call creates.
|
||||
const MAX_GENERATED: usize = 10_000;
|
||||
|
||||
/// HATCHGENERATEBOUNDARY: a closed polyline around every boundary loop (outer and islands) of
|
||||
/// the selected hatches, at each hatch's height. The hatches are not changed: an associative
|
||||
/// hatch stays linked to its own boundary objects and is not linked to the new polylines.
|
||||
pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let selected = targets(s, p)?;
|
||||
// The polylines go to the current space, so every hatch must be there too.
|
||||
let space = s.space();
|
||||
let mut loops = Vec::new();
|
||||
let mut found = false;
|
||||
// A hatch named twice gets its boundary once.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
{
|
||||
let d = s.doc()?;
|
||||
for h in selected {
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let EntityKind::Hatch(x) = &e.kind else { continue };
|
||||
if !seen.insert(h) {
|
||||
continue;
|
||||
}
|
||||
found = true;
|
||||
if d.space_of(h).as_ref() != Some(&space) {
|
||||
return Err(bad("hatchgenerateboundary", format!("hatch {} is not in the current space; switch to its layout first", h.hex())));
|
||||
}
|
||||
// Every selected hatch counts: none is left out of a call that succeeds. Compared
|
||||
// against the room left, so a hostile loop count can't overflow the sum.
|
||||
if x.loops.len() > MAX_GENERATED.saturating_sub(loops.len()) {
|
||||
return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches")));
|
||||
}
|
||||
// The elevation runs along the hatch's normal: one facing down Z (mirrored) lies at its
|
||||
// negative, where the polyline, facing up, goes.
|
||||
let z = if e.common.extrusion.z < 0.0 { -x.elevation } else { x.elevation };
|
||||
loops.extend(x.loops.iter().map(|l| (l.vertices.clone(), z)));
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return Err(bad("hatchgenerateboundary", "select one or more hatches"));
|
||||
}
|
||||
// Everything is checked before anything is added, so a refused call leaves nothing behind.
|
||||
let mut created = Vec::new();
|
||||
for (vs, elevation) in loops {
|
||||
let mut kind = lwpoly(vs, true);
|
||||
if let EntityKind::LwPolyline(pl) = &mut kind {
|
||||
pl.elevation = elevation;
|
||||
}
|
||||
created.push(s.add_entity(kind)?.hex());
|
||||
}
|
||||
let n = created.len();
|
||||
Ok(json!({ "handles": created, "message": format!("{n} boundary polyline(s) created.") }))
|
||||
}
|
||||
|
||||
fn outline(l: &HatchLoop) -> Vec<Vec2> {
|
||||
Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(1e-3)
|
||||
}
|
||||
|
||||
@@ -466,3 +466,61 @@ fn plot_path_extension_picks_the_format_like_export() {
|
||||
assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree");
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn osnap_in_mspace_skips_vplayer_frozen_layers() {
|
||||
let mut s = Session::new();
|
||||
s.execute("layer.new", &json!({"name": "Hidden"})).unwrap();
|
||||
s.execute("line", &json!({"points": [[60, -25], [70, -25]]})).unwrap();
|
||||
let line_h = s.doc().unwrap().model.iter().last().unwrap().handle;
|
||||
s.execute("properties.set", &json!({"handles": [line_h], "layer": "Hidden"})).unwrap();
|
||||
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
|
||||
s.execute("mview", &json!({"p1": [20, 20], "p2": [220, 120]})).unwrap();
|
||||
let vp_h = viewports(&s, "Layout1").last().unwrap().0;
|
||||
s.execute("vplayer", &json!({"handles": [vp_h], "freeze": ["Hidden"]})).unwrap();
|
||||
s.execute("mspace", &json!({"handle": vp_h})).unwrap();
|
||||
|
||||
let ap = s.pixel_size() * s.settings.aperture.max(1.0);
|
||||
let d = ap * 0.5;
|
||||
let model_before = s.doc().unwrap().model.len();
|
||||
for (ovr, pt, name) in [
|
||||
("end", format!("{},-25", 60.0 + d), "Endpoint"),
|
||||
("mid", format!("{},-25", 65.0 + d), "Midpoint"),
|
||||
("nea", format!("63,{}", -25.0 + d), "Nearest"),
|
||||
] {
|
||||
s.cmdline("line").unwrap();
|
||||
s.cmdline(ovr).unwrap();
|
||||
s.cmdline(&pt).unwrap();
|
||||
assert_eq!(
|
||||
s.log.last().map(String::as_str),
|
||||
Some(format!("No {name} found for specified point.").as_str()),
|
||||
"{ovr} should not snap to a line on a VPLAYER-frozen layer; log: {:?}",
|
||||
s.log
|
||||
);
|
||||
s.cmdline("").unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().model.len(), model_before, "no new line should be created");
|
||||
|
||||
// Running osnaps through snap_cursor must also ignore the VPLAYER-frozen layer.
|
||||
s.settings.osmode = crate::snap::mode::END | crate::snap::mode::MID | crate::snap::mode::NEA;
|
||||
let cs = s.snap_cursor(
|
||||
cadcraft_geom::Vec2::new(60.0 + d, -25.0),
|
||||
&crate::snap::tracking::CursorQuery { base: None, deferred: false, corner: false, aperture: ap, tol: ap, now: 0.0, shift: false },
|
||||
);
|
||||
assert!(cs.snap.is_none(), "running osnap should not snap to a VPLAYER-frozen line: {:?}", cs.snap);
|
||||
|
||||
// A block reference on layer "0" containing an entity on "Hidden" must also not snap.
|
||||
s.execute("block", &json!({"name": "B", "base": [60, -25], "handles": [line_h]})).unwrap();
|
||||
let model_with_block = s.doc().unwrap().model.len();
|
||||
s.cmdline("line").unwrap();
|
||||
s.cmdline("end").unwrap();
|
||||
s.cmdline(&format!("{},-25", 60.0 + d)).unwrap();
|
||||
assert_eq!(
|
||||
s.log.last().map(String::as_str),
|
||||
Some("No Endpoint found for specified point."),
|
||||
"end should not snap to a block entity on a VPLAYER-frozen layer; log: {:?}",
|
||||
s.log
|
||||
);
|
||||
s.cmdline("").unwrap();
|
||||
assert_eq!(s.doc().unwrap().model.len(), model_with_block);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,90 @@ fn text_of(k: &EntityKind) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A box for the in-place editor showing one line of text where `t` sits.
|
||||
pub(crate) fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText {
|
||||
use cadcraft_doc::{HAlign, VAlign};
|
||||
let col = match t.halign {
|
||||
HAlign::Left => 0u8,
|
||||
HAlign::Right => 2,
|
||||
_ => 1,
|
||||
};
|
||||
let row = match t.valign {
|
||||
VAlign::Top => 0u8,
|
||||
VAlign::Middle => 1,
|
||||
_ if t.halign == HAlign::Middle => 1,
|
||||
_ => 2,
|
||||
};
|
||||
// Aligned and fit text is centred between its two points.
|
||||
let at = match t.halign {
|
||||
HAlign::Aligned | HAlign::Fit => t.align_pt.map_or(t.insert, |b| (t.insert + b) * 0.5),
|
||||
_ => t.justify_point().to3(t.insert.z),
|
||||
};
|
||||
cadcraft_doc::MText {
|
||||
insert: at,
|
||||
height: t.height,
|
||||
width: 0.0,
|
||||
attach: row * 3 + col + 1,
|
||||
rotation: t.rotation,
|
||||
style: t.style.clone(),
|
||||
contents: t.value.clone(),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The extents of one line of text as drawn (`value` in `t`'s place, style and justification);
|
||||
/// `None` for empty or unusable extents.
|
||||
fn drawn(d: &cadcraft_doc::Drawing, t: &cadcraft_doc::Text, value: &str) -> Option<cadcraft_geom::Bounds2> {
|
||||
let (_, b) = cadcraft_render::place_text_entity(d, t, value);
|
||||
let ok = [b.min.x, b.min.y, b.max.x, b.max.y].iter().all(|v| v.is_finite()) && b.min.x <= b.max.x && b.min.y <= b.max.y;
|
||||
ok.then_some(b)
|
||||
}
|
||||
|
||||
/// What the in-place editor edits for object `h`: an MTEXT or multileader text as multiline
|
||||
/// text, a TEXT or attribute definition as one line, a dimension's text with `<>` for its value.
|
||||
pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
|
||||
use crate::{EditorKind, TextEditor};
|
||||
let d = s.doc().ok()?;
|
||||
let key = h.hex();
|
||||
let e: &cadcraft_doc::Entity = d.entity(h)?;
|
||||
// Annotative text and dimensions are drawn scaled to the current annotation scale: the box
|
||||
// follows what is drawn. Multiline text keeps its stored height (it is written back from it).
|
||||
let scaled = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
|
||||
Some(cadcraft_doc::anno_scaled(e, f))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match &scaled.as_ref().unwrap_or(e).kind {
|
||||
EntityKind::MText(t) => Some(TextEditor { mtext: t.clone(), kind: EditorKind::MText, key, extents: None }),
|
||||
// A multileader's text opens in the same editor (#1081).
|
||||
EntityKind::MLeader(m) => m.text.clone().map(|mtext| TextEditor { mtext, kind: EditorKind::MText, key, extents: None }),
|
||||
// The box covers the text as drawn: its value, or a definition's tag.
|
||||
EntityKind::Text(t) => Some(TextEditor { mtext: line_box(t), kind: EditorKind::Line, key, extents: drawn(d, t, &t.value) }),
|
||||
EntityKind::AttDef(a) => Some(TextEditor { mtext: line_box(&a.text), kind: EditorKind::Line, key, extents: drawn(d, &a.text, &a.tag) }),
|
||||
EntityKind::Dimension(dm) => {
|
||||
let g = cadcraft_render::dimension_in(d, dm);
|
||||
let measured = cadcraft_render::dimension_in(d, &cadcraft_doc::Dimension { text: String::new(), block: None, ..dm.clone() }).value;
|
||||
let mtext = cadcraft_doc::MText {
|
||||
insert: g.text_pos.to3(0.0),
|
||||
height: if g.text_height > 0.0 && g.text_height.is_finite() { g.text_height } else { 0.18 },
|
||||
width: 0.0,
|
||||
attach: 5,
|
||||
rotation: if g.text_angle.is_finite() { g.text_angle } else { 0.0 },
|
||||
style: d.dim_style(&dm.style).map_or_else(|| "Standard".to_string(), |st| st.text_style.clone()),
|
||||
contents: if dm.text.is_empty() { "<>".into() } else { dm.text.clone() },
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
};
|
||||
Some(TextEditor { mtext, kind: EditorKind::Dimension { measured }, key, extents: None })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> {
|
||||
if curves::is_locked(s, h) {
|
||||
return Err(other("The object is on a locked layer."));
|
||||
@@ -60,8 +144,8 @@ pub(super) struct TextEditM {
|
||||
single: bool,
|
||||
/// Asking for the edit mode.
|
||||
mode: bool,
|
||||
/// The MTEXT being edited, for the in-place editor (#842).
|
||||
mtext: Option<cadcraft_doc::MText>,
|
||||
/// What the in-place editor shows for the picked object (#842).
|
||||
editor: Option<crate::TextEditor>,
|
||||
}
|
||||
|
||||
impl Interactive for TextEditM {
|
||||
@@ -70,7 +154,12 @@ impl Interactive for TextEditM {
|
||||
}
|
||||
/// An MTEXT asking for its new text opens in the in-place editor with its contents.
|
||||
fn editing_mtext(&self) -> Option<cadcraft_doc::MText> {
|
||||
self.h.as_ref().and(self.mtext.clone())
|
||||
self.h.as_ref().and(self.editor.as_ref().filter(|e| e.kind == crate::EditorKind::MText).map(|e| e.mtext.clone()))
|
||||
}
|
||||
/// TEXT, an attribute definition or a dimension asking for its new text opens in the one-line
|
||||
/// in-place editor; MTEXT and multileader text in the MTEXT editor.
|
||||
fn text_editor(&self) -> Option<crate::TextEditor> {
|
||||
if self.mode || self.h.is_none() { None } else { self.editor.clone() }
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
if self.mode {
|
||||
@@ -100,18 +189,13 @@ impl Interactive for TextEditM {
|
||||
if curves::is_locked(s, h) {
|
||||
return Err(other("The object is on a locked layer."));
|
||||
}
|
||||
let kind = curves::entity(s, h)?.kind;
|
||||
let old = text_of(&kind).ok_or_else(|| other("Select a text, mtext, multileader, attribute definition or dimension."))?;
|
||||
self.mtext = match kind {
|
||||
EntityKind::MText(m) => Some(m),
|
||||
// A multileader's text opens in the same editor (#1081).
|
||||
EntityKind::MLeader(m) => m.text,
|
||||
_ => None,
|
||||
};
|
||||
let old = text_of(&curves::entity(s, h)?.kind)
|
||||
.ok_or_else(|| other("Select a text, mtext, multileader, attribute definition or dimension."))?;
|
||||
self.editor = editor_for(s, h);
|
||||
// The editor would drop part of a text this long, and saving would lose it: the
|
||||
// command line asks for it instead.
|
||||
if self.mtext.as_ref().is_some_and(|m| !crate::mtext_edit::Formatted::fits(&m.contents)) {
|
||||
self.mtext = None;
|
||||
if self.editor.as_ref().is_some_and(|e| !crate::mtext_edit::Formatted::fits(&e.mtext.contents)) {
|
||||
self.editor = None;
|
||||
s.echo("This text is too long for the editor; enter the new text at the command line.");
|
||||
}
|
||||
self.h = Some((h, old));
|
||||
@@ -123,12 +207,12 @@ impl Interactive for TextEditM {
|
||||
set_text(s, h, &t)?;
|
||||
self.edits.push((h, before));
|
||||
self.h = None;
|
||||
self.mtext = None;
|
||||
self.editor = None;
|
||||
Ok(if self.single { Step::Done } else { Step::Continue })
|
||||
}
|
||||
(Some(_), Input::Enter) => {
|
||||
self.h = None;
|
||||
self.mtext = None;
|
||||
self.editor = None;
|
||||
Ok(if self.single { Step::Done } else { Step::Continue })
|
||||
}
|
||||
(None, Input::Enter) => Ok(Step::Done),
|
||||
|
||||
@@ -235,6 +235,7 @@ pub const NO_FILES: &[&str] = &[
|
||||
"boundary",
|
||||
"region",
|
||||
"hatchedit",
|
||||
"hatchgenerateboundary",
|
||||
"hatchpick",
|
||||
"overkill",
|
||||
"block",
|
||||
|
||||
@@ -110,6 +110,15 @@ impl Interactive for Guarded {
|
||||
None
|
||||
})
|
||||
}
|
||||
fn text_editor(&self) -> Option<crate::TextEditor> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
}
|
||||
catch_unwind(AssertUnwindSafe(|| self.inner.text_editor())).unwrap_or_else(|_| {
|
||||
self.broken.set(Some("panic in prompt"));
|
||||
None
|
||||
})
|
||||
}
|
||||
fn display_only(&self, s: &Session) -> Option<crate::prompt::DisplayOnly> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
|
||||
@@ -54,7 +54,7 @@ pub use cadcraft_geom as geom;
|
||||
pub use cadcraft_render as render;
|
||||
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
|
||||
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
|
||||
pub use prompt::{Accept, DisplayOnly, Drag, Input, Interactive, Picker, Prompt, Step};
|
||||
pub use prompt::{Accept, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
|
||||
|
||||
mod doc_state;
|
||||
mod error;
|
||||
|
||||
@@ -127,18 +127,31 @@ pub fn snap_name(m: u32) -> &'static str {
|
||||
}
|
||||
|
||||
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
|
||||
/// first, then the closest snap of each other mode in `osmode`, nearest first, without repeats.
|
||||
/// first, then every other snap of the modes in `osmode` under the aperture (each endpoint of
|
||||
/// each object, each intersection …; [`crate::snap::osnap_all`]), best first, without repeats.
|
||||
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
|
||||
snap_candidates_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||
}
|
||||
|
||||
/// [`snap_candidates`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn snap_candidates_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> Vec<SnapHit> {
|
||||
// A base that is not a number would give meaningless perpendiculars and tangents.
|
||||
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 || base.is_some_and(|b| !b.is_finite()) {
|
||||
return Vec::new();
|
||||
}
|
||||
let osnap = |m: u32| crate::snap::osnap(d, space, cursor, aperture, m, base, deferred);
|
||||
let extra = osmode & mode::HATCH;
|
||||
let mut per_mode: Vec<SnapHit> = mode::ALL.iter().filter(|(b, _)| osmode & b != 0).filter_map(|(b, _)| osnap(*b | extra)).collect();
|
||||
per_mode.sort_by(|a, b| a.point.dist(cursor).total_cmp(&b.point.dist(cursor)));
|
||||
let mut out: Vec<SnapHit> = osnap(osmode).into_iter().collect();
|
||||
for h in per_mode {
|
||||
if !out.iter().any(|o| o.mode == h.mode && o.point.near(h.point, aperture * 1e-6)) {
|
||||
let mut out: Vec<SnapHit> = crate::snap::osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen).into_iter().collect();
|
||||
for h in crate::snap::osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen) {
|
||||
if !out.iter().any(|o| o.same(&h, aperture)) {
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
@@ -352,12 +365,15 @@ impl Session {
|
||||
Frame::Snap { mode } => {
|
||||
// Snap the point with this mode alone, within the aperture.
|
||||
let prompt = self.current_prompt();
|
||||
let space = self.space();
|
||||
let (doc, space, frozen) = {
|
||||
let st = self.state()?;
|
||||
(st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec())
|
||||
};
|
||||
let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
|
||||
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
|
||||
let base = prompt.as_ref().and_then(|q| q.base);
|
||||
let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
|
||||
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred);
|
||||
let hit = crate::snap::osnap_with_frozen(&doc, &space, p, aperture, mode | hatch, base, deferred, &frozen);
|
||||
match hit {
|
||||
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
|
||||
Some(h) => p = h.point,
|
||||
|
||||
@@ -75,8 +75,9 @@ pub struct Prompt {
|
||||
/// Rubber-band origin (for direct distance entry, ortho and polar).
|
||||
pub base: Option<Vec2>,
|
||||
/// The command resolves deferred tangent/perpendicular snaps ([`Input::Deferred`]) at this
|
||||
/// prompt (a point with no base yet, e.g. the first point of a line). Elsewhere a deferred
|
||||
/// pick arrives as the plain point it was picked at.
|
||||
/// prompt (a point with no base yet, e.g. the first point of a line; with a base, only
|
||||
/// tangents, e.g. a circle's radius). Elsewhere a deferred pick arrives as the plain point it
|
||||
/// was picked at.
|
||||
pub deferred: bool,
|
||||
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
|
||||
/// cell): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
||||
@@ -338,6 +339,11 @@ pub trait Interactive: Send {
|
||||
fn editing_mtext(&self) -> Option<cadcraft_doc::MText> {
|
||||
None
|
||||
}
|
||||
/// The text the in-place editor edits: where, how, its current contents and what kind of
|
||||
/// object holds it. By default the new multiline text of [`Interactive::editing_mtext`].
|
||||
fn text_editor(&self) -> Option<TextEditor> {
|
||||
self.editing_mtext().map(|mtext| TextEditor { mtext, kind: EditorKind::NewMText, key: String::new(), extents: None })
|
||||
}
|
||||
/// What the drawing area shows in place of the drawing while the command runs (DVIEW draws
|
||||
/// only its preview set); `None` shows the drawing.
|
||||
fn display_only(&self, _s: &Session) -> Option<DisplayOnly> {
|
||||
@@ -356,6 +362,34 @@ pub struct DisplayOnly {
|
||||
pub extra: Vec<cadcraft_doc::Entity>,
|
||||
}
|
||||
|
||||
/// What the in-place text editor edits ([`Interactive::text_editor`]). The editor answers the
|
||||
/// command's text prompt with the new contents (`Input::Text`), or Enter to keep the old text.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TextEditor {
|
||||
/// Where the box sits (insertion point, attachment, rotation), its width (0: grows with the
|
||||
/// text), text height and style; `contents` is the text to start from.
|
||||
pub mtext: cadcraft_doc::MText,
|
||||
pub kind: EditorKind,
|
||||
/// Which object is being edited: a new key means a new text to load.
|
||||
pub key: String,
|
||||
/// The drawn text's extents in drawing units, when known (one line of text): the box covers
|
||||
/// them, whatever the justification.
|
||||
pub extents: Option<cadcraft_geom::Bounds2>,
|
||||
}
|
||||
|
||||
/// The kind of text the in-place editor edits.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EditorKind {
|
||||
/// Multiline text being created (MTEXT).
|
||||
NewMText,
|
||||
/// Existing multiline text: an MTEXT, a multileader's text.
|
||||
MText,
|
||||
/// One line of plain text (TEXT, attribute definition): no formatting, Enter finishes.
|
||||
Line,
|
||||
/// A dimension's text: `<>` stands for the measured value, shown as `measured`.
|
||||
Dimension { measured: String },
|
||||
}
|
||||
|
||||
/// See [`Interactive::drag`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Drag {
|
||||
|
||||
@@ -536,6 +536,11 @@ impl Session {
|
||||
self.running.as_ref().and_then(|r| r.machine.editing_mtext())
|
||||
}
|
||||
|
||||
/// The text the running command edits in place ([`Interactive::text_editor`]).
|
||||
pub fn text_editor(&self) -> Option<crate::TextEditor> {
|
||||
self.running.as_ref().and_then(|r| r.machine.text_editor())
|
||||
}
|
||||
|
||||
pub fn current_prompt(&self) -> Option<Prompt> {
|
||||
if let Some(p) = self.lisp_prompt() {
|
||||
return Some(p);
|
||||
|
||||
+520
-97
@@ -65,6 +65,21 @@ pub struct SnapHit {
|
||||
}
|
||||
|
||||
impl SnapHit {
|
||||
fn plain(mode: u32, point: Vec2) -> SnapHit {
|
||||
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
|
||||
}
|
||||
|
||||
/// The same snap as `o`, for a Tab list without repeats: the same mode at the same point
|
||||
/// (within a millionth of `aperture`), deferred or not alike, and from the same source (this
|
||||
/// space, or one viewport). Overlapping viewports can show different model points at one paper
|
||||
/// point; each stays a candidate, since DIST measures in the model units of the viewport picked.
|
||||
pub(crate) fn same(&self, o: &SnapHit, aperture: f64) -> bool {
|
||||
self.mode == o.mode
|
||||
&& self.deferred.is_some() == o.deferred.is_some()
|
||||
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
|
||||
&& self.point.near(o.point, aperture * 1e-6)
|
||||
}
|
||||
|
||||
/// The command input a pick at this snap gives: a deferred snap or a plain point.
|
||||
pub fn input(&self) -> crate::Input {
|
||||
match self.deferred {
|
||||
@@ -110,7 +125,7 @@ impl SnapCurve {
|
||||
}
|
||||
/// Points on the curve whose perpendicular passes through `p`; `picked` is where the curve
|
||||
/// was picked, kept when `p` is the center of a circle or arc (every radius is perpendicular).
|
||||
fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
|
||||
pub(crate) fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
|
||||
match self {
|
||||
SnapCurve::Circle { center, radius } | SnapCurve::Arc { center, radius, .. } => {
|
||||
let u = (p - *center).normalized();
|
||||
@@ -202,15 +217,34 @@ fn prim_segments(p: &Prim) -> Vec<Segment> {
|
||||
/// Tangent and perpendicular snaps need the base point (the other end of the line). With no
|
||||
/// base and `deferred` set (the prompt says it can resolve them, `Prompt.deferred`),
|
||||
/// they snap as *deferred*: the hit carries the curve and is resolved once the other end is
|
||||
/// known. Deferred hits only win where no other snap does (they are as unspecific as Nearest).
|
||||
/// known. With a base and `deferred` set, tangents to circles and circular arcs are deferred too
|
||||
/// (CIRCLE's radius: the circle around the base that touches the curve, #1512); an elliptical arc
|
||||
/// or a spline keeps its ordinary tangent from the base. Deferred hits only win
|
||||
/// where no other snap does (they are as unspecific as Nearest).
|
||||
pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Option<SnapHit> {
|
||||
osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||
}
|
||||
|
||||
/// [`osnap`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn osnap_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> Option<SnapHit> {
|
||||
if osmode == 0 || osmode & mode::OFF != 0 {
|
||||
return None;
|
||||
}
|
||||
let ix = crate::spatial::index(d, space);
|
||||
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
|
||||
osnap_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred, frozen).0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn osnap_with(
|
||||
d: &Drawing,
|
||||
@@ -222,7 +256,7 @@ pub(crate) fn osnap_with(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> Option<SnapHit> {
|
||||
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred).0
|
||||
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred, &[]).0
|
||||
}
|
||||
|
||||
/// Find the best object snap and retain the local-space primitives gathered for that query.
|
||||
@@ -236,17 +270,18 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
|
||||
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
|
||||
return (None, None);
|
||||
}
|
||||
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
||||
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, None) {
|
||||
Some((hit, prims)) => (hit, Some(prims)),
|
||||
None => (None, None),
|
||||
};
|
||||
let views = viewport::near(d, space, cursor, aperture);
|
||||
if views.is_empty() {
|
||||
return (best, near_prims);
|
||||
return (best.map(|(h, _)| h), near_prims);
|
||||
}
|
||||
let model = Space::Model;
|
||||
let model_ix = crate::spatial::index(d, &model);
|
||||
@@ -269,14 +304,35 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
&view.viewport.frozen_layers,
|
||||
Some(view.model_clip),
|
||||
)
|
||||
.and_then(|h| view.hit(h));
|
||||
if let Some(hit) = hit
|
||||
&& best.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
|
||||
// The rank was found in model units: paper units are model units times the scale.
|
||||
.and_then(|(h, r)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r })));
|
||||
if let Some((hit, rank)) = hit
|
||||
&& best.as_ref().is_none_or(|(_, b)| rank.beats(b))
|
||||
{
|
||||
best = Some(hit);
|
||||
best = Some((hit, rank));
|
||||
}
|
||||
}
|
||||
(best, near_prims)
|
||||
(best.map(|(h, _)| h), near_prims)
|
||||
}
|
||||
|
||||
/// How a hit ranks against the hits of another space (paper space, another viewport) and, for
|
||||
/// Tab, against the other candidates: first the order [`finish`] tries them in (snap points, then
|
||||
/// a perpendicular or tangent on the object under the cursor or a center found from its curve,
|
||||
/// then deferred snaps, then Nearest), then its score within that tier, in the units of the cursor.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Rank {
|
||||
tier: u8,
|
||||
score: f64,
|
||||
}
|
||||
|
||||
impl Rank {
|
||||
fn cmp(&self, other: &Rank) -> std::cmp::Ordering {
|
||||
self.tier.cmp(&other.tier).then(self.score.total_cmp(&other.score))
|
||||
}
|
||||
|
||||
fn beats(&self, other: &Rank) -> bool {
|
||||
self.cmp(other).is_lt()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -291,7 +347,7 @@ fn osnap_in(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<SnapHit> {
|
||||
) -> Option<(SnapHit, Rank)> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit)
|
||||
}
|
||||
|
||||
@@ -307,7 +363,92 @@ fn osnap_in_with_prims(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<(Option<SnapHit>, Vec<Prim>)> {
|
||||
) -> Option<(Option<(SnapHit, Rank)>, Vec<Prim>)> {
|
||||
let (cands, near_prims) = collect_in(d, space, ix, cursor, aperture, osmode, frozen)?;
|
||||
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hit, near_prims))
|
||||
}
|
||||
|
||||
/// Every snap of `osmode` under the aperture round `cursor`, best first: Tab cycles through
|
||||
/// these. Each mode's points of every object nearby, the intersections, perpendicular and
|
||||
/// tangent points from `base`, the centers found from their curves, the deferred snaps and the
|
||||
/// nearest point of each object, ranked as [`osnap`] ranks them, without repeats and at most
|
||||
/// [`MAX_CYCLE`]; in viewports too, as [`osnap`] snaps.
|
||||
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||
}
|
||||
|
||||
/// [`osnap_all`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn osnap_all_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> Vec<SnapHit> {
|
||||
if osmode == 0
|
||||
|| osmode & mode::OFF != 0
|
||||
|| !cursor.is_finite()
|
||||
|| !(aperture.is_finite() && aperture > 0.0)
|
||||
|| base.is_some_and(|b| !b.is_finite())
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let mut out: Vec<(SnapHit, Rank)> = Vec::new();
|
||||
if let Some((cands, prims)) = collect_in(d, space, &ix, cursor, aperture, osmode, frozen) {
|
||||
out = finish_all(cands, &prims, cursor, aperture, osmode, base, deferred, None);
|
||||
}
|
||||
let model = Space::Model;
|
||||
let views = viewport::near(d, space, cursor, aperture);
|
||||
if !views.is_empty() {
|
||||
let model_ix = crate::spatial::index(d, &model);
|
||||
for view in views {
|
||||
let (mc, ma, mb) = (view.to_model(cursor), aperture / view.scale, base.map(|p| view.to_model(p)));
|
||||
if !mc.is_finite() || !(ma.is_finite() && ma > 0.0) || mb.is_some_and(|p| !p.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let Some((cands, prims)) = collect_in(d, &model, &model_ix, mc, ma, osmode, &view.viewport.frozen_layers) else { continue };
|
||||
// The rank was found in model units: paper units are model units times the scale.
|
||||
out.extend(
|
||||
finish_all(cands, &prims, mc, ma, osmode, mb, deferred, Some(view.model_clip))
|
||||
.into_iter()
|
||||
.filter_map(|(h, r)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }))),
|
||||
);
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.1.cmp(&b.1));
|
||||
let mut unique: Vec<SnapHit> = Vec::with_capacity(out.len().min(MAX_CYCLE));
|
||||
for (h, _) in out {
|
||||
if unique.len() >= MAX_CYCLE {
|
||||
break;
|
||||
}
|
||||
if !unique.iter().any(|u| u.same(&h, aperture)) {
|
||||
unique.push(h);
|
||||
}
|
||||
}
|
||||
unique
|
||||
}
|
||||
|
||||
/// Most snaps [`osnap_all`] offers.
|
||||
const MAX_CYCLE: usize = 256;
|
||||
|
||||
/// The candidate snap points near `cursor` (each with its mode) and the primitives near it:
|
||||
/// [`gather_in`]'s, plus the intersections between those primitives.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn collect_in(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
frozen: &[String],
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
|
||||
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
|
||||
// Intersections between nearby primitives; Apparent Intersection also where their extensions
|
||||
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
|
||||
@@ -345,8 +486,7 @@ fn osnap_in_with_prims(
|
||||
}
|
||||
}
|
||||
}
|
||||
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hit, near_prims))
|
||||
Some((cands, near_prims))
|
||||
}
|
||||
|
||||
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
|
||||
@@ -390,18 +530,7 @@ pub(crate) fn extendable(p: &Prim) -> bool {
|
||||
|
||||
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
|
||||
/// when the drawing can't be searched.
|
||||
pub(crate) fn gather(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
|
||||
gather_in(d, space, ix, cursor, aperture, osmode, &[])
|
||||
}
|
||||
|
||||
fn gather_in(
|
||||
pub(crate) fn gather_in(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
@@ -458,7 +587,19 @@ fn gather_in(
|
||||
Some((cands, near_prims))
|
||||
}
|
||||
|
||||
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps.
|
||||
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps, with
|
||||
/// its [`Rank`].
|
||||
///
|
||||
/// In order of preference (the rank's tier):
|
||||
/// 0. the snap point within `aperture` of the cursor that scores best (see [`snap_score`]),
|
||||
/// perpendicular and tangent points from the base point included;
|
||||
/// 1. with a base point, a perpendicular or tangent on an object that passes within `aperture`,
|
||||
/// wherever its point lies (see [`from_base_on_objects`]), or the center of a circle, arc or
|
||||
/// ellipse under the cursor (see [`curve_centers`]): the object nearest the cursor;
|
||||
/// 2. a deferred perpendicular or tangent (no base point yet);
|
||||
/// 3. Nearest.
|
||||
///
|
||||
/// [`finish_all`] keeps every candidate in this order, for Tab.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish(
|
||||
mut cands: Vec<(u32, Vec2)>,
|
||||
@@ -469,87 +610,248 @@ fn finish(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<SnapHit> {
|
||||
// Perpendicular / tangent from the base point.
|
||||
if let Some(bp) = base {
|
||||
for p in near_prims {
|
||||
if osmode & mode::PER != 0 {
|
||||
match p {
|
||||
Prim::Seg(Segment::Line(l)) => cands.push((mode::PER, l.project(bp))),
|
||||
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
|
||||
// not offered, and the far side is still found.
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => {
|
||||
let curve = SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end };
|
||||
cands.extend(curve.perpendiculars(bp, bp).into_iter().map(|q| (mode::PER, q)));
|
||||
}
|
||||
Prim::Circle(c) => cands.push((mode::PER, c.closest(bp))),
|
||||
Prim::Infinite { base: b0, dir, .. } => cands.push((mode::PER, *b0 + *dir * (bp - *b0).dot(*dir))),
|
||||
Prim::Ellipse(e) => cands.extend(curves::ellipse_perpendiculars(e, bp).into_iter().map(|q| (mode::PER, q))),
|
||||
Prim::Spline(s) => cands.extend(curves::spline_perpendiculars(s, bp).into_iter().map(|q| (mode::PER, q))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if osmode & mode::TAN != 0 {
|
||||
let pts = match p {
|
||||
// Only the tangent points that lie on the arc itself (not its circle).
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
|
||||
.tangent_points(bp)
|
||||
.into_iter()
|
||||
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
|
||||
.collect(),
|
||||
Prim::Circle(c) => c.tangent_points(bp),
|
||||
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
|
||||
Prim::Spline(s) => curves::spline_tangents(s, bp),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
cands.extend(pts.into_iter().map(|t| (mode::TAN, t)));
|
||||
}
|
||||
}
|
||||
}
|
||||
) -> Option<(SnapHit, Rank)> {
|
||||
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
|
||||
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
|
||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||
let best = cands.iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).min_by(|a, b| {
|
||||
// Prefer more specific modes when nearly equidistant.
|
||||
let da = snap_score(a.0, a.1, cursor, aperture);
|
||||
let db = snap_score(b.0, b.1, cursor, aperture);
|
||||
da.total_cmp(&db)
|
||||
});
|
||||
if let Some((m, p)) = best {
|
||||
return Some(SnapHit { point: *p, mode: *m, name: name_of(*m), viewport: None, deferred: None });
|
||||
// Prefer more specific modes when nearly equidistant.
|
||||
let best = cands
|
||||
.iter()
|
||||
.filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture)
|
||||
.map(|(m, p)| (snap_score(*m, *p, cursor, aperture), *m, *p))
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if let Some((score, m, p)) = best {
|
||||
return Some((SnapHit::plain(m, p), Rank { tier: 0, score }));
|
||||
}
|
||||
if base.is_none()
|
||||
&& deferred
|
||||
&& let Some(h) = deferred_hit(near_prims, cursor, aperture, osmode, clip)
|
||||
{
|
||||
return Some(h);
|
||||
// A perpendicular or tangent on the object under the cursor, or the center found from its
|
||||
// curve, only when no snap point is in the aperture: the Midpoint or Quadrant under the cursor
|
||||
// wins over the center of the same curve, as in AutoCAD. Of the two, the object nearer the
|
||||
// cursor; on a tie (the same curve), the perpendicular or tangent.
|
||||
let on_object = from_base_on_objects(&from_base, near_prims, cursor, aperture, visible)
|
||||
.into_iter()
|
||||
.min_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)))
|
||||
.map(|(h, r, _)| (h, r));
|
||||
let center = curve_centers(near_prims, cursor, aperture, osmode)
|
||||
.into_iter()
|
||||
.filter(|(_, c)| visible(*c))
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0))
|
||||
.map(|(score, c)| (SnapHit::plain(mode::CEN, c), Rank { tier: 1, score }));
|
||||
match (on_object, center) {
|
||||
(Some(o), Some(c)) => return Some(if c.1.beats(&o.1) { c } else { o }),
|
||||
(Some(h), None) | (None, Some(h)) => return Some(h),
|
||||
(None, None) => {}
|
||||
}
|
||||
// With a base, perpendiculars are resolved from it above; only tangents are left to defer.
|
||||
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
|
||||
if deferred && let Some(h) = deferred_hit(near_prims, cursor, aperture, deferrable, clip) {
|
||||
let score = h.point.dist(cursor);
|
||||
return Some((h, Rank { tier: 2, score }));
|
||||
}
|
||||
if osmode & mode::NEA != 0 {
|
||||
// The closest point of all nearby objects, whatever their drawing order.
|
||||
let mut nb: Option<(f64, Vec2)> = None;
|
||||
let mut consider = |c: Vec2| {
|
||||
let dd = c.dist(cursor);
|
||||
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
|
||||
nb = Some((dd, c));
|
||||
}
|
||||
};
|
||||
for p in near_prims {
|
||||
for s in prim_segments(p) {
|
||||
consider(fix_circle(&s).closest(cursor));
|
||||
}
|
||||
if let Prim::Circle(c) = p {
|
||||
consider(c.closest(cursor));
|
||||
}
|
||||
}
|
||||
if let Some((_, p)) = nb {
|
||||
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
|
||||
let nb = near_prims.iter().filter_map(|p| nearest_point(p, cursor, aperture, &visible)).min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if let Some((score, p)) = nb {
|
||||
return Some((SnapHit::plain(mode::NEA, p), Rank { tier: 3, score }));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// [`finish`], keeping every candidate with its [`Rank`], in the order [`finish`] prefers them:
|
||||
/// the snap points best first, then the perpendiculars and tangents on the objects under the
|
||||
/// cursor and the centers found from their curves, then the deferred snaps, then the nearest point
|
||||
/// of each object nearby.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish_all(
|
||||
mut cands: Vec<(u32, Vec2)>,
|
||||
near_prims: &[Prim],
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
clip: Option<Bounds2>,
|
||||
) -> Vec<(SnapHit, Rank)> {
|
||||
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
|
||||
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
|
||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||
let mut out: Vec<(SnapHit, Rank)> = cands
|
||||
.iter()
|
||||
.filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture)
|
||||
.map(|(m, p)| (SnapHit::plain(*m, *p), Rank { tier: 0, score: snap_score(*m, *p, cursor, aperture) }))
|
||||
.collect();
|
||||
// Of several points on one object (a circle's two tangents), the one nearer the cursor first,
|
||||
// as `finish` picks it; the sort below is stable.
|
||||
let mut on_object = from_base_on_objects(&from_base, near_prims, cursor, aperture, visible);
|
||||
on_object.sort_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)));
|
||||
out.extend(on_object.into_iter().map(|(h, r, _)| (h, r)));
|
||||
out.extend(
|
||||
curve_centers(near_prims, cursor, aperture, osmode)
|
||||
.into_iter()
|
||||
.filter(|(_, c)| visible(*c))
|
||||
.map(|(score, c)| (SnapHit::plain(mode::CEN, c), Rank { tier: 1, score })),
|
||||
);
|
||||
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
|
||||
if deferred {
|
||||
let hits = deferred_hits(near_prims, cursor, aperture, deferrable, clip);
|
||||
out.extend(hits.into_iter().map(|h| (h, Rank { tier: 2, score: h.point.dist(cursor) })));
|
||||
}
|
||||
if osmode & mode::NEA != 0 {
|
||||
let near = near_prims.iter().filter_map(|p| nearest_point(p, cursor, aperture, &visible));
|
||||
out.extend(near.map(|(score, p)| (SnapHit::plain(mode::NEA, p), Rank { tier: 3, score })));
|
||||
}
|
||||
out.sort_by(|a, b| a.1.cmp(&b.1));
|
||||
out
|
||||
}
|
||||
|
||||
/// The point of `p` closest to `cursor` among its visible points within `aperture`, with its
|
||||
/// distance: each segment's closest point is checked before the closest is chosen, so a curve
|
||||
/// whose closest point is clipped away (outside a viewport) still offers the visible one.
|
||||
fn nearest_point(p: &Prim, cursor: Vec2, aperture: f64, visible: &impl Fn(Vec2) -> bool) -> Option<(f64, Vec2)> {
|
||||
let mut nb: Option<(f64, Vec2)> = None;
|
||||
let mut consider = |c: Vec2| {
|
||||
let dd = c.dist(cursor);
|
||||
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
|
||||
nb = Some((dd, c));
|
||||
}
|
||||
};
|
||||
for s in prim_segments(p) {
|
||||
consider(fix_circle(&s).closest(cursor));
|
||||
}
|
||||
if let Prim::Circle(c) = p {
|
||||
consider(c.closest(cursor));
|
||||
}
|
||||
nb
|
||||
}
|
||||
|
||||
/// The perpendicular and tangent points from the base point `base` (none without one), each
|
||||
/// with the index in `near_prims` of the object it lies on. At a `deferred` prompt the tangents to
|
||||
/// circles and arcs are left out: the prompt resolves them itself (CIRCLE's radius, #1512).
|
||||
fn base_snaps(near_prims: &[Prim], osmode: u32, base: Option<Vec2>, cursor: Vec2, deferred: bool) -> Vec<FromBase> {
|
||||
let mut from_base: Vec<FromBase> = Vec::new();
|
||||
let Some(bp) = base else { return from_base };
|
||||
for (prim, p) in near_prims.iter().enumerate() {
|
||||
let mut found = |mode: u32, points: Vec<Vec2>| from_base.extend(points.into_iter().map(|point| FromBase { mode, point, prim }));
|
||||
if osmode & mode::PER != 0 {
|
||||
let pts = match p {
|
||||
Prim::Seg(Segment::Line(l)) => vec![l.project(bp)],
|
||||
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
|
||||
// not offered, and the far side is still found.
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => {
|
||||
SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end }.perpendiculars(bp, bp)
|
||||
}
|
||||
// Both antipodes too, so a pick on the far side of the circle snaps there
|
||||
// rather than across it. From the centre every point is perpendicular: the
|
||||
// one under the cursor.
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius }.perpendiculars(bp, cursor),
|
||||
Prim::Infinite { base: b0, dir, .. } => vec![*b0 + *dir * (bp - *b0).dot(*dir)],
|
||||
Prim::Ellipse(e) => curves::ellipse_perpendiculars(e, bp),
|
||||
Prim::Spline(s) => curves::spline_perpendiculars(s, bp),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
found(mode::PER, pts);
|
||||
}
|
||||
if osmode & mode::TAN != 0 {
|
||||
let pts = match p {
|
||||
// A deferred prompt resolves tangents to circles and arcs itself.
|
||||
Prim::Seg(Segment::Arc { .. }) | Prim::Circle(_) if deferred => Vec::new(),
|
||||
// Only the tangent points that lie on the arc itself (not its circle).
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
|
||||
.tangent_points(bp)
|
||||
.into_iter()
|
||||
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
|
||||
.collect(),
|
||||
Prim::Circle(c) => c.tangent_points(bp),
|
||||
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
|
||||
Prim::Spline(s) => curves::spline_tangents(s, bp),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
found(mode::TAN, pts);
|
||||
}
|
||||
}
|
||||
from_base
|
||||
}
|
||||
|
||||
/// Center, as in AutoCAD: with the cursor over a circle, an arc (also a polyline's) or an
|
||||
/// ellipse, the running Center snap finds its center however far away it is. Each center comes
|
||||
/// with how far the curve is from `cursor` (its score); [`finish`] tries them only when no snap
|
||||
/// point is in the aperture. Empty unless Center is among `osmode`.
|
||||
fn curve_centers(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32) -> Vec<(f64, Vec2)> {
|
||||
let mut out = Vec::new();
|
||||
if osmode & mode::CEN == 0 {
|
||||
return out;
|
||||
}
|
||||
// The work limit counts the curves only, so straight segments before them can't hide them.
|
||||
let curves = prims.iter().filter_map(|p| match p {
|
||||
Prim::Circle(c) => Some((c.center, c.closest(cursor))),
|
||||
Prim::Seg(s @ Segment::Arc { arc, .. }) => Some((arc.center, fix_circle(s).closest(cursor))),
|
||||
Prim::Ellipse(e) => Some((e.center, e.closest(cursor))),
|
||||
_ => None,
|
||||
});
|
||||
for (center, on) in curves.take(2000) {
|
||||
let d = on.dist(cursor);
|
||||
if center.is_finite() && d.is_finite() && d <= aperture {
|
||||
out.push((d, center));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
|
||||
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A perpendicular ([`mode::PER`]) or tangent ([`mode::TAN`]) point found from the base point,
|
||||
/// with the index in `near_prims` of the object it lies on.
|
||||
struct FromBase {
|
||||
mode: u32,
|
||||
point: Vec2,
|
||||
prim: usize,
|
||||
}
|
||||
|
||||
/// The perpendiculars and tangents from the base point on the objects that pass within
|
||||
/// `aperture` of the cursor, wherever the foot or tangent point lies (#2800), each with its
|
||||
/// [`Rank`] (tier 1, scored by the cursor's distance to the object) and its distance to the cursor.
|
||||
///
|
||||
/// These snaps name an object, not a spot on it: you can't know in advance where the foot of a
|
||||
/// perpendicular will be, so, as in AutoCAD, hovering anywhere over the object finds it and the
|
||||
/// point jumps there. [`finish`] asks for this only when no snap point lies within the aperture,
|
||||
/// so an endpoint, midpoint or intersection under the cursor still wins.
|
||||
///
|
||||
/// [`finish`] takes the object nearest the cursor; of several points on it (an arc's two
|
||||
/// antipodes, a circle's two tangents), the one nearest the cursor.
|
||||
fn from_base_on_objects(
|
||||
found: &[FromBase],
|
||||
near_prims: &[Prim],
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
visible: impl Fn(Vec2) -> bool,
|
||||
) -> Vec<(SnapHit, Rank, f64)> {
|
||||
let mut out = Vec::new();
|
||||
if found.is_empty() {
|
||||
return out;
|
||||
}
|
||||
// `near_prims` holds every object whose box comes near the cursor, so the true distance is
|
||||
// checked here. It is measured once per object, and only for objects with a point to offer:
|
||||
// an ellipse or a spline is measured on its tessellation.
|
||||
let mut reach: Vec<Option<f64>> = vec![None; near_prims.len()];
|
||||
for f in found.iter().filter(|f| visible(f.point)) {
|
||||
let Some(slot) = reach.get_mut(f.prim) else { continue };
|
||||
let to_object = *slot.get_or_insert_with(|| near_prims.get(f.prim).map_or(f64::INFINITY, |p| distance_to_prim(p, cursor)));
|
||||
// A NaN distance (from a degenerate object) never qualifies.
|
||||
if to_object.is_nan() || to_object > aperture {
|
||||
continue;
|
||||
}
|
||||
out.push((SnapHit::plain(f.mode, f.point), Rank { tier: 1, score: to_object }, f.point.dist(cursor)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The distance from `cursor` to the nearest point of `p`, measured as Nearest measures it.
|
||||
fn distance_to_prim(p: &Prim, cursor: Vec2) -> f64 {
|
||||
prim_segments(p).iter().map(|s| fix_circle(s).closest(cursor).dist(cursor)).fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// Upper bound on the block-reference objects one snap query looks at (hostile files).
|
||||
const MAX_BLOCK_LEAVES: usize = 20_000;
|
||||
|
||||
@@ -848,6 +1150,47 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every deferred tangent and perpendicular within `aperture` of `cursor`, for Tab: one per curve
|
||||
/// and mode, in drawing order (the caller ranks them), so Tab can go from the tangent to the
|
||||
/// perpendicular on the same circle, and to the deferred snap of each curve nearby. A click takes
|
||||
/// the nearest one ([`deferred_hit`]).
|
||||
fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
|
||||
let mut hits = Vec::new();
|
||||
if osmode & (mode::TAN | mode::PER) == 0 {
|
||||
return hits;
|
||||
}
|
||||
for p in prims {
|
||||
let curve = match p {
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end },
|
||||
Prim::Seg(Segment::Line(l)) => SnapCurve::Line { a: l.a, b: l.b },
|
||||
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
|
||||
_ => continue,
|
||||
};
|
||||
// Where the curve was picked: a circle's, an arc's or a segment's own span, an xline/ray
|
||||
// anywhere.
|
||||
let at = match curve {
|
||||
SnapCurve::Circle { center, radius } => Circle::new(center, radius).closest(cursor),
|
||||
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor),
|
||||
SnapCurve::Line { a, b } => {
|
||||
let l = cadcraft_geom::Line::new(a, b);
|
||||
if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) }
|
||||
}
|
||||
};
|
||||
if !(at.is_finite() && clip.is_none_or(|c| c.contains(at)) && at.dist(cursor) <= aperture) {
|
||||
continue;
|
||||
}
|
||||
let modes: &[(u32, &'static str)] = match curve {
|
||||
SnapCurve::Circle { .. } | SnapCurve::Arc { .. } => &[(mode::TAN, "Deferred Tangent"), (mode::PER, "Deferred Perpendicular")],
|
||||
SnapCurve::Line { .. } => &[(mode::PER, "Deferred Perpendicular")],
|
||||
};
|
||||
for &(m, name) in modes.iter().filter(|(m, _)| osmode & m != 0) {
|
||||
hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) });
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
|
||||
fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
|
||||
let mut best: Option<(f64, SnapHit)> = None;
|
||||
@@ -1121,6 +1464,17 @@ mod tests {
|
||||
assert_eq!(h.name, "Intersection");
|
||||
}
|
||||
|
||||
/// Tab cycling sees every deferred snap within the aperture: on a circle with no base point,
|
||||
/// its quadrant, then the deferred tangent and the deferred perpendicular at the same spot.
|
||||
#[test]
|
||||
fn osnap_all_ranks_every_candidate() {
|
||||
let d = drawing();
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
|
||||
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
|
||||
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
|
||||
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, mode::QUA | mode::TAN | mode::PER, None, true).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn center_quadrant_tangent() {
|
||||
let d = drawing();
|
||||
@@ -1137,6 +1491,70 @@ mod tests {
|
||||
assert!(h.point.near(Vec2::new(3.0, 0.0), 1e-9));
|
||||
}
|
||||
|
||||
/// #2800: hovering anywhere over the line finds the perpendicular, though its foot (2,0) is
|
||||
/// six units from the cursor; it used to snap only within the aperture of the foot.
|
||||
#[test]
|
||||
fn perpendicular_from_base_anywhere_on_the_line() {
|
||||
let d = drawing();
|
||||
let h = osnap(&d, &Space::Model, Vec2::new(8.0, 0.1), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(2.0, 0.0), 1e-9), "{h:?}");
|
||||
assert_eq!(h.mode, mode::PER);
|
||||
}
|
||||
|
||||
/// #2800: the tangent point is found from anywhere on the circle; of its two tangent points
|
||||
/// from the base, the one nearer the cursor.
|
||||
#[test]
|
||||
fn tangent_from_base_anywhere_on_the_circle() {
|
||||
let d = drawing();
|
||||
// From (30,0), 10 from the centre (20,0) of the radius-2 circle: the tangent points are
|
||||
// at cos = 2/10 from the line to the base, (20.4, ±1.9596).
|
||||
let upper = Vec2::new(20.4, 2.0 * (1.0f64 - 0.04).sqrt());
|
||||
let on_circle = Vec2::new(20.0 - 2.0 * std::f64::consts::FRAC_1_SQRT_2, 2.0 * std::f64::consts::FRAC_1_SQRT_2);
|
||||
let h = osnap(&d, &Space::Model, on_circle, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
|
||||
assert!(h.point.near(upper, 1e-9), "{h:?}");
|
||||
let mirrored = Vec2::new(on_circle.x, -on_circle.y);
|
||||
let h = osnap(&d, &Space::Model, mirrored, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(upper.x, -upper.y), 1e-9), "{h:?}");
|
||||
}
|
||||
|
||||
/// A circle offers both perpendicular points from the base, so a pick on its far side snaps
|
||||
/// there, not to the near side across the circle (CodeRabbit on #2825).
|
||||
#[test]
|
||||
fn perpendicular_from_base_on_a_circle_takes_the_side_under_the_cursor() {
|
||||
let d = drawing();
|
||||
// The circle at (20,0), radius 2, seen from (30,0): perpendicular at (22,0) and (18,0).
|
||||
let base = Some(Vec2::new(30.0, 0.0));
|
||||
let far = osnap(&d, &Space::Model, Vec2::new(18.1, 0.1), 0.5, mode::PER, base, false).unwrap();
|
||||
assert!(far.point.near(Vec2::new(18.0, 0.0), 1e-9), "{far:?}");
|
||||
// Away from both points, at (19, √3) on the circle: 2 from (18,0) and √12 from (22,0).
|
||||
let top = osnap(&d, &Space::Model, Vec2::new(19.0, 3.0f64.sqrt()), 0.5, mode::PER, base, false).unwrap();
|
||||
assert!(top.point.near(Vec2::new(18.0, 0.0), 1e-9), "{top:?}");
|
||||
let near = osnap(&d, &Space::Model, Vec2::new(21.9, 0.1), 0.5, mode::PER, base, false).unwrap();
|
||||
assert!(near.point.near(Vec2::new(22.0, 0.0), 1e-9), "{near:?}");
|
||||
}
|
||||
|
||||
/// With several objects under the aperture, the one nearest the cursor gives the
|
||||
/// perpendicular, even when another object's foot is nearer.
|
||||
#[test]
|
||||
fn perpendicular_from_base_takes_the_object_nearest_the_cursor() {
|
||||
let d = drawing();
|
||||
// 0.4 above the horizontal line and 0.2 right of the vertical one: the vertical line wins,
|
||||
// with its foot (5,4) farther from the cursor than the horizontal line's (2,0).
|
||||
let h = osnap(&d, &Space::Model, Vec2::new(5.2, 0.4), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(5.0, 4.0), 1e-9), "{h:?}");
|
||||
}
|
||||
|
||||
/// A snap point under the cursor still beats a perpendicular whose foot is away from it, and
|
||||
/// an object outside the aperture gives none, though its box is near.
|
||||
#[test]
|
||||
fn perpendicular_from_base_yields_to_points_under_the_cursor() {
|
||||
let d = drawing();
|
||||
let base = Some(Vec2::new(2.0, 4.0));
|
||||
let h = osnap(&d, &Space::Model, Vec2::new(9.9, 0.05), 0.5, mode::END | mode::PER, base, false).unwrap();
|
||||
assert_eq!((h.point, h.mode), (Vec2::new(10.0, 0.0), mode::END));
|
||||
assert!(osnap(&d, &Space::Model, Vec2::new(8.0, 0.7), 0.5, mode::PER, base, false).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ortho_and_polar() {
|
||||
assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0));
|
||||
@@ -1179,9 +1597,14 @@ mod tests {
|
||||
let df = h.deferred.unwrap();
|
||||
assert_eq!(df.curve, SnapCurve::Circle { center: Vec2::new(20.0, 0.0), radius: 2.0 });
|
||||
assert_eq!(h.input(), crate::Input::Deferred(df));
|
||||
// With a base it is an ordinary tangent.
|
||||
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
|
||||
// With a base it is an ordinary tangent, unless the prompt resolves it (CIRCLE's radius).
|
||||
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), false).unwrap();
|
||||
assert!(t.deferred.is_none() && t.name == "Tangent");
|
||||
let t = osnap(&d, &Space::Model, at, 0.5, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
|
||||
assert_eq!(t.name, "Deferred Tangent");
|
||||
// A perpendicular from the base is still resolved from it.
|
||||
let p = osnap(&d, &Space::Model, Vec2::new(2.0, 0.2), 0.5, mode::PER, Some(Vec2::new(2.0, 5.0)), true).unwrap();
|
||||
assert!(p.deferred.is_none() && p.point.near(Vec2::new(2.0, 0.0), 1e-9));
|
||||
// A specific snap still wins over a deferred one.
|
||||
let q = osnap(&d, &Space::Model, at, 0.5, mode::TAN | mode::QUA, None, true).unwrap();
|
||||
assert_eq!(q.mode, mode::QUA);
|
||||
|
||||
@@ -482,13 +482,38 @@ impl Tracker {
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
) -> Option<Track> {
|
||||
let t = self.find(d, space, cursor, aperture, tol, cfg, base);
|
||||
self.track_with_frozen(d, space, cursor, aperture, tol, cfg, base, &[])
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn track_with_frozen(
|
||||
&mut self,
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
tol: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
frozen: &[String],
|
||||
) -> Option<Track> {
|
||||
let t = self.find(d, space, cursor, aperture, tol, cfg, base, frozen);
|
||||
self.last = t.clone();
|
||||
t
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn find(&self, d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, tol: f64, cfg: &TrackConfig, base: Option<Vec2>) -> Option<Track> {
|
||||
fn find(
|
||||
&self,
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
tol: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
frozen: &[String],
|
||||
) -> Option<Track> {
|
||||
if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) {
|
||||
return None;
|
||||
}
|
||||
@@ -538,7 +563,7 @@ impl Tracker {
|
||||
// 2. A path crossing an object.
|
||||
if cfg.running(mode::INT | mode::APP) {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
|
||||
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen).map(|(_, p)| p).unwrap_or_default();
|
||||
for prim in prims.iter().take(200) {
|
||||
let extend = cfg.running(mode::APP) && super::extendable(prim);
|
||||
for seg in super::prim_segments(prim) {
|
||||
@@ -588,12 +613,26 @@ pub fn candidate(
|
||||
aperture: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
) -> Option<Acquired> {
|
||||
candidate_with_frozen(d, space, cursor, hit, aperture, cfg, base, &[])
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn candidate_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
hit: Option<&SnapHit>,
|
||||
aperture: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
frozen: &[String],
|
||||
) -> Option<Acquired> {
|
||||
if !can_acquire(cursor, aperture, cfg) {
|
||||
return None;
|
||||
}
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
|
||||
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen).map(|(_, p)| p).unwrap_or_default();
|
||||
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
|
||||
}
|
||||
|
||||
@@ -789,7 +828,7 @@ impl crate::Session {
|
||||
s.orthomode ^= q.shift;
|
||||
let angbase = self.angle_settings().angbase;
|
||||
let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } };
|
||||
let (doc, space) = (st.doc.clone(), st.edit_space());
|
||||
let (doc, space, frozen) = (st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec());
|
||||
if !raw.is_finite() {
|
||||
return CursorSnap { point: raw, ..Default::default() };
|
||||
}
|
||||
@@ -798,10 +837,10 @@ impl crate::Session {
|
||||
let cfg = TrackConfig::relative_to(&s, angbase, last);
|
||||
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
|
||||
let ix = crate::spatial::index(&doc, &space);
|
||||
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred);
|
||||
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred, &frozen);
|
||||
let cand = match (osmode & mode::HATCH, near_prims.as_deref()) {
|
||||
(0, Some(prims)) => candidate_with_prims(raw, hit.as_ref(), q.aperture, &cfg, q.base, prims),
|
||||
_ => candidate(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base),
|
||||
_ => candidate_with_frozen(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base, &frozen),
|
||||
};
|
||||
let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift);
|
||||
if let Some(h) = hit {
|
||||
@@ -816,7 +855,7 @@ impl crate::Session {
|
||||
let (origin, angle) = super::grid_frame_in(&doc, &space);
|
||||
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
|
||||
}
|
||||
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) {
|
||||
if let Some(mut t) = self.tracking.track_with_frozen(&doc, &space, p, q.aperture, q.tol, &cfg, q.base, &frozen) {
|
||||
// PolarSnap (SNAPTYPE 1): steps of POLARDIST, or of the snap X spacing when it is 0.
|
||||
let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
|
||||
if s.snapmode
|
||||
|
||||
@@ -336,3 +336,24 @@ fn annotative_mtext_columns_follow_the_scale() {
|
||||
assert_eq!((t.height, t.width, c.count, c.gutter, c.height, c.heights), (2.0, 20.0, 2, 2.0, 40.0, vec![6.0, 10.0]));
|
||||
}
|
||||
}
|
||||
|
||||
/// TEXTEDIT's in-place box for annotative text at a non-unit annotation scale has the height and
|
||||
/// extents of the text as drawn (scaled), not as stored (#842 review).
|
||||
#[test]
|
||||
fn the_text_edit_box_of_annotative_text_is_as_drawn() {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
let r = s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap();
|
||||
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let drawn = drawn_height(s.doc().unwrap(), h).unwrap();
|
||||
assert!(drawn > 5.0, "drawn {drawn}");
|
||||
s.cmdline("TEXTEDIT").unwrap();
|
||||
s.input(cadcraft_engine::Input::Point(cadcraft_engine::geom::Vec2::new(0.0, 0.0))).unwrap();
|
||||
let ed = s.text_editor().expect("the editor opens on the text");
|
||||
assert!((ed.mtext.height - 12.5).abs() < 1e-9, "box height {}", ed.mtext.height);
|
||||
let b = ed.extents.unwrap();
|
||||
// The text's layout box (cell height), so a little taller than the strokes, never the
|
||||
// stored 0.25-high text's.
|
||||
assert!(b.height() >= drawn * 0.95 && b.height() <= drawn * 2.0, "box extents {} vs drawn {drawn}", b.height());
|
||||
}
|
||||
|
||||
@@ -317,6 +317,23 @@ fn tolerance_justification_angular_zeros_and_arc_symbol() {
|
||||
assert_eq!(dim_lines(&g1).len(), dim_lines(&g2).len() + 1, "the symbol drawn over the text");
|
||||
}
|
||||
|
||||
/// DIMPOST frames the angle too, as AutoCAD 2026 does to its own angular dimensions (#1653).
|
||||
#[test]
|
||||
fn dimpost_applies_to_angular_dimensions() {
|
||||
let mut s = Session::new();
|
||||
set(&mut s, "DIMPOST", json!("<> m"));
|
||||
set(&mut s, "DIMADEC", json!(1));
|
||||
// Vertex and two points.
|
||||
s.execute("dimangular", &json!({ "vertex": [0, 0], "p1": [10, 0], "p2": [0, 10], "at": [3, 3] })).unwrap();
|
||||
assert_eq!(last_dim(&s).1.value, "90.0° m");
|
||||
// Two lines picked: the same suffix.
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [5, 8.660254037844387]] })).unwrap();
|
||||
let h: Vec<String> = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).map(|e| e.handle.hex()).collect();
|
||||
s.execute("dimangular", &json!({ "lines": h, "at": [4, 1] })).unwrap();
|
||||
assert_eq!(last_dim(&s).1.value, "60.0° m");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linetypes_and_lineweights_of_dimension_and_extension_lines() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
//! HATCHGENERATEBOUNDARY (#2801): closed polylines around existing hatches, which stay as they are.
|
||||
|
||||
use cadcraft_engine::doc::{EntityKind, Handle, Hatch, LwPolyline};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn hatch(s: &Session, h: &str) -> Hatch {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::Hatch(x) => x.clone(),
|
||||
k => panic!("not a hatch: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn poly(s: &Session, h: &str) -> LwPolyline {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::LwPolyline(p) => p.clone(),
|
||||
k => panic!("not a polyline: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(v: &Value) -> String {
|
||||
v["handle"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn handles(v: &Value) -> Vec<String> {
|
||||
v["handles"].as_array().unwrap().iter().map(|h| h.as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String {
|
||||
handle(&s.execute("rectang", &json!({ "p1": a, "p2": b })).unwrap())
|
||||
}
|
||||
|
||||
fn count(s: &Session) -> usize {
|
||||
s.doc().unwrap().model.iter().count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generates_a_closed_polyline_around_a_hatch_without_its_outline() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()] })).unwrap());
|
||||
s.execute("erase", &json!({ "handles": [r] })).unwrap();
|
||||
let before = hatch(&s, &h);
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
|
||||
let new = handles(&v);
|
||||
assert_eq!(new.len(), 1);
|
||||
let p = poly(&s, &new[0]);
|
||||
assert!(p.closed);
|
||||
assert_eq!(p.vertices, before.loops[0].vertices);
|
||||
assert_eq!(hatch(&s, &h), before, "the hatch is not changed");
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
assert_eq!(count(&s), 1, "one undo step removes what was generated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn islands_get_their_own_polylines() {
|
||||
let mut s = Session::new();
|
||||
rect(&mut s, [0.0, 0.0], [20.0, 20.0]);
|
||||
rect(&mut s, [5.0, 5.0], [10.0, 10.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "points": [[2, 2]] })).unwrap());
|
||||
assert_eq!(hatch(&s, &h).loops.len(), 2);
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_selected_hatch_gets_its_boundary() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let b = rect(&mut s, [10.0, 0.0], [14.0, 2.0]);
|
||||
let ha = handle(&s.execute("hatch", &json!({ "handles": [a] })).unwrap());
|
||||
let hb = handle(&s.execute("hatch", &json!({ "handles": [b] })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [ha, hb] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hatch_named_twice_gets_one_boundary() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone(), h] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_associative_hatch_stays_linked_to_its_own_boundary() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()], "associative": true })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
|
||||
let p = handles(&v)[0].clone();
|
||||
// Moving the generated polyline leaves the hatch where it is.
|
||||
s.execute("move", &json!({ "handles": [p], "delta": [0, 10] })).unwrap();
|
||||
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.y, 0.0);
|
||||
// Moving the original rectangle still moves the hatch.
|
||||
s.execute("move", &json!({ "handles": [r], "delta": [10, 0] })).unwrap();
|
||||
assert!(hatch(&s, &h).associative);
|
||||
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.x, 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boundaries_keep_the_hatch_elevation() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
x.elevation = 300.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
assert_eq!(poly(&s, &handles(&v)[0]).elevation, 300.0);
|
||||
}
|
||||
|
||||
/// A mirrored hatch (normal 0,0,-1, as exploding a mirrored block makes) at elevation 300 lies at
|
||||
/// world Z -300; its boundary, facing up, goes there too, not to +300.
|
||||
#[test]
|
||||
fn a_mirrored_hatchs_boundary_keeps_its_world_height() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
e.common.extrusion = cadcraft_engine::geom::Vec3::new(0.0, 0.0, -1.0);
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
x.elevation = 300.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
let new = Handle::parse_hex(&handles(&v)[0]).unwrap();
|
||||
let e = s.doc().unwrap().entity(new).unwrap().clone();
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
|
||||
assert_eq!(e.common.extrusion.z.signum() * p.elevation, -300.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_hatch_in_another_space_and_adds_nothing() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
|
||||
let before = s.doc().unwrap().entity_count();
|
||||
let e = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap_err();
|
||||
assert!(e.to_string().contains("not in the current space"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().entity_count(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_more_boundaries_than_the_limit_and_adds_nothing() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
// One hatch with more loops than one call may turn into polylines.
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
let l = x.loops[0].clone();
|
||||
x.loops = vec![l; 10_001];
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let before = count(&s);
|
||||
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).is_err());
|
||||
assert_eq!(count(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_a_hatch() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [r] })).is_err());
|
||||
assert_eq!(count(&s), 1, "nothing is added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_at_once_on_selected_hatches() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.set_selection(vec![Handle::parse_hex(&h).unwrap()]);
|
||||
s.start("hatchgenerateboundary").unwrap();
|
||||
assert!(s.current_prompt().is_none(), "a pickfirst selection needs no prompt");
|
||||
assert_eq!(count(&s), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asks_for_hatches_without_a_selection() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.set_selection(Vec::new());
|
||||
s.start("hatchgenerateboundary").unwrap();
|
||||
assert!(s.current_prompt().is_some());
|
||||
s.input(Input::Pick(vec![Handle::parse_hex(&h).unwrap()])).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert_eq!(count(&s), 3);
|
||||
}
|
||||
@@ -68,6 +68,7 @@ mod group_selection;
|
||||
mod groups;
|
||||
mod hatch_assoc;
|
||||
mod hatch_dialog_helpers;
|
||||
mod hatch_generate_boundary;
|
||||
mod hatch_numeric_validation;
|
||||
mod hatch_options;
|
||||
mod helix;
|
||||
@@ -114,6 +115,7 @@ mod offset_ellipse_side;
|
||||
mod offset_move;
|
||||
mod oops_command;
|
||||
mod options_profile;
|
||||
mod osnap_opened_drawings;
|
||||
mod overkill;
|
||||
mod parallel_display_list;
|
||||
mod pedit_multiple;
|
||||
@@ -156,10 +158,12 @@ mod setvar_coverage;
|
||||
mod shapes;
|
||||
mod snap_annotations;
|
||||
mod snap_blocks;
|
||||
mod snap_center_on_curve;
|
||||
mod snap_curves;
|
||||
mod snap_intersections_aperture;
|
||||
mod snap_nearest;
|
||||
mod snap_overrides;
|
||||
mod snap_tab_cycling;
|
||||
mod snap_tracking;
|
||||
mod snaps_more;
|
||||
mod solid_command;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! DIST snaps to the model geometry displayed in paper-space viewports (#516).
|
||||
|
||||
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
||||
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Ellipse, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap};
|
||||
use cadcraft_engine::pointmod::snap_candidates;
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -278,6 +279,46 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
|
||||
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
|
||||
}
|
||||
|
||||
/// Across spaces a click takes the viewport's Endpoint over a paper-space Nearest that scores
|
||||
/// closer, as within one space a snap point beats Nearest. Tab starts at the click's snap and
|
||||
/// still reaches the paper-space Nearest.
|
||||
#[test]
|
||||
fn a_viewport_endpoint_beats_a_closer_paper_space_nearest() {
|
||||
let (mut d, paper) = drawing();
|
||||
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
|
||||
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
|
||||
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
|
||||
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
|
||||
assert!(hit.mode == mode::END && hit.viewport.is_some() && hit.point.near(Vec2::new(95.0, 50.0), 1e-9), "{hit:?}");
|
||||
let all = snap_candidates(&d, &paper, cursor, 0.5, modes, None, false);
|
||||
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
|
||||
assert!(
|
||||
all.iter().any(|h| h.mode == mode::NEA && h.viewport.is_none() && h.point.near(Vec2::new(94.7, 50.0), 1e-9)),
|
||||
"Tab reaches the paper-space Nearest: {all:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Overlapping viewports can show different model points at one paper point; Tab offers each,
|
||||
/// since DIST measures in the model units of the viewport picked.
|
||||
#[test]
|
||||
fn overlapping_viewports_each_offer_their_model_point() {
|
||||
let (mut d, paper) = drawing();
|
||||
// This viewport shows the model endpoint (20, 0) at paper (100, 50), a second one over it (0, 0).
|
||||
edit_viewport(&mut d, &paper, |vp| vp.view_center = Vec2::new(20.0, 0.0));
|
||||
let mut vp = match &d.entity(viewport(&d, &paper)).unwrap().kind {
|
||||
EntityKind::Viewport(vp) => vp.clone(),
|
||||
_ => panic!("viewport fixture"),
|
||||
};
|
||||
vp.view_center = Vec2::new(0.0, 0.0);
|
||||
vp.id = 3;
|
||||
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||||
let all = osnap_all(&d, &paper, Vec2::new(100.05, 50.04), 0.5, mode::END, None, false);
|
||||
let mut models: Vec<Vec2> =
|
||||
all.iter().filter(|h| h.point.near(Vec2::new(100.0, 50.0), 1e-9)).filter_map(|h| h.viewport).map(|v| v.point).collect();
|
||||
models.sort_by(|a, b| a.x.total_cmp(&b.x));
|
||||
assert_eq!(models, [Vec2::new(0.0, 0.0), Vec2::new(20.0, 0.0)], "{all:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewport_frozen_layers_do_not_hide_paper_space_geometry() {
|
||||
let (mut d, paper) = drawing();
|
||||
@@ -389,3 +430,22 @@ fn malformed_and_paper_space_viewports_are_not_snap_sources() {
|
||||
assert!(osnap(&d, &paper, Vec2::new(95.1, 50.1), 0.5, mode::END, None, false).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// Nearest on a curve that leaves the viewport: the curve's closest point to the cursor is outside
|
||||
/// the viewport, another point of it within the aperture is inside, and Nearest snaps there.
|
||||
#[test]
|
||||
fn nearest_takes_the_visible_part_of_a_curve_crossing_the_viewport_edge() {
|
||||
let (mut d, paper) = drawing();
|
||||
// The viewport shows model y up to 20. A tall ellipse peaks at (15, 20.1), just outside.
|
||||
let ellipse = Ellipse { center: Vec3::new(15.0, 0.0, 0.0), major: Vec3::new(0.0, 20.1, 0.0), ratio: 0.1, start: 0.0, end: std::f64::consts::TAU };
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Ellipse(ellipse)).unwrap();
|
||||
// The viewport's border is on a layer that is off, so it offers no Nearest of its own.
|
||||
d.layers.push(cadcraft_engine::doc::Layer { name: "Border".into(), on: false, ..Default::default() });
|
||||
let vp = viewport(&d, &paper);
|
||||
d.modify_entity(vp, |e| e.common.layer = "Border".into()).unwrap();
|
||||
// Model (15, 19.99): 0.11 from the peak, about 0.2 from where the ellipse comes back inside.
|
||||
let cursor = Vec2::new(102.5, 59.995);
|
||||
let hit = osnap(&d, &paper, cursor, 0.5, mode::NEA, None, false).expect("a visible nearest point");
|
||||
let model = hit.viewport.expect("seen through the viewport").point;
|
||||
assert!(model.y <= 20.0 + 1e-9 && model.dist(Vec2::new(15.0, 19.99)) <= 1.0, "{hit:?}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Running object snaps in a fresh drawing and in drawings opened from DXF and DWG files, with
|
||||
//! AutoCAD's default modes (OSMODE 4133: Endpoint, Center, Intersection, Extension).
|
||||
//!
|
||||
//! Moving onto a circle, an arc or a polyline arc finds its Center. OSMODE is a profile setting,
|
||||
//! as in AutoCAD (saved in the registry there, not the drawing): a file's `$OSMODE` header
|
||||
//! variable, 0 included, never changes the running snaps.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Drawing;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_engine::snap::{mode, tracking::CursorQuery};
|
||||
use serde_json::json;
|
||||
|
||||
/// AutoCAD's default running snaps.
|
||||
const DEFAULT: u32 = 4133;
|
||||
|
||||
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
|
||||
let a = deg.to_radians();
|
||||
c + Vec2::new(r * a.cos(), r * a.sin())
|
||||
}
|
||||
|
||||
/// A line crossed by another, a circle, an arc and a polyline with a straight and an arc segment.
|
||||
fn draw(s: &mut Session) {
|
||||
s.execute("line", &json!({ "points": [[0, 0], [20, 0]] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[5, -5], [5, 5]] })).unwrap();
|
||||
s.execute("circle", &json!({ "center": [50, 0], "radius": 5 })).unwrap();
|
||||
s.execute("arc", &json!({ "center": [80, 0], "radius": 5, "start": 0, "end": 180 })).unwrap();
|
||||
// 100,0 to 110,0 straight, then a half circle (bulge 1) to 130,0 round 120,0, below the axis.
|
||||
s.execute("pline", &json!({ "vertices": [[100, 0], {"p": [110, 0], "bulge": 1.0}, [130, 0]] })).unwrap();
|
||||
}
|
||||
|
||||
fn drawing() -> Drawing {
|
||||
let mut s = Session::new();
|
||||
draw(&mut s);
|
||||
s.doc().unwrap().clone()
|
||||
}
|
||||
|
||||
/// Where a click at `cursor` lands while LINE asks for its first point (the drawing area's path).
|
||||
fn snap(s: &mut Session, cursor: Vec2) -> Option<(Vec2, u32)> {
|
||||
if s.running.is_none() {
|
||||
s.start("line").unwrap();
|
||||
}
|
||||
let q = CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
|
||||
let r = s.snap_cursor(cursor, &q);
|
||||
r.snap.map(|h| (r.point, h.mode))
|
||||
}
|
||||
|
||||
fn assert_snaps(s: &mut Session, what: &str) {
|
||||
assert_eq!(s.settings.osmode, DEFAULT, "{what}: the running snaps are the profile's");
|
||||
let cases = [
|
||||
("the line's end", Vec2::new(20.2, 0.1), Vec2::new(20.0, 0.0), &[mode::END][..]),
|
||||
("the lines' crossing", Vec2::new(5.2, 0.15), Vec2::new(5.0, 0.0), &[mode::INT][..]),
|
||||
("the circle", polar(Vec2::new(50.0, 0.0), 5.3, 45.0), Vec2::new(50.0, 0.0), &[mode::CEN][..]),
|
||||
("the arc", polar(Vec2::new(80.0, 0.0), 5.2, 90.0), Vec2::new(80.0, 0.0), &[mode::CEN][..]),
|
||||
("the arc's end", Vec2::new(85.2, 0.1), Vec2::new(85.0, 0.0), &[mode::END][..]),
|
||||
("the polyline's vertex", Vec2::new(110.2, 0.1), Vec2::new(110.0, 0.0), &[mode::END][..]),
|
||||
("the polyline's arc", polar(Vec2::new(120.0, 0.0), 10.2, 270.0), Vec2::new(120.0, 0.0), &[mode::CEN][..]),
|
||||
];
|
||||
for (name, cursor, want, modes) in cases {
|
||||
let (p, m) = snap(s, cursor).unwrap_or_else(|| panic!("{what}: no snap on {name}"));
|
||||
assert!(modes.contains(&m), "{what}, {name}: mode {m}");
|
||||
assert!(p.near(want, 1e-6), "{what}, {name}: {p:?}");
|
||||
}
|
||||
// Away from everything: nothing.
|
||||
assert_eq!(snap(s, Vec2::new(35.0, 20.0)), None, "{what}");
|
||||
// F3 off: nothing; on again: back.
|
||||
s.execute("osnap", &json!({})).unwrap();
|
||||
assert_eq!(snap(s, Vec2::new(20.2, 0.1)), None, "{what}: F3 off");
|
||||
s.execute("osnap", &json!({})).unwrap();
|
||||
assert_eq!(snap(s, Vec2::new(20.2, 0.1)).map(|h| h.1), Some(mode::END), "{what}: F3 on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_snaps_work_in_a_fresh_drawing() {
|
||||
let mut s = Session::new();
|
||||
draw(&mut s);
|
||||
assert_snaps(&mut s, "fresh drawing");
|
||||
}
|
||||
|
||||
/// `text` with `$OSMODE` set to `value` at the top of its header.
|
||||
fn with_osmode(text: &str, value: u32) -> String {
|
||||
let at = text.find("HEADER").expect("a header section") + "HEADER".len();
|
||||
let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
|
||||
let (head, tail) = text.split_at(at);
|
||||
format!("{head}{eol} 9{eol}$OSMODE{eol} 70{eol}{value}{tail}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dxf_with_osmode_0_keeps_the_running_snaps() {
|
||||
let text = String::from_utf8(cadcraft_io::write(&drawing(), "snaps.dxf").unwrap()).unwrap();
|
||||
let text = with_osmode(&text, 0);
|
||||
let d = cadcraft_io::read(text.as_bytes(), "snaps.dxf").unwrap();
|
||||
let mut s = Session::new();
|
||||
// OSMODE is the profile's: the user's own choice survives opening the file.
|
||||
s.execute("setvar", &json!({ "name": "OSMODE", "value": DEFAULT })).unwrap();
|
||||
s.open_drawing(d, "snaps.dxf", None);
|
||||
assert_snaps(&mut s, "DXF with $OSMODE 0");
|
||||
// Nor does a file change a profile without Center.
|
||||
let mut s = Session::new();
|
||||
s.execute("setvar", &json!({ "name": "OSMODE", "value": mode::END })).unwrap();
|
||||
s.open_drawing(cadcraft_io::read(with_osmode(&text, DEFAULT).as_bytes(), "x.dxf").unwrap(), "x.dxf", None);
|
||||
assert_eq!(s.settings.osmode, mode::END);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_snaps_work_in_a_drawing_opened_from_dwg() {
|
||||
// The drawing is the test's own, so it is converted in this process.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let bytes = cadcraft_io::write(&drawing(), "snaps.dwg").unwrap();
|
||||
let d = cadcraft_io::read(&bytes, "snaps.dwg").unwrap();
|
||||
let mut s = Session::new();
|
||||
s.open_drawing(d, "snaps.dwg", None);
|
||||
assert_snaps(&mut s, "DWG");
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Center snaps from the curve, as in AutoCAD: with the cursor over a circle, an arc, an
|
||||
//! ellipse or a polyline arc (also inside a block reference) the running Center snap finds its
|
||||
//! center, however far away it is. Before, the center was only found with the cursor on the
|
||||
//! center itself, so moving onto a circle with the default running snaps (END, CEN, INT, EXT)
|
||||
//! showed nothing.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Common, EntityKind, Insert, Space};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::pointmod::snap_candidates;
|
||||
use cadcraft_engine::snap::{self, mode};
|
||||
use serde_json::json;
|
||||
|
||||
/// AutoCAD's default running snaps (OSMODE 4133).
|
||||
const DEFAULT: u32 = 4133;
|
||||
|
||||
fn snap_at(s: &Session, cursor: Vec2, aperture: f64, osmode: u32) -> Option<(Vec2, u32)> {
|
||||
snap::osnap(s.doc().unwrap(), &Space::Model, cursor, aperture, osmode, None, false).map(|h| (h.point, h.mode))
|
||||
}
|
||||
|
||||
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
|
||||
let a = deg.to_radians();
|
||||
c + Vec2::new(r * a.cos(), r * a.sin())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_on_a_circle_snaps_to_its_center() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [100, 50], "radius": 20 })).unwrap();
|
||||
let c = Vec2::new(100.0, 50.0);
|
||||
for deg in [10.0, 45.0, 130.0, 250.0, 300.0] {
|
||||
// A hair off the circle, well inside the aperture; the center is 20 units away.
|
||||
let cursor = polar(c, 20.3, deg);
|
||||
let (p, m) = snap_at(&s, cursor, 1.0, DEFAULT).unwrap_or_else(|| panic!("no snap on the circle at {deg}°"));
|
||||
assert_eq!(m, mode::CEN, "at {deg}°");
|
||||
assert!(p.near(c, 1e-9), "at {deg}°: {p:?}");
|
||||
}
|
||||
// Away from the circle (outside the aperture) there is nothing.
|
||||
assert_eq!(snap_at(&s, polar(c, 23.0, 45.0), 1.0, DEFAULT), None);
|
||||
// Center off: no center.
|
||||
assert_eq!(snap_at(&s, polar(c, 20.3, 45.0), 1.0, mode::END), None);
|
||||
// On the center itself, as before.
|
||||
assert_eq!(snap_at(&s, c + Vec2::new(0.2, 0.1), 1.0, DEFAULT).map(|h| h.1), Some(mode::CEN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arcs_ellipses_and_polyline_arcs_snap_to_their_centers() {
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap();
|
||||
s.execute("ellipse", &json!({ "center": [50, 0], "major": [8, 0], "ratio": 0.5 })).unwrap();
|
||||
// A polyline with a half-circle bulge from (100,0) to (120,0): center (110,0), radius 10.
|
||||
s.execute("pline", &json!({ "vertices": [{"p": [100, 0], "bulge": 1.0}, [120, 0]] })).unwrap();
|
||||
let arc = snap_at(&s, polar(Vec2::ZERO, 10.2, 45.0), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(arc.1, mode::CEN);
|
||||
assert!(arc.0.near(Vec2::ZERO, 1e-9));
|
||||
// The arc runs 0°-90°: on its circle at 200° (not on the arc) there is no center.
|
||||
assert_eq!(snap_at(&s, polar(Vec2::ZERO, 10.2, 200.0), 1.0, DEFAULT), None);
|
||||
let el = snap_at(&s, Vec2::new(50.0, 4.2), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(el.1, mode::CEN);
|
||||
assert!(el.0.near(Vec2::new(50.0, 0.0), 1e-9));
|
||||
let pl = snap_at(&s, polar(Vec2::new(110.0, 0.0), 10.2, 270.0), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(pl.1, mode::CEN, "the bulge's arc");
|
||||
assert!(pl.0.near(Vec2::new(110.0, 0.0), 1e-9), "{:?}", pl.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nearer_endpoint_or_intersection_still_wins() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[10, 0], [30, 0]] })).unwrap();
|
||||
// At the line's end on the circle: Endpoint/Intersection, not the far center.
|
||||
let (p, m) = snap_at(&s, Vec2::new(10.2, 0.1), 1.0, DEFAULT).unwrap();
|
||||
assert!(m == mode::END || m == mode::INT, "{m}");
|
||||
assert!(p.near(Vec2::new(10.0, 0.0), 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_inside_block_references_snap_to_their_centers() {
|
||||
let mut s = Session::new();
|
||||
let c = s.execute("circle", &json!({ "center": [5, 0], "radius": 2 })).unwrap()["handle"].as_str().unwrap().to_string();
|
||||
s.execute("block", &json!({ "name": "H", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap();
|
||||
let kind = EntityKind::Insert(Insert {
|
||||
block: "H".into(),
|
||||
insert: Vec3::new(100.0, 100.0, 0.0),
|
||||
scale: Vec3::new(3.0, 3.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
});
|
||||
s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap();
|
||||
// The circle lands at (115,100) with radius 6.
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(115.0, 100.0), 6.2, 60.0), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(115.0, 100.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_cycling_offers_the_center_from_the_curve() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
|
||||
let all = snap_candidates(s.doc().unwrap(), &Space::Model, polar(Vec2::ZERO, 10.2, 30.0), 1.0, DEFAULT, None, false);
|
||||
assert_eq!(all.iter().filter(|h| h.mode == mode::CEN && h.point.near(Vec2::ZERO, 1e-9)).count(), 1, "{all:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cursor_query_snaps_to_the_center_from_the_curve() {
|
||||
// The path the drawing area uses (Session::snap_cursor): the point a click would take.
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 50 })).unwrap();
|
||||
s.start("line").unwrap();
|
||||
let q = snap::tracking::CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
|
||||
let r = s.snap_cursor(polar(Vec2::ZERO, 50.4, 33.0), &q);
|
||||
assert_eq!(r.snap.map(|h| h.mode), Some(mode::CEN));
|
||||
assert!(r.point.near(Vec2::ZERO, 1e-9), "{:?}", r.point);
|
||||
}
|
||||
|
||||
/// The arc of the review of #2347 (and #1114's test): center (100,50), radius 80, 30°-150°.
|
||||
fn review_arc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &json!({ "center": [100, 50], "radius": 80, "start": 30, "end": 150 })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_midpoint_under_the_cursor_beats_the_center_from_the_curve() {
|
||||
let s = review_arc();
|
||||
// On the arc's midpoint (100,130) with Center and Midpoint running: Midpoint, as in AutoCAD.
|
||||
for cursor in [Vec2::new(100.05, 130.0), Vec2::new(100.2, 130.1)] {
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
|
||||
}
|
||||
// Elsewhere on the arc, with no snap point in the aperture, the center from the curve.
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(100.0, 50.0), 80.1, 70.0), 0.5, mode::CEN | mode::MID).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(100.0, 50.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quadrant_under_the_cursor_beats_the_center_from_the_curve() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [20, 0], "radius": 2 })).unwrap();
|
||||
let cursor = Vec2::new(20.1, 2.0);
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
|
||||
// Away from the quadrants the center from the curve.
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(20.0, 0.0), 2.1, 45.0), 0.5, mode::CEN | mode::QUA).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(20.0, 0.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_straight_segments_do_not_hide_a_circle_from_center() {
|
||||
// A polyline of 2,500 straight segments zigzagging over the cursor, then a circle: the
|
||||
// work limit counts circles and arcs only, so the circle's center is still found.
|
||||
let mut s = Session::new();
|
||||
let vertices: Vec<[f64; 2]> = (0..=2500).map(|i| [i as f64 * 0.04, if i % 2 == 0 { 0.0 } else { 100.0 }]).collect();
|
||||
s.execute("pline", &json!({ "vertices": vertices })).unwrap();
|
||||
s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap();
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(50.0, 50.0), 20.2, 100.0), 0.5, mode::CEN).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(50.0, 50.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_viewport_center_keeps_its_curve_distance_against_paper_space() {
|
||||
use cadcraft_engine::doc::{Circle, Drawing, Viewport};
|
||||
let mut d = Drawing::new_imperial();
|
||||
let paper = Space::Paper("Layout1".into());
|
||||
// Model circle (10,0) r16 seen through a viewport at half scale: paper center (100,50), radius 8.
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(10.0, 0.0, 0.0), radius: 16.0 })).unwrap();
|
||||
let vp = Viewport {
|
||||
center: Vec3::new(100.0, 50.0, 0.0),
|
||||
width: 20.0,
|
||||
height: 20.0,
|
||||
view_center: Vec2::new(10.0, 0.0),
|
||||
view_height: 40.0,
|
||||
id: 2,
|
||||
locked: false,
|
||||
frozen_layers: Vec::new(),
|
||||
layer_colors: Vec::new(),
|
||||
clip: None,
|
||||
on: true,
|
||||
twist: 0.0,
|
||||
};
|
||||
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||||
// A small paper-space circle whose curve passes 0.3 from the cursor and whose center is
|
||||
// nearer the cursor (3.3) than the model circle's (8).
|
||||
d.add(&paper, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(108.0, 53.3, 0.0), radius: 3.0 })).unwrap();
|
||||
// The cursor is on the model circle (0.1 off in paper units): its center wins.
|
||||
let h = snap::osnap(&d, &paper, Vec2::new(108.1, 50.0), 0.5, mode::CEN, None, false).unwrap();
|
||||
assert_eq!(h.mode, mode::CEN);
|
||||
assert!(h.point.near(Vec2::new(100.0, 50.0), 1e-9), "{h:?}");
|
||||
assert!(h.viewport.is_some());
|
||||
// On the paper circle, away from the model one: its center.
|
||||
let h = snap::osnap(&d, &paper, Vec2::new(108.0, 56.35), 0.5, mode::CEN, None, false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(108.0, 53.3), 1e-9), "{h:?}");
|
||||
assert!(h.viewport.is_none());
|
||||
}
|
||||
@@ -70,6 +70,9 @@ fn elliptical_arc_perpendicular_and_tangent_from_a_base_point() {
|
||||
let (q, m) = along_quarter(&s, mode::TAN, Some(base)).expect("a tangent point on the arc");
|
||||
assert_eq!(m, mode::TAN);
|
||||
assert!(on_quarter(q) && Vec2::new(q.x / 16.0, q.y / 4.0).dot(q - base).abs() < 1e-9, "{q:?}");
|
||||
// The same tangent at a prompt that resolves deferred snaps (CIRCLE's 3P points, #1512).
|
||||
let h = snap::osnap(s.doc().unwrap(), &Space::Model, q, 0.3, mode::TAN, Some(base), true).expect("tangent at a deferred prompt");
|
||||
assert!(h.mode == mode::TAN && h.deferred.is_none() && h.point.near(q, 1e-9), "{h:?}");
|
||||
// Perpendicular from (10,10): the line from the base runs along the normal.
|
||||
let base = Vec2::new(10.0, 10.0);
|
||||
let (q, m) = along_quarter(&s, mode::PER, Some(base)).expect("a perpendicular foot on the arc");
|
||||
|
||||
@@ -21,6 +21,17 @@ fn last_line(s: &Session) -> (Vec2, Vec2) {
|
||||
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).last().unwrap()
|
||||
}
|
||||
|
||||
/// The last circle drawn as (center, radius).
|
||||
fn last_circle(s: &Session) -> (Vec2, f64) {
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some((c.center.xy(), c.radius)) } else { None })
|
||||
.last()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn near(p: Vec2, x: f64, y: f64) -> bool {
|
||||
p.near(Vec2::new(x, y), 1e-9)
|
||||
}
|
||||
@@ -80,6 +91,23 @@ fn nothing_to_snap_to_rejects_the_point() {
|
||||
assert!(near(s.last_point, 10.0, 10.0));
|
||||
}
|
||||
|
||||
/// #2800: a typed PER or TAN finds its point from a pick anywhere on the object, as in AutoCAD.
|
||||
/// The pick used to have to land within the aperture (0.125 here) of the foot or tangent point,
|
||||
/// which you can't know in advance; elsewhere it said "No Perpendicular found".
|
||||
#[test]
|
||||
fn typed_per_and_tan_snap_from_anywhere_on_the_object() {
|
||||
let mut s = drawing();
|
||||
// From (5,5), PER picked at (3,0) on the line 0,0–10,0: two units from the foot (5,0).
|
||||
s.script("LINE 5,5 PER 3,0\n\n").unwrap();
|
||||
let (a, b) = last_line(&s);
|
||||
assert!(near(a, 5.0, 5.0) && near(b, 5.0, 0.0), "{a:?} {b:?}");
|
||||
// From (30,20), TAN picked at the top of the circle (centre 20,20, radius 3): the tangent
|
||||
// points are at cos = 3/10 from the line to the base, and the upper one is nearer the pick.
|
||||
s.script("LINE 30,20 TAN 20,23\n\n").unwrap();
|
||||
let (a, b) = last_line(&s);
|
||||
assert!(near(a, 30.0, 20.0) && near(b, 20.9, 20.0 + 3.0 * 0.91f64.sqrt()), "{a:?} {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_nests_with_a_snap_override() {
|
||||
let mut s = drawing();
|
||||
@@ -116,3 +144,86 @@ fn a_command_keyword_wins_over_a_snap_word() {
|
||||
s.cmdline("arc _cen").unwrap();
|
||||
assert!(s.prompt_text().ends_with("Center of:"), "{}", s.prompt_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_circle_radius_touches_the_picked_circle() {
|
||||
// #1512: the circle around the center that touches the circle at 20,20 radius 3, on the side
|
||||
// it was picked: the near side (radius 7), the far side (13), and through Diameter.
|
||||
for (script, center, r) in [
|
||||
("CIRCLE 30,20 TAN 23.02,20.03\n", (30.0, 20.0), 7.0),
|
||||
("CIRCLE 30,20 TAN 16.98,19.97\n", (30.0, 20.0), 13.0),
|
||||
("CIRCLE 20,10 D TAN 20.03,17.02\n", (20.0, 10.0), 7.0),
|
||||
] {
|
||||
let mut s = drawing();
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
let (c, got) = last_circle(&s);
|
||||
assert!(near(c, center.0, center.1) && (got - r).abs() < 1e-9, "{script}: {c:?} r={got}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_touches_the_picked_circles() {
|
||||
// #1512: through two points and tangent to the circle at 20,20 radius 3, the tangent pick
|
||||
// first or last.
|
||||
for script in ["CIRCLE 3P 26,20 26,26 TAN 23.02,20.03\n", "CIRCLE 3P TAN 23.02,20.03 26,20 26,26\n"] {
|
||||
let mut s = drawing();
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
let (c, r) = last_circle(&s);
|
||||
assert!((c.dist(Vec2::new(26.0, 20.0)) - r).abs() < 1e-9 && (c.dist(Vec2::new(26.0, 26.0)) - r).abs() < 1e-9, "{script}");
|
||||
assert!((c.dist(Vec2::new(20.0, 20.0)) - (3.0 + r)).abs() < 1e-9, "{script}: {c:?} r={r}");
|
||||
}
|
||||
// Tan, Tan, Tan: the circle between three circles of radius 1, picked on their inner sides.
|
||||
let mut s = Session::new();
|
||||
s.script("CIRCLE 0,0 1\nCIRCLE 6,0 1\nCIRCLE 3,5 1\nCIRCLE 3P TAN 0.98,0.2 TAN 5.02,0.2 TAN 3.01,3.98\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (c, r) = last_circle(&s);
|
||||
for k in [(0.0, 0.0), (6.0, 0.0), (3.0, 5.0)] {
|
||||
assert!((c.dist(Vec2::new(k.0, k.1)) - (1.0 + r)).abs() < 1e-9, "{c:?} r={r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_touches_an_arc_within_its_sweep() {
|
||||
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
|
||||
// on the right or the far left, both off an arc swept from 90° to 100°: no circle.
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 90, "end": 100})).unwrap();
|
||||
s.script("CIRCLE 3P 26,20 26,26 TAN 19.74,22.99\n").unwrap();
|
||||
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
|
||||
assert!(!s.doc().unwrap().model.iter().any(|e| matches!(e.kind, EntityKind::Circle(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_takes_the_solution_that_touches_the_arc() {
|
||||
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
|
||||
// at about 29.6° and -103.3°. Picked at 20° on an arc swept from 200° to 25°, the 29.6°
|
||||
// circle is nearer the pick but off the arc: the -103.3° one (radius 6.0826) is drawn.
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 200, "end": 25})).unwrap();
|
||||
s.script("CIRCLE 3P 26,20 26,26 TAN 22.82,21.03\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (c, r) = last_circle(&s);
|
||||
assert!((c.dist(Vec2::new(20.0, 20.0)) - (r - 3.0)).abs() < 1e-9 && (r - 6.082575694955838).abs() < 1e-9, "{c:?} r={r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_circle_radius_refuses_the_picked_circles_own_center() {
|
||||
// #1512: a circle around 20,20 would lie on the circle there, not touch it.
|
||||
let mut s = drawing();
|
||||
s.script("CIRCLE 20,20 TAN 23.02,20.03\n").unwrap();
|
||||
assert!(s.prompt_text().contains("radius of circle"), "{}", s.prompt_text());
|
||||
assert!(s.log.iter().any(|l| l.contains("No circle around the center is tangent there.")), "{:?}", s.log);
|
||||
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_refuses_the_picked_circle_itself() {
|
||||
// #1512: tangent twice to the circle and through a point on it is only the circle itself.
|
||||
let mut s = drawing();
|
||||
s.script("CIRCLE 3P TAN 23.02,20.03 TAN 16.98,20.03 20,23\n").unwrap();
|
||||
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
|
||||
assert!(s.log.iter().any(|l| l.contains("Circle does not exist.")), "{:?}", s.log);
|
||||
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
//! Tab cycling through object snaps: a crowd of candidates is capped, hostile cursors and
|
||||
//! apertures give no candidates, and the list never repeats a snap.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Space;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_engine::pointmod::snap_candidates;
|
||||
use cadcraft_engine::snap::mode;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn a_crowd_of_snaps_is_capped_and_never_repeats() {
|
||||
let mut s = Session::new();
|
||||
// 600 short lines fanning out from points packed round the origin: 1,200 endpoints.
|
||||
for i in 0..600 {
|
||||
let a = f64::from(i) * 0.01;
|
||||
let p = [1e-3 * a.cos(), 1e-3 * a.sin()];
|
||||
s.execute("line", &json!({ "points": [p, [a.cos(), a.sin()]] })).unwrap();
|
||||
}
|
||||
let d = s.doc().unwrap();
|
||||
let cands = snap_candidates(d, &Space::Model, Vec2::ZERO, 0.5, mode::END | mode::INT | mode::NEA, None, false);
|
||||
assert!(!cands.is_empty());
|
||||
assert!(cands.len() <= 257, "{} candidates", cands.len());
|
||||
for (i, a) in cands.iter().enumerate() {
|
||||
assert!(a.point.is_finite());
|
||||
assert!(!cands.iter().skip(i + 1).any(|b| b.mode == a.mode && b.point == a.point), "{a:?} repeats");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_cursor_and_aperture_give_no_candidates() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let space = Space::Model;
|
||||
let all = mode::END | mode::MID | mode::INT | mode::NEA | mode::PER;
|
||||
for (c, ap) in [
|
||||
(Vec2::new(f64::NAN, 0.0), 0.5),
|
||||
(Vec2::new(0.0, f64::INFINITY), 0.5),
|
||||
(Vec2::ZERO, f64::NAN),
|
||||
(Vec2::ZERO, 0.0),
|
||||
(Vec2::ZERO, -1.0),
|
||||
(Vec2::ZERO, f64::INFINITY),
|
||||
] {
|
||||
assert!(snap_candidates(d, &space, c, ap, all, None, false).is_empty(), "{c:?} {ap}");
|
||||
assert!(snap_candidates(d, &space, c, ap, all, Some(Vec2::new(f64::NAN, 1.0)), true).is_empty(), "{c:?} {ap}");
|
||||
}
|
||||
// A huge but finite aperture still answers, from the objects there are.
|
||||
let far = snap_candidates(d, &space, Vec2::ZERO, 1e300, mode::END, None, false);
|
||||
assert!(far.iter().all(|h| h.point.is_finite()));
|
||||
// Object snaps off (or only the OFF bit) offer nothing.
|
||||
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, 0, None, false).is_empty());
|
||||
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, mode::END | mode::OFF, None, false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_endpoint_under_the_aperture_is_offered_not_one_per_mode() {
|
||||
let mut s = Session::new();
|
||||
// Three line ends close together, all within the aperture of the cursor between them.
|
||||
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
|
||||
s.execute("line", &json!({ "points": [a, b] })).unwrap();
|
||||
}
|
||||
let d = s.doc().unwrap();
|
||||
let cands = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false);
|
||||
let ends: Vec<Vec2> = cands.iter().filter(|h| h.mode == mode::END).map(|h| h.point).collect();
|
||||
assert_eq!(ends.len(), 3, "{cands:?}");
|
||||
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
|
||||
assert!(ends.iter().any(|p| p.near(want, 1e-12)), "{want:?} in {ends:?}");
|
||||
}
|
||||
// The first is the snap a click would take.
|
||||
let first = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).first().map(|h| h.point);
|
||||
assert_eq!(first, cadcraft_engine::snap::osnap(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).map(|h| h.point));
|
||||
}
|
||||
|
||||
/// A base point that is not a number gives no candidates, though the cursor is on an endpoint: the
|
||||
/// perpendicular and tangent points from it would be meaningless, as a viewport already treats it.
|
||||
#[test]
|
||||
fn a_non_finite_base_gives_no_candidates() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let all = mode::END | mode::PER | mode::TAN | mode::NEA;
|
||||
for base in [Vec2::new(f64::NAN, 1.0), Vec2::new(1.0, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NAN)] {
|
||||
assert!(snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), false).is_empty(), "{base:?}");
|
||||
assert!(cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), true).is_empty(), "{base:?}");
|
||||
}
|
||||
// A finite base still offers them.
|
||||
assert!(!snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(Vec2::new(5.0, 5.0)), false).is_empty());
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! What a DXF before 2007 leaves out for its proxies' string streams, counted by the real DXF
|
||||
//! writer (#3229): only what 2007 would keep, from the drawing the command writes. In its own
|
||||
//! test binary because it installs the real io hooks for the whole process.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, SaveAs, set_io, set_proxies_lost, set_write_as};
|
||||
use cadcraft_engine::doc::Drawing;
|
||||
use serde_json::{Value, json};
|
||||
#[path = "support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
|
||||
/// The real reader and writer, and the real proxy-loss count.
|
||||
fn install() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
set_write_as(|d, name, o: &SaveAs| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
}
|
||||
|
||||
/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes.
|
||||
fn proxy(handle: &str, owner: &str, strings: &str, class: &str) -> Vec<(String, String)> {
|
||||
let p = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
vec![
|
||||
p("0", "ACAD_PROXY_ENTITY"),
|
||||
p("5", handle),
|
||||
p("330", owner),
|
||||
p("100", "AcDbEntity"),
|
||||
p("8", "0"),
|
||||
p("100", "AcDbProxyEntity"),
|
||||
p("90", "498"),
|
||||
p("91", class),
|
||||
p("95", "393245"),
|
||||
p("70", "0"),
|
||||
p("162", strings),
|
||||
p("161", "16"),
|
||||
p("310", "AABB"),
|
||||
]
|
||||
}
|
||||
|
||||
fn pairs(text: &str) -> Vec<(String, String)> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
lines.chunks(2).map(|c| (c[0].trim().to_string(), c.get(1).map_or(String::new(), |v| v.trim().to_string()))).collect()
|
||||
}
|
||||
|
||||
/// A drawing with `$ACADVER` `acadver` read from a DXF holding the class WIDGETX and, in model
|
||||
/// space, the proxies `entities` gives (each from the model space block record's handle).
|
||||
fn drawing(acadver: &str, entities: impl Fn(&str) -> Vec<Vec<(String, String)>>) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", "AC1024");
|
||||
let text = String::from_utf8(cadcraft_io::write(&d, "p.dxf").unwrap()).unwrap();
|
||||
let mut p = pairs(&text);
|
||||
let g = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
let classes = p.iter().position(|q| q.0 == "2" && q.1 == "CLASSES").unwrap() + 1;
|
||||
let class =
|
||||
[g("0", "CLASS"), g("1", "WIDGETX"), g("2", "AcDbWidgetX"), g("3", "ObjectDBX Classes"), g("90", "4095"), g("280", "0"), g("281", "1")];
|
||||
p.splice(classes..classes, class);
|
||||
// The model space block record: the owner of model space entities.
|
||||
let record_end = |i: usize| i + 1 + p[i + 1..].iter().position(|q| q.0 == "0").unwrap_or(p.len() - i - 1);
|
||||
let ms = (0..p.len())
|
||||
.filter(|&i| p[i].0 == "0" && p[i].1 == "BLOCK_RECORD")
|
||||
.find(|&i| p[i..record_end(i)].iter().any(|q| q.0 == "2" && q.1.eq_ignore_ascii_case("*Model_Space")))
|
||||
.unwrap();
|
||||
let owner = p[ms..].iter().find(|q| q.0 == "5").unwrap().1.clone();
|
||||
let ents = p.iter().position(|q| q.0 == "2" && q.1 == "ENTITIES").unwrap();
|
||||
let end = ents + p[ents..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap();
|
||||
p.splice(end..end, entities(&owner).into_iter().flatten());
|
||||
let bytes: String = p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect();
|
||||
let mut d = cadcraft_io::read(bytes.as_bytes(), "p.dxf").unwrap();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d
|
||||
}
|
||||
|
||||
/// Two proxies with string streams, one whose class number names no class (no version writes
|
||||
/// it), and one without: before 2007 only the first one is lost to the string stream.
|
||||
fn three_proxies(owner: &str) -> Vec<Vec<(String, String)>> {
|
||||
vec![proxy("AAA1", owner, "8", "500"), proxy("AAA2", owner, "8", "777"), proxy("AAA3", owner, "0", "500")]
|
||||
}
|
||||
|
||||
fn not_saved(r: &Value) -> Value {
|
||||
r.get("notSaved").cloned().unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_no_version_writes_is_not_reported() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let path = dir.path_str("out.dxf");
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "{:?}", s.log);
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2007 })).unwrap();
|
||||
assert_eq!(not_saved(&r), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_reports_the_drawing_it_writes() {
|
||||
// In the Block Editor EXPORT writes the block, which holds no proxy: nothing is lost.
|
||||
install();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }));
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
let line = s.execute("entities", &json!({ "type": "LINE" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string();
|
||||
s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [line], "keep": "convert" })).unwrap();
|
||||
s.execute("bedit", &json!({ "name": "B" })).unwrap();
|
||||
let n = s.log.len();
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(not_saved(&r), Value::Null, "{:?}", &s.log[n..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reference_edit_working_copy_is_not_counted_twice() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", |o| vec![proxy("AAA1", o, "8", "500")]), "proxy.dxf", None);
|
||||
s.execute("block", &json!({ "name": "W", "base": [0, 0], "handles": ["AAA1"], "keep": "convert" })).unwrap();
|
||||
let ins = s.execute("entities", &json!({ "type": "INSERT" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string();
|
||||
let path = dir.path_str("before.dxf");
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "in the block");
|
||||
s.execute("refedit", &json!({ "handle": ins })).unwrap();
|
||||
// Saves wait for REFCLOSE; the QSAVE question and `document.bytes` count the committed drawing.
|
||||
let r = s.execute("document.bytes", &json!({ "format": "dxf", "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "the working copy isn't written");
|
||||
assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&s, "during.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_wblock_of_the_whole_drawing_reports_a_pre_2007_dxf() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let path = dir.path_str("whole.dxf").replace('\\', "/");
|
||||
s.cmdline(&format!("(command \"_.-WBLOCK\" \"{path}\" \"\" \"*\")")).unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(std::path::Path::new(&path).exists());
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.ends_with("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Kept render settings are in the form of the file they were read from, whatever the drawing's
|
||||
//! `$ACADVER` says after a SAVEAS to another version: saving a 2018 drawing down to 2000 and back
|
||||
//! up to 2018 writes the class version the 2018 file had, not one higher (which BricsCAD refuses,
|
||||
//! #907).
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, set_io, set_write_as};
|
||||
use serde_json::json;
|
||||
|
||||
/// A 2018 DXF with one mental ray render settings object, stored as `90 2` (class version 1 in the
|
||||
/// 2013+ form).
|
||||
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n\
|
||||
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\
|
||||
0\nMENTALRAYRENDERSETTINGS\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n\
|
||||
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nENDSEC\n0\nEOF\n";
|
||||
|
||||
/// The `AcDbRenderSettings` class version in a written DXF.
|
||||
fn class_version(path: &std::path::Path) -> Option<i64> {
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
let l: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = l.windows(2).position(|w| w == ["0", "MENTALRAYRENDERSETTINGS"])?;
|
||||
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
|
||||
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saveas_down_and_back_up_keeps_the_render_settings_class_version() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
set_write_as(|d, name, o| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-render-settings-saveas-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "render.dxf", None);
|
||||
let save = |s: &mut Session, name: &str, version: &str| {
|
||||
let path = dir.join(name);
|
||||
s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": version })).unwrap();
|
||||
class_version(&path)
|
||||
};
|
||||
|
||||
assert_eq!(save(&mut s, "2018.dxf", "2018"), Some(2), "same version: as read");
|
||||
assert_eq!(save(&mut s, "2000.dxf", "2000"), Some(1), "the 2000 form is one lower");
|
||||
s.execute("qsave", &json!({})).unwrap();
|
||||
assert_eq!(class_version(&dir.join("2000.dxf")), Some(1), "QSAVE keeps the 2000 form");
|
||||
assert_eq!(save(&mut s, "back.dxf", "2018"), Some(2), "back to 2018: the 2018 file's value, not one higher");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -268,19 +268,27 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
|
||||
assert_eq!(r["notSaved"], json!({ "REGION": 1 }));
|
||||
}
|
||||
|
||||
/// A DWG before 2013 writes a solid's SAT text as it is, so a save there doesn't list a solid that
|
||||
/// holds it; from 2013 the geometry must be in the data store and SAT text alone is lost, so the
|
||||
/// save lists it. A solid with neither is always listed (#2334).
|
||||
/// A DWG before 2013 writes a solid's SAT text of ACIS 7.0 and later, so a save there doesn't list
|
||||
/// a solid that holds it; from 2013 the geometry must be in the data store and SAT text alone is
|
||||
/// lost, so the save lists it. Older SAT (ACIS 4.0) and a solid with neither are always listed
|
||||
/// (#2334).
|
||||
#[test]
|
||||
fn a_dwg_keeps_sat_text_solids_only_before_2013() {
|
||||
use cadcraft_engine::cmd::file::{Version, not_saved_as};
|
||||
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
|
||||
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags });
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 1 1 0")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "700 0 1 0")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 1)].into_iter().collect(), "2010 keeps the SAT-text solid");
|
||||
assert_eq!(not_saved_as(&d, Version::R2018), [("3DSOLID".to_string(), 2)].into_iter().collect(), "2018 loses it");
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 85 1 0")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2)].into_iter().collect(), "ACIS 4.0 SAT is listed");
|
||||
// The same versions encoded, as a DXF before 2013 holds them: 700 is kept, 400 is listed.
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "hoo o n o")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2)].into_iter().collect(), "encoded ACIS 7.0 SAT is kept");
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "koo gj n o")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 3)].into_iter().collect(), "encoded ACIS 4.0 SAT is listed");
|
||||
}
|
||||
|
||||
/// The DWG bridge writes OLE objects (`ole2frame_roundtrip` in the io tests), so saving one as
|
||||
@@ -302,3 +310,109 @@ fn ole_objects_are_not_reported() {
|
||||
assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1), ("ole2frame".to_string(), 1)].into_iter().collect(), "{v:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A solid whose geometry only the data store keeps (read from a 2013+ file) has nothing to write
|
||||
/// to a DXF of 2010 or earlier, which has no data store: the save leaves it out and says so, and
|
||||
/// the interactive save knows it beforehand; 2013 and later keep it (#2334).
|
||||
#[test]
|
||||
fn saving_data_store_solids_as_dxf_2010_reports_them() {
|
||||
use cadcraft_engine::cmd::file::loss_on_save;
|
||||
use cadcraft_engine::doc::foreign::Foreign;
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec()));
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", "AC1032");
|
||||
let h = d.add(&Space::Model, Common::default(), unknown("3DSOLID")).unwrap();
|
||||
let record = vec![
|
||||
RawTag { code: 0, value: "ACDSRECORD".into() },
|
||||
RawTag { code: 320, value: h.hex() },
|
||||
RawTag { code: 2, value: "ASM_Data".into() },
|
||||
RawTag { code: 310, value: "00".into() },
|
||||
];
|
||||
d.foreign = std::sync::Arc::new(Foreign { data_store: record, ..Foreign::default() });
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "solid.dxf", None);
|
||||
assert!(loss_on_save(&s, "solid.dxf").is_empty(), "2018 keeps it");
|
||||
|
||||
let path = std::env::temp_dir().join(format!("cadcraft-ds-note-{}.dxf", std::process::id()));
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2010 })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "3DSOLID": 1 }));
|
||||
assert!(s.log.iter().any(|l| l.contains("2010 and earlier have no data store") && l.contains("1 3DSOLID")), "{:?}", s.log);
|
||||
assert_eq!(loss_on_save(&s, "solid.dxf"), [("3DSOLID".to_string(), 1)].into_iter().collect(), "now a 2010 drawing");
|
||||
|
||||
let n = s.log.len();
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2018 })).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(r.get("notSaved").is_none() && s.log.len() == n);
|
||||
}
|
||||
|
||||
/// A proxy entity (as a 2010 file has it) whose string stream is `strings` long (group 162).
|
||||
fn proxy_entity(strings: &str) -> EntityKind {
|
||||
let tags = [(8, "0"), (100, "AcDbProxyEntity"), (90, "498"), (91, "500"), (162, strings), (161, "16"), (310, "AABB")];
|
||||
EntityKind::Unknown(Unknown {
|
||||
dxf_type: "ACAD_PROXY_ENTITY".into(),
|
||||
tags: tags.iter().map(|(code, value)| RawTag { code: *code, value: (*value).into() }).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A DXF before 2007 has no form for a proxy's separate string stream: the writer leaves such a
|
||||
/// proxy out, and the save says so instead of dropping it silently (#3229).
|
||||
#[test]
|
||||
fn a_dxf_before_2007_reports_the_proxies_it_leaves_out() {
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
// SAVEAS at a chosen version goes through this hook (each test may run in its own process).
|
||||
set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec()));
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "proxy.dxf", None);
|
||||
let path = std::env::temp_dir().join(format!("cadcraft-proxy-r2000-{}.dxf", std::process::id()));
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2000 })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings");
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2007 })).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(r.get("notSaved").is_none(), "2007 keeps it");
|
||||
}
|
||||
|
||||
/// The interactive QSAVE asks before a pre-2007 DXF replaces a file and leaves such proxies out,
|
||||
/// with the same list (#3229).
|
||||
#[test]
|
||||
fn a_pre_2007_dxf_proxy_loss_is_known_before_saving() {
|
||||
use cadcraft_engine::cmd::file::loss_on_save;
|
||||
let drawing = |acadver: &str| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d
|
||||
};
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015"), "proxy.dxf", None);
|
||||
assert_eq!(loss_on_save(&s, "proxy.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect());
|
||||
s.open_drawing(drawing("AC1021"), "proxy.dxf", None);
|
||||
assert!(loss_on_save(&s, "proxy.dxf").is_empty(), "2007 keeps it");
|
||||
}
|
||||
|
||||
/// EXPORT writes a DXF at the drawing's own version: before 2007 it leaves the same proxies out
|
||||
/// and says so, like a save (#3229).
|
||||
#[test]
|
||||
fn exporting_a_dxf_before_2007_reports_the_proxies_it_leaves_out() {
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
let drawing = |acadver: &str| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap();
|
||||
d
|
||||
};
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015"), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings");
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1021"), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert!(r.get("notSaved").is_none(), "2007 keeps it");
|
||||
}
|
||||
|
||||
@@ -477,6 +477,18 @@ mod tests {
|
||||
ttf::fallback_for('\u{0E01}').filter(|f| ['\u{0E14}', '\u{0E34}', '\u{0E4C}', '\u{0E33}', '\u{0E10}'].iter().all(|c| f.has_glyph(*c)))
|
||||
}
|
||||
|
||||
/// A Thai face's letters are measured in ems: ก has neither ascender nor descender, ไ rises
|
||||
/// above it, and a space or an unmapped character has no height.
|
||||
#[test]
|
||||
fn thai_glyph_heights_are_measured_in_ems() {
|
||||
let Some(face) = thai_face() else { return };
|
||||
let ko = face.glyph_height('ก').unwrap_or_default();
|
||||
assert!((0.2..1.0).contains(&ko), "ก is {ko} em");
|
||||
assert!(face.glyph_height('ไ').is_some_and(|h| h > ko), "ไ is taller than ก");
|
||||
assert_eq!(face.glyph_height(' '), None);
|
||||
assert_eq!(face.glyph_height('\u{10fffd}'), None);
|
||||
}
|
||||
|
||||
/// Lowest point of the glyph that shows `c`.
|
||||
fn bottom_of(sh: &Shaped, c: char) -> Option<f64> {
|
||||
let t = sh.text.iter().find(|t| t.ch == c)?;
|
||||
|
||||
@@ -95,6 +95,17 @@ impl Face {
|
||||
Some(s.chars().filter(|c| !c.is_control()).take(80).collect::<String>()).filter(|s| !s.trim().is_empty())
|
||||
})
|
||||
}
|
||||
/// How tall the glyph of `c` is, from its lowest to its highest point, in ems: `None` when the
|
||||
/// face doesn't map `c` or its glyph has no outline (a space, or one too big to keep).
|
||||
pub fn glyph_height(&self, c: char) -> Option<f64> {
|
||||
let g = glyph(self, c);
|
||||
if !g.mapped {
|
||||
return None;
|
||||
}
|
||||
let (low, high) = g.contours.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), p| (low.min(p.y), high.max(p.y)));
|
||||
let height = (high - low) / f64::from(UPEM);
|
||||
(height.is_finite() && height > 0.0).then_some(height)
|
||||
}
|
||||
|
||||
/// The glyph ids the face's character map gives `chars` (`None` for an unmapped one).
|
||||
pub(crate) fn glyph_ids(&self, chars: &[char]) -> Vec<Option<u32>> {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
//! The angles of a hatch's elliptic boundary edges in the DXF a DWG is read through.
|
||||
//!
|
||||
//! A DWG holds an elliptic edge's start and end angles in radians, and so does the DXF the DWG
|
||||
//! decoder writes (groups 50 and 51 of an edge of type 3). DXF itself keeps them in degrees, which
|
||||
//! is how [`crate::dxf_read`] reads them: a circle stored as an elliptic edge with the end angle
|
||||
//! 6.2832 became an arc of 6.28 degrees, and the hatch covered the hole it should have left open.
|
||||
//! Only the DWG path needs this; a DXF file is read as written.
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
/// `dxf` with the start and end angles (groups 50 and 51) of every elliptic hatch edge (edge type
|
||||
/// 3, group 72) turned from radians to degrees. The text is handled as bytes: a drawing from
|
||||
/// before 2007 is written in its code page, which is not UTF-8, and every other byte is kept as it
|
||||
/// was. Binary DXF, and text with no such edge, come back as they were.
|
||||
pub(crate) fn elliptic_edge_degrees(dxf: Vec<u8>) -> Vec<u8> {
|
||||
if dxf.starts_with(b"AutoCAD Binary DXF") || !dxf.windows(5).any(|w| w == b"HATCH") {
|
||||
return dxf;
|
||||
}
|
||||
let mut out = Vec::with_capacity(dxf.len());
|
||||
let mut lines = dxf.split_inclusive(|b| *b == b'\n');
|
||||
let mut in_hatch = false;
|
||||
// After an elliptic edge's type, until the next edge or loop: the angles still to convert.
|
||||
let mut ellipse = false;
|
||||
let mut changed = false;
|
||||
while let Some(code_line) = lines.next() {
|
||||
let Some(value_line) = lines.next() else {
|
||||
out.extend_from_slice(code_line);
|
||||
break;
|
||||
};
|
||||
let code = code_line.trim_ascii();
|
||||
let value = value_line.trim_ascii();
|
||||
match code {
|
||||
b"0" => {
|
||||
in_hatch = value == b"HATCH";
|
||||
ellipse = false;
|
||||
}
|
||||
b"72" if in_hatch => ellipse = value == b"3",
|
||||
b"92" | b"97" if in_hatch => ellipse = false,
|
||||
b"50" | b"51" if in_hatch && ellipse => {
|
||||
if let Some(radians) = std::str::from_utf8(value).ok().and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) {
|
||||
let ending = &value_line[value_line.trim_ascii_end().len()..];
|
||||
out.extend_from_slice(code_line);
|
||||
out.extend_from_slice(format!("{}", radians * 180.0 / PI).as_bytes());
|
||||
out.extend_from_slice(ending);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out.extend_from_slice(code_line);
|
||||
out.extend_from_slice(value_line);
|
||||
}
|
||||
if changed { out } else { dxf }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pairs(text: &str) -> Vec<(String, String)> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
|
||||
}
|
||||
|
||||
const HATCH: &str = "0\r\nHATCH\r\n91\r\n1\r\n92\r\n1\r\n93\r\n2\r\n72\r\n3\r\n10\r\n5.0\r\n20\r\n6.0\r\n11\r\n-55.5\r\n21\r\n0.0\r\n40\r\n1.0\r\n50\r\n0.0\r\n51\r\n6.283185307179586\r\n73\r\n1\r\n72\r\n1\r\n10\r\n1.0\r\n20\r\n2.0\r\n11\r\n3.0\r\n21\r\n4.0\r\n50\r\n7.0\r\n0\r\nLINE\r\n50\r\n9.0\r\n";
|
||||
|
||||
#[test]
|
||||
fn an_elliptic_edge_gets_its_angles_in_degrees_and_nothing_else_changes() {
|
||||
let out = String::from_utf8(elliptic_edge_degrees(HATCH.as_bytes().to_vec())).unwrap();
|
||||
let p = pairs(&out.replace("\r\n", "\n"));
|
||||
let value = |code: &str, n: usize| p.iter().filter(|(c, _)| c == code).nth(n).map(|(_, v)| v.parse::<f64>().unwrap());
|
||||
assert!((value("51", 0).unwrap() - 360.0).abs() < 1e-9);
|
||||
assert_eq!(value("50", 0), Some(0.0));
|
||||
// A line edge's 50 and another entity's are left alone, as is the line ending.
|
||||
assert_eq!(value("50", 1), Some(7.0));
|
||||
assert_eq!(value("50", 2), Some(9.0));
|
||||
assert!(out.contains("\r\n") && !out.replace("\r\n", "").contains('\r'));
|
||||
}
|
||||
|
||||
/// A drawing from before 2007 is written in its code page: an accented letter is one byte that
|
||||
/// is not valid UTF-8, and it must not stop the angles being converted or change.
|
||||
#[test]
|
||||
fn a_code_page_drawing_still_has_its_angles_converted() {
|
||||
let mut dxf = b"0\r\nTEXT\r\n1\r\ncaf".to_vec();
|
||||
dxf.push(0xE9);
|
||||
dxf.extend_from_slice(b"\r\n");
|
||||
dxf.extend_from_slice(HATCH.as_bytes());
|
||||
let out = elliptic_edge_degrees(dxf.clone());
|
||||
assert!(std::str::from_utf8(&dxf).is_err(), "the input is not UTF-8");
|
||||
assert!(out.windows(4).any(|w| w == b"caf\xE9"), "the accented byte is kept");
|
||||
let text: String = out.iter().map(|b| char::from(*b)).collect();
|
||||
assert!(text.contains("51\r\n360"), "the end angle is 360 degrees: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_without_a_hatch_ellipse_comes_back_untouched() {
|
||||
let dxf = b"0\nLINE\n50\n1.5\n".to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(dxf.clone()), dxf);
|
||||
let binary = b"AutoCAD Binary DXF\r\n\x1a\x00HATCH".to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(binary.clone()), binary);
|
||||
// A hatch with no elliptic edge is left as it is.
|
||||
let plain = "0\nHATCH\n72\n1\n50\n2.0\n".as_bytes().to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(plain.clone()), plain);
|
||||
}
|
||||
}
|
||||
+179
-13
@@ -16,9 +16,9 @@ use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number};
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
|
||||
use craft_dxf::{SectionRef, Tag};
|
||||
use craft_dxf::{SectionRef, Tag, Version};
|
||||
|
||||
/// Named object dictionary entries CADCraft writes itself from its model (plus every key that
|
||||
/// starts with `CADCRAFT`): they are read into the model, not kept raw. A change that starts
|
||||
@@ -457,6 +457,10 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
if !f.is_empty() {
|
||||
f.version = file_version(secs);
|
||||
}
|
||||
// Added after the version: registered applications alone are no kept objects whose groups
|
||||
// the DWG writer must read as the file's version, and nearly every file has some (ACAD).
|
||||
let appids = tables.iter().filter(|(k, _, _)| k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string());
|
||||
f.appids = appids.take(MAX_OBJECTS).collect();
|
||||
// The file's handles of the objects CADCraft writes itself (AutoLISP's `handent`).
|
||||
f.handles = ids.iter().filter(|(h, _)| !ents.contains_key(*h)).filter_map(|(h, k)| Some((handle(h)?, k.clone()))).take(MAX_OBJECTS).collect();
|
||||
if !f.is_empty() || !f.handles.is_empty() {
|
||||
@@ -686,6 +690,102 @@ pub(crate) fn data_store(tags: &mut Vec<Tag>, d: &Drawing, modern: bool) {
|
||||
tags.splice(at..at, out);
|
||||
}
|
||||
|
||||
/// Most constraint nodes, and connections per node, looked at in one constraint group.
|
||||
const MAX_CONSTRAINT_NODES: usize = 100_000;
|
||||
|
||||
/// Put the status of every node of the kept 2D constraint groups (`ACDBASSOC2DCONSTRAINTGROUP`)
|
||||
/// where a reader of the version the text is read as expects it: AutoCAD 2013 and later
|
||||
/// (`modern`) write it after the node's connections, earlier versions right after its id. The
|
||||
/// groups are kept as read, so a 2013+ drawing written in an older version's form had them in the
|
||||
/// wrong order, and its reader took every node's status from somewhere else: AutoCAD refused the
|
||||
/// DWG the bridge made from it ("Error Decrypting Data"). A group whose nodes can't all be found
|
||||
/// is left as it is.
|
||||
pub(crate) fn constraint_node_order(tags: &mut [Tag], modern: bool) {
|
||||
let mut i = 0;
|
||||
while i < tags.len() {
|
||||
let end = tags.iter().skip(i + 1).position(|t| t.code == 0).map_or(tags.len(), |k| i + 1 + k);
|
||||
if tags.get(i).is_some_and(|t| t.code == 0 && t.str().trim().eq_ignore_ascii_case("ACDBASSOC2DCONSTRAINTGROUP"))
|
||||
&& let Some(rec) = tags.get_mut(i + 1..end)
|
||||
{
|
||||
constraint_group_order(rec, modern);
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
}
|
||||
|
||||
/// [`constraint_node_order`] for one group's groups after its type.
|
||||
fn constraint_group_order(rec: &mut [Tag], modern: bool) {
|
||||
let Some(start) = rec.iter().position(|t| t.code == 100 && t.str().trim().eq_ignore_ascii_case("AcDbAssoc2dConstraintGroup")) else {
|
||||
return;
|
||||
};
|
||||
let end = rec.iter().skip(start + 1).position(|t| t.code == 100 || t.code >= 1000).map_or(rec.len(), |k| start + 1 + k);
|
||||
let Some(sec) = rec.get_mut(start + 1..end) else { return };
|
||||
let Some(nodes) = constraint_nodes(sec) else { return };
|
||||
for (at, len, old) in nodes {
|
||||
// Old order: id, status, count, connections; modern: id, count, connections, status.
|
||||
if let Some(head) = sec.get_mut(at + 1..at + len) {
|
||||
match (old, modern) {
|
||||
(true, true) => head.rotate_left(1),
|
||||
(false, false) => head.rotate_right(1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where each non-root node of a constraint group section starts: (index of its id, length of its
|
||||
/// id, status and connections, whether its status comes right after the id). `None` unless every
|
||||
/// node the group lists is found.
|
||||
fn constraint_nodes(sec: &[Tag]) -> Option<Vec<(usize, usize, bool)>> {
|
||||
let int = |p: usize, code: i32| sec.get(p).filter(|t| t.code == code).and_then(|t| t.str().trim().parse::<i64>().ok());
|
||||
let count = |p: usize| int(p, 90).and_then(|n| usize::try_from(n).ok()).filter(|n| *n <= MAX_CONSTRAINT_NODES);
|
||||
// Version, flag and work plane, then the dependency and the actions.
|
||||
let mut p = sec.iter().position(|t| t.code == 360)? + 1;
|
||||
p += count(p)? + 1;
|
||||
// The next node id, then the root node: id, connections, status (290).
|
||||
int(p, 90)?;
|
||||
int(p + 1, 90)?;
|
||||
p += count(p + 2)? + 3;
|
||||
int(p, 290)?;
|
||||
p += 1;
|
||||
// The registry: class name and id of each node.
|
||||
let n = count(p)?;
|
||||
p += 1;
|
||||
let mut ids = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
sec.get(p).filter(|t| t.code == 1)?;
|
||||
ids.push(int(p + 1, 90)?);
|
||||
p += 2;
|
||||
}
|
||||
let known: HashSet<i64> = ids.iter().copied().collect();
|
||||
// Groups looked at while searching for headers, capped so a hostile group can't take long.
|
||||
let budget = std::cell::Cell::new(MAX_CONSTRAINT_NODES.saturating_mul(100));
|
||||
// A node header at `q`: its length and whether it is in the old order. Connections are ids of
|
||||
// nodes (or of the root, 0), which keeps a node's data from passing for the next header.
|
||||
let header = |q: usize, id: i64| -> Option<(usize, bool)> {
|
||||
int(q, 90).filter(|v| *v == id)?;
|
||||
let old = sec.get(q + 1)?.code == 70;
|
||||
let c = q + 1 + usize::from(old);
|
||||
let n = count(c).filter(|n| *n <= known.len())?;
|
||||
budget.set(budget.get().checked_sub(n + 1)?);
|
||||
for k in 0..n {
|
||||
int(c + 1 + k, 90).filter(|v| *v == 0 || known.contains(v))?;
|
||||
}
|
||||
if !old {
|
||||
int(c + 1 + n, 70)?;
|
||||
}
|
||||
Some((n + 3, old))
|
||||
};
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
let at = (p..sec.len()).find(|q| header(*q, id).is_some())?;
|
||||
let (len, old) = header(at, id)?;
|
||||
out.push((at, len, old));
|
||||
p = at + len;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Drop a dictionary's modelled entries (key and handle) from its groups.
|
||||
fn strip_entries(tags: &mut Vec<RawTag>) {
|
||||
let mut out = Vec::with_capacity(tags.len());
|
||||
@@ -941,13 +1041,61 @@ fn unknown_handles(d: &Drawing) -> HashSet<String> {
|
||||
all_entities(d).filter(|e| matches!(e.kind, EntityKind::Unknown(_))).map(|e| e.handle.hex()).collect()
|
||||
}
|
||||
|
||||
/// Render settings (`RENDERSETTINGS`, `MENTALRAYRENDERSETTINGS`, `RAPIDRTRENDERSETTINGS`) store
|
||||
/// their `AcDbRenderSettings` class version (the first group 90 after that marker) in the form of
|
||||
/// the file's version: a 2013+ file stores it one higher, and a 2013 file stores a rapid RT one
|
||||
/// one lower, as acadrust reads and writes them (`write_render_settings_dxf` in acadrust 0.6.6's
|
||||
/// `io/dxf/writer/section_writer.rs`, and its DWG class-object reader and writer; the test
|
||||
/// `render_settings_class_version_matches_what_acadrust_writes` fails if the two drift apart). A
|
||||
/// kept object carries the form of the file it was read from ([`Foreign::version`], not the
|
||||
/// drawing's `$ACADVER`, which SAVEAS changes); written into a file read as another version, it
|
||||
/// takes that version's form. The DWG bridge's R2000 text is read as the version the kept objects
|
||||
/// came from (craft-dwg's `encode_kept_noted`), so there they stay as read (#907, #2471).
|
||||
///
|
||||
/// Only that first group 90 is converted, on purpose: the group 90 that starts a kind's own
|
||||
/// subclass (`AcDbMentalRayRenderSettings`, `AcDbRapidRTRenderSettings`) is that kind's version,
|
||||
/// stored the same in every file version, and is left as read.
|
||||
pub(crate) fn render_settings_versions(tags: &mut [Tag], source: Option<Version>, declared: Version) {
|
||||
let Some(source) = source.filter(|s| *s != declared) else { return };
|
||||
let shift = |rapid: bool, v: Version| if rapid { -i64::from(v == Version::R2013) } else { i64::from(v >= Version::R2013) };
|
||||
let (mut kind, mut in_base) = (String::new(), false);
|
||||
for t in tags.iter_mut() {
|
||||
match t.code {
|
||||
0 => {
|
||||
kind = up(&t.str());
|
||||
in_base = false;
|
||||
}
|
||||
100 if matches!(kind.as_str(), "RENDERSETTINGS" | "MENTALRAYRENDERSETTINGS" | "RAPIDRTRENDERSETTINGS") => {
|
||||
in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings");
|
||||
}
|
||||
90 if in_base => {
|
||||
let rapid = kind == "RAPIDRTRENDERSETTINGS";
|
||||
let logical = t.i64().saturating_sub(shift(rapid, source));
|
||||
*t = Tag::i(90, logical.saturating_add(shift(rapid, declared)));
|
||||
in_base = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the drawing's foreign data back into a written file's tags (see the module comment).
|
||||
pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle, Vec<String>>, modern: bool) {
|
||||
/// `strings`: whether the file has a form for a proxy's separate string stream (a DXF of 2007 or
|
||||
/// later, or the DWG bridge); without one such a proxy is left out (#3229). Returns the foreign
|
||||
/// objects written, by their handles in the drawing (the file gives them new ones).
|
||||
pub(crate) fn finish(
|
||||
tags: &mut Vec<Tag>,
|
||||
d: &Drawing,
|
||||
reactors: &HashMap<Handle, Vec<String>>,
|
||||
modern: bool,
|
||||
target_modern: bool,
|
||||
strings: bool,
|
||||
) -> HashSet<Handle> {
|
||||
let f = d.foreign.as_ref();
|
||||
let unknown = unknown_handles(d);
|
||||
let xd: XdataOf = all_entities(d).filter(|e| !e.common.xdata.is_empty()).map(|e| (e.handle, e.common.xdata.as_slice())).collect();
|
||||
if f.is_empty() && unknown.is_empty() && xd.is_empty() {
|
||||
return;
|
||||
return HashSet::new();
|
||||
}
|
||||
let recs = written_records(tags);
|
||||
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
|
||||
@@ -970,14 +1118,21 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
numbers.entry(n).or_insert(500_i64.saturating_add(i64::try_from(i).unwrap_or(i64::MAX)));
|
||||
}
|
||||
let renumber = |old| proxy_class_number(f, &numbers, old);
|
||||
// A proxy is dropped when its class isn't written, or when its strings have no place here.
|
||||
let no_room = |t: &[(i32, &str)]| !strings && proxy_has_string_stream(t.iter().copied());
|
||||
// Entities of types CADCraft doesn't model, placed among the written ones.
|
||||
let mut planned = plan_unknown(d, &recs, tags, &roles, modern);
|
||||
let mut planned = plan_unknown(d, &recs, tags, &roles, modern, target_modern);
|
||||
for list in planned.values_mut() {
|
||||
list.retain_mut(|(_, t)| {
|
||||
if !t.first().is_some_and(|z| is_proxy(&z.str())) {
|
||||
return true;
|
||||
}
|
||||
let Some(n) = renumber(class_number(t.iter().map(|x| (x.code, x.str())))) else { return false };
|
||||
let groups: Vec<(i32, String)> = t.iter().map(|x| (x.code, x.str())).collect();
|
||||
let groups: Vec<(i32, &str)> = groups.iter().map(|(c, v)| (*c, v.as_str())).collect();
|
||||
if no_room(&groups) {
|
||||
return false;
|
||||
}
|
||||
let Some(n) = renumber(class_number(groups.iter().copied())) else { return false };
|
||||
set_class_number(t, n);
|
||||
true
|
||||
});
|
||||
@@ -1015,8 +1170,11 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
// Keep established live paths available to descendants during this pass as well.
|
||||
let mut alive_memo: HashMap<String, bool> = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect();
|
||||
let kept = |h: &str| kept.get(h) == Some(&true);
|
||||
for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none())
|
||||
{
|
||||
let dropped = |o: &ForeignObject| {
|
||||
let groups: Vec<(i32, &str)> = o.tags.iter().map(|r| (r.code, r.value.as_str())).collect();
|
||||
no_room(&groups) || renumber(class_number(groups.iter().copied())).is_none()
|
||||
};
|
||||
for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && dropped(o)) {
|
||||
alive_memo.insert(o.handle.hex(), false);
|
||||
}
|
||||
for o in &f.objects {
|
||||
@@ -1113,7 +1271,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
join_entries(&map, b, kept, &mut out);
|
||||
}
|
||||
}
|
||||
add_appids(&mut out);
|
||||
add_appids(&mut out, &f.appids);
|
||||
let top = max_handle(&out).saturating_add(1);
|
||||
if let Some(t) = seed_index(&out).and_then(|i| out.get_mut(i))
|
||||
&& Handle::parse_hex(&t.str()).is_none_or(|h| h.0 < top)
|
||||
@@ -1121,6 +1279,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
*t = Tag::s(5, format!("{top:X}"));
|
||||
}
|
||||
*tags = out;
|
||||
map.alive.keys().filter_map(|h| handle(h)).collect()
|
||||
}
|
||||
|
||||
/// Kept extension dictionaries of written records: those that go on a record without its own,
|
||||
@@ -1202,6 +1361,7 @@ fn plan_unknown(
|
||||
tags: &[Tag],
|
||||
roles: &HashMap<ForeignKey, String>,
|
||||
modern: bool,
|
||||
target_modern: bool,
|
||||
) -> HashMap<usize, Vec<(String, Vec<Tag>)>> {
|
||||
let stored = d.foreign.data_store_entities();
|
||||
let mut out: HashMap<usize, Vec<(String, Vec<Tag>)>> = HashMap::new();
|
||||
@@ -1241,7 +1401,9 @@ fn plan_unknown(
|
||||
for e in store.iter() {
|
||||
match &e.kind {
|
||||
EntityKind::Unknown(u) => {
|
||||
if modern && cadcraft_doc::foreign::sat_text_acis(u, e.handle, &stored) {
|
||||
if (modern && cadcraft_doc::foreign::sat_text_acis(u, e.handle, &stored))
|
||||
|| (!target_modern && cadcraft_doc::foreign::acis_left_out(u, e.handle, &stored, false))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let t = unknown_entity(u, e, &owner, paper);
|
||||
@@ -1435,9 +1597,13 @@ fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>)
|
||||
}
|
||||
}
|
||||
|
||||
/// APPID records for every application with xdata in the file, added to the APPID table.
|
||||
fn add_appids(out: &mut Vec<Tag>) {
|
||||
let used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
|
||||
/// APPID records for every application with xdata in the file and every one the file read had
|
||||
/// (`kept`), added to the APPID table.
|
||||
fn add_appids(out: &mut Vec<Tag>, kept: &[String]) {
|
||||
let mut used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
|
||||
for name in kept.iter().filter(|n| !n.is_empty()) {
|
||||
used.entry(up(name)).or_insert_with(|| name.clone());
|
||||
}
|
||||
let recs = written_records(out);
|
||||
let Some(table) = recs.iter().position(|r| {
|
||||
r.sec == "TABLES" && r.kind == "TABLE" && val(out.get(r.start + 1..r.end).unwrap_or(&[]), 2).is_some_and(|n| up(&n) == "APPID")
|
||||
|
||||
@@ -88,6 +88,7 @@ fn lwpolyline(tags: &[Tag], c: &mut Common, t: &T) -> Option<EntityKind> {
|
||||
// In a tilted plane: drawn as seen from above, at the vertices' mean height, its
|
||||
// vertices now plan coordinates.
|
||||
(verts, elevation) = plan_of_tilted(c.extrusion, elevation, &verts, flags & 1 != 0);
|
||||
thickness_along_z(c);
|
||||
c.extrusion = Vec3::Z;
|
||||
} else if c.extrusion.z < 0.0 {
|
||||
for v in &mut verts {
|
||||
@@ -577,7 +578,7 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
|
||||
break;
|
||||
}
|
||||
}
|
||||
let c = common(t);
|
||||
let mut c = common(t);
|
||||
let mut extra: Vec<EntityKind> = Vec::new();
|
||||
let k = if flags & 64 != 0 {
|
||||
// Face records that name a missing vertex (or fewer than three) are dropped: they draw
|
||||
@@ -599,13 +600,26 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
|
||||
} else if flags & 8 != 0 {
|
||||
EntityKind::Polyline3d(Polyline3d { points: pts.iter().map(|p| p.0).collect(), closed: flags & 1 != 0 })
|
||||
} else {
|
||||
// A 2D polyline's vertices are in its OCS: mirrored like LWPOLYLINE.
|
||||
let m = if c.extrusion.z < 0.0 { -1.0 } else { 1.0 };
|
||||
// A 2D polyline's vertices are in its OCS, at the elevation of the POLYLINE's own point:
|
||||
// in a tilted plane drawn as seen from above like LWPOLYLINE, else mirrored like it.
|
||||
let closed = flags & 1 != 0;
|
||||
let mut vertices: Vec<PolyVertex> = pts.iter().map(|p| PolyVertex { p: p.0.xy(), bulge: p.1, start_width: p.2, end_width: p.3 }).collect();
|
||||
let mut elevation = t.p(10).z;
|
||||
if tilted(c.extrusion, run_points(&vertices, elevation, closed)) {
|
||||
(vertices, elevation) = plan_of_tilted(c.extrusion, elevation, &vertices, closed);
|
||||
thickness_along_z(&mut c);
|
||||
c.extrusion = Vec3::Z;
|
||||
} else if c.extrusion.z < 0.0 {
|
||||
for v in &mut vertices {
|
||||
v.p.x = -v.p.x;
|
||||
v.bulge = -v.bulge;
|
||||
}
|
||||
}
|
||||
EntityKind::LwPolyline(LwPolyline {
|
||||
vertices: pts.iter().map(|p| PolyVertex { p: Vec2::new(m * p.0.x, p.0.y), bulge: m * p.1, start_width: p.2, end_width: p.3 }).collect(),
|
||||
closed: flags & 1 != 0,
|
||||
vertices,
|
||||
closed,
|
||||
const_width: t.fd(40, 0.0).min(t.fd(41, 0.0)).max(0.0),
|
||||
elevation: t.p(10).z,
|
||||
elevation,
|
||||
plinegen: flags & 128 != 0,
|
||||
})
|
||||
};
|
||||
@@ -714,3 +728,11 @@ fn helix(tags: &[Tag]) -> Helix {
|
||||
}
|
||||
.sanitized()
|
||||
}
|
||||
|
||||
/// A polyline drawn as seen from above gets the normal +Z: its thickness keeps the side of Z it
|
||||
/// extruded toward, which the normal it is losing said.
|
||||
fn thickness_along_z(c: &mut Common) {
|
||||
if c.extrusion.z < 0.0 {
|
||||
c.thickness = -c.thickness;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,6 +421,8 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
|
||||
// Plot layout flags: 2 display plot styles, 4 centred, 16 standard scale (75 = 0: scaled
|
||||
// to fit), 128 lineweights.
|
||||
if let Some(flags) = t.i(70) {
|
||||
// Kept to be written back (a 16-bit group: only those bits).
|
||||
p.file_plot_flags = Some(flags & 0xFFFF);
|
||||
p.show_plot_styles = flags & 2 != 0;
|
||||
p.center = flags & 4 != 0;
|
||||
p.lineweights = flags & 128 != 0;
|
||||
@@ -432,6 +434,13 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
|
||||
if let Some(s) = pos(ratio).or_else(|| pos(t.f(147))) {
|
||||
p.scale = s;
|
||||
}
|
||||
// A standard scale (flag 16, group 75 above 0: 0 is scaled to fit, the DXF Reference lists
|
||||
// 1 to 32), kept with the scale it stands for so a save can tell it was not changed.
|
||||
if t.i(70).is_some_and(|f| f & 16 != 0)
|
||||
&& let Some(code) = t.i(75).filter(|c| (1..=32).contains(c))
|
||||
{
|
||||
p.file_standard_scale = Some((code, p.scale));
|
||||
}
|
||||
p.plot_area = match t.i(74) {
|
||||
Some(0) => "display",
|
||||
Some(1) => "extents",
|
||||
|
||||
@@ -24,6 +24,8 @@ mod entity;
|
||||
mod header;
|
||||
mod layout;
|
||||
mod objects;
|
||||
mod proxy;
|
||||
pub use proxy::proxies_lost;
|
||||
mod sections;
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -149,7 +151,16 @@ pub fn write(d: &Drawing) -> String {
|
||||
|
||||
/// The drawing's DXF tags, declaring `version` in `$ACADVER`.
|
||||
pub fn tags(d: &Drawing, version: Version) -> Vec<Tag> {
|
||||
tags_for(d, version, version, version < Version::R2004)
|
||||
tags_kept(d, version).0
|
||||
}
|
||||
|
||||
/// [`tags`], with the foreign objects the file keeps, by their handles in the drawing.
|
||||
fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::HashSet<cadcraft_doc::Handle>) {
|
||||
let (mut tags, kept) = sections::tags_kept_for(d, version, version, version < Version::R2004, false);
|
||||
// Kept proxies in this version's layout (#3229). Not for the DWG bridge, whose writer reads
|
||||
// them in the layout of the DWG they came from.
|
||||
proxy::proxy_layout(&mut tags, version);
|
||||
(tags, kept)
|
||||
}
|
||||
|
||||
/// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG
|
||||
|
||||
@@ -2,13 +2,15 @@ use super::{
|
||||
Block, Color, Common, Dimension, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext,
|
||||
};
|
||||
|
||||
/// What happens to the anonymous `*D` blocks read from a file (#495): a dimension that still
|
||||
/// names its block regenerates its geometry under that name, keeping the block's entity
|
||||
/// handles, and `*D` blocks nothing else references are not written again.
|
||||
/// What happens to the dimension blocks read from a file (#495): a dimension that still names
|
||||
/// its block is written with that block, under its name, and `*D` blocks nothing else
|
||||
/// references are not written again. The block a dimension names may have any name: other
|
||||
/// programs don't always use `*D` (#3299).
|
||||
pub(super) struct DimBlockPlan {
|
||||
/// Dimension (model or paper space) → the read block whose name and handles it reuses.
|
||||
pub(super) reuse: HashMap<Handle, std::sync::Arc<Block>>,
|
||||
/// Upper-case names of `*D` blocks not written as ordinary blocks.
|
||||
/// Upper-case names of blocks not written as ordinary blocks: `*D` blocks and the blocks
|
||||
/// dimensions name, when nothing else uses them.
|
||||
pub(super) skip: std::collections::HashSet<String>,
|
||||
}
|
||||
|
||||
@@ -16,6 +18,12 @@ fn is_dim_block(name: &str) -> bool {
|
||||
name.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("*D"))
|
||||
}
|
||||
|
||||
/// The read block, not named `*D`, that a dimension block definition named `name` is written
|
||||
/// from (#3299): its record and block properties are written as read.
|
||||
pub(super) fn kept_named_dim_block<'a>(d: &'a Drawing, name: &str) -> Option<&'a Block> {
|
||||
d.block(name).filter(|_| !is_dim_block(name)).map(|b| b.as_ref())
|
||||
}
|
||||
|
||||
pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan {
|
||||
let spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect();
|
||||
// Block names other objects use: inserts and multileader contents anywhere, and dimensions
|
||||
@@ -35,12 +43,19 @@ pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan {
|
||||
for e in d.blocks.values().flat_map(|b| b.entities.iter()) {
|
||||
note(e, true, &mut used);
|
||||
}
|
||||
let skip = d.blocks.keys().filter(|n| is_dim_block(n)).map(|n| n.to_ascii_uppercase()).filter(|n| !used.contains(n)).collect();
|
||||
// Blocks the dimensions of model and paper space still name, whatever their names.
|
||||
let named: std::collections::HashSet<String> = spaces
|
||||
.iter()
|
||||
.flat_map(|s| s.iter())
|
||||
.filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { dm.block.as_ref().map(|n| n.to_ascii_uppercase()) } else { None })
|
||||
.collect();
|
||||
let skip =
|
||||
d.blocks.keys().map(|n| n.to_ascii_uppercase()).filter(|n| is_dim_block(n) || named.contains(n)).filter(|n| !used.contains(n)).collect();
|
||||
let mut plan = DimBlockPlan { reuse: HashMap::new(), skip };
|
||||
let mut claimed = std::collections::HashSet::new();
|
||||
for e in spaces.iter().flat_map(|s| s.iter()) {
|
||||
let EntityKind::Dimension(dm) = &e.kind else { continue };
|
||||
let Some(b) = dm.block.as_deref().filter(|n| is_dim_block(n)).and_then(|n| d.block(n)) else { continue };
|
||||
let Some(b) = dm.block.as_deref().and_then(|n| d.block(n)) else { continue };
|
||||
let key = b.name.to_ascii_uppercase();
|
||||
if plan.skip.contains(&key) && claimed.insert(key) {
|
||||
plan.reuse.insert(e.handle, b.clone());
|
||||
|
||||
@@ -108,7 +108,10 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
EntityKind::Line(l) => {
|
||||
w.s(0, "LINE");
|
||||
common(w, e, owner, paper, "AcDbLine");
|
||||
thickness(w, e);
|
||||
// Along the normal written with it (210 below), as read.
|
||||
if e.common.thickness != 0.0 {
|
||||
w.f(39, e.common.thickness);
|
||||
}
|
||||
w.p(10, l.a);
|
||||
w.p(11, l.b);
|
||||
extrusion(w, e);
|
||||
@@ -156,8 +159,13 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
if p.const_width > 0.0 {
|
||||
w.f(43, p.const_width);
|
||||
}
|
||||
if p.elevation != 0.0 {
|
||||
w.f(38, p.elevation);
|
||||
// The elevation runs along the polyline's normal, which isn't written: one facing down
|
||||
// Z is at the elevation's negative. That is exact for a normal of 0,0,-1 only; a tilted
|
||||
// one pointing partly down is flipped the same way (the reader brings tilted polylines
|
||||
// into plan with normal Z, so only other sources make one).
|
||||
let elevation = if e.common.extrusion.z < 0.0 { -p.elevation } else { p.elevation };
|
||||
if elevation != 0.0 {
|
||||
w.f(38, elevation);
|
||||
}
|
||||
thickness(w, e);
|
||||
for v in &p.vertices {
|
||||
@@ -603,14 +611,16 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a HATCH: its pattern name, solid and associative flags, its boundary loops, and the
|
||||
/// pattern angle, scale and double flag (written for solid hatches too). Pattern lines are written
|
||||
/// only for non-solid hatches.
|
||||
/// Writes a HATCH: its pattern name, solid and associative flags, its boundary loops, and for a
|
||||
/// pattern fill its angle, scale, double flag and pattern lines.
|
||||
fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, _cx: &Ctx) {
|
||||
if let EntityKind::Hatch(h) = &e.kind {
|
||||
w.s(0, "HATCH");
|
||||
common(w, e, owner, paper, "AcDbHatch");
|
||||
w.p(10, Vec3::new(0.0, 0.0, h.elevation));
|
||||
// Its elevation runs along its normal, written as Z: one facing down is at the negative.
|
||||
// Exact for a normal of 0,0,-1; the reader brings a tilted hatch into plan with normal Z.
|
||||
let elevation = if e.common.extrusion.z < 0.0 { -h.elevation } else { h.elevation };
|
||||
w.p(10, Vec3::new(0.0, 0.0, elevation));
|
||||
w.p(210, Vec3::Z);
|
||||
w.s(2, &h.pattern);
|
||||
w.i(70, i64::from(h.solid));
|
||||
@@ -640,12 +650,13 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
}
|
||||
w.i(75, i64::from(h.style));
|
||||
w.i(76, 1);
|
||||
// Angle, scale and double flag are written for solid fills too, as read (AutoCAD and
|
||||
// other writers keep them on SOLID hatches; readers ignore them there).
|
||||
w.f(52, h.angle.to_degrees());
|
||||
w.f(41, h.scale);
|
||||
w.i(77, 0);
|
||||
// Angle, scale and double flag are a pattern fill's: AutoCAD 2024 writes none of them on a
|
||||
// solid or gradient fill, and refuses a file whose solid HATCH has any of them ("Error:
|
||||
// expected group code 98", the whole drawing discarded; measured).
|
||||
if !h.solid {
|
||||
w.f(52, h.angle.to_degrees());
|
||||
w.f(41, h.scale);
|
||||
w.i(77, 0);
|
||||
// The lines read from the file, else the library's pattern of that name.
|
||||
let lines = if h.pattern_lines.is_empty() {
|
||||
cadcraft_doc::library::pattern_for(d, &h.pattern).map(|p| p.lines).unwrap_or_default()
|
||||
@@ -829,10 +840,14 @@ fn gradient(w: &mut W, g: &Gradient) {
|
||||
w.s(1000, g.color2.name());
|
||||
}
|
||||
|
||||
/// Group 39 (thickness) of the entities whose DXF Reference record has one; only when set.
|
||||
/// Group 39 (thickness) of the entities whose DXF Reference record has one; only when set. They
|
||||
/// are written with no normal, so they extrude along Z: one whose normal points down Z extrudes
|
||||
/// the other way, and its thickness changes sign. That is exact for a normal of 0,0,-1; a tilted
|
||||
/// one pointing partly down only gets the closer of the two directions.
|
||||
fn thickness(w: &mut W, e: &Entity) {
|
||||
if e.common.thickness != 0.0 {
|
||||
w.f(39, e.common.thickness);
|
||||
let t = if e.common.extrusion.z < 0.0 { -e.common.thickness } else { e.common.thickness };
|
||||
if t != 0.0 {
|
||||
w.f(39, t);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
//! Kept proxy records (ACAD_PROXY_OBJECT, ACAD_PROXY_ENTITY) in the group layout of the DXF version
|
||||
//! written (#3229). Proxies are kept with the groups they were read with, and the DWG bridge
|
||||
//! brings them in the DWG's own version's layout, so a 2010 drawing saved as an R2000 DXF wrote
|
||||
//! 2010 groups that R2000 readers reject ("Out of range").
|
||||
//!
|
||||
//! The layouts, after the `AcDbProxyObject` / `AcDbProxyEntity` marker:
|
||||
//! - R2000 and R2004 (DXF Reference): 92 graphics size, 93 data size in bits, 95 the drawing
|
||||
//! format (low word the DWG version, high word the maintenance release), 70 the data format.
|
||||
//! - 2007: as R2000, with 96 for the size of the separate string stream. A proxy whose string
|
||||
//! stream isn't empty has no earlier form: the raw writer leaves it out of an earlier file and
|
||||
//! the save says so.
|
||||
//! - 2010 and 2013: 160 graphics size, 161 data size, 162 string stream size.
|
||||
//! - 2018 and later: as 2010, with the drawing format split into 71 (DWG version) and 97
|
||||
//! (maintenance release).
|
||||
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use cadcraft_doc::foreign::is_proxy;
|
||||
use cadcraft_doc::{Drawing, EntityKind, Handle};
|
||||
use craft_dxf::{Tag, Version};
|
||||
|
||||
/// What a DXF of `version` leaves out of `d` because a file earlier than 2007 has no form for a
|
||||
/// proxy's separate string stream, counted by DXF type: those proxies, and the objects that go
|
||||
/// with them (their extension dictionary and its records) because nothing written owns them any
|
||||
/// more. Found by writing the drawing as 2007 and as `version` and comparing what each keeps, so a proxy that no version writes (its class isn't written, or no written block holds
|
||||
/// it) is not counted, and nothing that stays in the file is. Empty from 2007 on (#3229).
|
||||
pub fn proxies_lost(d: &Drawing, version: Version) -> BTreeMap<String, usize> {
|
||||
// Writing twice only for a drawing that holds such a proxy at all.
|
||||
if version >= Version::R2007 || cadcraft_doc::foreign::proxies_dropped_before_2007(d).is_empty() {
|
||||
return BTreeMap::new();
|
||||
}
|
||||
// Unknown entities keep their handles in the file; kept foreign objects get new ones, so
|
||||
// the writer names those by their handles in the drawing.
|
||||
let (tags_2007, objects_2007) = super::tags_kept(d, Version::R2007);
|
||||
let (tags_here, objects_here) = super::tags_kept(d, version);
|
||||
let (entities_2007, entities_here) = (written_handles(&tags_2007), written_handles(&tags_here));
|
||||
let lost = |h: Handle| entities_2007.contains(&h) && !entities_here.contains(&h);
|
||||
let lost_object = |h: Handle| objects_2007.contains(&h) && !objects_here.contains(&h);
|
||||
let mut out = BTreeMap::new();
|
||||
let mut count = |kind: &str| {
|
||||
let n: &mut usize = out.entry(kind.trim().to_ascii_uppercase()).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
};
|
||||
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities));
|
||||
for e in stores.flat_map(|s| s.iter()) {
|
||||
if let EntityKind::Unknown(u) = &e.kind
|
||||
&& lost(e.handle)
|
||||
{
|
||||
count(&u.dxf_type);
|
||||
}
|
||||
}
|
||||
for o in d.foreign.objects.iter().filter(|o| lost_object(o.handle)) {
|
||||
count(&o.kind);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The handles of the records in written `tags` (group 5, and 105 for a DIMSTYLE).
|
||||
fn written_handles(tags: &[Tag]) -> HashSet<Handle> {
|
||||
tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(t.str().trim())).collect()
|
||||
}
|
||||
|
||||
/// What a proxy group holds, whatever version's code it was read with.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Field {
|
||||
/// Size of the graphics data in bytes (92, 160).
|
||||
Graphics,
|
||||
/// Size of the object or entity data in bits (93, 161).
|
||||
Data,
|
||||
/// Size of the separate string stream (96, 162), from the 2007 format.
|
||||
Strings,
|
||||
}
|
||||
|
||||
fn field(code: i32) -> Option<Field> {
|
||||
match code {
|
||||
92 | 160 => Some(Field::Graphics),
|
||||
93 | 161 => Some(Field::Data),
|
||||
96 | 162 => Some(Field::Strings),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The code `version` writes `f` with; `None` when it has none (a string stream before 2007).
|
||||
fn code_for(f: Field, version: Version) -> Option<i32> {
|
||||
let late = version >= Version::R2010;
|
||||
match f {
|
||||
Field::Graphics => Some(if late { 160 } else { 92 }),
|
||||
Field::Data => Some(if late { 161 } else { 93 }),
|
||||
Field::Strings if late => Some(162),
|
||||
Field::Strings => (version >= Version::R2007).then_some(96),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrite every proxy record in `tags` into `version`'s layout. Other records are untouched.
|
||||
pub(super) fn proxy_layout(tags: &mut Vec<Tag>, version: Version) {
|
||||
if !tags.iter().any(|t| t.code == 0 && is_proxy(&t.str())) {
|
||||
return;
|
||||
}
|
||||
let src = std::mem::take(tags);
|
||||
let mut out = Vec::with_capacity(src.len());
|
||||
let mut rest = src.as_slice();
|
||||
while let Some((first, tail)) = rest.split_first() {
|
||||
// One record: its type, and its groups up to the next record.
|
||||
let end = tail.iter().position(|t| t.code == 0).unwrap_or(tail.len());
|
||||
let (body, next) = tail.split_at(end);
|
||||
out.push(first.clone());
|
||||
if first.code == 0 && is_proxy(&first.str()) {
|
||||
convert(body, version, &mut out);
|
||||
} else {
|
||||
out.extend_from_slice(body);
|
||||
}
|
||||
rest = next;
|
||||
}
|
||||
*tags = out;
|
||||
}
|
||||
|
||||
/// One proxy record's groups (after its type) in `version`'s layout. Only the groups after the
|
||||
/// proxy subclass marker change: before it, an entity's common groups have a 92 and a 160 of
|
||||
/// their own.
|
||||
fn convert(body: &[Tag], version: Version, out: &mut Vec<Tag>) {
|
||||
let marker = body.iter().position(|t| t.code == 100 && t.str().trim().to_ascii_lowercase().starts_with("acdbproxy"));
|
||||
let Some(marker) = marker else {
|
||||
out.extend_from_slice(body);
|
||||
return;
|
||||
};
|
||||
let (common, own) = body.split_at(marker.saturating_add(1));
|
||||
out.extend_from_slice(common);
|
||||
let format = drawing_format(own);
|
||||
let mut format_written = false;
|
||||
for t in own {
|
||||
if matches!(t.code, 95 | 71 | 97) {
|
||||
// The drawing format goes where the first of its groups was, in this version's form.
|
||||
if !format_written && let Some(f) = format {
|
||||
if version >= Version::R2018 {
|
||||
out.push(Tag::i(71, f & 0xFFFF));
|
||||
out.push(Tag::i(97, (f >> 16) & 0xFFFF));
|
||||
} else {
|
||||
out.push(Tag::i(95, f));
|
||||
}
|
||||
}
|
||||
format_written = true;
|
||||
continue;
|
||||
}
|
||||
match field(t.code) {
|
||||
Some(f) => {
|
||||
if let Some(code) = code_for(f, version) {
|
||||
out.push(Tag { code, value: t.value.clone() });
|
||||
}
|
||||
}
|
||||
None => out.push(t.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The proxy's drawing format (DWG version in the low word, maintenance release in the high
|
||||
/// word), from a 95 or from 71 and 97.
|
||||
fn drawing_format(own: &[Tag]) -> Option<i64> {
|
||||
let get = |code| own.iter().find(|t| t.code == code).map(|t| t.value.as_i64());
|
||||
get(95).map(|f| f & 0xFFFF_FFFF).or_else(|| get(71).map(|lo| ((get(97).unwrap_or(0) & 0xFFFF) << 16) | (lo & 0xFFFF)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn record(groups: &[(i32, &str)]) -> Vec<Tag> {
|
||||
groups.iter().map(|(c, v)| Tag::s(*c, *v)).collect()
|
||||
}
|
||||
|
||||
fn codes(tags: &[Tag]) -> Vec<(i32, String)> {
|
||||
tags.iter().map(|t| (t.code, t.str())).collect()
|
||||
}
|
||||
|
||||
/// A proxy object as a 2010 DWG brings it (the record in the report).
|
||||
fn from_2010() -> Vec<Tag> {
|
||||
record(&[
|
||||
(0, "ACAD_PROXY_OBJECT"),
|
||||
(5, "2CBA9C"),
|
||||
(100, "AcDbProxyObject"),
|
||||
(90, "499"),
|
||||
(91, "521"),
|
||||
(95, "393245"),
|
||||
(70, "0"),
|
||||
(162, "0"),
|
||||
(161, "303"),
|
||||
(310, "00FF"),
|
||||
(340, "1F"),
|
||||
(94, "0"),
|
||||
(0, "ENDSEC"),
|
||||
])
|
||||
}
|
||||
|
||||
fn own(tags: &[Tag]) -> Vec<(i32, String)> {
|
||||
codes(tags).into_iter().skip(3).take_while(|(c, _)| *c != 0).collect()
|
||||
}
|
||||
|
||||
fn s(c: i32, v: &str) -> (i32, String) {
|
||||
(c, v.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2010_proxy_takes_each_versions_layout() {
|
||||
// 393245 = 0x6001D: DWG version 29, maintenance release 6.
|
||||
let mut t = from_2010();
|
||||
proxy_layout(&mut t, Version::R2000);
|
||||
assert_eq!(own(&t), [s(90, "499"), s(91, "521"), s(95, "393245"), s(70, "0"), s(93, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")]);
|
||||
let mut t = from_2010();
|
||||
proxy_layout(&mut t, Version::R2007);
|
||||
assert_eq!(
|
||||
own(&t),
|
||||
[s(90, "499"), s(91, "521"), s(95, "393245"), s(70, "0"), s(96, "0"), s(93, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")]
|
||||
);
|
||||
let mut t = from_2010();
|
||||
proxy_layout(&mut t, Version::R2010);
|
||||
assert_eq!(codes(&t), codes(&from_2010()), "already 2010");
|
||||
let mut t = from_2010();
|
||||
proxy_layout(&mut t, Version::R2018);
|
||||
assert_eq!(
|
||||
own(&t),
|
||||
[s(90, "499"), s(91, "521"), s(71, "29"), s(97, "6"), s(70, "0"), s(162, "0"), s(161, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")]
|
||||
);
|
||||
// And back from the 2018 form.
|
||||
proxy_layout(&mut t, Version::R2004);
|
||||
assert_eq!(own(&t), [s(90, "499"), s(91, "521"), s(95, "393245"), s(70, "0"), s(93, "303"), s(310, "00FF"), s(340, "1F"), s(94, "0")]);
|
||||
// The ENDSEC after it is untouched.
|
||||
assert_eq!(t.last().map(Tag::str).as_deref(), Some("ENDSEC"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entitys_common_groups_stay() {
|
||||
// Before the subclass marker, 92 and 160 are the entity's own proxy graphics.
|
||||
let mut t = record(&[
|
||||
(0, "ACAD_PROXY_ENTITY"),
|
||||
(100, "AcDbEntity"),
|
||||
(92, "4"),
|
||||
(310, "AA"),
|
||||
(100, "AcDbProxyEntity"),
|
||||
(90, "498"),
|
||||
(91, "500"),
|
||||
(160, "8"),
|
||||
(310, "BB"),
|
||||
(161, "16"),
|
||||
(310, "CC"),
|
||||
(94, "0"),
|
||||
(95, "393245"),
|
||||
(70, "0"),
|
||||
]);
|
||||
proxy_layout(&mut t, Version::R2000);
|
||||
let c: Vec<i32> = t.iter().map(|x| x.code).collect();
|
||||
assert_eq!(c, [0, 100, 92, 310, 100, 90, 91, 92, 310, 93, 310, 94, 95, 70]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_records_and_hostile_values_are_safe() {
|
||||
let mut t = record(&[(0, "LINE"), (95, "1"), (100, "AcDbProxyObject"), (93, "1")]);
|
||||
let before = codes(&t);
|
||||
proxy_layout(&mut t, Version::R2018);
|
||||
assert_eq!(codes(&t), before, "not a proxy");
|
||||
// A huge or negative drawing format doesn't overflow.
|
||||
let mut t = record(&[(0, "ACAD_PROXY_OBJECT"), (100, "AcDbProxyObject"), (95, "-1"), (71, "99999999999")]);
|
||||
proxy_layout(&mut t, Version::R2018);
|
||||
assert_eq!(codes(&t), [s(0, "ACAD_PROXY_OBJECT"), s(100, "AcDbProxyObject"), s(71, "65535"), s(97, "65535")]);
|
||||
// No marker: left as it is.
|
||||
let mut t = record(&[(0, "ACAD_PROXY_OBJECT"), (93, "1")]);
|
||||
proxy_layout(&mut t, Version::R2018);
|
||||
assert_eq!(codes(&t), [s(0, "ACAD_PROXY_OBJECT"), s(93, "1")]);
|
||||
}
|
||||
}
|
||||
@@ -413,6 +413,23 @@ struct LayoutWriteData<'a> {
|
||||
limits: Option<(Vec2, Vec2)>,
|
||||
}
|
||||
|
||||
/// The plot layout flags (AcDbPlotSettings group 70) for `page`. The bits CADCraft models come
|
||||
/// from the page: 2 display plot styles, 4 centred, 128 lineweights, and 16 standard scale where
|
||||
/// the scale decides it (scaled to fit: set; a custom scale: clear). The rest are kept as the file
|
||||
/// had them (#3227); a page CADCraft made gets 512 (plot paper space last) and 32 (plot with plot
|
||||
/// styles), and 16 when its scale is standard.
|
||||
fn plot_layout_flags(page: &PageSetup, standard: bool) -> i64 {
|
||||
const MODELED: i64 = 2 | 4 | 128;
|
||||
const STANDARD_SCALE: i64 = 16;
|
||||
let kept = match page.file_plot_flags {
|
||||
Some(f) if page.scale_to_fit => (f & !MODELED) | STANDARD_SCALE,
|
||||
Some(f) if !standard => f & !MODELED & !STANDARD_SCALE,
|
||||
Some(f) => f & !MODELED,
|
||||
None => 512 | 32 | if standard { STANDARD_SCALE } else { 0 },
|
||||
};
|
||||
kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 }
|
||||
}
|
||||
|
||||
fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<'_>) {
|
||||
let d = context.drawing;
|
||||
let layout_dict = context.dictionary;
|
||||
@@ -426,13 +443,10 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
|
||||
// Plot scale: a standard scale when fitting or 1:1, otherwise custom (142 paper units
|
||||
// per 143 drawing units).
|
||||
let scale = if page.scale.is_finite() && page.scale > 0.0 { page.scale } else { 1.0 };
|
||||
let standard = page.scale_to_fit || scale == 1.0;
|
||||
let plot_flags = 512
|
||||
| 32
|
||||
| if standard { 16 } else { 0 }
|
||||
| if page.lineweights { 128 } else { 0 }
|
||||
| if page.center { 4 } else { 0 }
|
||||
| if page.show_plot_styles { 2 } else { 0 };
|
||||
// The file's standard scale (such as 1:50) while the scale is still the one read with it.
|
||||
let file_standard = page.file_standard_scale.filter(|&(_, s)| !page.scale_to_fit && s == scale).map(|(code, _)| code);
|
||||
let standard = page.scale_to_fit || scale == 1.0 || file_standard.is_some();
|
||||
let plot_flags = plot_layout_flags(page, standard);
|
||||
let plot_type = match page.plot_area.as_str() {
|
||||
"display" => 0,
|
||||
"extents" => 1,
|
||||
@@ -474,7 +488,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
|
||||
w.i(73, rotation);
|
||||
w.i(74, plot_type);
|
||||
w.s(7, &page.plot_style_table);
|
||||
w.i(75, if page.scale_to_fit { 0 } else { 16 });
|
||||
w.i(75, if page.scale_to_fit { 0 } else { file_standard.unwrap_or(16) });
|
||||
w.f(147, scale);
|
||||
// The paper image origin the file had (#2109), else 0,0.
|
||||
let origin = page.image_origin.filter(|o| o.is_finite()).unwrap_or(Vec2::ZERO);
|
||||
@@ -978,10 +992,24 @@ fn plan_dimension_associations(d: &Drawing, all_spaces: &[&EntityStore], w: &mut
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawing's DXF tags, declaring `version` in `$ACADVER`, with what `target` (the version the
|
||||
/// file ends up in: `version`, or the DWG version the bridge writes) has.
|
||||
/// The DWG bridge's DXF tags, declaring `version` in `$ACADVER`, with what `target` (the DWG
|
||||
/// version the bridge writes) has.
|
||||
/// `frozen_341`: see [`Ctx::frozen_341`].
|
||||
pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_341: bool) -> Vec<Tag> {
|
||||
tags_kept_for(d, version, target, frozen_341, true).0
|
||||
}
|
||||
|
||||
/// The drawing's DXF tags, declaring `version` in `$ACADVER`, with what `target` (the version the
|
||||
/// file ends up in) has, and the foreign objects the file keeps, by their handles in the drawing.
|
||||
/// `bridge`: the text is for the DWG bridge, not a DXF file. The versions alone can't say so: an
|
||||
/// R2000 DWG is bridged from R2000 text.
|
||||
pub(super) fn tags_kept_for(
|
||||
d: &Drawing,
|
||||
version: Version,
|
||||
target: Version,
|
||||
frozen_341: bool,
|
||||
bridge: bool,
|
||||
) -> (Vec<Tag>, std::collections::HashSet<Handle>) {
|
||||
// An in-place block edit in progress is not written: the drawing as before it.
|
||||
let committed = d.committed();
|
||||
let d: &Drawing = &committed;
|
||||
@@ -1129,7 +1157,12 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
for (n, h, b) in &user_blocks {
|
||||
br_rec(&mut w, h, n, None, Some(b));
|
||||
}
|
||||
for (n, h, _) in dim_defs.iter().chain(arrow_defs.iter()).chain(table_defs.iter()) {
|
||||
// A block with another name that a dimension was read with keeps its record's properties
|
||||
// (insertion units, explodability) as read (#3299).
|
||||
for (n, h, _) in &dim_defs {
|
||||
br_rec(&mut w, h, n, None, super::blocks::kept_named_dim_block(d, n));
|
||||
}
|
||||
for (n, h, _) in arrow_defs.iter().chain(table_defs.iter()) {
|
||||
br_rec(&mut w, h, n, None, None);
|
||||
}
|
||||
w.s(0, "ENDTAB");
|
||||
@@ -1190,7 +1223,15 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
}
|
||||
}
|
||||
for (n, h, ents) in &dim_defs {
|
||||
block(&mut w, (n, ""), h, Vec3::ZERO, 1, &mut ents.iter(), false);
|
||||
// A block with another name that a dimension was read with keeps its description, flags
|
||||
// and base point as read (#3299); `*D` blocks are anonymous at the origin. A picture
|
||||
// regenerated into an empty read block is drawn in world coordinates, so it is at the
|
||||
// origin too.
|
||||
let (desc, base, flags) = match super::blocks::kept_named_dim_block(d, n) {
|
||||
Some(b) => (b.description.as_str(), if b.entities.is_empty() { Vec3::ZERO } else { b.base }, i64::from(b.anonymous)),
|
||||
None => ("", Vec3::ZERO, 1),
|
||||
};
|
||||
block(&mut w, (n, desc), h, base, flags, &mut ents.iter(), false);
|
||||
}
|
||||
for (n, h, ents) in &arrow_defs {
|
||||
block(&mut w, (n, ""), h, Vec3::ZERO, 0, &mut ents.iter(), false);
|
||||
@@ -1232,12 +1273,23 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
|
||||
*t = Tag::s(5, seed);
|
||||
}
|
||||
// Only a DXF declares the version it is written for: the DWG bridge writes R2000 text for the
|
||||
// DWG writer, which keeps SAT-text solids (#2334).
|
||||
crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013);
|
||||
// DWG writer, which keeps SAT-text solids (#2334). A file of 2010 or earlier, DXF or DWG, has
|
||||
// no data store, so a solid whose geometry is only there is left out of it.
|
||||
// The DWG bridge keeps proxies in the DWG's own layout.
|
||||
let strings = bridge || version >= Version::R2007;
|
||||
let kept = crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013, target >= Version::R2013, strings);
|
||||
// Kept constraint groups go in the order their reader expects: a DXF's own version. The
|
||||
// bridge's R2000 text is read as the version its kept groups came from when that is newer
|
||||
// (craft-dwg's `encode_kept_noted` declares it), so there they stay as read.
|
||||
let read_as =
|
||||
if !bridge { version } else { d.foreign.version.as_deref().and_then(Version::for_acadver).filter(|from| *from > version).unwrap_or(version) };
|
||||
crate::dxf_raw::constraint_node_order(&mut w.t, read_as >= Version::R2013);
|
||||
// Kept render settings take the class-version form of the version the text is read as (#907).
|
||||
crate::dxf_raw::render_settings_versions(&mut w.t, d.foreign.version.as_deref().and_then(Version::for_acadver), read_as);
|
||||
crate::dxf_raw::data_store(&mut w.t, d, target >= Version::R2013);
|
||||
add_class_instance_counts(&mut w.t, target);
|
||||
mark_xrefs(&mut w.t, d);
|
||||
w.t
|
||||
(w.t, kept)
|
||||
}
|
||||
|
||||
/// Paper size (groups 44, 45) and plot rotation (group 73) for a LAYOUT object. Page setups
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
/// A DWG hatch's elliptic boundary edge angles, in degrees in the DXF the DWG is read through (#3332).
|
||||
mod dwg_hatch;
|
||||
/// What a DXF file holds that CADCraft doesn't model, kept and written back (#528).
|
||||
mod dxf_raw;
|
||||
|
||||
@@ -35,7 +37,7 @@ pub use cadcraft_doc::Format;
|
||||
pub use craft_dxf::Version;
|
||||
pub use dxf_raw::{ObjectRecord, object_records};
|
||||
pub use dxf_read::entity_from_groups;
|
||||
pub use dxf_write::entity_groups;
|
||||
pub use dxf_write::{entity_groups, proxies_lost};
|
||||
pub use pdf::{PdfOptions, pdf, plot};
|
||||
|
||||
/// How a drawing is saved as DXF or DWG.
|
||||
@@ -98,6 +100,8 @@ pub fn read(bytes: &[u8], name: impl AsRef<Path>) -> Result<Drawing> {
|
||||
pub(crate) fn read_source(bytes: &[u8], name: &Path) -> Result<(Drawing, Option<Vec<u8>>)> {
|
||||
if craft_dwg::is_dwg(bytes) {
|
||||
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(dwg_error)?;
|
||||
// The decoder writes an elliptic hatch edge's angles in radians; DXF keeps degrees.
|
||||
let dxf = dwg_hatch::elliptic_edge_degrees(dxf);
|
||||
let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?;
|
||||
d.read_notes = notes.into_iter().map(|note| cadcraft_dwg_message(¬e)).collect();
|
||||
return Ok((d, Some(dxf)));
|
||||
|
||||
+344
-5
@@ -2683,6 +2683,84 @@ fn mirrored_2d_polyline_extrusion_flips_x_and_bulge() {
|
||||
assert_eq!(got, vec![(-1.0, 0.0, -1.0), (-3.0, 0.0, 0.0)]);
|
||||
}
|
||||
|
||||
/// Objects whose normal is 0,0,-1, at OCS height 5 and most of them 2 thick, keep their world height
|
||||
/// and the side they extrude to through a save. They are written with no normal (along Z), so an
|
||||
/// elevation or a thickness written as read put a polyline or a hatch at Z +5 instead of -5, and
|
||||
/// extruded a circle, point, solid or text up instead of down (AutoCAD 2024 opening the saved file,
|
||||
/// measured). A line writes its normal, and keeps its thickness as read. The same objects facing up
|
||||
/// (no normal, and 0,0,1) keep +5 and +2: only a normal pointing down Z changes the sign.
|
||||
#[test]
|
||||
fn mirrored_objects_keep_their_world_height_and_thickness_side() {
|
||||
let records = |normal: &str| {
|
||||
format!(
|
||||
"0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n38\n5\n39\n2\n{normal}10\n0\n20\n0\n42\n0.5\n10\n-10\n20\n0\n\
|
||||
0\nPOLYLINE\n8\n0\n66\n1\n70\n0\n10\n0\n20\n0\n30\n5\n{normal}0\nVERTEX\n8\n0\n10\n0\n20\n10\n0\nVERTEX\n8\n0\n10\n-10\n20\n10\n0\nSEQEND\n\
|
||||
0\nCIRCLE\n8\n0\n10\n-10\n20\n5\n30\n5\n40\n5\n39\n2\n{normal}\
|
||||
0\nARC\n8\n0\n10\n-30\n20\n5\n30\n5\n40\n5\n50\n180\n51\n270\n{normal}\
|
||||
0\nPOINT\n8\n0\n10\n-40\n20\n0\n30\n5\n39\n2\n{normal}\
|
||||
0\nSOLID\n8\n0\n10\n50\n20\n0\n30\n5\n11\n60\n21\n0\n31\n5\n12\n50\n22\n5\n32\n5\n13\n60\n23\n5\n33\n5\n39\n2\n{normal}\
|
||||
0\nHATCH\n8\n0\n10\n0\n20\n0\n30\n5\n{normal}2\nSOLID\n70\n1\n71\n0\n91\n1\n92\n2\n72\n0\n73\n1\n93\n4\n\
|
||||
10\n70\n20\n0\n10\n80\n20\n0\n10\n80\n20\n5\n10\n70\n20\n5\n97\n0\n75\n0\n76\n1\n98\n0\n\
|
||||
0\nTEXT\n8\n0\n10\n-90\n20\n0\n30\n5\n40\n2\n1\nA\n39\n2\n{normal}\
|
||||
0\nLINE\n8\n0\n39\n2\n10\n0\n20\n20\n30\n3\n11\n10\n21\n20\n31\n3\n{normal}"
|
||||
)
|
||||
};
|
||||
let (down, up) = ("210\n0\n220\n0\n230\n-1\n", "210\n0\n220\n0\n230\n1\n");
|
||||
let text = format!("0\nSECTION\n2\nENTITIES\n{}{}{}0\nENDSEC\n0\nEOF\n", records(down), records(""), records(up));
|
||||
// Each object's kind, world height and thickness along world Z.
|
||||
let place = |d: &Drawing| -> Vec<(&'static str, f64, f64)> {
|
||||
d.model
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let n = e.common.extrusion.z.signum();
|
||||
let (kind, z) = match &e.kind {
|
||||
EntityKind::LwPolyline(p) => ("polyline", n * p.elevation),
|
||||
EntityKind::Circle(c) => ("circle", c.center.z),
|
||||
EntityKind::Arc(a) => ("arc", a.center.z),
|
||||
EntityKind::Point(p) => ("point", p.p.z),
|
||||
EntityKind::Solid(s) => ("solid", s.corners[0].z),
|
||||
EntityKind::Hatch(h) => ("hatch", n * h.elevation),
|
||||
EntityKind::Text(t) => ("text", t.insert.z),
|
||||
EntityKind::Line(l) => ("line", l.a.z),
|
||||
_ => ("other", f64::NAN),
|
||||
};
|
||||
(kind, z, n * e.common.thickness)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let d = read(text.as_bytes(), "m.dxf").unwrap();
|
||||
let mut want = vec![
|
||||
("polyline", -5.0, -2.0),
|
||||
("polyline", -5.0, 0.0),
|
||||
("circle", -5.0, -2.0),
|
||||
("arc", -5.0, 0.0),
|
||||
("point", 5.0, -2.0),
|
||||
("solid", -5.0, -2.0),
|
||||
("hatch", -5.0, 0.0),
|
||||
("text", -5.0, -2.0),
|
||||
("line", 3.0, -2.0),
|
||||
];
|
||||
let facing_up = [
|
||||
("polyline", 5.0, 2.0),
|
||||
("polyline", 5.0, 0.0),
|
||||
("circle", 5.0, 2.0),
|
||||
("arc", 5.0, 0.0),
|
||||
("point", 5.0, 2.0),
|
||||
("solid", 5.0, 2.0),
|
||||
("hatch", 5.0, 0.0),
|
||||
("text", 5.0, 2.0),
|
||||
("line", 3.0, 2.0),
|
||||
];
|
||||
want.extend(facing_up);
|
||||
want.extend(facing_up);
|
||||
assert_eq!(place(&d), want, "as read");
|
||||
let out = write(&d, "m.dxf").unwrap();
|
||||
assert_eq!(place(&read(&out, "m.dxf").unwrap()), want, "after a save");
|
||||
let pairs = dxf_pairs(std::str::from_utf8(&out).unwrap());
|
||||
let lines: Vec<_> = dxf_records(&pairs, "LINE").into_iter().map(|l| (group(l, "39"), group(l, "230"))).collect();
|
||||
assert_eq!(lines, [(Some("2.0"), Some("-1.0")), (Some("2.0"), None), (Some("2.0"), None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirrored_hatch_extrusion_flips_boundary() {
|
||||
// HATCH boundaries are OCS: the square (1,0)..(3,2) under extrusion (0,0,-1) lies at (-3,0)..(-1,2).
|
||||
@@ -2727,6 +2805,20 @@ fn tilted_hatch_turns_its_gradient() {
|
||||
assert!((g.angle - std::f64::consts::PI).abs() < 1e-9, "gradient angle {}", g.angle);
|
||||
}
|
||||
|
||||
/// A tilted polyline with a thickness, its normal pointing partly down Z, still extrudes toward -Z
|
||||
/// once it is drawn as seen from above and saved with no normal.
|
||||
#[test]
|
||||
fn tilted_thick_polyline_keeps_its_extrusion_side() {
|
||||
let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n39\n5\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\
|
||||
10\n1\n20\n0\n10\n3\n20\n2\n0\nENDSEC\n0\nEOF\n";
|
||||
let d = read(text.as_bytes(), "p.dxf").unwrap();
|
||||
let e = d.model.iter().next().unwrap();
|
||||
assert_eq!((e.common.thickness, e.common.extrusion), (-5.0, Vec3::Z));
|
||||
let back = roundtrip(&d);
|
||||
let e = back.model.iter().next().unwrap();
|
||||
assert_eq!((e.common.thickness, e.common.extrusion), (-5.0, Vec3::Z), "saved with no normal, it still extrudes toward -Z");
|
||||
}
|
||||
|
||||
/// A straight tilted LWPOLYLINE keeps its vertex widths (groups 40/41) on the projected vertices.
|
||||
#[test]
|
||||
fn tilted_straight_lwpolyline_keeps_its_widths() {
|
||||
@@ -2841,6 +2933,57 @@ fn tilted_lwpolyline_is_drawn_as_seen_from_above() {
|
||||
assert_eq!(p.vertices.iter().map(|v| v.bulge).collect::<Vec<_>>(), vec![1.0, 1.0]);
|
||||
}
|
||||
|
||||
/// A 2D POLYLINE (heavy polyline) in a tilted plane is drawn as seen from above, like a
|
||||
/// LWPOLYLINE: before, its OCS points were taken for world coordinates. With extrusion
|
||||
/// (0, 0.5, -√3/2) the OCS axes are x = (-1,0,0) and y = (0, √3/2, 1/2), and the elevation of 2
|
||||
/// moves the plane by twice the normal, (0, 1, -√3): the square (1,0)..(3,2) lies over
|
||||
/// (-3,1)..(-1,1+√3), its corners at a mean height of 1/2 - √3.
|
||||
#[test]
|
||||
fn tilted_2d_polyline_is_drawn_as_seen_from_above() {
|
||||
let square = |n: &str| {
|
||||
format!(
|
||||
"0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n2\n70\n1\n{n}\
|
||||
0\nVERTEX\n8\n0\n10\n1\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n2\n\
|
||||
0\nVERTEX\n8\n0\n10\n1\n20\n2\n0\nSEQEND\n0\nENDSEC\n0\nEOF\n"
|
||||
)
|
||||
};
|
||||
let d = read(square("210\n0\n220\n0.5\n230\n-0.8660254037844386\n").as_bytes(), "p.dxf").unwrap();
|
||||
let b = d.extents(&Space::Model);
|
||||
let r3 = 3f64.sqrt();
|
||||
for (got, want) in [(b.min.x, -3.0), (b.min.y, 1.0), (b.max.x, -1.0), (b.max.y, 1.0 + r3)] {
|
||||
assert!((got - want).abs() < 1e-9, "extents {b:?}");
|
||||
}
|
||||
let e = d.model.iter().next().unwrap();
|
||||
assert_eq!(e.common.extrusion, Vec3::Z, "its points are plan coordinates now");
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
|
||||
assert!((p.elevation - (0.5 - r3)).abs() < 1e-9, "the mean height of its corners: {}", p.elevation);
|
||||
// In plan and in the mirrored plane the polyline stays as it was: mirrored only in x.
|
||||
let plain = read(square("").as_bytes(), "p.dxf").unwrap();
|
||||
let b = plain.extents(&Space::Model);
|
||||
assert!((b.min.x - 1.0).abs() < 1e-9 && (b.max.y - 2.0).abs() < 1e-9, "extents {b:?}");
|
||||
let mirrored = read(square("210\n0\n220\n0\n230\n-1\n").as_bytes(), "p.dxf").unwrap();
|
||||
let b = mirrored.extents(&Space::Model);
|
||||
assert!((b.min.x + 3.0).abs() < 1e-9 && (b.max.x + 1.0).abs() < 1e-9, "extents {b:?}");
|
||||
assert_eq!(mirrored.model.iter().next().unwrap().common.extrusion, Vec3::new(0.0, 0.0, -1.0));
|
||||
}
|
||||
|
||||
/// A tilted 2D POLYLINE with an arc keeps its shape as seen from above: the half circle from
|
||||
/// (0,0) to (2,0) is flattened into its half ellipse, in plan x from -2 to 0 and reaching √3/2.
|
||||
#[test]
|
||||
fn tilted_2d_polyline_arc_is_flattened() {
|
||||
let text = "0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n0\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\
|
||||
0\nVERTEX\n8\n0\n10\n0\n20\n0\n42\n1\n0\nVERTEX\n8\n0\n10\n2\n20\n0\n0\nSEQEND\n0\nENDSEC\n0\nEOF\n";
|
||||
let d = read(text.as_bytes(), "p.dxf").unwrap();
|
||||
let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None });
|
||||
assert!(p.vertices.len() > 8 && p.vertices.iter().all(|v| v.bulge == 0.0), "{} vertices", p.vertices.len());
|
||||
let b = d.extents(&Space::Model);
|
||||
// Bulge 1 turns counter-clockwise from (0,0) to (2,0), so the arc runs below its chord, down
|
||||
// to OCS y -1: plan y -√3/2.
|
||||
for (got, want) in [(b.min.x, -2.0), (b.max.x, 0.0), (b.min.y, -(3f64.sqrt()) / 2.0), (b.max.y, 0.0)] {
|
||||
assert!((got - want).abs() < 5e-3, "extents {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The model extents of a one-loop solid HATCH whose edge boundary is `edges` (group 72 onwards).
|
||||
fn hatch_edge_extents(edges: &str) -> Bounds2 {
|
||||
let n = edges.matches("72\n").count();
|
||||
@@ -3552,6 +3695,44 @@ fn drawing_without_insunits_stays_unitless() {
|
||||
assert_eq!(insunits(&write_dxf(&Drawing::new_imperial())), Some("1".into()));
|
||||
}
|
||||
|
||||
/// Constraint groups with hostile node counts, truncated nodes and a registry that doesn't match
|
||||
/// the nodes are left as they are; nothing panics or loops for long.
|
||||
#[test]
|
||||
fn hostile_constraint_groups_never_panic() {
|
||||
use craft_dxf::Tag;
|
||||
let group = |rest: &[(i32, &str)]| {
|
||||
let mut t = vec![Tag::s(0, "ACDBASSOC2DCONSTRAINTGROUP"), Tag::s(100, "AcDbAssoc2dConstraintGroup"), Tag::s(360, "0"), Tag::s(90, "0")];
|
||||
t.extend(rest.iter().map(|(c, v)| Tag::s(*c, *v)));
|
||||
t
|
||||
};
|
||||
let many: Vec<(i32, &str)> = std::iter::repeat_n((90, "1"), 200_000).collect();
|
||||
let cases: Vec<Vec<Tag>> = vec![
|
||||
group(&[]),
|
||||
group(&[(90, "3"), (90, "0"), (90, "99999999999"), (290, "0")]),
|
||||
group(&[(90, "3"), (90, "0"), (90, "0"), (290, "0"), (90, "-5")]),
|
||||
group(&[(90, "3"), (90, "0"), (90, "0"), (290, "0"), (90, "100000"), (1, "AcFixedConstraint"), (90, "1")]),
|
||||
group(&[(90, "3"), (90, "0"), (90, "0"), (290, "0"), (90, "1"), (1, "AcFixedConstraint"), (90, "1"), (90, "1"), (90, "4")]),
|
||||
group(
|
||||
&[(90, "3"), (90, "0"), (90, "0"), (290, "0"), (90, "1"), (1, "AcFixedConstraint"), (90, "1")]
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(many)
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
vec![Tag::s(0, "ACDBASSOC2DCONSTRAINTGROUP")],
|
||||
];
|
||||
// Each group's content (code, value), unchanged after each mode: a rotation keeps the
|
||||
// length, and a second mode could rotate it back.
|
||||
let pairs = |t: &[Tag]| t.iter().map(|x| (x.code, x.str())).collect::<Vec<_>>();
|
||||
for mut tags in cases {
|
||||
let before = pairs(&tags);
|
||||
for modern in [false, true] {
|
||||
crate::dxf_raw::constraint_node_order(&mut tags, modern);
|
||||
assert_eq!(pairs(&tags), before, "modern: {modern}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_clips_a_primitive_beyond_the_coordinate_range() {
|
||||
let mut d = Drawing::new_metric();
|
||||
@@ -3711,6 +3892,144 @@ fn proxy_file() -> Vec<u8> {
|
||||
pairs.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::<String>().into_bytes()
|
||||
}
|
||||
|
||||
/// #3229: a file with a proxy object in the 2010 layout (as the DWG bridge brings it from a 2010
|
||||
/// DWG), with its class and a dictionary entry.
|
||||
/// A 2010 DXF with one proxy object (dictionary entry WIDGETS) whose string stream is `strings`
|
||||
/// long (group 162).
|
||||
fn proxy_2010_file(strings: &str) -> Vec<u8> {
|
||||
let text = String::from_utf8(write(&Drawing::new_metric(), "p.dxf").unwrap()).unwrap();
|
||||
let mut pairs = dxf_pairs(&text);
|
||||
let p = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
let classes = pairs.iter().position(|q| q.0 == "2" && q.1 == "CLASSES").unwrap() + 1;
|
||||
pairs.splice(
|
||||
classes..classes,
|
||||
[p("0", "CLASS"), p("1", "WIDGETX"), p("2", "AcDbWidgetX"), p("3", "ObjectDBX Classes"), p("90", "4095"), p("280", "1"), p("281", "0")],
|
||||
);
|
||||
let objects = pairs.iter().position(|q| q.0 == "2" && q.1 == "OBJECTS").unwrap();
|
||||
let nod = objects + 1;
|
||||
let after = nod + pairs[nod..].iter().position(|q| q.0 == "281").unwrap() + 1;
|
||||
pairs.splice(after..after, [p("3", "WIDGETS"), p("350", "AAA1")]);
|
||||
let nod_handle = pairs[nod + 1].1.clone();
|
||||
let proxy = [
|
||||
p("0", "ACAD_PROXY_OBJECT"),
|
||||
p("5", "AAA1"),
|
||||
p("330", &nod_handle),
|
||||
p("100", "AcDbProxyObject"),
|
||||
p("90", "499"),
|
||||
p("91", "500"),
|
||||
p("95", "393245"),
|
||||
p("70", "0"),
|
||||
p("162", strings),
|
||||
p("161", "303"),
|
||||
p("310", "00FF"),
|
||||
p("94", "0"),
|
||||
];
|
||||
let end = objects + pairs[objects..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap();
|
||||
pairs.splice(end..end, proxy);
|
||||
pairs.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::<String>().into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxies_take_the_layout_of_the_version_written() {
|
||||
let d = read(&proxy_2010_file("0"), "p.dxf").unwrap();
|
||||
let own = |version: Version| {
|
||||
let text = String::from_utf8(write_with(&d, "out.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap();
|
||||
let pairs = dxf_pairs(&text);
|
||||
let recs = dxf_records(&pairs, "ACAD_PROXY_OBJECT");
|
||||
let r = recs.first().expect("the proxy is kept");
|
||||
r.iter().skip_while(|q| q.1 != "AcDbProxyObject").skip(1).map(|q| q.0.clone()).collect::<Vec<_>>().join(" ")
|
||||
};
|
||||
// R2000: no 161/162 (ODA and BricsCAD refused the file), the data size is 93.
|
||||
assert_eq!(own(Version::R2000), "90 91 95 70 93 310 94");
|
||||
assert_eq!(own(Version::R2007), "90 91 95 70 96 93 310 94");
|
||||
assert_eq!(own(Version::R2010), "90 91 95 70 162 161 310 94");
|
||||
assert_eq!(own(Version::R2018), "90 91 71 97 70 162 161 310 94");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_with_a_string_stream_is_left_out_before_2007() {
|
||||
// Before 2007 a proxy's strings are part of its data: a separate stream has no form there.
|
||||
// The proxy and its dictionary entry are left out rather than written with half its data.
|
||||
let d = read(&proxy_2010_file("10"), "p.dxf").unwrap();
|
||||
assert_eq!(cadcraft_doc::foreign::proxies_dropped_before_2007(&d), [("ACAD_PROXY_OBJECT".to_string(), 1)].into_iter().collect());
|
||||
let pairs = |version: Version| {
|
||||
let text = String::from_utf8(write_with(&d, "out.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap();
|
||||
dxf_pairs(&text)
|
||||
};
|
||||
let entry = |p: &[(String, String)]| p.iter().any(|q| q.0 == "3" && q.1 == "WIDGETS");
|
||||
for version in [Version::R2000, Version::R2004] {
|
||||
let p = pairs(version);
|
||||
assert!(dxf_records(&p, "ACAD_PROXY_OBJECT").is_empty(), "{version:?}");
|
||||
assert!(!entry(&p), "{version:?}: the dictionary entry goes with it");
|
||||
}
|
||||
// From 2007 it is kept, with its string stream and its dictionary entry.
|
||||
let p = pairs(Version::R2007);
|
||||
let recs = dxf_records(&p, "ACAD_PROXY_OBJECT");
|
||||
assert_eq!(recs.first().and_then(|r| group(r, "96")), Some("10"));
|
||||
assert!(entry(&p));
|
||||
}
|
||||
|
||||
/// #3229 review: the loss a DXF before 2007 reports is what the writer leaves out for the string
|
||||
/// stream alone. A proxy no version writes (its class number names no class) is not counted, and
|
||||
/// the objects a dropped proxy owns (its extension dictionary and the XRECORD in it) are.
|
||||
#[test]
|
||||
fn proxies_lost_counts_what_the_string_stream_takes_with_it() {
|
||||
let lost = |d: &Drawing, v| crate::proxies_lost(d, v);
|
||||
// The records of the file written at `version` (the file gives kept objects new handles).
|
||||
let written = |d: &Drawing, version: Version| {
|
||||
let text = String::from_utf8(write_with(d, "out.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap();
|
||||
dxf_pairs(&text)
|
||||
};
|
||||
// Its class isn't written: every version leaves it out, so 2007 would not keep it either.
|
||||
let text = String::from_utf8(proxy_2010_file("10")).unwrap();
|
||||
assert_eq!(text.matches("\n91\n500\n").count(), 1, "the proxy's class number");
|
||||
let orphan = read(text.replacen("\n91\n500\n", "\n91\n777\n", 1).as_bytes(), "p.dxf").unwrap();
|
||||
assert!(!cadcraft_doc::foreign::proxies_dropped_before_2007(&orphan).is_empty(), "the proxy itself is counted");
|
||||
assert!(dxf_records(&written(&orphan, Version::R2007), "ACAD_PROXY_OBJECT").is_empty(), "no version writes it");
|
||||
assert_eq!(lost(&orphan, Version::R2000), std::collections::BTreeMap::new());
|
||||
// With an extension dictionary holding an XRECORD: all three go before 2007.
|
||||
let mut p = dxf_pairs(&text);
|
||||
let at = p.iter().position(|q| q.0 == "5" && q.1 == "AAA1").unwrap() + 1;
|
||||
let g = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
p.splice(at..at, [g("102", "{ACAD_XDICTIONARY"), g("360", "BBB1"), g("102", "}")]);
|
||||
// The proxy is the last object: its owned objects go after it.
|
||||
let objects_end = at + p[at..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap();
|
||||
p.splice(
|
||||
objects_end..objects_end,
|
||||
[
|
||||
g("0", "DICTIONARY"),
|
||||
g("5", "BBB1"),
|
||||
g("330", "AAA1"),
|
||||
g("100", "AcDbDictionary"),
|
||||
g("280", "1"),
|
||||
g("281", "1"),
|
||||
g("3", "WIDGETDATA"),
|
||||
g("350", "CCC1"),
|
||||
g("0", "XRECORD"),
|
||||
g("5", "CCC1"),
|
||||
g("330", "BBB1"),
|
||||
g("100", "AcDbXrecord"),
|
||||
g("280", "1"),
|
||||
g("1", "kept with the widget"),
|
||||
],
|
||||
);
|
||||
let bytes: Vec<u8> = p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::<String>().into_bytes();
|
||||
let d = read(&bytes, "p.dxf").unwrap();
|
||||
let held = |version| {
|
||||
let p = written(&d, version);
|
||||
let xrecord = dxf_records(&p, "XRECORD").iter().any(|r| group(r, "1") == Some("kept with the widget"));
|
||||
let dictionary = p.iter().any(|q| q.0 == "3" && q.1 == "WIDGETDATA");
|
||||
(dxf_records(&p, "ACAD_PROXY_OBJECT").len(), dictionary, xrecord)
|
||||
};
|
||||
assert_eq!(held(Version::R2007), (1, true, true), "2007 keeps all three");
|
||||
assert_eq!(held(Version::R2000), (0, false, false), "R2000 keeps none");
|
||||
let want: std::collections::BTreeMap<String, usize> =
|
||||
[("ACAD_PROXY_OBJECT", 1), ("DICTIONARY", 1), ("XRECORD", 1)].into_iter().map(|(k, n)| (k.to_string(), n)).collect();
|
||||
assert_eq!(lost(&d, Version::R2000), want);
|
||||
assert_eq!(lost(&d, Version::R2004), want);
|
||||
assert_eq!(lost(&d, Version::R2007), std::collections::BTreeMap::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxies_keep_their_class_when_classes_are_rewritten() {
|
||||
let d = read(&proxy_file(), "p.dxf").unwrap();
|
||||
@@ -3870,20 +4189,40 @@ fn non_unicode_names_pick_the_format_by_extension() {
|
||||
assert!(write(&d, name("dwt")).is_ok(), "a template is written as DWG");
|
||||
}
|
||||
|
||||
/// A SOLID hatch keeps its angle (52), scale (41) and double flag (77) through a save: the writer
|
||||
/// wrote them for pattern fills only.
|
||||
/// A solid or gradient HATCH goes from its pattern type (76) straight to its seed points (98), as
|
||||
/// AutoCAD 2024 writes it, even one read with an angle, scale and double flag: AutoCAD 2024 refuses
|
||||
/// a file whose solid HATCH has any of 52, 41 or 77 there ("Error: expected group code 98", the
|
||||
/// whole drawing discarded; measured). A pattern fill keeps all three.
|
||||
#[test]
|
||||
fn solid_hatch_keeps_angle_scale_and_double_flag() {
|
||||
fn solid_and_gradient_hatches_have_no_pattern_groups() {
|
||||
let src = "0\nSECTION\n2\nENTITIES\n0\nHATCH\n5\n40\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n2\nSOLID\n70\n1\n71\n0\n\
|
||||
91\n1\n92\n2\n72\n0\n73\n1\n93\n4\n10\n0\n20\n0\n10\n40\n20\n0\n10\n40\n20\n40\n10\n0\n20\n40\n97\n0\n\
|
||||
75\n0\n76\n1\n52\n30\n41\n2\n77\n0\n98\n0\n0\nENDSEC\n0\nEOF\n";
|
||||
let out = write_dxf(&read_dxf(src.as_bytes()).unwrap());
|
||||
let (mut d, _) = gradient_sample();
|
||||
for e in read_dxf(src.as_bytes()).unwrap().model.iter() {
|
||||
d.add(&Space::Model, e.common.clone(), e.kind.clone()).unwrap();
|
||||
}
|
||||
let mut pattern = hatches(&d)[0].clone();
|
||||
(pattern.pattern, pattern.solid, pattern.gradient, pattern.angle, pattern.scale) = ("ANSI31".into(), false, None, 30f64.to_radians(), 2.0);
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Hatch(pattern)).unwrap();
|
||||
let out = write_dxf(&d);
|
||||
let pairs = dxf_pairs(&out);
|
||||
let h = dxf_records(&pairs, "HATCH")[0];
|
||||
let records = dxf_records(&pairs, "HATCH");
|
||||
let (solid, pattern): (Vec<&[(String, String)]>, Vec<_>) = records.into_iter().partition(|h| group(h, "70") == Some("1"));
|
||||
assert_eq!((solid.len(), pattern.len()), (4, 1), "three from the sample, one read");
|
||||
for h in solid {
|
||||
let after = h.iter().position(|p| p.0 == "76").and_then(|k| h.get(k + 1)).map(|p| p.0.as_str());
|
||||
assert_eq!(after, Some("98"), "{h:?}");
|
||||
for code in ["52", "41", "77", "78"] {
|
||||
assert_eq!(group(h, code), None, "group {code}: {h:?}");
|
||||
}
|
||||
}
|
||||
let h = pattern[0];
|
||||
let f = |code: &str| group(h, code).and_then(|v| v.parse::<f64>().ok());
|
||||
assert!(f("52").is_some_and(|a| (a - 30.0).abs() < 1e-9), "{h:?}");
|
||||
assert!(f("41").is_some_and(|s| (s - 2.0).abs() < 1e-12), "{h:?}");
|
||||
assert_eq!(group(h, "77"), Some("0"), "{h:?}");
|
||||
assert!(group(h, "78").is_some(), "{h:?}");
|
||||
}
|
||||
|
||||
/// A layer state of CADCraft's own record from before states had a mask, a current layer and a
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! A kept 2D constraint group (`ACDBASSOC2DCONSTRAINTGROUP`, the geometric constraints of a
|
||||
//! parametric block) keeps its nodes through the DWG bridge and through DXF of another version.
|
||||
//! AutoCAD 2013 and later write a node's status after its connections, earlier versions right
|
||||
//! after its id; the group was written as read, so the bridge's R2000 DXF gave acadrust every
|
||||
//! node's status and connections from the wrong groups, and AutoCAD refused the DWG of a drawing
|
||||
//! with parametric blocks ("Error Decrypting Data").
|
||||
|
||||
// The DWG bridge and acadrust are unavailable on wasm and FreeBSD ARM64 (#2526).
|
||||
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use acadrust::objects::{AssociativeData, ObjectType};
|
||||
use cadcraft_io::{SaveOptions, Version, write_with};
|
||||
|
||||
/// A drawing of `acadver` whose named object dictionary holds a constraint group with two
|
||||
/// constraints: node 1 (status 1) connected to node 2, node 2 (status 2) connected to node 1.
|
||||
/// `modern` writes the nodes in the 2013+ order.
|
||||
fn dxf(acadver: &str, modern: bool) -> String {
|
||||
let node = |id: u32, status: u32, other: u32| {
|
||||
let (head, tail) = if modern { (String::new(), format!("70\n{status}\n")) } else { (format!("70\n{status}\n"), String::new()) };
|
||||
format!("90\n{id}\n{head}90\n1\n90\n{other}\n{tail}90\n0\n290\n0\n290\n1\n")
|
||||
};
|
||||
format!(
|
||||
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\n{acadver}\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nACDBASSOC2DCONSTRAINTGROUP\n2\nAcDbAssoc2dConstraintGroup\n3\nObjectDBX Classes\n90\n1025\n280\n0\n281\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n\
|
||||
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n3\nTESTCG\n350\n20\n\
|
||||
0\nACDBASSOC2DCONSTRAINTGROUP\n5\n20\n330\nC\n100\nAcDbAssocAction\n90\n2\n90\n0\n330\n0\n360\n0\n90\n2\n90\n45\n90\n0\n90\n0\n90\n0\n90\n0\n90\n0\n\
|
||||
100\nAcDbAssoc2dConstraintGroup\n90\n2\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n10\n1.0\n20\n0.0\n30\n0.0\n10\n0.0\n20\n1.0\n30\n0.0\n360\n0\n90\n0\n\
|
||||
90\n3\n90\n0\n90\n2\n90\n1\n90\n2\n290\n0\n90\n2\n1\nAcPerpendicularConstraint\n90\n1\n1\nAcPointCoincidenceConstraint\n90\n2\n{}{}\
|
||||
0\nENDSEC\n0\nEOF\n",
|
||||
node(1, 1, 2),
|
||||
node(2, 2, 1)
|
||||
)
|
||||
}
|
||||
|
||||
/// The (id, status, connections) of every non-root node of the document's constraint group.
|
||||
fn nodes(doc: &acadrust::CadDocument) -> Vec<(i32, u8, Vec<i32>)> {
|
||||
let group = doc.objects.values().find_map(|o| match o {
|
||||
ObjectType::Associative(a) => match &a.data {
|
||||
AssociativeData::ConstraintGroup(g) => Some(g.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
});
|
||||
let group = group.expect("the constraint group is written");
|
||||
group.nodes.iter().skip(1).map(|n| (n.node_id, n.status, n.connections.clone())).collect()
|
||||
}
|
||||
|
||||
fn expected() -> Vec<(i32, u8, Vec<i32>)> {
|
||||
vec![(1, 1, vec![2]), (2, 2, vec![1])]
|
||||
}
|
||||
|
||||
fn save(src: &str, name: &str, version: Version) -> Vec<u8> {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = cadcraft_io::read(src.as_bytes(), "a.dxf").expect("read");
|
||||
write_with(&d, name, &SaveOptions { version: Some(version), binary: false }).expect("write")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constraint_group_nodes_survive_the_dwg_bridge() {
|
||||
for (acadver, modern) in [("AC1032", true), ("AC1024", false)] {
|
||||
for version in [Version::R2018, Version::R2010, Version::R2004, Version::R2000] {
|
||||
let dwg = save(&dxf(acadver, modern), "a.dwg", version);
|
||||
let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg)).read().expect("acadrust reads the DWG");
|
||||
assert_eq!(nodes(&doc), expected(), "{acadver} drawing saved as {version:?} DWG");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constraint_group_nodes_follow_the_dxf_version() {
|
||||
for (acadver, modern) in [("AC1032", true), ("AC1024", false)] {
|
||||
for version in [Version::R2018, Version::R2013, Version::R2010, Version::R2000] {
|
||||
let out = save(&dxf(acadver, modern), "a.dxf", version);
|
||||
let doc = acadrust::DxfReader::from_reader(Cursor::new(out)).expect("dxf").read().expect("acadrust reads the DXF");
|
||||
assert_eq!(nodes(&doc), expected(), "{acadver} drawing saved as {version:?} DXF");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//! A hatch boundary stored in a DWG as an elliptic edge keeps its sweep: a circle (0 to 2π) stays a
|
||||
//! circle, so the hatch leaves the hole open. The DWG decoder writes the edge's angles in radians
|
||||
//! and DXF reads degrees, so the circle used to come out as an arc of 6.28 degrees.
|
||||
|
||||
// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DXF still works.
|
||||
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
|
||||
use acadrust::entities::{BoundaryEdge, BoundaryPath, BoundaryPathFlags, EllipticArcEdge, EntityType, Hatch, LineEdge};
|
||||
use acadrust::types::Vector2;
|
||||
use cadcraft_doc::EntityKind;
|
||||
|
||||
fn line(a: (f64, f64), b: (f64, f64)) -> BoundaryEdge {
|
||||
BoundaryEdge::Line(LineEdge { start: Vector2::new(a.0, a.1), end: Vector2::new(b.0, b.1) })
|
||||
}
|
||||
|
||||
/// A DWG with a pattern hatch over a 100 x 100 square with a round hole of radius 10 stored as an
|
||||
/// elliptic edge from `start` to `end` radians.
|
||||
fn dwg_with_hole(start: f64, end: f64) -> Vec<u8> {
|
||||
let mut hatch = Hatch::new();
|
||||
hatch.is_solid = false;
|
||||
let mut outer = BoundaryPath::new();
|
||||
outer.flags = BoundaryPathFlags::EXTERNAL;
|
||||
outer.edges =
|
||||
vec![line((0.0, 0.0), (100.0, 0.0)), line((100.0, 0.0), (100.0, 100.0)), line((100.0, 100.0), (0.0, 100.0)), line((0.0, 100.0), (0.0, 0.0))];
|
||||
let mut hole = BoundaryPath::new();
|
||||
hole.flags = BoundaryPathFlags::DEFAULT;
|
||||
hole.edges = vec![BoundaryEdge::EllipticArc(EllipticArcEdge {
|
||||
center: Vector2::new(50.0, 50.0),
|
||||
major_axis_endpoint: Vector2::new(-10.0, 0.0),
|
||||
minor_axis_ratio: 1.0,
|
||||
start_angle: start,
|
||||
end_angle: end,
|
||||
counter_clockwise: true,
|
||||
})];
|
||||
hatch.paths = vec![outer, hole];
|
||||
let mut doc = acadrust::CadDocument::new();
|
||||
doc.add_entity(EntityType::Hatch(Box::new(hatch))).unwrap();
|
||||
acadrust::DwgWriter::write_to_vec(&doc).unwrap()
|
||||
}
|
||||
|
||||
/// The x range of the hatch's hole, from the bulge polyline the drawing keeps for it.
|
||||
fn hole_extent(dwg: &[u8]) -> (f64, f64) {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = cadcraft_io::read(dwg, "hole.dwg").unwrap();
|
||||
let EntityKind::Hatch(h) = &d.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).expect("the hatch").kind else { panic!("hatch") };
|
||||
let hole = h.loops.iter().find(|l| !l.outer).expect("the hole's loop");
|
||||
let pl = cadcraft_geom::Polyline { vertices: hole.vertices.clone(), closed: true };
|
||||
let mut pts = Vec::new();
|
||||
for s in pl.segments() {
|
||||
s.tessellate(0.01, &mut pts);
|
||||
}
|
||||
let (min, max) = pts.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.x), hi.max(p.x)));
|
||||
(min, max)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_stored_as_an_elliptic_edge_stays_a_circle() {
|
||||
let (min, max) = hole_extent(&dwg_with_hole(0.0, std::f64::consts::TAU));
|
||||
// The hole spans its whole diameter: x from 40 to 60. Read as 6.28 degrees it spanned about 0.07.
|
||||
assert!(max - min > 19.9 && max - min < 20.1, "the hole spans {} in x", max - min);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quarter_arc_stored_as_an_elliptic_edge_keeps_its_quarter() {
|
||||
let (min, max) = hole_extent(&dwg_with_hole(0.0, std::f64::consts::FRAC_PI_2));
|
||||
// From the point at 0 degrees (60, 50) to the one at 90 degrees (50, 60), closed by a chord: x spans 10.
|
||||
assert!(max - min > 9.9 && max - min < 10.5, "the arc spans {} in x", max - min);
|
||||
}
|
||||
@@ -220,3 +220,25 @@ fn a_dwg_keeps_a_sat_text_region_only_before_2013() {
|
||||
assert!(holds_sat(cadcraft_io::Version::R2010), "2010 keeps the SAT text");
|
||||
assert!(!holds_sat(cadcraft_io::Version::R2018), "2018 comes back without it");
|
||||
}
|
||||
|
||||
/// The other way round: a solid whose geometry is only in the data store (a 2013+ file) has no
|
||||
/// SAT text to write to a DXF of 2010 or earlier, which has no data store. Writing it would leave
|
||||
/// an empty 2013-style record (290/2 groups) other programs reject, so it is left out and counted
|
||||
/// there, and kept in 2013 and later (#2334).
|
||||
#[test]
|
||||
fn data_store_solids_are_left_out_of_dxf_2010_and_earlier() {
|
||||
let d = cadcraft_io::read_dxf(dxf().as_bytes()).unwrap();
|
||||
let text = |v: cadcraft_io::Version| {
|
||||
let out = cadcraft_io::write_with(&d, "x.dxf", &cadcraft_io::SaveOptions { version: Some(v), binary: false }).unwrap();
|
||||
String::from_utf8(out).unwrap().replace("\r\n", "\n")
|
||||
};
|
||||
let solids = |t: &str| t.matches("\n0\n3DSOLID\n").count() + t.matches("\n 0\n3DSOLID\n").count();
|
||||
assert_eq!(cadcraft_doc::foreign::acis_dropped(&d, false), [("3DSOLID".to_string(), 2)].into());
|
||||
assert!(cadcraft_doc::foreign::acis_dropped(&d, true).is_empty());
|
||||
for v in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] {
|
||||
let t = text(v);
|
||||
assert_eq!(solids(&t), 0, "{v:?} leaves them out");
|
||||
assert!(!t.contains("AcDbModelerGeometry"), "{v:?} writes no empty modeler record");
|
||||
}
|
||||
assert_eq!(solids(&text(cadcraft_io::Version::R2018)), 2, "2018 keeps them");
|
||||
}
|
||||
|
||||
@@ -284,3 +284,104 @@ fn an_unedited_dimension_keeps_the_block_it_was_read_with() {
|
||||
let again = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&edited).as_bytes()).unwrap();
|
||||
assert_eq!(circles(&again).0, 0);
|
||||
}
|
||||
|
||||
/// Other programs name a dimension's picture block as they like (DXF group 2 may name any
|
||||
/// block; some exporters write `DIMBLOCK1-<view>`). An unedited dimension keeps that block as
|
||||
/// read, under its own name, as a `*D` one does; no `*D` copy is made next to it (#3299).
|
||||
#[test]
|
||||
fn an_unedited_dimension_keeps_a_block_with_any_name() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
use cadcraft_doc::{Circle, Text};
|
||||
const NAME: &str = "DIMBLOCK1-PLAN";
|
||||
let mut d = Drawing::new_metric();
|
||||
// The picture as the other program drew it: its own text format and a circle CADCraft never
|
||||
// generates for a linear dimension.
|
||||
let mut b = Block::new(NAME);
|
||||
for kind in [
|
||||
EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) }),
|
||||
EntityKind::Circle(Circle { center: Vec3::new(5.0, 3.0, 0.0), radius: 0.25 }),
|
||||
EntityKind::Text(Text {
|
||||
insert: Vec3::new(5.0, 3.5, 0.0),
|
||||
align_pt: None,
|
||||
height: 2.5,
|
||||
value: "10,00".into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: Default::default(),
|
||||
valign: Default::default(),
|
||||
}),
|
||||
] {
|
||||
let h = d.new_handle();
|
||||
b.entities.push(Entity::new(h, kind));
|
||||
}
|
||||
b.base = Vec3::new(1.0, 2.0, 0.0);
|
||||
d.blocks.insert(NAME.into(), Arc::new(b));
|
||||
let mut dm = linear([0.0, 0.0], [10.0, 0.0], [5.0, 3.0]);
|
||||
dm.block = Some(NAME.into());
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap();
|
||||
|
||||
// (block the dimension names, anonymous, base point, its circles, its texts)
|
||||
let picture = |d: &Drawing| {
|
||||
let Some(EntityKind::Dimension(dm)) = d.entity(h).map(|e| &e.kind) else { panic!("dimension lost") };
|
||||
let name = dm.block.clone().unwrap_or_default();
|
||||
let blk = d.block(&name).unwrap();
|
||||
let circles = blk.entities.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
let texts: Vec<String> =
|
||||
blk.entities.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.value.clone()) } else { None }).collect();
|
||||
(name, blk.anonymous, blk.base, circles, texts)
|
||||
};
|
||||
let kept = (NAME.to_string(), false, Vec3::new(1.0, 2.0, 0.0), 1, vec!["10,00".to_string()]);
|
||||
let dxf = cadcraft_io::write_dxf(&d);
|
||||
assert_eq!(picture(&cadcraft_io::read_dxf(dxf.as_bytes()).unwrap()), kept, "DXF save");
|
||||
assert!(dim_blocks(&dxf).is_empty(), "no *D copy is written: {:?}", dim_blocks(&dxf));
|
||||
let dwg = cadcraft_io::read(&cadcraft_io::write(&d, "a.dwg").unwrap(), "a.dwg").unwrap();
|
||||
assert_eq!(picture(&dwg), kept, "DWG save");
|
||||
|
||||
// Edited (edits drop the link): regenerated from the dimension, as before.
|
||||
let mut edited = d.clone();
|
||||
edited
|
||||
.modify_entity(h, |e| {
|
||||
if let EntityKind::Dimension(dm) = &mut e.kind {
|
||||
dm.block = None;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let again = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&edited).as_bytes()).unwrap();
|
||||
let (name, _, _, circles, texts) = picture(&again);
|
||||
assert!(name.starts_with("*D") && circles == 0 && !texts.contains(&"10,00".to_string()), "edited: {name} {circles} {texts:?}");
|
||||
}
|
||||
|
||||
/// A block with another name that a dimension names keeps its record's properties and its
|
||||
/// description through a save; when it is empty the picture is regenerated in world coordinates,
|
||||
/// so the block is written at the origin, not at the read base point, which would shift it.
|
||||
#[test]
|
||||
fn a_kept_dimension_block_with_another_name_keeps_its_properties_and_an_empty_one_is_at_the_origin() {
|
||||
const NAME: &str = "DIMBLOCK2-PLAN";
|
||||
let build = |with_picture: bool| {
|
||||
let mut d = Drawing::new_metric();
|
||||
let mut b = Block::new(NAME);
|
||||
if with_picture {
|
||||
let h = d.new_handle();
|
||||
b.entities.push(Entity::new(h, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) })));
|
||||
}
|
||||
b.base = Vec3::new(1.0, 2.0, 0.0);
|
||||
b.description = "picture of a plan dimension".into();
|
||||
b.units = 4;
|
||||
b.explodable = false;
|
||||
d.blocks.insert(NAME.into(), Arc::new(b));
|
||||
let mut dm = linear([0.0, 0.0], [10.0, 0.0], [5.0, 3.0]);
|
||||
dm.block = Some(NAME.into());
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap();
|
||||
d
|
||||
};
|
||||
let back = |d: &Drawing| {
|
||||
let read = cadcraft_io::read_dxf(cadcraft_io::write_dxf(d).as_bytes()).unwrap();
|
||||
let b = read.block(NAME).expect("the named block is written").as_ref().clone();
|
||||
(b.base, b.description, b.units, b.explodable, b.entities.is_empty())
|
||||
};
|
||||
let props = |base: Vec3| (base, "picture of a plan dimension".to_string(), 4u8, false, false);
|
||||
assert_eq!(back(&build(true)), props(Vec3::new(1.0, 2.0, 0.0)), "kept picture");
|
||||
assert_eq!(back(&build(false)), props(Vec3::ZERO), "regenerated picture");
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The anonymous `*D` block written for a dimension (what other programs draw) holds its text at
|
||||
//! the height it is drawn at: the dimension's overrides and DIMSCALE (0 = the drawing's) count
|
||||
//! (issue #367). Angular text also keeps its decimal separator in the stored block (#1646).
|
||||
//! (issue #367). Angular text also keeps its decimal separator in the stored block (#1646), and
|
||||
//! the style's DIMPOST reaches angular dimensions' blocks too (#1653).
|
||||
|
||||
use cadcraft_doc::{Common, DimKind, DimStyle, Dimension, Drawing, EntityKind, Space};
|
||||
use cadcraft_geom::Vec3;
|
||||
@@ -130,3 +131,98 @@ fn dwg_angular_block_text_keeps_the_decimal_separator() {
|
||||
assert_eq!(texts, [expected], "DIMDSEP override: {separator_override:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The group 1 (contents) values of every MTEXT in the BLOCKS section, in file order.
|
||||
fn block_mtext_contents(dxf: &str) -> Vec<String> {
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
let t: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect();
|
||||
let blocks = t.iter().position(|&(c, v)| c == "2" && v == "BLOCKS").unwrap();
|
||||
let end_blocks = blocks + t[blocks..].iter().position(|&(c, v)| c == "0" && v == "ENDSEC").unwrap();
|
||||
let mut out = Vec::new();
|
||||
let mut i = blocks;
|
||||
while let Some(k) = t[i..end_blocks].iter().position(|&(c, v)| c == "0" && v == "MTEXT") {
|
||||
let start = i + k;
|
||||
let end = t[start + 1..end_blocks].iter().position(|&(c, _)| c == "0").map_or(end_blocks, |n| start + 1 + n);
|
||||
// Contents are group 1 (the last chunk) after any 250-char group 3 chunks.
|
||||
out.push(t[start + 1..end].iter().filter(|&&(c, _)| c == "3" || c == "1").map(|&(_, v)| v).collect());
|
||||
i = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An angular dimension whose style sets DIMPOST `post` and one decimal place for angles.
|
||||
fn posted_angular_drawing(kind: DimKind, points: [Vec3; 5], post: &str) -> Drawing {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.dim_styles.iter_mut().for_each(|s| {
|
||||
s.post = post.into();
|
||||
s.angular_decimals = 1;
|
||||
});
|
||||
let [p13, p14, p15, p16, defpt] = points;
|
||||
let dm = Dimension {
|
||||
kind,
|
||||
defpt,
|
||||
text_mid: Vec3::ZERO,
|
||||
p13,
|
||||
p14,
|
||||
p15,
|
||||
p16,
|
||||
text: String::new(),
|
||||
style: "Standard".into(),
|
||||
measurement: 0.0,
|
||||
text_rotation: 0.0,
|
||||
user_text_pos: false,
|
||||
block: None,
|
||||
overrides: Default::default(),
|
||||
assoc: Vec::new(),
|
||||
marks: Default::default(),
|
||||
insertion_point: Vec3::ZERO,
|
||||
};
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// The DXF text of the drawing's one dimension block.
|
||||
fn dxf_block_text(d: &Drawing) -> String {
|
||||
let mut texts = block_mtext_contents(&cadcraft_io::write_dxf(d));
|
||||
assert_eq!(texts.len(), 1, "{texts:?}");
|
||||
texts.remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimpost_reaches_three_point_and_two_line_angular_dimension_blocks() {
|
||||
// Vertex p15 at the origin, legs through p13 (0°) and p14 (90°), the arc through defpt.
|
||||
let three_point = posted_angular_drawing(
|
||||
DimKind::Angular3P,
|
||||
[Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::ZERO, Vec3::ZERO, Vec3::new(3.0, 3.0, 0.0)],
|
||||
"<> m",
|
||||
);
|
||||
// The DXF is ASCII: the degree sign is its `\U+00B0` escape.
|
||||
assert_eq!(dxf_block_text(&three_point), "90.0\\U+00B0 m");
|
||||
// Lines p13-p14 (along +X) and defpt-p15 (45°), the arc through p16.
|
||||
let two_line = posted_angular_drawing(
|
||||
DimKind::Angular,
|
||||
[Vec3::ZERO, Vec3::new(10.0, 0.0, 0.0), Vec3::new(15.0, 15.0, 0.0), Vec3::new(4.0, 1.5, 0.0), Vec3::new(-5.0, -5.0, 0.0)],
|
||||
"<> m",
|
||||
);
|
||||
assert_eq!(dxf_block_text(&two_line), "45.0\\U+00B0 m");
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn dwg_angular_block_text_keeps_dimpost() {
|
||||
use cadcraft_io::{SaveOptions, Version};
|
||||
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
|
||||
// Vertex p15 at the origin, legs through p13 (0°) and p14 (90°), the arc through defpt.
|
||||
let d = posted_angular_drawing(
|
||||
DimKind::Angular3P,
|
||||
[Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::ZERO, Vec3::ZERO, Vec3::new(3.0, 3.0, 0.0)],
|
||||
"<> m",
|
||||
);
|
||||
let dwg = cadcraft_io::write_with(&d, "case.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap();
|
||||
let from_dwg = String::from_utf8(craft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap();
|
||||
let mut texts = block_mtext_contents(&from_dwg);
|
||||
assert_eq!(texts.len(), 1, "{texts:?}");
|
||||
assert_eq!(texts.remove(0), "90.0° m");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! #3227: saving kept the layout's plot flags only for the bits CADCraft models and forced 512
|
||||
//! (plot paper space last), 32 (plot with plot styles) and 16 (standard scale) on, so a layout
|
||||
//! with flags 0 came back as 560, in DXF and in DWG.
|
||||
|
||||
use cadcraft_doc::{Drawing, Layout, PageSetup};
|
||||
use cadcraft_io::{read, write};
|
||||
|
||||
/// A drawing with layout SHEET read with plot layout `flags` (lineweights, centring and display
|
||||
/// plot styles follow them, as the reader sets them).
|
||||
fn drawing(flags: i64) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut l = Layout::new("SHEET", 1);
|
||||
l.page = PageSetup {
|
||||
lineweights: flags & 128 != 0,
|
||||
center: flags & 4 != 0,
|
||||
show_plot_styles: flags & 2 != 0,
|
||||
file_plot_flags: Some(flags),
|
||||
..PageSetup::default()
|
||||
};
|
||||
d.layouts.push(l);
|
||||
d
|
||||
}
|
||||
|
||||
/// The plot layout flags of SHEET after saving `d` as `name` and reading it back.
|
||||
fn flags_after_save(d: &Drawing, name: &str) -> Option<i64> {
|
||||
let bytes = write(d, name).unwrap();
|
||||
let back = read(&bytes, name).unwrap();
|
||||
back.layouts.iter().find(|l| l.name == "SHEET")?.page.file_plot_flags
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plot_layout_flags_are_saved_as_read() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
for name in ["sheet.dxf", "sheet.dwg"] {
|
||||
for flags in [0, 176, 560, 688] {
|
||||
assert_eq!(flags_after_save(&drawing(flags), name), Some(flags), "{name}: flags {flags}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_standard_scale_keeps_its_flag_and_choice() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
// Flags 176 with standard scale 25 (1:50): the scale is 0.02, not 1:1, and still standard.
|
||||
let mut d = drawing(176);
|
||||
let page = &mut d.layouts.last_mut().unwrap().page;
|
||||
page.scale = 0.02;
|
||||
page.file_standard_scale = Some((25, 0.02));
|
||||
for name in ["sheet.dxf", "sheet.dwg"] {
|
||||
let back = read(&write(&d, name).unwrap(), name).unwrap();
|
||||
let page = &back.layouts.iter().find(|l| l.name == "SHEET").unwrap().page;
|
||||
assert_eq!(page.file_plot_flags, Some(176), "{name}");
|
||||
assert_eq!(page.file_standard_scale, Some((25, 0.02)), "{name}");
|
||||
}
|
||||
// A scale changed after reading is a custom one: 16 is cleared and the choice dropped.
|
||||
d.layouts.last_mut().unwrap().page.scale = 0.05;
|
||||
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(160));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_still_decides_the_bits_cadcraft_models() {
|
||||
// Lineweights turned on and a custom scale chosen after reading flags 16: 128 is set and the
|
||||
// standard scale bit cleared, the rest kept.
|
||||
let mut d = drawing(16 | 512);
|
||||
let page = &mut d.layouts.last_mut().unwrap().page;
|
||||
page.lineweights = true;
|
||||
page.scale = 0.02;
|
||||
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128));
|
||||
// A page made in CADCraft keeps the defaults (plot paper space last, plot with plot styles,
|
||||
// standard scale, lineweights).
|
||||
let mut d = drawing(0);
|
||||
d.layouts.last_mut().unwrap().page = PageSetup::default();
|
||||
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128 | 32 | 16));
|
||||
}
|
||||
@@ -36,6 +36,7 @@ mod helix_roundtrip;
|
||||
mod layer_states_acad;
|
||||
mod layout_limits_roundtrip;
|
||||
mod layout_paper_units;
|
||||
mod layout_plot_flags;
|
||||
mod layout_plot_window;
|
||||
mod leader_vertex_elevation;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -68,6 +69,8 @@ mod plot_styles;
|
||||
mod polyface_roundtrip;
|
||||
mod portable_fonts;
|
||||
mod region_roundtrip;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod render_settings_version;
|
||||
mod roundtrip;
|
||||
mod roundtrip_audit;
|
||||
mod skipped_records;
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! Render settings store their `AcDbRenderSettings` class version in the form of the file's
|
||||
//! version: a 2013+ file stores it one higher (a 2013 file stores a rapid RT one one lower), as
|
||||
//! acadrust reads and writes them. A kept object carries the form of the file it came from; written
|
||||
//! into a file declaring another version, it takes that version's form. The DWG bridge is an R2000
|
||||
//! DXF for a 2018 DWG: without this, a 2018 drawing's MENTALRAYRENDERSETTINGS went in with the 2018
|
||||
//! form, the DWG writer raised it once more, and BricsCAD refused the DWG ("Object improperly
|
||||
//! read", #907).
|
||||
|
||||
use cadcraft_io::{SaveOptions, Version};
|
||||
|
||||
/// A DXF of `version` with a named object dictionary, its render settings dictionary and one
|
||||
/// mental ray render settings object whose `AcDbRenderSettings` class version is `class_version`.
|
||||
fn dxf(version: &str, kind: &str, class_version: i64) -> String {
|
||||
let body = match kind {
|
||||
"MENTALRAYRENDERSETTINGS" => {
|
||||
"100\nAcDbMentalRayRenderSettings\n90\n2\n90\n0\n90\n1\n70\n2\n40\n3.0\n40\n3.0\n40\n0.05\n40\n0.05\n40\n0.05\n40\n0.05\n\
|
||||
70\n0\n290\n0\n290\n1\n90\n5\n90\n5\n90\n5\n290\n0\n90\n500\n290\n0\n40\n1.0\n90\n10000\n90\n5\n90\n5\n90\n5\n290\n0\n\
|
||||
90\n200\n290\n0\n290\n0\n290\n0\n40\n0.1\n40\n1.0\n40\n1500.0\n70\n0\n70\n0\n40\n10.0\n70\n0\n70\n0\n290\n0\n1\n\n\
|
||||
90\n128\n70\n0\n90\n1048\n290\n0\n40\n1.0\n"
|
||||
}
|
||||
_ => "",
|
||||
};
|
||||
let cpp = match kind {
|
||||
"MENTALRAYRENDERSETTINGS" => "AcDbMentalRayRenderSettings",
|
||||
"RAPIDRTRENDERSETTINGS" => "AcDbRapidRTRenderSettings",
|
||||
_ => "AcDbRenderSettings",
|
||||
};
|
||||
format!(
|
||||
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\n{version}\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\n{kind}\n2\n{cpp}\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n\
|
||||
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\
|
||||
0\n{kind}\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n{class_version}\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n{body}\
|
||||
0\nENDSEC\n0\nEOF\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// The `AcDbRenderSettings` class version of the `kind` object in DXF text.
|
||||
fn class_version(text: &str, kind: &str) -> Option<i64> {
|
||||
let l: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = l.windows(2).position(|w| w == ["0", kind])?;
|
||||
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
|
||||
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
|
||||
}
|
||||
|
||||
fn written(d: &cadcraft_doc::Drawing, version: Version) -> String {
|
||||
String::from_utf8(cadcraft_io::write_with(d, "x.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_settings_class_version_takes_the_declared_versions_form() {
|
||||
let kind = "MENTALRAYRENDERSETTINGS";
|
||||
// From a 2018 file (stored 2 = class version 1 in the 2013+ form).
|
||||
let d = cadcraft_io::read_dxf(dxf("AC1032", kind, 2).as_bytes()).unwrap();
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2), "same version: as read");
|
||||
assert_eq!(class_version(&written(&d, Version::R2013), kind), Some(2));
|
||||
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1), "2000 form: one lower");
|
||||
assert_eq!(class_version(&written(&d, Version::R2010), kind), Some(1));
|
||||
// From a 2000 file (stored 1), written as 2018: one higher.
|
||||
let d = cadcraft_io::read_dxf(dxf("AC1015", kind, 1).as_bytes()).unwrap();
|
||||
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
|
||||
// Rapid RT settings: the 2013 file alone stores one lower.
|
||||
let kind = "RAPIDRTRENDERSETTINGS";
|
||||
let d = cadcraft_io::read_dxf(dxf("AC1027", kind, 1).as_bytes()).unwrap();
|
||||
assert_eq!(class_version(&written(&d, Version::R2013), kind), Some(1));
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
|
||||
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(2));
|
||||
}
|
||||
|
||||
/// A file that declares no `$ACADVER` gives no source form: its kept objects are written as read,
|
||||
/// not as if the new drawing's 2018 were their form.
|
||||
#[test]
|
||||
fn render_settings_without_a_declared_version_are_written_as_read() {
|
||||
let kind = "MENTALRAYRENDERSETTINGS";
|
||||
let text = dxf("AC1032", kind, 1).replace("9\n$ACADVER\n1\nAC1032\n", "");
|
||||
assert!(!text.contains("$ACADVER"));
|
||||
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
assert_eq!(d.foreign.version, None);
|
||||
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(1));
|
||||
}
|
||||
|
||||
/// Through the DWG bridge (an R2000 DXF for a 2018 DWG) and back, the class version is what the
|
||||
/// 2018 file had: before, it came back one higher each time, and BricsCAD refused the DWG.
|
||||
#[test]
|
||||
fn render_settings_class_version_survives_the_dwg_bridge() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let kind = "MENTALRAYRENDERSETTINGS";
|
||||
let d = cadcraft_io::read_dxf(dxf("AC1032", kind, 2).as_bytes()).unwrap();
|
||||
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
|
||||
let back = cadcraft_io::read(&dwg, "x.dwg").unwrap();
|
||||
assert_eq!(class_version(&written(&back, Version::R2018), kind), Some(2), "{}", written(&back, Version::R2018));
|
||||
let dwg = cadcraft_io::write(&back, "x.dwg").unwrap();
|
||||
let again = cadcraft_io::read(&dwg, "x.dwg").unwrap();
|
||||
assert_eq!(class_version(&written(&again, Version::R2018), kind), Some(2));
|
||||
}
|
||||
|
||||
/// The conversion mirrors how acadrust stores the value, so it is checked against acadrust itself:
|
||||
/// acadrust reads the fixture and writes it in each version, and CADCraft, reading any of those
|
||||
/// files and saving it in any version, stores what acadrust stores for that version. If acadrust
|
||||
/// changes the encoding, this fails before the DWG bridge drifts.
|
||||
#[test]
|
||||
fn render_settings_class_version_matches_what_acadrust_writes() {
|
||||
use acadrust::DxfVersion;
|
||||
let versions = [
|
||||
(DxfVersion::AC1015, Version::R2000),
|
||||
(DxfVersion::AC1024, Version::R2010),
|
||||
(DxfVersion::AC1027, Version::R2013),
|
||||
(DxfVersion::AC1032, Version::R2018),
|
||||
];
|
||||
// As a 2018 file stores them: mental ray one higher than its class version, rapid RT as is.
|
||||
for (kind, stored) in [("MENTALRAYRENDERSETTINGS", 2), ("RAPIDRTRENDERSETTINGS", 2)] {
|
||||
let source = std::io::Cursor::new(dxf("AC1032", kind, stored).into_bytes());
|
||||
let mut doc = acadrust::DxfReader::from_reader(source).unwrap().read().unwrap();
|
||||
let by_acadrust: Vec<(Version, String)> = versions
|
||||
.iter()
|
||||
.map(|(theirs, ours)| {
|
||||
doc.version = *theirs;
|
||||
(*ours, String::from_utf8(acadrust::DxfWriter::new(&doc).write_to_vec().unwrap()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let forms: Vec<Option<i64>> = by_acadrust.iter().map(|(_, text)| class_version(text, kind)).collect();
|
||||
let expected = if kind == "RAPIDRTRENDERSETTINGS" { [2, 2, 1, 2] } else { [1, 1, 2, 2] };
|
||||
assert_eq!(forms, expected.map(Some), "{kind}: acadrust's own forms for 2000, 2010, 2013, 2018");
|
||||
for (read_from, text) in &by_acadrust {
|
||||
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
for ((declared, _), form) in by_acadrust.iter().zip(&forms) {
|
||||
assert_eq!(class_version(&written(&d, *declared), kind), *form, "{kind}: read from {read_from:?}, saved as {declared:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -257,7 +257,8 @@ pub(super) fn assert_layouts(a: &Drawing, b: &Drawing, context: &str) {
|
||||
let back = b.layouts.iter().find(|l| l.name == layout.name).expect("layout must survive");
|
||||
assert_eq!(back.tab_order, layout.tab_order, "{context}.{}.tab_order", layout.name);
|
||||
// The groups 44, 45 and 73 the file stored are provenance, not a setting.
|
||||
let setting = |p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, ..p.clone() };
|
||||
let setting =
|
||||
|p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..p.clone() };
|
||||
assert_eq!(setting(&back.page), setting(&layout.page), "{context}.{}.page", layout.name);
|
||||
assert_eq!(back.view, layout.view, "{context}.{}.view", layout.name);
|
||||
compare::entities(a, b, &layout.entities, &back.entities, &format!("{context}.layout[{}]", layout.name));
|
||||
|
||||
@@ -112,7 +112,7 @@ fn layout_page_setup_and_paper_view_round_trip() {
|
||||
for (a, b) in d.layouts.iter().zip(&r.layouts) {
|
||||
assert_eq!(a.name, b.name);
|
||||
// The groups 44, 45 and 73 the file stored are provenance, not a setting.
|
||||
let read = cadcraft_doc::PageSetup { file_paper: None, ..b.page.clone() };
|
||||
let read = cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..b.page.clone() };
|
||||
assert_eq!(a.page, read, "{}", a.name);
|
||||
assert_eq!(a.view, b.view, "{}", a.name);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! The registered applications (APPID) of a file are saved back, in DXF and in DWG, save after
|
||||
//! save, also those no xdata names.
|
||||
|
||||
use cadcraft_doc::Drawing;
|
||||
use cadcraft_io::{read, read_dxf, write, write_dxf};
|
||||
|
||||
/// The records of a DXF: each `(code, value)` from its `0` group on.
|
||||
fn records(text: &str) -> Vec<Vec<(i32, String)>> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let mut out: Vec<Vec<(i32, String)>> = Vec::new();
|
||||
for chunk in lines.chunks(2) {
|
||||
let [code, value] = chunk else { break };
|
||||
let Ok(c) = code.trim().parse::<i32>() else { continue };
|
||||
let pair = (c, value.trim().to_string());
|
||||
if c == 0 {
|
||||
out.push(vec![pair]);
|
||||
} else if let Some(r) = out.last_mut() {
|
||||
r.push(pair);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The value of the record's first group `code`.
|
||||
fn value(r: &[(i32, String)], code: i32) -> Option<&str> {
|
||||
r.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// A file whose APPID table has `Other_App` (handle 7A00), which no xdata names; with `xdata`,
|
||||
/// a line's xdata names it as `OTHER_APP`.
|
||||
fn source(xdata: bool) -> String {
|
||||
let mut out = String::new();
|
||||
let mut put = |c: i32, v: &str| out.push_str(&format!("{c:>3}\n{v}\n"));
|
||||
for r in records(&write_dxf(&Drawing::new_metric())) {
|
||||
for (c, v) in &r {
|
||||
put(*c, v);
|
||||
}
|
||||
if xdata && r[0].1 == "SECTION" && value(&r, 2) == Some("ENTITIES") {
|
||||
for (c, v) in [
|
||||
(0, "LINE"),
|
||||
(5, "7A01"),
|
||||
(100, "AcDbEntity"),
|
||||
(8, "0"),
|
||||
(100, "AcDbLine"),
|
||||
(10, "0"),
|
||||
(20, "0"),
|
||||
(30, "0"),
|
||||
(11, "10"),
|
||||
(21, "0"),
|
||||
(31, "0"),
|
||||
(1001, "OTHER_APP"),
|
||||
(1000, "x"),
|
||||
] {
|
||||
put(c, v);
|
||||
}
|
||||
}
|
||||
if r[0].1 == "TABLE" && value(&r, 2) == Some("APPID") {
|
||||
let table = value(&r, 5).unwrap_or("0").to_string();
|
||||
for (c, v) in [
|
||||
(0, "APPID"),
|
||||
(5, "7A00"),
|
||||
(330, table.as_str()),
|
||||
(100, "AcDbSymbolTableRecord"),
|
||||
(100, "AcDbRegAppTableRecord"),
|
||||
(2, "Other_App"),
|
||||
(70, "0"),
|
||||
] {
|
||||
put(c, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How many APPID records of the DXF are named `Other_App`, in any case.
|
||||
fn appids(text: &str) -> usize {
|
||||
records(text).into_iter().filter(|r| r[0].1 == "APPID" && value(r, 2).is_some_and(|n| n.eq_ignore_ascii_case("Other_App"))).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_applications_no_xdata_names_are_kept() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read_dxf(source(false).as_bytes()).expect("read");
|
||||
for generation in 1..=2 {
|
||||
let text = write_dxf(&d);
|
||||
assert_eq!(appids(&text), 1, "DXF {generation}");
|
||||
d = read_dxf(text.as_bytes()).expect("reread");
|
||||
}
|
||||
for generation in 1..=2 {
|
||||
let dwg = write(&d, "kept.dwg").expect("DWG");
|
||||
d = read(&dwg, "kept.dwg").expect("DWG read");
|
||||
assert_eq!(appids(&write_dxf(&d)), 1, "DWG {generation}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An application both registered and named by xdata, in another case, gets one record.
|
||||
#[test]
|
||||
fn a_registered_application_xdata_names_gets_one_record() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read_dxf(source(true).as_bytes()).expect("read");
|
||||
for generation in 1..=2 {
|
||||
let text = write_dxf(&d);
|
||||
assert!(text.contains("OTHER_APP"), "DXF {generation}: the line's xdata is kept");
|
||||
assert_eq!(appids(&text), 1, "DXF {generation}");
|
||||
d = read_dxf(text.as_bytes()).expect("reread");
|
||||
}
|
||||
for generation in 1..=2 {
|
||||
let dwg = write(&d, "kept.dwg").expect("DWG");
|
||||
d = read(&dwg, "kept.dwg").expect("DWG read");
|
||||
assert_eq!(appids(&write_dxf(&d)), 1, "DWG {generation}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Registered applications alone are not kept objects: a file with nothing else to keep notes no
|
||||
/// version, so the DWG writer reads its R2000 text as before rather than as the file's version.
|
||||
#[test]
|
||||
fn registered_applications_alone_note_no_version() {
|
||||
let d = read_dxf(source(false).as_bytes()).expect("read");
|
||||
assert!(d.foreign.appids.iter().any(|n| n == "Other_App"), "{:?}", d.foreign.appids);
|
||||
assert_eq!(d.foreign.version, None);
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
//! fixed-length extension lines (DIMFXL/DIMFXLON), text placement (DIMTAD, DIMTVP, DIMJUST,
|
||||
//! DIMTIH/DIMTOH, DIMGAP, DIMTMOVE) and text formatting (DIMLUNIT, DIMDEC, DIMZIN, DIMRND,
|
||||
//! DIMPOST, DIMTOL/DIMLIM with DIMTZIN and DIMTOLJ, DIMALT with DIMALTU/DIMALTZ/DIMALTRND,
|
||||
//! DIMAZIN, DIMARCSYM) with its background (DIMTFILL).
|
||||
//! DIMAZIN, DIMARCSYM) with its background (DIMTFILL). DIMPOST wraps angles as well, as
|
||||
//! AutoCAD does (#1653).
|
||||
|
||||
use cadcraft_doc::{DimKind, DimStyle, Dimension};
|
||||
use cadcraft_fonts::{MTextParams, TextFont};
|
||||
|
||||
@@ -67,7 +67,7 @@ fn tol_height_code(st: &DimStyle) -> String {
|
||||
}
|
||||
|
||||
/// Apply measurement placeholders or append a dimension suffix, bounding the resulting UTF-8 text.
|
||||
fn post(template: &str, meas: &str) -> String {
|
||||
pub(super) fn post(template: &str, meas: &str) -> String {
|
||||
if template.contains("<>") {
|
||||
bounded_replace(template, meas)
|
||||
} else {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::text::{apply_override, inspected, linear_text};
|
||||
use super::text::{apply_override, inspected, linear_text, post};
|
||||
use super::{Arrowhead, DimConfig, DimGeometry, DimKind, Vec2, ext_line, readable};
|
||||
use crate::units::format_angle_with_separator;
|
||||
use cadcraft_geom::{Arc, ccw_sweep};
|
||||
@@ -178,8 +178,9 @@ pub(super) fn draw_angular(config: &DimConfig<'_>, g: &mut DimGeometry, text_ang
|
||||
g.measurement = sweep;
|
||||
// DIMAZIN 1 / 2 suppress leading / trailing zeros (DIMZIN's bits 4 / 8).
|
||||
let azin = (st.angular_zero_suppression & 3) * 4;
|
||||
let txt = format_angle_with_separator(sweep, st.angular_unit, st.angular_decimals, azin, &st.decimal_separator);
|
||||
// DIMPOST is a linear-dimension prefix/suffix; angles have their own format only.
|
||||
// DIMPOST wraps the angle too, as AutoCAD 2026 does to its own 2-line and 3-point
|
||||
// angular dimensions ("36.9° m" for a style with "<> m"; issue #1653, after #376).
|
||||
let txt = post(&st.post, &format_angle_with_separator(sweep, st.angular_unit, st.angular_decimals, azin, &st.decimal_separator));
|
||||
g.mtext = inspected(apply_override(&txt, d), d);
|
||||
let mut pts = Vec::new();
|
||||
arc.tessellate(r * 1e-3, &mut pts);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Dimension text formatting (issue #373): DIMRND rounds the measurement only, tolerances use
|
||||
//! DIMTZIN, alternate units DIMALTRND/DIMALTU/DIMALTZ, and DIMPOST is not added to angles.
|
||||
//! DIMTZIN, alternate units DIMALTRND/DIMALTU/DIMALTZ, and DIMPOST wraps angles too (#1653).
|
||||
|
||||
use cadcraft_doc::{DimKind, DimStyle, Dimension};
|
||||
use cadcraft_geom::Vec3;
|
||||
@@ -60,18 +60,23 @@ fn dimrnd_rounds_neither_tolerances_nor_alternate_units() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimpost_is_not_added_to_angular_dimensions() {
|
||||
fn dimpost_applies_to_angular_dimensions_too() {
|
||||
let mut a = linear(0.0);
|
||||
a.kind = DimKind::Angular3P;
|
||||
a.p15 = Vec3::ZERO;
|
||||
a.p13 = Vec3::new(10.0, 0.0, 0.0);
|
||||
a.p14 = Vec3::new(0.0, 10.0, 0.0);
|
||||
a.defpt = Vec3::new(3.0, 3.0, 0.0);
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°");
|
||||
// Linear dimensions keep it, and an angular text override still wraps the angle.
|
||||
// AutoCAD 2026 applies the style's DIMPOST to angular dimensions it builds: with "<> m"
|
||||
// its own 2-line and 3-point dimensions read "36.9° m" (#1653, follow-up to #373/#376).
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°mm");
|
||||
// A prefix before `<>` works as on a linear dimension.
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "A=<>"})), "A=90°");
|
||||
// Linear dimensions keep it, and an angular text override wraps the posted angle, as for
|
||||
// a linear dimension.
|
||||
assert_eq!(text(&linear(10.0), serde_json::json!({"DIMPOST": "<>mm", "DIMDEC": 1})), "10.0mm");
|
||||
a.text = "<> TYP".into();
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90° TYP");
|
||||
assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°mm TYP");
|
||||
}
|
||||
|
||||
fn angular(radians: f64) -> Dimension {
|
||||
|
||||
@@ -200,12 +200,14 @@ pub(super) fn override_cursor(app: &mut CadApp, raw: Vec2, xf: &Xf) {
|
||||
let s = &app.session.settings;
|
||||
let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 };
|
||||
let Ok(st) = app.session.state() else { return };
|
||||
let space = st.edit_space();
|
||||
let frozen = st.viewport_frozen();
|
||||
let hit = match cycle {
|
||||
Some(i) => {
|
||||
let cands = cadcraft_engine::pointmod::snap_candidates(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred);
|
||||
let cands = cadcraft_engine::pointmod::snap_candidates_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen);
|
||||
cands.get(i % cands.len().max(1)).copied()
|
||||
}
|
||||
None => snap::osnap(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred),
|
||||
None => snap::osnap_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen),
|
||||
};
|
||||
let p = match (hit, app.canvas.snap) {
|
||||
(Some(h), _) => {
|
||||
|
||||
@@ -26,13 +26,14 @@ pub(super) fn wheel_zoom_points(events: &[egui::Event], opts: &egui::InputOption
|
||||
}
|
||||
|
||||
/// The model space tiles on screen (none without tiling): each tile's rectangle in `full`.
|
||||
/// Start TEXTEDIT on the text, mtext, attribute definition or multileader text at `p` (the objects
|
||||
/// its shortcut menu offers Edit Text for, and multileaders, #1081); false when there is none.
|
||||
/// Start TEXTEDIT on the text, mtext, attribute definition, dimension or multileader text at `p`
|
||||
/// (the objects its shortcut menu offers Edit Text for, multileaders, #1081, and dimensions, #842);
|
||||
/// false when there is none.
|
||||
pub(super) fn edit_text_at(app: &mut CadApp, p: Vec2) -> bool {
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
let is_text = cadcraft_engine::cmd::curves::pick_at(&app.session, p).and_then(|h| {
|
||||
app.session.doc().ok()?.entity(h).map(|e| match &e.kind {
|
||||
EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) => true,
|
||||
EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_) => true,
|
||||
EntityKind::MLeader(m) => m.text.is_some(),
|
||||
_ => false,
|
||||
})
|
||||
|
||||
@@ -462,6 +462,10 @@ pub fn submit(app: &mut CadApp) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
// OPEN with a file name reads it in the background, as File ▸ Open does (no frozen window).
|
||||
if !app.session.prompting() && app.open_typed(&text) {
|
||||
return;
|
||||
}
|
||||
// A partly typed command name runs the highlighted (first) AutoComplete suggestion.
|
||||
let completion = if app.session.prompting() { None } else { suggestions_in(&app.session, text.trim()).into_iter().next() };
|
||||
app.cmdline_or(&text, completion.map(|s| s.id.to_ascii_lowercase()).as_deref());
|
||||
@@ -825,11 +829,15 @@ mod tests {
|
||||
#[test]
|
||||
fn ime_preedit_is_shown_and_its_commit_is_inserted_once() {
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
// TEXT's own text prompt: the command line collects it (TEXTEDIT on a TEXT edits it in
|
||||
// place instead, #842, with the IME going into that box).
|
||||
let mut app = CadApp::new(Session::new(), crate::Services::default());
|
||||
app.run("text", serde_json::json!({"at": [0, 0], "text": "HELLO", "height": 2.5})).unwrap();
|
||||
app.start("textedit");
|
||||
app.session.input(Input::Point(Vec2::new(1.0, 1.0))).unwrap();
|
||||
assert_eq!(app.session.current_prompt().map(|p| p.message.clone()).as_deref(), Some("Enter new text"));
|
||||
app.start("text");
|
||||
app.session.input(Input::Point(Vec2::new(0.0, 0.0))).unwrap();
|
||||
app.session.input(Input::Text("2.5".into())).unwrap();
|
||||
app.session.input(Input::Enter).unwrap();
|
||||
assert_eq!(app.session.current_prompt().map(|p| p.message.clone()).as_deref(), Some("Enter text"));
|
||||
assert!(app.session.text_editor().is_none(), "no in-place editor at this prompt");
|
||||
let ctx = egui::Context::default();
|
||||
let out = frame(&mut app, &ctx, Vec::new());
|
||||
// The IME is enabled for the command line while it is collecting text.
|
||||
@@ -849,7 +857,10 @@ mod tests {
|
||||
_ => String::new(),
|
||||
});
|
||||
assert_eq!(text.as_deref(), Some("中文"));
|
||||
// Back to selecting objects: the next frame lets the IME go, so it can't swallow ASCII typing.
|
||||
// An empty line ends TEXT.
|
||||
frame(&mut app, &ctx, vec![enter(true), enter(false)]);
|
||||
assert!(app.session.running.is_none());
|
||||
// No text asked for: the next frame lets the IME go, so it can't swallow ASCII typing.
|
||||
let out = frame(&mut app, &ctx, Vec::new());
|
||||
assert!(out.platform_output.ime.is_none());
|
||||
}
|
||||
|
||||
@@ -133,8 +133,8 @@ pub fn entries(app: &CadApp) -> Vec<Vec<Entry>> {
|
||||
}
|
||||
|
||||
/// The edit commands of the selected objects' type (when they are all of one type), with their
|
||||
/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit,
|
||||
/// Polyline Edit, Spline Edit…
|
||||
/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit
|
||||
/// and Generate Boundary for hatches, Polyline Edit, Spline Edit…
|
||||
fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> {
|
||||
let Ok(d) = app.session.doc() else { return Vec::new() };
|
||||
let sel = app.session.selection();
|
||||
@@ -153,7 +153,7 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> {
|
||||
}
|
||||
v
|
||||
}
|
||||
EntityKind::Hatch(_) => vec![("hatchedit", None)],
|
||||
EntityKind::Hatch(_) => vec![("hatchedit", None), ("hatchgenerateboundary", None)],
|
||||
EntityKind::LwPolyline(_) | EntityKind::Polyline3d(_) => vec![("pedit", Some("Polyline Edit"))],
|
||||
EntityKind::Spline(_) => vec![("splinedit", Some("Spline Edit"))],
|
||||
EntityKind::Dimension(_) => vec![("dimtedit", None)],
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::theme::Tokens;
|
||||
|
||||
pub fn show(app: &mut CadApp, ctx: &egui::Context) {
|
||||
crate::mtext_editor::show(app, ctx);
|
||||
crate::line_editor::show(app, ctx);
|
||||
crate::quick::quick_properties(app, ctx);
|
||||
let Some(d) = app.ui.dialog.clone() else { return };
|
||||
let mut open = true;
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Drawing text in the interface. egui's bundled faces and the fonts
|
||||
//! [`crate::theme::install_fonts`] loads cover the interface's own languages, but the interface
|
||||
//! also shows drawing text, which can be in any script the drawing uses: MTEXT contents in the
|
||||
//! in-place editor, layer, layout and block names, a prompt that quotes a text. A character none
|
||||
//! of those fonts has would be a box, while the canvas draws it from a fallback font.
|
||||
//!
|
||||
//! An egui font provider closes that gap: egui asks it once per family and character no
|
||||
//! installed font has, and it answers with the face drawing text takes for that character
|
||||
//! ([`cadcraft_fonts::ttf::fallback_for`]), so the interface shows what the canvas shows. The
|
||||
//! provider hands egui the font table's own bytes: nothing is bundled, read again or copied.
|
||||
//!
|
||||
//! A fallback face is sized to the interface text, not to its own em: the Thai faces drawings use
|
||||
//! (Cordia New, Angsana New) draw their letters small for their size, so their consonants are
|
||||
//! scaled up to the interface's x-height ([`scale`]). Its glyphs sit on the interface text's
|
||||
//! baseline, and a line with them grows to fit their stacked marks.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_fonts::ttf::Face;
|
||||
|
||||
/// Let egui ask the drawing-text fallback for characters no interface font has. Once per
|
||||
/// context: providers outlive the `set_fonts` of [`crate::theme::install_fonts`], so a second
|
||||
/// call (a language change) adds nothing.
|
||||
pub(crate) fn install(ctx: &egui::Context) {
|
||||
let id = egui::Id::unique("cadcraft::drawing_fonts");
|
||||
let installed = ctx.data_mut(|d| std::mem::replace(d.get_temp_mut_or_default::<bool>(id), true));
|
||||
if !installed {
|
||||
ctx.add_font_provider(Arc::new(|request: &egui::FallbackRequest<'_>| font_for(request.cluster, cadcraft_fonts::ttf::fallback_for)));
|
||||
}
|
||||
}
|
||||
|
||||
/// How tall a lowercase x is in the interface faces, in ems (Ubuntu Light, egui's bundled face,
|
||||
/// 0.52; Segoe UI 0.50). A Thai consonant without ascender or descender (ก) is about as tall in
|
||||
/// the Thai faces made for screens (Leelawadee UI 0.51, Tahoma and Noto Sans Thai 0.56).
|
||||
const X_HEIGHT: f64 = 0.52;
|
||||
/// The most a fallback face is scaled up, so a face with an odd or tiny reference letter never
|
||||
/// draws huge text. Cordia New needs 1.28, Angsana New 1.30.
|
||||
const MAX_SCALE: f64 = 1.5;
|
||||
|
||||
/// The font for the first character of `cluster`: the face `fallback` finds for it, if any.
|
||||
fn font_for(cluster: &str, fallback: impl Fn(char) -> Option<Face>) -> Option<egui::FontInsert> {
|
||||
let c = cluster.chars().next()?;
|
||||
fallback(c).map(|face| font_insert(&face, c))
|
||||
}
|
||||
|
||||
/// The letter of `c`'s script that the interface's x-height measures: a Thai consonant without
|
||||
/// ascender or descender, else the face's own Latin x.
|
||||
fn reference_letter(c: char) -> char {
|
||||
if ('\u{0e00}'..='\u{0e7f}').contains(&c) { 'ก' } else { 'x' }
|
||||
}
|
||||
|
||||
/// How much a face is scaled up whose reference letter is `height` ems tall: to [`X_HEIGHT`],
|
||||
/// at most [`MAX_SCALE`]. A face that is already big enough, or whose letter has no height, keeps
|
||||
/// its size.
|
||||
fn scale(height: Option<f64>) -> f32 {
|
||||
height.filter(|h| h.is_finite() && *h > 0.0).map_or(1.0, |h| (X_HEIGHT / h).clamp(1.0, MAX_SCALE) as f32)
|
||||
}
|
||||
|
||||
/// `face`, found for character `c`, as an egui font: the font table's bytes, shared rather than
|
||||
/// copied, under a name that is the same for every character of the face, so egui loads the face
|
||||
/// once (sized by the first character's script); scaled to the interface text and on its baseline.
|
||||
fn font_insert(face: &Face, c: char) -> egui::FontInsert {
|
||||
let name = format!("drawing-text-{:p}-{}-{}", Arc::as_ptr(&face.bytes), face.bytes.len(), face.index);
|
||||
let tweak = egui::FontTweak {
|
||||
scale: scale(face.glyph_height(reference_letter(c))),
|
||||
fallback_align: egui::epaint::text::FallbackAlign::Baseline,
|
||||
..Default::default()
|
||||
};
|
||||
egui::FontInsert::new(&name, egui::FontData::from_blob(face.bytes.clone(), face.index).tweak(tweak), Vec::new())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A face from one of egui's bundled fonts (there are no font files in this repository).
|
||||
fn bundled_face() -> Face {
|
||||
let defs = egui::FontDefinitions::default();
|
||||
let bytes = defs.font_data.get("Hack").map(|d| d.bytes().to_vec()).unwrap_or_default();
|
||||
Face::new(Arc::new(bytes), 0).expect("egui bundles Hack")
|
||||
}
|
||||
|
||||
/// Every character of a face names the same font, whose bytes are the face's own (not a
|
||||
/// copy); a character without a fallback face, or no character, gets no font.
|
||||
#[test]
|
||||
fn a_fallback_face_is_one_shared_font() {
|
||||
let face = bundled_face();
|
||||
let fallback = |c: char| (c != '\u{e000}').then(|| face.clone());
|
||||
let a = font_for("ก", fallback).expect("a font");
|
||||
let b = font_for("ขั", fallback).expect("a font");
|
||||
assert_eq!(a.name, b.name);
|
||||
assert!(std::ptr::eq(a.data.bytes().as_ptr(), face.bytes.as_ptr()), "the font table's bytes, not a copy");
|
||||
assert_eq!(a.data.index, face.index);
|
||||
assert!(font_for("\u{e000}", fallback).is_none());
|
||||
assert!(font_for("", fallback).is_none());
|
||||
let other = Face::new(Arc::new(face.bytes.as_ref().clone()), 0).expect("a second copy parses");
|
||||
assert_ne!(font_insert(&other, 'ก').name, a.name, "another file is another font");
|
||||
assert_eq!(a.data.tweak.fallback_align, egui::epaint::text::FallbackAlign::Baseline, "on the interface text's baseline");
|
||||
}
|
||||
|
||||
/// A face whose reference letter is short is scaled up to the interface's x-height, at most
|
||||
/// by half; one that is tall enough, or can't be measured, keeps its size.
|
||||
#[test]
|
||||
fn short_faces_are_scaled_to_the_interface_x_height() {
|
||||
assert_eq!(reference_letter('ค'), 'ก');
|
||||
assert_eq!(reference_letter('\u{0e4c}'), 'ก', "a Thai mark measures by the consonant too");
|
||||
assert_eq!(reference_letter('א'), 'x');
|
||||
// Cordia New's ก is 0.405 em.
|
||||
assert!((f64::from(scale(Some(0.405))) * 0.405 - X_HEIGHT).abs() < 1e-6);
|
||||
assert_eq!(scale(Some(0.56)), 1.0, "never scaled down");
|
||||
assert_eq!(scale(Some(0.01)), MAX_SCALE as f32);
|
||||
for unmeasured in [None, Some(0.0), Some(-1.0), Some(f64::NAN), Some(f64::INFINITY)] {
|
||||
assert_eq!(scale(unmeasured), 1.0, "{unmeasured:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every Thai face found here (Cordia New, Angsana New on Windows; Noto Sans Thai from
|
||||
/// craft-fonts in CI) draws ก at least as tall as the interface's x-height, and is never shrunk.
|
||||
#[test]
|
||||
fn thai_faces_draw_their_consonants_at_the_interface_x_height() {
|
||||
let names = ["Cordia New", "Angsana New", "Browallia New", "Noto Sans Thai", "IBM Plex Sans Thai", "Leelawadee UI", "Tahoma"];
|
||||
let faces = names.iter().filter_map(|n| cadcraft_fonts::ttf::find(n)).chain(cadcraft_fonts::ttf::fallback_for('ก'));
|
||||
for face in faces.filter(|f| f.has_glyph('ก')) {
|
||||
let height = face.glyph_height('ก').unwrap_or_default();
|
||||
let drawn = height * f64::from(font_insert(&face, 'ก').data.tweak.scale);
|
||||
let family = face.family_name();
|
||||
assert!(drawn >= X_HEIGHT - 1e-6, "{family:?}: ก drawn {drawn} em");
|
||||
assert!(drawn <= height.max(X_HEIGHT) + 1e-6, "{family:?}: ก drawn {drawn} em, not shrunk or overshot");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -374,6 +374,7 @@
|
||||
From Desde
|
||||
From Template... Desde plantilla...
|
||||
General General
|
||||
Generate Boundary Generar contorno
|
||||
Geometric Center Centro geométrico
|
||||
Geometric Constraint Restricción geométrica
|
||||
Geometric Constraints Restricciones geométricas
|
||||
|
||||
|
@@ -296,6 +296,7 @@
|
||||
Freeze/Thaw in the current viewport 在当前视口中冻结/解冻
|
||||
From 自
|
||||
General 常规
|
||||
Generate Boundary 生成边界
|
||||
Geometric Center 几何中心
|
||||
Geometric Constraint 几何约束
|
||||
Geometric Constraints 几何约束
|
||||
|
||||
|
@@ -32,10 +32,12 @@ pub mod control;
|
||||
pub mod credits;
|
||||
pub mod dialogs;
|
||||
pub mod docking;
|
||||
mod drawing_fonts;
|
||||
pub mod fault;
|
||||
// The Find and Replace window behind the FIND command.
|
||||
pub mod finddlg;
|
||||
pub mod hatchdlg;
|
||||
mod line_editor;
|
||||
mod mtext_editor;
|
||||
mod panel_state;
|
||||
pub mod spacemouse;
|
||||
@@ -797,6 +799,18 @@ impl CadApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// OPEN typed at the command line with the file to open (`OPEN C:\plans\big.dwg`, or the JSON
|
||||
/// form with only a path, `open {"path": "…"}`): read in the background as File ▸ Open reads it
|
||||
/// ([`Self::open_path`]), so a large drawing doesn't freeze the window. False, and the line runs
|
||||
/// as before, for anything else: other parameters (`data`), a LISP file, and on the web, which
|
||||
/// has no threads. Only the keyboard's Enter calls this; programmatic calls (the control
|
||||
/// channel, MCP, scripts, LISP) keep getting their answer at once.
|
||||
pub(crate) fn open_typed(&mut self, line: &str) -> bool {
|
||||
let Some(path) = typed_open_path(line).filter(|p| !is_lisp_file(p)) else { return false };
|
||||
self.open_path(Path::new(&path));
|
||||
true
|
||||
}
|
||||
|
||||
/// Add the files whose background read has finished; report the ones that failed as a failed
|
||||
/// OPEN is reported. Called every frame.
|
||||
pub fn finish_opening(&mut self) {
|
||||
@@ -1052,6 +1066,7 @@ impl CadApp {
|
||||
let ctx = &ctx;
|
||||
let language = self.language();
|
||||
if self.fonts_language != Some(language) {
|
||||
drawing_fonts::install(ctx);
|
||||
theme::install_fonts(ctx, language);
|
||||
self.fonts_language = Some(language);
|
||||
}
|
||||
@@ -1200,6 +1215,27 @@ fn is_lisp_file(name: impl AsRef<Path>) -> bool {
|
||||
name.as_ref().extension().is_some_and(|e| e.eq_ignore_ascii_case("lsp"))
|
||||
}
|
||||
|
||||
/// The file an `OPEN <path>` or `open {"path": "…"}` line names ([`CadApp::open_typed`]). `None`
|
||||
/// for other lines, JSON with other keys, and on the web.
|
||||
fn typed_open_path(line: &str) -> Option<String> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return None;
|
||||
}
|
||||
let (name, rest) = line.trim().split_once(char::is_whitespace)?;
|
||||
if !name.trim_start_matches(['_', '.']).eq_ignore_ascii_case("open") {
|
||||
return None;
|
||||
}
|
||||
let rest = rest.trim();
|
||||
let path = if rest.starts_with('{') {
|
||||
let v: Value = serde_json::from_str(rest).ok()?;
|
||||
let o = v.as_object().filter(|o| o.len() == 1)?;
|
||||
o.get("path")?.as_str()?.to_string()
|
||||
} else {
|
||||
rest.strip_prefix('"').and_then(|r| r.strip_suffix('"')).unwrap_or(rest).to_string()
|
||||
};
|
||||
(!path.trim().is_empty()).then_some(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
//! The one-line in-place text editor (#842): double-clicking TEXT, an attribute definition or a
|
||||
//! dimension (TEXTEDIT with the object picked) opens a text box over the text, at its position
|
||||
//! and height. Enter or a click outside keeps what was typed, Esc cancels; an emptied box keeps a
|
||||
//! text's old value and gives a dimension back its measured value (`<>`). What the box edits comes
|
||||
//! from the engine ([`cadcraft_engine::Session::text_editor`]); the new text goes back through
|
||||
//! the running command, so undo, scripts and the command line work as before.
|
||||
|
||||
use cadcraft_engine::{EditorKind, Input, TextEditor};
|
||||
use egui::text::{CCursor, CCursorRange};
|
||||
use egui::{Color32, FontId, Key, LayerId, RichText, Stroke, pos2};
|
||||
|
||||
use crate::CadApp;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// Smallest and largest size of the text in the box, in points: readable at any zoom.
|
||||
const MIN_PX: f32 = 13.0;
|
||||
const MAX_PX: f32 = 36.0;
|
||||
/// The box's margin around the text, in points.
|
||||
const MARGIN: f32 = 3.0;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct State {
|
||||
/// The object being edited ([`TextEditor::key`]): another one starts afresh.
|
||||
key: String,
|
||||
/// The drawing that holds the object ([`cadcraft_engine::DocState::uid`]): handles repeat
|
||||
/// across drawings, so a draft never goes to another drawing's object.
|
||||
drawing: Option<u64>,
|
||||
text: String,
|
||||
/// The box has taken the keyboard once (typing goes into it, not the command line).
|
||||
focused: bool,
|
||||
}
|
||||
|
||||
fn state_id() -> egui::Id {
|
||||
egui::Id::unique("line_editor_state")
|
||||
}
|
||||
|
||||
fn edit_id() -> egui::Id {
|
||||
egui::Id::unique("line_editor_text")
|
||||
}
|
||||
|
||||
/// The one-line text the running command asks for, when it is asking for it now.
|
||||
fn current(app: &CadApp) -> Option<TextEditor> {
|
||||
let ed = app.session.text_editor()?;
|
||||
let asking = app.session.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point);
|
||||
(asking && matches!(ed.kind, EditorKind::Line | EditorKind::Dimension { .. })).then_some(ed)
|
||||
}
|
||||
|
||||
enum Done {
|
||||
No,
|
||||
Ok,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// Show the editor while TEXTEDIT asks for one line of text; clears its state otherwise.
|
||||
pub fn show(app: &mut CadApp, ctx: &egui::Context) {
|
||||
let Some(ed) = current(app) else {
|
||||
ctx.data_mut(|d| d.remove::<State>(state_id()));
|
||||
return;
|
||||
};
|
||||
let t = Tokens::get();
|
||||
let mt = &ed.mtext;
|
||||
let drawing = app.session.state().ok().map(|st| st.uid);
|
||||
let kept = ctx.data_mut(|d| d.get_temp::<State>(state_id())).filter(|st| st.key == ed.key && st.drawing == drawing);
|
||||
// A click outside counts from the frame after the box opened (not the double-click itself).
|
||||
let armed = kept.is_some();
|
||||
let mut st = kept.unwrap_or_else(|| State { key: ed.key.clone(), drawing, text: mt.contents.clone(), focused: false });
|
||||
|
||||
let (rect, scale) = app.canvas.xf.map_or((ctx.content_rect(), 20.0), |x| (x.rect, x.scale.max(1e-6)));
|
||||
let height = if mt.height > 0.0 && mt.height.is_finite() { mt.height } else { 0.2 };
|
||||
let text_px = (height * scale) as f32;
|
||||
let text_px = if text_px.is_finite() { text_px.clamp(0.0, 10_000.0) } else { 0.0 };
|
||||
let px = text_px.clamp(MIN_PX, MAX_PX);
|
||||
let font = FontId::proportional(px);
|
||||
let typed_w = ctx.layer_painter(LayerId::background()).layout_no_wrap(st.text.clone(), font.clone(), Color32::WHITE).size().x;
|
||||
// The text as drawn on screen (one line of text): the box covers it, for every justification.
|
||||
let drawn = ed.extents.zip(app.canvas.xf).map(|(b, x)| {
|
||||
let corners = [(b.min.x, b.min.y), (b.max.x, b.min.y), (b.max.x, b.max.y), (b.min.x, b.max.y)];
|
||||
egui::Rect::from_points(&corners.map(|(cx, cy)| x.to_screen(cadcraft_geom::Vec2::new(cx, cy))))
|
||||
});
|
||||
let drawn = drawn.filter(|r| r.is_finite() && r.is_positive());
|
||||
let width = (typed_w.max(drawn.map_or(0.0, |r| r.width())) + 2.0 * px).clamp(120.0, (rect.width() * 0.9).max(120.0));
|
||||
// Without drawn extents the box sits over the text by its justification: left, centre or
|
||||
// right, and top, middle or baseline. Rotation is ignored while editing, as in the MTEXT editor.
|
||||
let code = mt.attach.clamp(1, 9) - 1;
|
||||
let (col, row) = (f32::from(code % 3), code / 3);
|
||||
let anchor = app.canvas.xf.map_or(rect.center(), |x| x.to_screen(mt.insert.xy()));
|
||||
let middle = match (drawn, row) {
|
||||
(Some(r), _) => r.center().y,
|
||||
(None, 0) => anchor.y + text_px / 2.0,
|
||||
(None, 1) => anchor.y,
|
||||
(None, _) => anchor.y - text_px / 2.0,
|
||||
};
|
||||
// Tall enough to cover the drawn text too.
|
||||
let pad_y = drawn.map_or(MARGIN, |r| ((r.height() - px) / 2.0 + MARGIN).clamp(MARGIN, 120.0));
|
||||
let box_h = px + 2.0 * pad_y + 2.0;
|
||||
let max_x = (rect.right() - width - 8.0).max(rect.left());
|
||||
let max_y = (rect.bottom() - box_h - 24.0).max(rect.top());
|
||||
let left = drawn.map_or(anchor.x - col * width / 2.0, |r| r.left() - MARGIN);
|
||||
let x = left.clamp(rect.left(), max_x);
|
||||
let y = (middle - box_h / 2.0).clamp(rect.top(), max_y);
|
||||
|
||||
let mut done = Done::No;
|
||||
let area = egui::Area::new(egui::Id::unique("line_editor_area"))
|
||||
.default_width(width + 2.0 * MARGIN)
|
||||
.order(egui::Order::Foreground)
|
||||
.fixed_pos(pos2(x, y))
|
||||
.show(ctx, |ui| {
|
||||
egui::Frame::NONE
|
||||
.fill(t.panel)
|
||||
.stroke(Stroke::new(1.0, t.accent))
|
||||
.inner_margin(egui::Margin::symmetric(MARGIN as i8, pad_y.round() as i8))
|
||||
.show(ui, |ui| {
|
||||
// As wide as worked out above (an area is otherwise narrower than a long text).
|
||||
ui.set_width(width);
|
||||
// Every box shares one text field: a new one starts with no undo history, so
|
||||
// Ctrl+Z can't bring back another object's text.
|
||||
if !st.focused {
|
||||
let mut s = egui::TextEdit::load_state(ui.ctx(), edit_id()).unwrap_or_default();
|
||||
s.clear_undoer();
|
||||
s.store(ui.ctx(), edit_id());
|
||||
}
|
||||
let out = egui::TextEdit::singleline(&mut st.text)
|
||||
.id(edit_id())
|
||||
.font(font)
|
||||
.text_color(t.text)
|
||||
.frame(egui::Frame::NONE)
|
||||
.desired_width(width)
|
||||
.show(ui);
|
||||
// It opens with the whole text selected, as AutoCAD's does: typing replaces it.
|
||||
if !st.focused {
|
||||
out.response.request_focus();
|
||||
let mut s = out.state;
|
||||
s.cursor.set_char_range(Some(CCursorRange::two(CCursor::new(0), CCursor::new(st.text.chars().count()))));
|
||||
s.store(ui.ctx(), edit_id());
|
||||
st.focused = true;
|
||||
}
|
||||
if out.response.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) {
|
||||
done = Done::Ok;
|
||||
}
|
||||
if let EditorKind::Dimension { measured } = &ed.kind {
|
||||
ui.label(RichText::new(format!("<> = {measured}")).small().color(t.text_dim));
|
||||
}
|
||||
});
|
||||
});
|
||||
let outside = ctx.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| !area.response.rect.contains(p)));
|
||||
if ctx.input(|i| i.key_pressed(Key::Escape)) {
|
||||
done = Done::Cancel;
|
||||
} else if armed && outside {
|
||||
done = Done::Ok;
|
||||
}
|
||||
match done {
|
||||
Done::No => {
|
||||
ctx.data_mut(|d| d.insert_temp(state_id(), st));
|
||||
}
|
||||
Done::Ok => {
|
||||
ctx.data_mut(|d| d.remove::<State>(state_id()));
|
||||
let new = st.text.replace(['\r', '\n'], " ");
|
||||
let dimension = matches!(ed.kind, EditorKind::Dimension { .. });
|
||||
// Emptied: a text keeps its value, a dimension shows its measurement again.
|
||||
let answer = match new.as_str() {
|
||||
"" if dimension => (mt.contents != "<>").then(|| "<>".to_string()),
|
||||
"" => None,
|
||||
s if s == mt.contents => None,
|
||||
_ => Some(new),
|
||||
};
|
||||
// Unchanged text is kept with Enter: no undo step.
|
||||
let r = app.session.input(answer.map_or(Input::Enter, Input::Text));
|
||||
if let Err(e) = r {
|
||||
app.session.echo(e.to_string());
|
||||
}
|
||||
}
|
||||
Done::Cancel => {
|
||||
ctx.data_mut(|d| d.remove::<State>(state_id()));
|
||||
app.session.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
use super::{State, state_id};
|
||||
use crate::{CadApp, Services};
|
||||
|
||||
fn frame(app: &mut CadApp, ctx: &egui::Context) {
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
|
||||
fn edit_text_at_origin(app: &mut CadApp) -> String {
|
||||
app.start("textedit");
|
||||
app.session.input(Input::Point(Vec2::new(0.5, 0.5))).unwrap();
|
||||
app.session.text_editor().expect("a one-line editor").key
|
||||
}
|
||||
|
||||
/// A draft typed for one drawing's object is never shown or kept for an object of another
|
||||
/// drawing with the same handle (review of #842).
|
||||
#[test]
|
||||
fn a_draft_stays_with_its_drawing() {
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
let ctx = egui::Context::default();
|
||||
app.run("text", json!({ "at": [0, 0], "text": "FIRST", "height": 2.5 })).unwrap();
|
||||
let first = edit_text_at_origin(&mut app);
|
||||
frame(&mut app, &ctx);
|
||||
// Something typed into the first drawing's box.
|
||||
ctx.data_mut(|d| {
|
||||
let mut st = d.get_temp::<State>(state_id()).unwrap();
|
||||
st.text = "DRAFT".into();
|
||||
d.insert_temp(state_id(), st);
|
||||
});
|
||||
// Another drawing, with an object of the same handle, edited before any frame without a box.
|
||||
app.session.cancel();
|
||||
app.session.execute("new", &json!({})).unwrap();
|
||||
app.run("text", json!({ "at": [0, 0], "text": "SECOND", "height": 2.5 })).unwrap();
|
||||
assert_eq!(edit_text_at_origin(&mut app), first, "the same handle in both drawings");
|
||||
frame(&mut app, &ctx);
|
||||
let st = ctx.data_mut(|d| d.get_temp::<State>(state_id())).unwrap();
|
||||
assert_eq!(st.text, "SECOND", "the box shows the second drawing's text, not the draft");
|
||||
}
|
||||
}
|
||||
@@ -658,6 +658,11 @@ fn fields(ui: &mut egui::Ui, d: &Drawing, st: &mut State) {
|
||||
combo(ui, egui::Id::unique(id), &cur, options)
|
||||
}
|
||||
});
|
||||
let new = new.map(|v| match (p.field, v.as_str()) {
|
||||
// An empty per-end name inherits DIMBLK.
|
||||
("arrowBlock1" | "arrowBlock2", Some("")) => json!("_CLOSEDFILLED"),
|
||||
_ => v,
|
||||
});
|
||||
if let Some(v) = new.filter(|v| *v != cur) {
|
||||
st.values.insert(p.field.into(), v);
|
||||
}
|
||||
|
||||
@@ -882,4 +882,40 @@ mod tests {
|
||||
assert!((big - 2.0 * height).abs() < 1e-9, "{big} for a {height} text");
|
||||
assert_eq!(st.fmt.fmt_at(5).height, None, "the rest keeps the text's height");
|
||||
}
|
||||
|
||||
/// A Thai MTEXT, which the canvas draws from a Thai fallback font, opens in the editor in
|
||||
/// letters, not boxes: the app's interface fonts take the face drawing text takes for a
|
||||
/// character they lack. Both interface families do, so Thai typed at the command line or in a
|
||||
/// layer name (proportional) and a FIND result (monospace) are letters too (#2949). Runs where
|
||||
/// a Thai face is found (CI embeds craft-fonts' Noto Sans Thai).
|
||||
#[test]
|
||||
fn thai_text_opens_in_the_editor_without_boxes() {
|
||||
let thai = "แบบขยายผนังห้องน้ำ ชั้นที่ ๒";
|
||||
let letters: Vec<char> = thai.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
if letters.iter().any(|c| cadcraft_fonts::ttf::fallback_for(*c).is_none()) {
|
||||
return;
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
app.run("mtext", serde_json::json!({ "at": [0, 20], "text": thai, "height": 2.5, "width": 40 })).unwrap();
|
||||
app.start("textedit");
|
||||
app.session.input(cadcraft_engine::Input::Point(cadcraft_geom::Vec2::new(1.0, 19.0))).unwrap();
|
||||
// Real app frames: the fonts are the ones the app installs.
|
||||
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() };
|
||||
for _ in 0..2 {
|
||||
let mut out = ctx.run_ui(input.clone(), |ui| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
assert_eq!(ctx.data_mut(|d| d.get_temp::<State>(state_id())).expect("editor open").fmt.text(), thai);
|
||||
let mut missing = Vec::new();
|
||||
ctx.fonts_mut(|f| {
|
||||
for font in [FontId::proportional(MIN_PX), FontId::monospace(MIN_PX)] {
|
||||
missing.extend(letters.iter().filter(|c| !f.has_glyph(&font, **c)).map(|c| format!("{:?} {c}", font.family)));
|
||||
}
|
||||
});
|
||||
assert!(missing.is_empty(), "drawn as boxes: {missing:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Asking before a save throws content away. DWG can't yet hold everything a drawing read from
|
||||
//! another program keeps (`cadcraft_engine::cmd::file::not_saved`), a DXF of 2013 or later can't
|
||||
//! hold a solid's SAT text (`cadcraft_doc::foreign::sat_text_dropped`), and QSAVE replaces the file
|
||||
//! another program keeps (`cadcraft_engine::cmd::file::not_saved`), a DXF can't hold every solid
|
||||
//! or proxy of every version (`cadcraft_engine::cmd::file::loss_on_save`), and QSAVE replaces the file
|
||||
//! that still has it, so File ▸ Save, its shortcut or typing QSAVE says what would go first:
|
||||
//! Save Anyway / Save As... / Cancel. Agreeing lasts for that same loss on that same file, so
|
||||
//! later saves in the session don't ask again; the file no longer holds what was agreed to.
|
||||
@@ -14,7 +14,7 @@ use egui::{RichText, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use cadcraft_engine::autosave::isavebak;
|
||||
use cadcraft_engine::cmd::file::{backup_path, loss_on_save, save_keeps_current};
|
||||
use cadcraft_engine::cmd::file::{Version, backup_path, drawing_version, loss_on_save, save_keeps_current};
|
||||
|
||||
use crate::CadApp;
|
||||
use crate::theme::Tokens;
|
||||
@@ -44,6 +44,8 @@ pub struct Accepted {
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Pending {
|
||||
loss: Accepted,
|
||||
/// The version the file would be saved in: which DXF keeps what it loses depends on it.
|
||||
version: Version,
|
||||
}
|
||||
|
||||
impl Pending {
|
||||
@@ -78,13 +80,14 @@ impl CadApp {
|
||||
if self.save_loss_accepted.as_ref() == Some(&loss) {
|
||||
return false;
|
||||
}
|
||||
self.save_loss = Some(Pending { loss });
|
||||
let version = drawing_version(&self.session, &loss.path);
|
||||
self.save_loss = Some(Pending { loss, version });
|
||||
true
|
||||
}
|
||||
|
||||
/// Answer the open warning (no-op without one).
|
||||
pub fn answer_save_loss(&mut self, choice: Choice) {
|
||||
let Some(Pending { loss }) = self.save_loss.take() else { return };
|
||||
let Some(Pending { loss, .. }) = self.save_loss.take() else { return };
|
||||
// The drawing can go away, or stop being the active one, while the warning is up.
|
||||
let i = self.session.docs.iter().position(|d| d.uid == loss.uid);
|
||||
match (choice, i) {
|
||||
@@ -108,6 +111,38 @@ impl CadApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which files keep what a save would lose: the hint under the warning.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Keeps {
|
||||
/// A DXF before 2007 leaves out proxies whose strings it can't hold (#3229).
|
||||
Dxf2007,
|
||||
/// A DXF of 2013 or later leaves out a solid's SAT text.
|
||||
Dxf2010,
|
||||
/// A DXF before 2013 leaves out a solid whose geometry only the data store holds (#2334), and
|
||||
/// 2013 keeps the proxies a file before 2007 leaves out too.
|
||||
Dxf2013,
|
||||
/// Any other file: DXF keeps everything.
|
||||
Dxf,
|
||||
}
|
||||
|
||||
/// The hint for saving to `path` at `version` and losing `lost`. A path names a DXF the way the
|
||||
/// save does (`Format::from_path`), so a name without an extension is a DXF too.
|
||||
fn keeps_hint(path: &std::path::Path, lost: &BTreeMap<String, usize>, version: Version) -> Keeps {
|
||||
if cadcraft_doc::Format::from_path(path) != Some(cadcraft_doc::Format::Dxf) {
|
||||
return Keeps::Dxf;
|
||||
}
|
||||
// A 2013 or later file only leaves out solids with SAT text alone. Before 2013 it leaves out
|
||||
// solids whose geometry is in the data store, and before 2007 also proxies, with what they
|
||||
// own (an XRECORD, a DICTIONARY).
|
||||
if version >= Version::R2013 {
|
||||
Keeps::Dxf2010
|
||||
} else if lost.keys().any(|k| ["3DSOLID", "REGION", "BODY"].iter().any(|m| k.eq_ignore_ascii_case(m))) {
|
||||
Keeps::Dxf2013
|
||||
} else {
|
||||
Keeps::Dxf2007
|
||||
}
|
||||
}
|
||||
|
||||
/// The warning, while a save waits for an answer. Cancel is what Escape does.
|
||||
pub fn prompt(app: &mut CadApp, ctx: &egui::Context) {
|
||||
let Some(pending) = app.save_loss.clone() else { return };
|
||||
@@ -121,10 +156,11 @@ pub fn prompt(app: &mut CadApp, ctx: &egui::Context) {
|
||||
ui.label(RichText::new(crate::tf!("Saving {name} will remove content", name = file)).strong());
|
||||
ui.add_space(4.0);
|
||||
ui.label(crate::tf!("This format can't keep these objects yet: {objects}.", objects = pending.summary()));
|
||||
let keeps = if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("dxf")) {
|
||||
crate::tl!("DXF 2010 and earlier keep them. Use Save As to keep them in the drawing.")
|
||||
} else {
|
||||
crate::tl!("DXF keeps them. Use Save As to keep them in the drawing.")
|
||||
let keeps = match keeps_hint(path, &pending.loss.lost, pending.version) {
|
||||
Keeps::Dxf2007 => crate::tl!("DXF 2007 and later keep them. Use Save As to keep them in the drawing."),
|
||||
Keeps::Dxf2013 => crate::tl!("DXF 2013 and later keep them. Use Save As to keep them in the drawing."),
|
||||
Keeps::Dxf2010 => crate::tl!("DXF 2010 and earlier keep them. Use Save As to keep them in the drawing."),
|
||||
Keeps::Dxf => crate::tl!("DXF keeps them. Use Save As to keep them in the drawing."),
|
||||
};
|
||||
ui.label(RichText::new(keeps).color(t.text_dim));
|
||||
let on_disk = if save_keeps_current(path) {
|
||||
@@ -158,3 +194,35 @@ pub fn prompt(app: &mut CadApp, ctx: &egui::Context) {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn lost(kind: &str) -> BTreeMap<String, usize> {
|
||||
BTreeMap::from([(kind.to_string(), 1)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_without_an_extension_is_a_dxf_for_the_hint() {
|
||||
let path = std::path::Path::new("plans/site");
|
||||
let old = Version::R2000;
|
||||
assert_eq!(keeps_hint(path, &lost("ACAD_PROXY_ENTITY"), old), Keeps::Dxf2007);
|
||||
assert_eq!(keeps_hint(path, &lost("3DSOLID"), Version::R2018), Keeps::Dxf2010);
|
||||
let with_owned = BTreeMap::from([("ACAD_PROXY_OBJECT".to_string(), 1), ("XRECORD".to_string(), 2)]);
|
||||
assert_eq!(keeps_hint(path, &with_owned, old), Keeps::Dxf2007);
|
||||
assert_eq!(keeps_hint(std::path::Path::new("plans/site.DXF"), &lost("ACAD_PROXY_ENTITY"), old), Keeps::Dxf2007);
|
||||
assert_eq!(keeps_hint(std::path::Path::new("plans/site.dwg"), &lost("ACAD_PROXY_ENTITY"), old), Keeps::Dxf);
|
||||
}
|
||||
|
||||
/// A DXF before 2013 leaves out solids whose geometry only the data store holds (#2334): 2013
|
||||
/// and later keep them, so the hint doesn't send the user to 2010 or earlier, which would lose
|
||||
/// them again; with a proxy loss beside them, 2013 keeps both.
|
||||
#[test]
|
||||
fn a_solid_lost_before_2013_is_kept_from_2013() {
|
||||
let path = std::path::Path::new("plans/site.dxf");
|
||||
assert_eq!(keeps_hint(path, &lost("3DSOLID"), Version::R2010), Keeps::Dxf2013);
|
||||
let both = BTreeMap::from([("ACAD_PROXY_ENTITY".to_string(), 1), ("REGION".to_string(), 1)]);
|
||||
assert_eq!(keeps_hint(path, &both, Version::R2000), Keeps::Dxf2013);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,6 +95,31 @@ fn modify_edits_the_style() {
|
||||
assert_eq!(h.state().ui.dialog.as_deref(), Some("dimstyle"), "back to the list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modify_keeps_closed_filled_per_end_arrowheads() {
|
||||
let mut h = manager(|app| {
|
||||
app.run("dimstyle", json!({ "name": "Standard", "DIMBLK": "_DOT" })).unwrap();
|
||||
});
|
||||
click(&mut h, "Modify...");
|
||||
click(&mut h, "Symbols and Arrows");
|
||||
for label in ["Arrow 1", "Arrow 2"] {
|
||||
h.get(by().label(label).role(egui::accesskit::Role::ComboBox)).click();
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Closed filled");
|
||||
}
|
||||
click(&mut h, "OK");
|
||||
let style = h.state().session.doc().unwrap().dim_style("Standard").unwrap();
|
||||
assert_eq!(style.arrow_block, "_DOT");
|
||||
assert_eq!(style.arrow_block1, "_CLOSEDFILLED");
|
||||
assert_eq!(style.arrow_block2, "_CLOSEDFILLED");
|
||||
|
||||
click(&mut h, "Modify...");
|
||||
click(&mut h, "Symbols and Arrows");
|
||||
for label in ["Arrow 1", "Arrow 2"] {
|
||||
h.get(by().label(label).role(egui::accesskit::Role::ComboBox).value("Closed filled"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_leaves_the_style_alone() {
|
||||
let mut h = manager(|_| {});
|
||||
|
||||
@@ -23,6 +23,7 @@ mod measure_distance_snapping;
|
||||
mod menubar_hover;
|
||||
mod moving_clicks;
|
||||
mod mspace_viewport_view;
|
||||
mod mtext_double_click;
|
||||
mod named_viewports_dialog;
|
||||
mod native_menu_text_keys;
|
||||
mod native_windows;
|
||||
@@ -41,13 +42,16 @@ mod shared_controls;
|
||||
mod shortcut_menus;
|
||||
mod shortcuts_checked;
|
||||
mod slow_clicks;
|
||||
mod snap_tab_cycling;
|
||||
mod space_at_options;
|
||||
mod status_bar_toggles;
|
||||
mod style_dialogs;
|
||||
mod system_cursor;
|
||||
mod text_double_click;
|
||||
mod text_edit_in_place;
|
||||
mod toolsets_gear;
|
||||
mod toolsets_parametric;
|
||||
mod typed_open;
|
||||
mod viewport_double_click_selection;
|
||||
mod workspace_focus;
|
||||
mod zoomed_far_in;
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
//! Double-clicking an MTEXT opens the in-place text editor on it with its contents (TEXTEDIT), as
|
||||
//! in AutoCAD; Ctrl+Enter keeps what was typed.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
|
||||
fn harness() -> (Harness<'static, CadApp>, Handle) {
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
let r = app.run("mtext", json!({ "at": [0, 5], "text": "hello", "height": 1 })).unwrap();
|
||||
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let mut harness = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
harness.run_steps(5);
|
||||
harness.state_mut().session.execute("view.set", &json!({ "center": [2, 4], "height": 20 })).unwrap();
|
||||
harness.state_mut().canvas.zoom_pending = false;
|
||||
harness.run_steps(3);
|
||||
(harness, h)
|
||||
}
|
||||
|
||||
fn contents(h: &Harness<'_, CadApp>, m: Handle) -> String {
|
||||
match &h.state().session.doc().unwrap().entity(m).unwrap().kind {
|
||||
EntityKind::MText(x) => x.contents.clone(),
|
||||
_ => panic!("not an mtext"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_clicking_mtext_opens_the_editor() {
|
||||
let (mut h, m) = harness();
|
||||
let pos: Pos2 = h.state().canvas.xf.unwrap().to_screen(Vec2::new(0.5, 4.5));
|
||||
h.event(Event::PointerMoved(pos));
|
||||
h.run_steps(2);
|
||||
for _ in 0..2 {
|
||||
for pressed in [true, false] {
|
||||
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
}
|
||||
}
|
||||
h.run_steps(3);
|
||||
let s = &h.state().session;
|
||||
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("textedit"));
|
||||
assert_eq!(s.editing_mtext().map(|t| t.contents), Some("hello".to_string()), "the editor has the text");
|
||||
h.event(Event::Text("!".into()));
|
||||
h.run_steps(2);
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::Enter);
|
||||
h.run_steps(3);
|
||||
assert_eq!(contents(&h, m), "hello!");
|
||||
assert!(h.state().session.editing_mtext().is_none(), "the editor closed");
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Tab at a point prompt steps through every object snap under the aperture (each endpoint of
|
||||
//! each object nearby), not just the closest snap of each running mode, and comes back round.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
|
||||
use cadcraft_engine::snap::mode;
|
||||
use cadcraft_geom::Vec2;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn tab_cycles_through_every_endpoint_under_the_aperture() {
|
||||
let mut s = Session::new();
|
||||
// Three line ends close together (within the aperture of the cursor between them).
|
||||
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
|
||||
s.execute("line", &json!({ "points": [a, b] })).unwrap();
|
||||
}
|
||||
s.execute("setvar", &json!({ "name": "OSMODE", "value": 1 })).unwrap();
|
||||
s.execute("view.set", &json!({ "center": [0, 0], "height": 20 })).unwrap();
|
||||
let mut app = CadApp::new(s, Services::default());
|
||||
app.canvas.zoom_pending = false;
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.state_mut().session.start("line").unwrap();
|
||||
h.run_steps(2);
|
||||
let xf = h.state().canvas.xf.unwrap();
|
||||
let at = xf.to_screen(Vec2::new(0.03, 0.0));
|
||||
h.event(Event::PointerMoved(at));
|
||||
h.run_steps(2);
|
||||
let mut seen: Vec<Vec2> = Vec::new();
|
||||
for i in 0..4 {
|
||||
let p = h.state().canvas.snap.map(|s| s.point).unwrap();
|
||||
if i < 3 {
|
||||
assert!(!seen.iter().any(|q| q.near(p, 1e-9)), "Tab {i} repeats {p:?} ({seen:?})");
|
||||
} else {
|
||||
assert!(seen.first().is_some_and(|q| q.near(p, 1e-9)), "the fourth Tab comes back round");
|
||||
}
|
||||
seen.push(p);
|
||||
h.event(Event::Text("\t".into()));
|
||||
h.run_steps(2);
|
||||
}
|
||||
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
|
||||
assert!(seen.iter().any(|q| q.near(want, 1e-9)), "{want:?} in {seen:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Three endpoints near 10,0: 10,0 (the nearest to the cursor), 10.03,0 and 9.95,0. Endpoint is
|
||||
/// the only running snap, so every candidate is an endpoint.
|
||||
fn three_ends() -> Harness<'static, CadApp> {
|
||||
let mut d = Drawing::new_imperial();
|
||||
for (a, b) in [((0.0, 0.0), (10.0, 0.0)), ((10.03, 0.0), (20.0, 0.0)), ((9.95, 0.0), (9.95, -5.0))] {
|
||||
let line = Line { a: Vec2::new(a.0, a.1).to3(0.0), b: Vec2::new(b.0, b.1).to3(0.0) };
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(line)).unwrap();
|
||||
}
|
||||
let mut session = Session::empty();
|
||||
session.open_drawing(d, "Tab snap cycling", None);
|
||||
session.execute("view.set", &json!({"center":[10,0],"height":8})).unwrap();
|
||||
session.settings.osmode = mode::END;
|
||||
session.settings.snapmode = false;
|
||||
session.settings.orthomode = false;
|
||||
let mut app = CadApp::new(session, Services::default());
|
||||
app.canvas.zoom_pending = false;
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h.state_mut().start("line");
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.running.as_ref().unwrap().id, "line");
|
||||
let ap = h.state().session.settings.aperture / h.state().canvas.xf.unwrap().scale;
|
||||
assert!(ap > 0.07, "all three endpoints lie in the aperture ({ap})");
|
||||
h
|
||||
}
|
||||
|
||||
const CURSOR: Vec2 = Vec2::new(10.01, 0.0);
|
||||
|
||||
fn hover(h: &mut Harness<'_, CadApp>, p: Vec2) -> Pos2 {
|
||||
let pos = h.state().canvas.xf.unwrap().to_screen(p);
|
||||
h.event(Event::PointerMoved(pos));
|
||||
h.run_steps(3);
|
||||
pos
|
||||
}
|
||||
|
||||
/// Tab, as the command line receives it (`cmdline::capture_tab`).
|
||||
fn tab(h: &mut Harness<'_, CadApp>) {
|
||||
h.event(Event::Text("\t".into()));
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
fn snapped(h: &Harness<'_, CadApp>) -> Vec2 {
|
||||
let hit = h.state().canvas.snap.expect("a snap marker");
|
||||
assert_eq!(hit.mode, mode::END);
|
||||
hit.point
|
||||
}
|
||||
|
||||
fn assert_at(got: Vec2, x: f64) {
|
||||
assert!(got.near(Vec2::new(x, 0.0), 1e-9), "{got:?}, expected {x},0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_the_cursor_away_starts_the_cycle_over() {
|
||||
let mut h = three_ends();
|
||||
hover(&mut h, CURSOR);
|
||||
tab(&mut h);
|
||||
assert_at(snapped(&h), 10.03);
|
||||
hover(&mut h, Vec2::new(10.0, 2.0));
|
||||
assert!(h.state().canvas.snap.is_none());
|
||||
hover(&mut h, CURSOR);
|
||||
assert_at(snapped(&h), 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_places_the_candidate_tab_chose() {
|
||||
let mut h = three_ends();
|
||||
let pos = hover(&mut h, CURSOR);
|
||||
tab(&mut h);
|
||||
assert_at(snapped(&h), 10.03);
|
||||
for pressed in [true, false] {
|
||||
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
}
|
||||
let base = h.state().session.current_prompt().and_then(|p| p.base).expect("LINE asks for the next point");
|
||||
assert_at(base, 10.03);
|
||||
}
|
||||
@@ -73,7 +73,7 @@ fn double_clicked_text_takes_ime_composition_and_commit() {
|
||||
let mut h = harness();
|
||||
double_click(&mut h, Vec2::new(4.0, 1.2));
|
||||
assert_eq!(h.state().session.current_prompt().unwrap().message, "Enter new text");
|
||||
// Without a CJK font (none installed, no craft-fonts) the command line draws 中文 as boxes,
|
||||
// Without a CJK font (none installed, no craft-fonts) the text box draws 中文 as boxes,
|
||||
// which the harness takes for a bug. The IME path below is the same either way.
|
||||
let drawable = h.ctx.fonts_mut(|view| {
|
||||
[egui::FontFamily::Proportional, egui::FontFamily::Monospace]
|
||||
@@ -83,17 +83,17 @@ fn double_clicked_text_takes_ime_composition_and_commit() {
|
||||
if !drawable {
|
||||
h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu);
|
||||
}
|
||||
// Composition is shown, not saved; the commit is inserted exactly once (#1761).
|
||||
// The double-clicked TEXT is edited in place (#842): composition goes into its box, not the
|
||||
// command line, and the commit is inserted exactly once (#1761).
|
||||
h.event(Event::Ime(ImeEvent::Preedit { text: "zhong".into(), active_range_chars: None }));
|
||||
h.run_steps(1);
|
||||
assert_eq!(h.state().cmd.preedit, "zhong");
|
||||
assert!(h.state().cmd.preedit.is_empty());
|
||||
assert!(h.state().cmd.buffer.is_empty());
|
||||
h.event(Event::Ime(ImeEvent::Commit("中文".into())));
|
||||
h.run_steps(1);
|
||||
assert!(h.state().cmd.preedit.is_empty());
|
||||
assert_eq!(h.state().cmd.buffer, "中文");
|
||||
assert!(h.state().cmd.buffer.is_empty());
|
||||
h.key_press(Key::Enter);
|
||||
h.run_steps(1);
|
||||
h.run_steps(2);
|
||||
assert_eq!(text_at(&h, 0), "中文");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
//! Double-clicking TEXT, an attribute definition or a dimension edits its text in place on the
|
||||
//! canvas, as in AutoCAD (#842): Enter or a click outside keeps it, Esc cancels.
|
||||
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_engine::{EditorKind, Session};
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
struct Drawing {
|
||||
text: Handle,
|
||||
attdef: Handle,
|
||||
dim: Handle,
|
||||
}
|
||||
|
||||
fn handle(v: &Value) -> Handle {
|
||||
Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn harness() -> (Harness<'static, CadApp>, Drawing) {
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
let text = handle(&app.run("text", json!({ "at": [0, 0], "text": "HELLO", "height": 2.5 })).unwrap());
|
||||
let attdef = handle(&app.run("attdef", json!({ "tag": "TAG", "default": "D1", "at": [0, 10], "height": 2.5 })).unwrap());
|
||||
let dim = handle(&app.run("dimlinear", json!({ "p1": [0, -10], "p2": [20, -10], "at": [10, -14] })).unwrap());
|
||||
app.session.execute("view.set", &json!({ "center": [10, 0], "height": 40 })).unwrap();
|
||||
app.canvas.zoom_pending = false;
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
(h, Drawing { text, attdef, dim })
|
||||
}
|
||||
|
||||
fn double_click(h: &mut Harness<'_, CadApp>, at: Vec2) {
|
||||
// Far enough from any earlier click not to count as its second or third.
|
||||
h.run_steps(40);
|
||||
let pos: Pos2 = h.state().canvas.xf.unwrap().to_screen(at);
|
||||
h.event(Event::PointerMoved(pos));
|
||||
h.run_steps(2);
|
||||
for _ in 0..2 {
|
||||
for pressed in [true, false] {
|
||||
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
}
|
||||
}
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
fn value(h: &Harness<'_, CadApp>, e: Handle) -> String {
|
||||
match &h.state().session.doc().unwrap().entity(e).unwrap().kind {
|
||||
EntityKind::Text(t) => t.value.clone(),
|
||||
EntityKind::AttDef(a) => a.text.value.clone(),
|
||||
EntityKind::Dimension(d) => d.text.clone(),
|
||||
k => panic!("not text: {}", k.type_name()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one-line editor open on the double-clicked object: its kind and starting text.
|
||||
fn editor(h: &Harness<'_, CadApp>) -> Option<(EditorKind, String)> {
|
||||
h.state().session.text_editor().map(|e| (e.kind, e.mtext.contents))
|
||||
}
|
||||
|
||||
/// Type into the in-place box: the command line gets none of it.
|
||||
fn type_text(h: &mut Harness<'_, CadApp>, s: &str) {
|
||||
h.event(Event::Text(s.into()));
|
||||
h.run_steps(2);
|
||||
assert!(h.state().cmd.buffer.is_empty(), "typed into the command line: {:?}", h.state().cmd.buffer);
|
||||
}
|
||||
|
||||
fn press(h: &mut Harness<'_, CadApp>, key: Key) {
|
||||
h.key_press(key);
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
const TEXT_AT: Vec2 = Vec2::new(4.0, 1.2);
|
||||
const ATTDEF_AT: Vec2 = Vec2::new(2.5, 11.2);
|
||||
const DIM_AT: Vec2 = Vec2::new(4.0, -14.0);
|
||||
|
||||
#[test]
|
||||
fn double_clicked_text_is_edited_in_place_and_undone_in_one_step() {
|
||||
let (mut h, d) = harness();
|
||||
double_click(&mut h, TEXT_AT);
|
||||
assert_eq!(editor(&h), Some((EditorKind::Line, "HELLO".into())));
|
||||
// The whole text opens selected: typing replaces it.
|
||||
type_text(&mut h, "WORLD");
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(value(&h, d.text), "WORLD");
|
||||
assert!(editor(&h).is_none(), "the editor closed");
|
||||
h.state_mut().session.cancel();
|
||||
h.state_mut().session.undo().unwrap();
|
||||
assert_eq!(value(&h, d.text), "HELLO", "one undo takes the edit back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_and_an_emptied_box_leave_the_text_as_it_was() {
|
||||
let (mut h, d) = harness();
|
||||
double_click(&mut h, TEXT_AT);
|
||||
type_text(&mut h, "WORLD");
|
||||
press(&mut h, Key::Escape);
|
||||
assert_eq!(value(&h, d.text), "HELLO");
|
||||
assert!(h.state().session.running.is_none(), "Esc ends the edit");
|
||||
|
||||
double_click(&mut h, TEXT_AT);
|
||||
assert!(editor(&h).is_some());
|
||||
press(&mut h, Key::Backspace);
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(value(&h, d.text), "HELLO", "an emptied box keeps the old text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_outside_the_box_keeps_what_was_typed() {
|
||||
let (mut h, d) = harness();
|
||||
double_click(&mut h, TEXT_AT);
|
||||
type_text(&mut h, "OUTSIDE");
|
||||
let pos = h.state().canvas.xf.unwrap().to_screen(Vec2::new(25.0, 15.0));
|
||||
h.event(Event::PointerMoved(pos));
|
||||
h.run_steps(2);
|
||||
for pressed in [true, false] {
|
||||
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(3);
|
||||
assert_eq!(value(&h, d.text), "OUTSIDE");
|
||||
assert!(editor(&h).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_clicked_attribute_definition_is_edited_in_place() {
|
||||
let (mut h, d) = harness();
|
||||
double_click(&mut h, ATTDEF_AT);
|
||||
// TEXTEDIT edits a definition's default value (as on the command line before #842).
|
||||
assert_eq!(editor(&h), Some((EditorKind::Line, "D1".into())));
|
||||
type_text(&mut h, "D2");
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(value(&h, d.attdef), "D2");
|
||||
h.state_mut().session.cancel();
|
||||
|
||||
double_click(&mut h, ATTDEF_AT);
|
||||
type_text(&mut h, "OTHER");
|
||||
press(&mut h, Key::Escape);
|
||||
assert_eq!(value(&h, d.attdef), "D2", "Esc keeps it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_clicked_dimension_edits_its_text_override() {
|
||||
let (mut h, d) = harness();
|
||||
double_click(&mut h, DIM_AT);
|
||||
let Some((EditorKind::Dimension { measured }, contents)) = editor(&h) else { panic!("no dimension editor: {:?}", editor(&h)) };
|
||||
assert_eq!(contents, "<>", "no override: the measured value");
|
||||
assert!(measured.starts_with("20"), "{measured}");
|
||||
type_text(&mut h, "<> TYP");
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(value(&h, d.dim), "<> TYP");
|
||||
h.state_mut().session.cancel();
|
||||
|
||||
double_click(&mut h, DIM_AT);
|
||||
assert_eq!(editor(&h).map(|e| e.1), Some("<> TYP".into()), "the editor shows the override");
|
||||
type_text(&mut h, "<>");
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(value(&h, d.dim), "", "<> alone is the measured value again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn textedit_through_engine_execute_opens_no_editor() {
|
||||
let (mut h, d) = harness();
|
||||
h.state_mut().run("textedit", json!({ "handle": d.text.hex(), "text": "SCRIPTED" })).unwrap();
|
||||
h.run_steps(3);
|
||||
assert_eq!(value(&h, d.text), "SCRIPTED");
|
||||
assert!(h.state().session.running.is_none());
|
||||
assert!(editor(&h).is_none());
|
||||
}
|
||||
|
||||
/// The box covers the text as drawn, from its drawn left edge, for left-justified and
|
||||
/// middle-centre text alike (not starting at a centred text's insertion point).
|
||||
#[test]
|
||||
fn the_box_covers_the_drawn_text_whatever_its_justification() {
|
||||
let (mut h, d) = harness();
|
||||
let mc = handle(&h.state_mut().run("text", json!({ "at": [16, 16], "text": "Middle centre", "height": 2.5, "justify": "MC" })).unwrap());
|
||||
h.run_steps(3);
|
||||
for (e, at) in [(d.text, TEXT_AT), (mc, Vec2::new(16.0, 16.0))] {
|
||||
double_click(&mut h, at);
|
||||
assert!(editor(&h).is_some(), "{e:?}: no editor");
|
||||
let drawn = {
|
||||
let s = &h.state().session;
|
||||
let doc = s.doc().unwrap();
|
||||
let EntityKind::Text(t) = &doc.entity(e).unwrap().kind else { panic!("not text") };
|
||||
let b = cadcraft_engine::render::place_text_entity(doc, t, &t.value).1;
|
||||
let xf = h.state().canvas.xf.unwrap();
|
||||
egui::Rect::from_points(&[
|
||||
xf.to_screen(b.min),
|
||||
xf.to_screen(b.max),
|
||||
xf.to_screen(Vec2::new(b.min.x, b.max.y)),
|
||||
xf.to_screen(Vec2::new(b.max.x, b.min.y)),
|
||||
])
|
||||
};
|
||||
let area = h.ctx.memory(|m| m.area_rect(egui::Id::unique("line_editor_area"))).expect("the box is shown");
|
||||
assert!(area.expand(0.5).contains_rect(drawn), "{e:?}: box {area:?} does not cover the drawn text {drawn:?}");
|
||||
assert!((area.left() - drawn.left()).abs() <= 4.0, "{e:?}: box starts at {} but the text at {}", area.left(), drawn.left());
|
||||
press(&mut h, Key::Escape);
|
||||
}
|
||||
}
|
||||
|
||||
/// Each box starts with no undo history: Ctrl+Z in a newly opened box can't bring back the text
|
||||
/// typed into the last one (review of #842).
|
||||
#[test]
|
||||
fn undo_in_a_new_box_does_not_bring_back_another_objects_text() {
|
||||
let (mut h, d) = harness();
|
||||
double_click(&mut h, TEXT_AT);
|
||||
type_text(&mut h, "WORLD");
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(value(&h, d.text), "WORLD");
|
||||
h.state_mut().session.cancel();
|
||||
|
||||
double_click(&mut h, ATTDEF_AT);
|
||||
assert_eq!(editor(&h).map(|e| e.1), Some("D1".into()));
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::Z);
|
||||
h.run_steps(2);
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(value(&h, d.attdef), "D1", "Ctrl+Z took another object's text");
|
||||
assert_eq!(value(&h, d.text), "WORLD");
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//! OPEN typed at the command line with the file to open reads it in the background, as
|
||||
//! File ▸ Open does, so a large drawing doesn't freeze the window. Programmatic calls (the control
|
||||
//! channel, MCP, scripts, LISP) still get their answer at once.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::{CadApp, Services, cmdline};
|
||||
use serde_json::json;
|
||||
|
||||
#[path = "../support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
|
||||
/// A reader that accepts any file (the same one other tests in this binary install, so whichever
|
||||
/// is installed first, opening works the same).
|
||||
fn install_reader() {
|
||||
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
|
||||
read: |_, _| Ok(cadcraft_engine::doc::Drawing::new_metric()),
|
||||
write: |_, _| Ok(b"0\nSECTION\n0\nENDSEC\n0\nEOF\n".to_vec()),
|
||||
plot: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// Type `line` and press Enter, as the person at the keyboard does.
|
||||
fn type_line(app: &mut CadApp, line: &str) {
|
||||
app.cmd.buffer = line.to_string();
|
||||
cmdline::submit(app);
|
||||
}
|
||||
|
||||
/// Wait for the drawings being read in the background to be added (or reported).
|
||||
fn settle(app: &mut CadApp) {
|
||||
let t = Instant::now();
|
||||
while app.opening.busy() && t.elapsed() < Duration::from_secs(10) {
|
||||
app.finish_opening();
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
app.finish_opening();
|
||||
}
|
||||
|
||||
fn title(app: &CadApp) -> Option<String> {
|
||||
app.session.state().ok().map(|s| s.title.clone())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_open_with_a_path_reads_in_the_background() {
|
||||
install_reader();
|
||||
let dir = TempDir::new("typed-open");
|
||||
let plan = dir.file("plan.dxf", b"0\nEOF\n");
|
||||
let section = dir.file("section.dxf", b"0\nEOF\n");
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
let before = app.session.docs.len();
|
||||
|
||||
type_line(&mut app, &format!("OPEN {plan}"));
|
||||
assert!(app.opening.busy(), "the read runs on the background reader: {:?}", app.session.log);
|
||||
assert_eq!(app.session.docs.len(), before, "nothing is added until the read finishes");
|
||||
settle(&mut app);
|
||||
assert_eq!(app.session.docs.len(), before + 1);
|
||||
assert_eq!(title(&app).as_deref(), Some("plan.dxf"), "the opened drawing is the active tab");
|
||||
assert_eq!(app.ui.recent_files.first(), Some(&plan));
|
||||
|
||||
// The JSON form with only a path, typed: the same.
|
||||
type_line(&mut app, &format!("open {}", json!({ "path": section })));
|
||||
assert!(app.opening.busy());
|
||||
settle(&mut app);
|
||||
assert_eq!(app.session.docs.len(), before + 2);
|
||||
assert_eq!(title(&app).as_deref(), Some("section.dxf"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn programmatic_open_with_a_path_still_answers_at_once() {
|
||||
install_reader();
|
||||
let dir = TempDir::new("programmatic-open");
|
||||
let plan = dir.file("plan.dxf", b"0\nEOF\n");
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
let before = app.session.docs.len();
|
||||
|
||||
// engine.execute / app.open on the control channel, and MCP.
|
||||
let r = app.run("open", json!({ "path": plan }));
|
||||
assert!(!app.opening.busy());
|
||||
let index = r.ok().and_then(|v| v.get("index").and_then(serde_json::Value::as_u64));
|
||||
assert_eq!(index, Some(before as u64), "the result names the opened drawing");
|
||||
assert_eq!(title(&app).as_deref(), Some("plan.dxf"));
|
||||
|
||||
// `cmdline.input` on the control channel and a script line: the drawing is open when they return.
|
||||
assert_eq!(app.cmdline(&format!("open {}", json!({ "path": plan }))), None);
|
||||
assert!(!app.opening.busy());
|
||||
assert_eq!(app.session.docs.len(), before + 2);
|
||||
app.session.script(&format!("open {}\n", json!({ "path": plan }))).ok();
|
||||
assert!(!app.opening.busy());
|
||||
assert_eq!(app.session.docs.len(), before + 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_open_of_a_missing_file_reports_the_same_error() {
|
||||
install_reader();
|
||||
let dir = TempDir::new("typed-open-missing");
|
||||
let missing = dir.path_str("gone.dxf");
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
let before = app.session.docs.len();
|
||||
let expected = app.run("open", json!({ "path": missing })).err().unwrap_or_default();
|
||||
assert!(expected.contains("gone.dxf"), "{expected}");
|
||||
|
||||
type_line(&mut app, &format!("OPEN {missing}"));
|
||||
settle(&mut app);
|
||||
assert_eq!(app.session.docs.len(), before);
|
||||
assert_eq!(app.session.log.last(), Some(&expected), "{:?}", app.session.log);
|
||||
assert_eq!(app.status.as_ref().map(|(s, _)| s.as_str()), Some(expected.as_str()));
|
||||
}
|
||||
+16
-14
@@ -1,6 +1,6 @@
|
||||
# Where CADCraft falls short of AutoCAD
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (re-audit against main 7cee28580: file-test and catalog counts, REFEDIT, dynamic-block and QSAVE rows; previously: QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated; previously: BEDIT in the Block Editor switches blocks: F3 updated; previously: Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected; previously: DIMTFILL limits in the `*D` block, EXPLODE and DXF: F7 updated; re-audit against main 41d9b5e95: CI gate (#6, S1), MVIEW Restore (F15, U11), open-PR and catalog counts, file-test count; previously: Command Aliases dialog for ALIASEDIT: U12 and E5 narrowed) · **Target:** Autodesk AutoCAD 2027
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (alpha-blocker marks follow the six-row gate of 2026-11-19; rows updated for what merged on 2026-11-19 and 2026-11-20: the Dimension Style Manager, the UCS command, in-place TEXT editing, -ATTEDIT, -RENAME and -LAYER options, ARRAY Key point, right-click settings and the interface reset; new row P4 for startup on older graphics hardware; previously: re-audit against main 7cee28580: file-test and catalog counts, REFEDIT, dynamic-block and QSAVE rows; previously: QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated; previously: BEDIT in the Block Editor switches blocks: F3 updated; previously: Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected; previously: DIMTFILL limits in the `*D` block, EXPLODE and DXF: F7 updated; re-audit against main 41d9b5e95: CI gate (#6, S1), MVIEW Restore (F15, U11), open-PR and catalog counts, file-test count; previously: Command Aliases dialog for ALIASEDIT: U12 and E5 narrowed) · **Target:** Autodesk AutoCAD 2027
|
||||
|
||||
Every known shortfall, one row each, ranked within each section by user impact. This is the work
|
||||
list: agents pick from here (top of a section first). A PR names the rows it closes in its
|
||||
@@ -16,7 +16,7 @@ do them first.
|
||||
| 1 | **[alpha blocker]** **Saving DWG drops what we don't model** (DXF now writes back unknown entities and objects, foreign xdata, extension dictionaries, reactors, layer states and colour books, #528, and native MULTILEADERs, #459 (not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour books and reactors; the ACIS data of 3D solids, regions and bodies is kept, #781; a user's QSAVE now asks before replacing the file and keeps the previous one as `.bak`, which reduces the harm but does not close this row) | Opening a colleague's DWG and saving it still deletes some content: the one thing a CAD user can't forgive | 6–10 | [file formats](file-format-parity.md) |
|
||||
| 2 | **[alpha blocker]** **No real-file test corpus and no check in AutoCAD** | All 88 file tests (`crates/io/src/tests.rs`) use synthetic data (the real-file runs in PRs #781 and #859 were manual and are not committed); nobody has verified a CADCraft DWG/DXF opens cleanly in AutoCAD | 10–15 + human | [file formats](file-format-parity.md#tests) |
|
||||
| 3 | **Ellipse and spline geometry is tessellated** (intersections, offsets, closest points; polyline offset recomputes arc bulges since #825 but has no loop cleanup) | Coordinates are subtly wrong; offsets of ellipses come out as polylines | 30–50 | [geometry](geometry-parity.md) |
|
||||
| 4 | **[alpha blocker]** **No dynamic-block authoring; xrefs can't be edited in place** (REFEDIT, REFSET and REFCLOSE edit block references in place, #818; XCLIP and XCLIPFRAME clip block and xref references, #2354; dynamic block references are read and edited, #838–#883; xrefs, #525, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) |
|
||||
| 4 | **No dynamic-block authoring; xrefs can't be edited in place** (REFEDIT, REFSET and REFCLOSE edit block references in place, #818; XCLIP and XCLIPFRAME clip block and xref references, #2354; dynamic block references are read and edited, #838–#883; xrefs, #525, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them; counted under beta since the gate revision of 2026-11-19 (few reports) | 55–90 | [features](#features) |
|
||||
| 5 | **No autosave in the web build** (the desktop app has SAVETIME autosave, Drawing Recovery, AUDIT and RECOVER since #406) | Browser users lose unsaved work when the tab or the browser goes down | 3–5 | [features](#features) |
|
||||
| 6 | ~~**No CI runs the Rust tests on pull requests**~~ fixed: `.github/workflows/ci.yml` runs `cargo xtask ci` on every pull request and push to main through the shared gate workflow (#1987); `cargo fmt` on main is fixed. | — | 0 | [stability](#stability) |
|
||||
|
||||
@@ -24,15 +24,15 @@ do them first.
|
||||
|
||||
| # | Gap | Evidence | User impact | Est. |
|
||||
|---|---|---|---|---|
|
||||
| F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations, DVIEW CAmera, TArget, Distance, POints, CLip and Hide (they need a 3D camera; TWist, PAn, Zoom, Off and Undo work). SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs`, `cmd/view/dview.rs` | Low: the most-used commands are done | 1–3 |
|
||||
| F1 | Prompt options that still print "not available yet": colour books in -ATTEDIT Color, -RENAME of materials and plot styles, -LAYER stAte Import and EXport, DVIEW CAmera, TArget, Distance, POints, CLip and Hide (they need a 3D camera; TWist, PAn, Zoom, Off and Undo work). -ATTEDIT one-at-a-time Position, Height, Angle and Style, -RENAME of viewport configurations and -LAYER stAte landed (#3311); the new -ATTEDIT prompt texts are not yet compared with AutoCAD's. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs`, `cmd/view/dview.rs` | Low: the most-used commands are done | 1–3 |
|
||||
| F2 | XREF editing in place: REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XCLIP clips a block or xref reference to a rectangular, polygonal or closed-polyline boundary (Invert clip, ON/OFF, Delete, generate Polyline; Clipdepth is ignored in 2D), drawn, plotted and framed as XCLIPFRAME says, with the extents cut to it, and kept through DXF and DWG as the reference's SPATIAL_FILTER (2026-10-27). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place | 12–20 |
|
||||
| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 |
|
||||
| F3 | No dynamic-block authoring (beta checklist): parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 |
|
||||
| F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 |
|
||||
| F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 |
|
||||
| F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 |
|
||||
| F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) (the Key point base point of ARRAY and ARRAYEDIT landed, #2368), levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 |
|
||||
| F7 | Dimensions: no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (the Dimension Style Manager, -DIMSTYLE and dimension properties landed, #1460; an edited dimension keeps its values on save, #3335; style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 |
|
||||
| F8 | TOLERANCE leftovers (feature control frames landed, #420: model, our own symbol drawing, DXF, command-line prompts, explode, grips): no Geometric Tolerance dialog, no LEADER/QLEADER tolerance annotation, no in-place editing of a frame's contents | `cmd/tolerance.rs` | Low-medium (mechanical) | 2–4 |
|
||||
| F10 | MLEADEREDIT (add/remove leader), MLEADERALIGN and MLEADERCOLLECT landed, but a multileader has one landing and one block (a collection keeps the other blocks as block references beside it; MLEADERALIGN has no Options-menu preview); MLEADERSTYLE has 6 settings (arrow size, text height, landing gap, dogleg, text style, annotative; block content and spline/no-leader types are per command, not in the style; block content has no attributes) | `annotate.rs`, `cmd/mleader_content.rs`, `cmd/mleader_edit.rs`, `doc/src/tables.rs` | Medium | 8–12 |
|
||||
| F9 | MTEXT is typed in an on-canvas editor with a formatting toolbar (font, height, bold, italic, underline, overline, colour, alignment, lists, tab and special characters) and a ruler for indents and tab stops (#532); left: the box does not lay the text out by the indents, tabs, columns or font weights while typing (bold shows wider, overline is not drawn), no justification (attachment) or columns controls in the editor, existing TEXT is edited as plain text on the command line with TEXTEDIT (alias DDEDIT; a double-click starts it, #868), while an existing MTEXT opens in the in-place editor with its contents (#1002, merged 2026-11-06); stacked fractions and other codes show as placeholders; no fields (FIELD, UPDATEFIELD) and no spell check (SPELL): open PR #551. Paragraph indents, tabs, bullets, numbering and columns landed (#547) | `ui-egui/mtext_editor.rs`, `engine/mtext_edit.rs` | Medium | 10–18 |
|
||||
| F9 | MTEXT is typed in an on-canvas editor with a formatting toolbar (font, height, bold, italic, underline, overline, colour, alignment, lists, tab and special characters) and a ruler for indents and tab stops (#532); left: the box does not lay the text out by the indents, tabs, columns or font weights while typing (bold shows wider, overline is not drawn), no justification (attachment) or columns controls in the editor, a double-click edits existing TEXT, an attribute definition or a dimension's text in a box on the canvas (#3345; table cells are not edited in place, and the box was not checked on a HiDPI screen or in a twisted view), and an existing MTEXT opens in the in-place editor with its contents (#1002); stacked fractions and other codes show as placeholders; no fields (FIELD, UPDATEFIELD) and no spell check (SPELL): open PR #551. Paragraph indents, tabs, bullets, numbering and columns landed (#547) | `ui-egui/mtext_editor.rs`, `engine/mtext_edit.rs` | Medium | 10–18 |
|
||||
| F11 | Tables (cell styles, formulas, TABLEDIT, TABLEEXPORT, table breaking and CSV data links landed, #534): formulas aren't read from or written as AutoCAD FIELD objects (other programs see values); number formats apply to formula results only; cell text doesn't wrap; custom cell styles, breaks and data links travel as CADCraft xdata (not through DWG); data links read CSV only (no Excel ranges, no write-back, not on the web); no cell-style tab in the Table Style dialog | `cmd/table/*`, `io/dxf_table.rs` | Low-medium | 6–10 |
|
||||
| F12 | Annotative scaling done (#468): scale list (SCALELISTEDIT), CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE/ANNOAUTOSCALE, viewport scale, DXF, status bar list. Left: per-scale positions (ANNORESET is a no-op), a viewport annotation scale apart from its viewport scale, annotative objects inside blocks and old LEADERs, AutoCAD files' per-object scale contexts (read as not annotative) | `cmd/annoscale.rs`, `doc/src/anno.rs` | Low-medium | 4–8 |
|
||||
| F14 | **[alpha blocker]** Plotting leftovers: binary `.ctb`/`.stb`/`.pc3` files can't be read; no system printers (H3); the page setup's "Plot transparency" is not saved in DXF/DWG (the public DXF Reference has no plot layout flag for it), so it lasts for the session and in JSON only. The Plot dialog (#160), Plot Preview and PUBLISH (#186), plot styles (CTB and STB, [plot-styles.md](plot-styles.md), #410) with their end, join and fill styles, plotter devices with paper sizes and printable areas ([plotters.md](plotters.md), #564), and plotted transparency (page setup and Plot dialog option, PLOTTRANSPARENCYOVERRIDE) landed | `io/src/plotter.rs`, `cmd/plotters.rs` | Medium | 4–8 |
|
||||
@@ -41,11 +41,11 @@ do them first.
|
||||
| F16 | Groups: no group bounding box or single grip when a group is selected (GROUPDISPLAYMODE), copying a whole group does not make a new group, no Object Grouping dialog (GROUP, GROUPEDIT, UNGROUP, -GROUP, PICKSTYLE group selection and the DXF/DWG round trip landed, #417); PICKSTYLE's associative-hatch bit is stored but unused | `cmd/groups.rs` | Low | 2–4 |
|
||||
| F17 | Attributes (ATTSYNC, global -ATTEDIT, BATTMAN editing and DATAEXTRACTION/EATTEXT landed, #433): the Verify, Preset and Lock position modes are kept in files and Lock position is applied by INSERT and ATTSYNC (#876), but INSERT doesn't act on Verify or Preset, and multiline attributes (read, drawn and saved since 2026-10-12) can't be created or switched in BATTMAN; data extraction covers block references and attribute values (CSV or a table) only — no wizard, nested blocks, other objects' properties, `.dxe` templates or spreadsheet output | `cmd/blocks/battman.rs`, `cmd/blocks/extract.rs` | Low | 4–6 |
|
||||
| F19 | MATCHPROP Settings is a keyword prompt (no dialog) and has no material, shadow or centre-object settings; TEXTTOFRONT and HATCHTOBACK act on the current space only; OVERKILL doesn't compare polyline segments with other objects (picker and Settings, DRAWORDER Above/Under, TEXTTOFRONT, HATCHTOBACK, OVERKILL tolerance/ignore/overlap/end-to-end options landed, #439) | `props/matchprop.rs`, `draworder.rs`, `overkill.rs` | Low | 2–4 |
|
||||
| F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Left: right-click customization, the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export Open and Save has the backup copy checkbox (ISAVEBAK). | `ui-egui/src/options/` | Low | 2–4 |
|
||||
| F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Right-Click Customization and the time-sensitive right-click landed (#2371, #3307), and Reset restores the whole interface (#3308). Left: the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export Open and Save has the backup copy checkbox (ISAVEBAK). | `ui-egui/src/options/` | Low | 2–4 |
|
||||
| F21 | MLINE, REGION and HELIX are objects since #510, with gaps: MLEDIT tees trim square; UNION/SUBTRACT/INTERSECT only combine regions whose boundaries don't meet; regions are saved as closed polylines (no ACIS data) | `draw2/mline.rs`, `inquiry/regions.rs`, `dxf_region.rs` | Low | 6–10 |
|
||||
| F22 | Inquiry leftovers (COUNT across spaces and nested blocks, the QuickCalc palette and COMPARE landed, #563; MASSPROP on regions, #510): COMPARE compares the tab shown, not every layout at once (COMPAREEXPORT, the comparison as a new drawing, landed); COMPAREEXPORT puts the two sets of objects in model-space groups, where AutoCAD puts them in blocks; QuickCalc keeps its history and variables for the session only | `file/compare.rs`, `palettes/quickcalc.rs` | Low | 3–5 |
|
||||
| F23 | No Sheet Set Manager, eTransmit, Share, Traces, Markup Import, Activity Insights | menu items uncovered | Low-medium (team workflows) | 40–70 |
|
||||
| F24 | No 3D: UCS, 3D views, orbit, solids, surfaces, meshes, sections, visual styles, materials, lights, rendering (150 menu items) | [parity-checklist](parity-checklist.md) | Medium (3D users) | 300–450 |
|
||||
| F24 | No 3D: 3D views (the UCS command, named UCSs and the UCS icon work in the drawing plane since #3310), orbit, solids, surfaces, meshes, sections, visual styles, materials, lights, rendering (150 menu items) | [parity-checklist](parity-checklist.md) | Medium (3D users) | 300–450 |
|
||||
|
||||
## UI/UX
|
||||
|
||||
@@ -65,7 +65,7 @@ or allow clicks and drag (2, default), saved in the user profile. Drag-only mode
|
||||
| U10 | SETVAR covers about 150 of ~1,000 variables (UNDO options, MREDO and UNDOCTL, and header variables such as CIRCLERAD, OFFSETDIST, POLYSIDES, HPNAME and the dimension variables in SETVAR ? landed, #461; typing a bare variable name as a command runs SETVAR on it) | Low-medium | 3–5 |
|
||||
| U11 | VIEW Orthographic, UCS and background settings (view twist: DVIEW on the Model tab, each VPORTS tile and each layout viewport, VIEWTWIST, landed; Zoom Realtime and Dynamic, ZOOMFACTOR, named views (VIEW) and tiled model viewports with saved configurations (VPORTS) landed in #463, MVIEW Restore in #633, and the Named Viewports dialog, which restores or deletes a saved configuration) | Low | 1–2 |
|
||||
| U12 | Workspaces, navigation bar, CUI customisation, ViewCube drag (#7) (the Command Aliases dialog landed, #1381) | Low-medium | 13–23 |
|
||||
| U13 | `.dxf` from Finder fails to open on macOS (#158) (window controls fixed, #161) | Medium | 1–2 |
|
||||
| U13 | `.dxf` from Finder fails to open on macOS (#158; #3344, which lands #1347, is written but has never been built or run on a Mac and waits for someone to check it there) (window controls fixed, #161) | Medium | 1–2 |
|
||||
|
||||
## File formats
|
||||
|
||||
@@ -78,7 +78,7 @@ Detail: [file-format-parity.md](file-format-parity.md).
|
||||
| FF3 | Save-version leftovers (DXF/DWG 2000–2018, binary DXF, SAVEAS `version`/`binary` and the default save version landed, #421): no R14 DWG or R12 DXF output; the Save dialog can't pick the version per file (the file picker doesn't report the chosen type; File > Default Save Format sets it); no command-line SAVEAS format prompt | Low | 2–4 |
|
||||
| FF4 | Code-page leftovers (pre-2007 DXF read in their `$DWGCODEPAGE` landed, #505): Johab (ANSI_1361) and DOS 855/857/860–865/869 read as ANSI_1252; saving declares `ANSI_1252` instead of the file's code page (the text is pure ASCII, so still correct); acadrust approximates DOS code pages in pre-2007 DWG (DOS437 as 866, DOS850 as 1252) | Low | 1–2 |
|
||||
| FF5 | **[alpha blocker]** Real-file corpus (`storytold/cadcraft-corpus`), open → save → reopen tests, black-box check in AutoCAD | High | 10–15 + human |
|
||||
| FF6 | **[alpha blocker]** DWG throughput: a 10 MB DWG took ~2 min to fail (#57) | High for real projects | 6–10 |
|
||||
| FF6 | **[alpha blocker]** DWG throughput: a 10 MB DWG took ~2 min to fail (#57); large DWGs are refused at the size limits of the shared DWG library (512 MB of DWG, 1 GiB once converted, which a DWG of about 150 MB can reach; #3102, #2633, #1088). A typed `OPEN <path>` reads in the background (#3343); an open can't be cancelled and shows no progress | High for real projects | 6–10 |
|
||||
| FF7 | Table record and object handles from other programs' files are renumbered on the first save (entity handles are kept; `*D` blocks no longer duplicate and once reopened, CADCraft's own files keep every handle across saves, #495) | Low | 4–6 |
|
||||
| FF8 | SHX shape fonts, big fonts and unifonts are read and drawn (2026-10-22; looked up by file name beside the drawing, in `CADCRAFT_SHXPATH`, via a font map or registered by the web app; FONTALT). Left: no Options entry for the search path or font map; no desktop drag-drop of `.shx`; big-font code page guessed from the file name; vertical text not justified along its column; extended big font box scaling unverified against real files | Medium | 2–4 |
|
||||
| FF9 | `.pc3` plotter configuration files; shape elements in user `.lin` files are dropped on load (DXF/DWG linetype shape elements are drawn since 2026-10-22; templates and `.dwt`, user `.lin`/`.pat` and `.pgp` alias files landed, #552; `.ctb`/`.stb`, #410) | Low-medium | 4–8 |
|
||||
@@ -96,7 +96,7 @@ Detail: [hardware-parity.md](hardware-parity.md).
|
||||
|---|---|---|
|
||||
| H1 | 3Dconnexion SpaceMouse: 2D pan and zoom through raw HID on Windows and Linux landed (#650, Tools ▸ 3D Mouse; PR #983 open); none on macOS or the web, no 3D navigation (needs 3D views), not yet checked on a physical device in #650 | 6–10 + human |
|
||||
| H2 | Multi-monitor: floating palettes on other screens, per-monitor DPI (the Windows 11 DPI fix is in open PR #668, which replaced the closed PR #110) | 4–6 |
|
||||
| H3 | System printers (PC3 devices) beyond PDF, PNG and SVG plotter devices (CUPS printing on macOS and Linux is open PR #755) | 6–10 |
|
||||
| H3 | **[alpha blocker]** System printers (PC3 devices) beyond PDF, PNG and SVG plotter devices (CUPS printing on macOS and Linux is open PR #755) | 6–10 |
|
||||
| H4 | Pen tablets / digitizer (TABLET) | 3–5 + human |
|
||||
| H5 | Screen magnifier tracking: the system-cursor option landed (PR #187); issue #39 is still open | 1–2 |
|
||||
|
||||
@@ -117,7 +117,7 @@ Detail: [localization-parity.md](localization-parity.md).
|
||||
|---|---|---|---|
|
||||
| S1 | ~~No CI runs `cargo xtask ci` on pull requests~~ fixed: `ci.yml` runs it on every pull request and push to main (#1987) | `.github/workflows/ci.yml` | 0 |
|
||||
| S2 | ~~`cargo fmt --check` fails on main~~ fixed on main (8fceaaf) | — | 0 |
|
||||
| S3 | 450 open PRs (2026-10-24), many community bug fixes awaiting review | `gh pr list` | 10–20 |
|
||||
| S3 | 661 open PRs (2026-11-20; 714 the day before), many community bug fixes awaiting review | `gh pr list` | 10–20 |
|
||||
| S4 | Open correctness issues: extents union far-apart geometry (#166), lines not visible mid-command (#44), browser plot shows raw PDF bytes (#134) (closing a tab and browser saves fixed, #76, #133) | issues | 4–6 |
|
||||
| S5 | No smoke test of every command through the UI (open PR #42 proposes one) | — | 6–10 |
|
||||
|
||||
@@ -127,7 +127,8 @@ Detail: [localization-parity.md](localization-parity.md).
|
||||
|---|---|---|
|
||||
| P1 | Web build: plot shows raw PDF bytes (#134), no DWG (File > Open and save downloads fixed, #55, #133) | 3–5 |
|
||||
| P2 | Windows and Linux get little runtime testing; Linux Mint mouse delay (#25: the vsync fix landed, #183, the issue is open); Windows magnifier (#39: system-cursor option landed, #187, the issue is open) | 6–10 |
|
||||
| P3 | macOS file associations: opening `.dxf` from Finder fails (#158; open PRs #683 and #899) | 1–2 |
|
||||
| P3 | macOS file associations: opening `.dxf` from Finder fails (#158; #3344 lands #1347 and waits for a check on a Mac; #683 and #899 are open) | 1–2 |
|
||||
| P4 | **[alpha blocker]** Startup on older graphics hardware: a black window or a crash on older Intel graphics, older macOS and some virtual machines (#1724, #1631, #3222, #1780). `CADCRAFT_STENCIL=0` starts the app without a stencil buffer (#3336) but has to be set by hand; there is no automatic fallback renderer | not estimated |
|
||||
|
||||
## Ecosystem and automation
|
||||
|
||||
@@ -150,6 +151,7 @@ Detail: [localization-parity.md](localization-parity.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | minor | Batch for what merged on 2026-11-19 and 2026-11-20, and the six-row alpha gate: alpha-blocker marks removed from row 4, F1 and F3 (not gate rows any more) and added to H3 and the new P4 (startup on older graphics hardware, #3336); F1 narrowed (-ATTEDIT, -RENAME and -LAYER options, #3311); F5 (ARRAY Key point, #2368); F7 (Dimension Style Manager, #1460; dimension values kept on save, #3335); F9 (double-click edits TEXT, attribute definitions and dimension text in place, #3345); F20 (right-click settings, interface reset, #3308); F24 (UCS in the drawing plane, #3310); FF6 (size limits, typed OPEN in the background, #3343); U13 and P3 (#3344 waits for a Mac); S3 count. Hours not re-estimated |
|
||||
| 2026-11-03 | minor | XCLIP (rectangular, polygonal and polyline boundaries, Invert clip, ON/OFF, Delete, generate Polyline) and XCLIPFRAME: a boundary per block or xref reference (`Insert::clip`, block coordinates), drawn, plotted and framed clipped, the extents cut to it, and read and written as the reference's ACAD_FILTER/SPATIAL SPATIAL_FILTER in DXF and DWG: F2 and top-10 row 4 narrowed |
|
||||
| 2026-11-03 | minor | SHX fonts: shape fonts, big fonts and unifonts read (`cadcraft_fonts::shx`, every count and offset bounded) and drawn for TEXT, MTEXT, attributes, dimensions and tables, with the style's big font and vertical flag; found by file name beside the drawing, in `CADCRAFT_SHXPATH`, through a font map or from `.shx` files opened in the web app, never in another CAD program's folder; FONTALT may name a font and a big font; linetype shape elements drawn when their file is found: FF8 and FF9 narrowed |
|
||||
| 2026-10-30 | minor | QSAVE asks before replacing a file with content the DWG writer can't keep, and ISAVEBAK keeps the previous file as `.bak`: row 1 narrowed, FF1 and F20 updated |
|
||||
|
||||
+10
-9
@@ -1,6 +1,6 @@
|
||||
# CADCraft roadmap detail
|
||||
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-19 · **Change:** major (alpha gate revised from user reports: six rows, Windows first; current focus re-ranked into three tiers; percentages and hours not re-scored; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-20 · **Change:** minor (alpha gate evidence updated for what merged on 2026-11-19 and 2026-11-20; no row changes its verdict until the reporters confirm; previously major: alpha gate revised from user reports: six rows, Windows first; current focus re-ranked into three tiers; percentages and hours not re-scored; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
|
||||
Forward-looking plan: milestones with status, the current focus, and what comes next with
|
||||
estimates. The summary is [ROADMAP.md](../ROADMAP.md); the work items behind every line are in
|
||||
@@ -14,11 +14,11 @@ already written and waiting in a pull request lands before new work starts, firs
|
||||
|
||||
1. **Urgent: security fixes, leaks, crashes and lost work.** The open security-audit findings
|
||||
(#1919–#1935) are checked against the input limits that landed on 2026-11-11, then closed or
|
||||
fixed; #1276 fixes the crafted-handle overwrite (#1921). Hostile-input fixes are waiting in
|
||||
#2820, #2821 and #2765. Crashes and hangs with a reproduction come next: #1603 (web, large DXF),
|
||||
fixed; #1276 fixes the crafted-handle overwrite (#1921). The hostile-input fixes #2820, #2821 and #2765 landed on
|
||||
2026-11-20 (#3304, #3305). Crashes and hangs with a reproduction come next: #1603 (web, large DXF),
|
||||
#2174 (DWG with 3D content), #1724, #1631 and #3222 (startup).
|
||||
2. **Parity with AutoCAD.** The failing [alpha gate](#alpha-gate) rows in their order, then the
|
||||
[beta checklist](#beta-checklist), apart from the checklist items named under tier 3. 714 pull requests are open (2026-11-19); about 230 of them are
|
||||
[beta checklist](#beta-checklist), apart from the checklist items named under tier 3. 661 pull requests are open (2026-11-20; 714 the day before); about 230 of them were
|
||||
mergeable, pass CI and are small, and many already fix a gate row.
|
||||
3. **Lower priority.** Work that affects fewer people and that nothing breaks without: dynamic-block
|
||||
authoring, editing an xref in place, exact ellipse and spline geometry, prompt options that need
|
||||
@@ -40,12 +40,12 @@ evidence has limits: there is no telemetry, and someone whose copy never starts
|
||||
|
||||
| Row | Passes? | Evidence | Passes when |
|
||||
|---|---|---|---|
|
||||
| It starts on the hardware people have | **no** | Black window or a crash at startup on older Intel graphics, older macOS and some virtual machines (#1724, #1631, #3222, #1780); `CADCRAFT_STENCIL=0` is waiting in #1596; no automatic fallback renderer | It reaches a usable drawing area on Windows 10 and 11 with old integrated graphics, in a virtual machine, and on the supported macOS and Linux versions, choosing a fallback renderer by itself |
|
||||
| It opens the DWG and DXF files people already have, correctly and in reasonable time | **no** | Large DWGs are refused at a size limit or freeze the window (#3102, #2633, #1088); layouts come in at the wrong scale or in the wrong units (#1672, #2836); a DWG with 3D content crashes or opens empty (#2174); the corpus holds four files, all written by CADCraft, and CI does not run it | A corpus of files made by AutoCAD and other CAD programs opens in CI with its objects, layouts, viewports and units right, compared with what the program that wrote it shows; a large file opens or says clearly why not; content we don't model is kept and never crashes |
|
||||
| Saving loses nothing, and other CAD programs open the result | **no** | DXF keeps what we don't model (#528); other applications' objects are kept as proxies (#2917, #2919, #2654); through DWG, custom-class objects without data for the version written are still dropped; fixes for files AutoCAD or BricsCAD refuse are waiting (#2904, #1687, #3234); never checked against a corpus in AutoCAD | The corpus round-trips with every object kept and its geometry and properties unchanged, a save names anything it could not keep, and AutoCAD opens the saved files without a recovery prompt |
|
||||
| Input feels like AutoCAD for Windows | **partial, blocking** | Running snaps, polar, ortho, coordinate entry, tracking, FROM/M2P/TK and dynamic input work; a click while the mouse moves can be lost (#1001, #2092), right-click and Space don't always act as Enter (#1387), a double-click doesn't edit TEXT in place (#842); fixes are waiting in pull requests | A click counts while the pointer moves; right-click and Space repeat or confirm as set in Options; a double-click edits text, multiline text and dimension text in place |
|
||||
| It starts on the hardware people have | **no** | Black window or a crash at startup on older Intel graphics, older macOS and some virtual machines (#1724, #1631, #3222, #1780); `CADCRAFT_STENCIL=0` starts without a stencil buffer (#3336) but must be set by hand, and no reporter has confirmed it yet; no automatic fallback renderer | It reaches a usable drawing area on Windows 10 and 11 with old integrated graphics, in a virtual machine, and on the supported macOS and Linux versions, choosing a fallback renderer by itself |
|
||||
| It opens the DWG and DXF files people already have, correctly and in reasonable time | **no** | Large DWGs are refused at the shared DWG library's size limit (#3102, #2633, #1088); a typed OPEN reads in the background (#3343), but an open can't be cancelled and shows no progress; a layout's paper units are explicit and kept since #3309 (#2836 closed; #1672 open); a DWG with 3D content crashes or opens empty (#2174); the corpus holds four files, all written by CADCraft, and CI does not run it | A corpus of files made by AutoCAD and other CAD programs opens in CI with its objects, layouts, viewports and units right, compared with what the program that wrote it shows; a large file opens or says clearly why not; content we don't model is kept and never crashes |
|
||||
| Saving loses nothing, and other CAD programs open the result | **no** | DXF keeps what we don't model (#528); other applications' objects are kept as proxies (#2917, #2919, #2654); through DWG, custom-class objects without data for the version written are still dropped; an edited dimension keeps its values on save (#3335); fixes for files AutoCAD or BricsCAD refuse landed on 2026-11-20 (#2904, #1687, #3234, #1728, #2882), and a file saved from a Rhino drawing still crashes AutoCAD 2021 as DWG (#3303); never checked against a corpus in AutoCAD | The corpus round-trips with every object kept and its geometry and properties unchanged, a save names anything it could not keep, and AutoCAD opens the saved files without a recovery prompt |
|
||||
| Input feels like AutoCAD for Windows | **partial, blocking until confirmed** | Running snaps, polar, ortho, coordinate entry, tracking, FROM/M2P/TK and dynamic input work; landed on 2026-11-20 and not yet confirmed by the people who reported them: a click counts where the button goes down (#3307; #1001, #2092), a quick right-click and Space act as Enter (#3307; #1387), a double-click edits TEXT, attribute definitions and dimension text in place (#3345; #842 stays open for table cells) | A click counts while the pointer moves; right-click and Space repeat or confirm as set in Options; a double-click edits text, multiline text and dimension text in place |
|
||||
| Draft, dimension and annotate a sheet, with styles | partial, not blocking | All core DIM types, associativity, the Dimension Style Manager (#1460), TEXT/MTEXT, MLEADER, tables, the in-place MTEXT editor, blocks with attributes, xrefs, the Block Editor and REFEDIT work; a few prompt options still print "not available yet" ([gaps.md](gaps.md) F1); ellipse and spline intersections are approximate | No "not available yet" in the most-used draw, modify and annotate commands, apart from options that need 3D |
|
||||
| Lay out and print a sheet at scale, and the interface can always be restored | **partial, blocking** | Layers, layouts, viewports, page setups, PDF output, plot styles, the Plot dialog, preview and PUBLISH work; a print can come out off scale (#3216); printers are reached only through PDF, PNG and SVG files (F14, H3); a hidden menu bar or closed panels can't always be brought back (#1240) | A metric sheet prints 1:1 on a system printer, and one command or key restores the menu bar and default panels from any state |
|
||||
| Lay out and print a sheet at scale, and the interface can always be restored | **partial, blocking** | Layers, layouts, viewports, page setups, PDF output, plot styles, the Plot dialog, preview and PUBLISH work; a print can come out off scale (#3216); printers are reached only through PDF, PNG and SVG files (F14, H3); MENUBAR, TOOLBAR and Options ▸ Reset bring a hidden menu bar and closed panels back (#3308; #1240 closed), and metric sheets are in millimetres (#3309) | A metric sheet prints 1:1 on a system printer, and one command or key restores the menu bar and default panels from any state |
|
||||
|
||||
Moved to the beta checklist on 2026-11-19, with the reports behind each: dynamic-block authoring (none),
|
||||
editing an xref in place (one), exact ellipse and spline intersections (one).
|
||||
@@ -114,6 +114,7 @@ AutoLISP surface, AI features with openly licensed local models, and every remai
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | minor | Alpha gate evidence updated for what merged on 2026-11-19 and 2026-11-20: the stencil switch (#3336), typed OPEN in the background (#3343), paper units (#3309), dimension values kept on save (#3335), clicks while moving and right-click or Space as Enter (#3307), in-place text editing (#3345), the interface reset (#3308). No verdict changed: the input row waits for confirmation from the reporters; pull-request count 714 → 661 |
|
||||
| 2026-11-19 | major | Alpha gate revised from user reports: six rows (starts on common hardware; opens existing files; saves without loss; input feel; draft and annotate with styles; print at scale and a restorable interface), main platform Windows; dynamic-block authoring, xref editing in place and exact curve geometry counted under beta only; current focus re-ranked into three tiers; percentages and hours not re-scored |
|
||||
| 2026-10-24 | minor | Re-audit against main 41d9b5e95: alpha-gate evidence, CI gate (#1987), beta-checklist states, open-PR and catalog counts re-checked against main 41d9b5e95; percentages and hours not re-scored |
|
||||
| 2026-10-13 | minor | Re-audit against main e707ab4d: alpha-gate evidence for drafting, annotation, blocks and DWG rows; beta-checklist states for DWG/DXF, blocks and languages; current-focus items 4–7; milestone notes M1, M12, M13; percentages and hours not re-scored |
|
||||
|
||||
@@ -79,9 +79,6 @@
|
||||
</dict>
|
||||
</dict>
|
||||
</array>
|
||||
<!-- With AutoCAD or LibreOffice installed, .dwg and .dxf files carry their exported types
|
||||
(com.autodesk.autocad.dwg, org.libreoffice.dxf-document) instead of ours, so those are
|
||||
claimed too. Otherwise Finder never offers CADCraft in Open With. -->
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
@@ -92,7 +89,7 @@
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Alternate</string>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array><string>ai.storyteller.cadcraft.dxf</string><string>org.libreoffice.dxf-document</string></array>
|
||||
<array><string>ai.storyteller.cadcraft.dxf</string></array>
|
||||
<key>CFBundleTypeIconFile</key>
|
||||
<string>CADCraft</string>
|
||||
</dict>
|
||||
@@ -104,7 +101,7 @@
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Alternate</string>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array><string>ai.storyteller.cadcraft.dwg</string><string>com.autodesk.autocad.dwg</string></array>
|
||||
<array><string>ai.storyteller.cadcraft.dwg</string></array>
|
||||
<key>CFBundleTypeIconFile</key>
|
||||
<string>CADCraft</string>
|
||||
</dict>
|
||||
|
||||
Reference in New Issue
Block a user