mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-23 21:00:42 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e7663b25c | ||
|
|
10727f5025 | ||
|
|
1515833f2c | ||
|
|
28d8ba72c5 | ||
|
|
5af8fc020a | ||
|
|
a3e04070be | ||
|
|
210a99ecc8 | ||
|
|
bc703cb134 | ||
|
|
84eb20b5c0 | ||
|
|
27e408d91b | ||
|
|
195c052931 | ||
|
|
7d1d0ba55b | ||
|
|
8920c0fb6f | ||
|
|
68fbe896a7 | ||
|
|
f9756d5083 | ||
|
|
7a199cc2e1 | ||
|
|
88ef222cdf | ||
|
|
64e0b5c2a4 | ||
|
|
b27cc3ce22 | ||
|
|
b355f1e14a | ||
|
|
ad6314967f |
@@ -60,4 +60,3 @@ jobs:
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
|
||||
+1
-3
@@ -19,9 +19,7 @@ Generated-in-code assets are original and have no file to list:
|
||||
- the standard linetype and hatch-pattern libraries (`crates/doc/src/library.rs`; industry-common
|
||||
names, our own dash/spacing values);
|
||||
- the colour index palette, generated from its structure (`crates/color/src/lib.rs`);
|
||||
- the sample drawings (`crates/engine/src/sample.rs`);
|
||||
- the synthetic two-hexagon hatch logo (`crates/io/tests/it/hatch_loop_flags.rs`, `logo`):
|
||||
original contributor geometry, generated in code from invented points, under MIT OR Apache-2.0.
|
||||
- the sample drawings (`crates/engine/src/sample.rs`).
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
|
||||
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"
|
||||
|
||||
@@ -58,7 +58,6 @@ fn install_io() {
|
||||
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);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
}
|
||||
|
||||
/// `path` as text, for the engine and io calls that take a file name as a string.
|
||||
@@ -96,7 +95,7 @@ where
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
|
||||
return match write!(to, "{}", e.render()).and_then(|()| to.flush()) {
|
||||
return match write!(to, "{}", e.render()) {
|
||||
Err(w) if w.kind() != std::io::ErrorKind::BrokenPipe => {
|
||||
let _ = writeln!(err, "error: can't write the output: {w}");
|
||||
1
|
||||
@@ -166,25 +165,6 @@ mod tests {
|
||||
assert_eq!(run(["--help"], &mut FailingWriter(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
|
||||
}
|
||||
|
||||
struct FailingFlush(std::io::ErrorKind);
|
||||
|
||||
impl Write for FailingFlush {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_flush_of_help_exits_1_unless_the_pipe_is_closed() {
|
||||
let mut err = Vec::new();
|
||||
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::StorageFull), &mut err), 1);
|
||||
assert!(String::from_utf8_lossy(&err).starts_with("error: "));
|
||||
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_atomic_replaces_file_and_leaves_no_staging_files() {
|
||||
let dir = scratch_dir("replace");
|
||||
|
||||
@@ -58,7 +58,7 @@ pub(crate) fn roundtrip(a: &RoundtripArgs, io: &mut Streams) -> Result {
|
||||
if a.keep_saved {
|
||||
opts.keep_saved = Some(out.join("saved"));
|
||||
}
|
||||
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| io.errln(format_args!("[{}/{n}] {rel}", i + 1)));
|
||||
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| eprintln!("[{}/{n}] {rel}", i + 1));
|
||||
for f in &report.files {
|
||||
let routes: Vec<String> = f
|
||||
.routes
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::args::{CmdStep, Drawing, RunArgs, Step};
|
||||
use super::error::Result;
|
||||
use super::open;
|
||||
use super::output::{Streams, export, export_framed, export_window, model_views, undrawn_message};
|
||||
use super::output::{Streams, export, export_framed, export_window, model_views};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Handle;
|
||||
use serde_json::Value;
|
||||
@@ -216,15 +216,7 @@ pub(crate) fn run_cmds(a: &RunArgs, io: &mut Streams) -> Result {
|
||||
export(&s, p, io)?;
|
||||
}
|
||||
if let Some(p) = export_to {
|
||||
let window = if cadcraft_io::is_image(p) {
|
||||
let window = export_window(&s, framing, Some(&before))?;
|
||||
if let Some(message) = undrawn_message(s.doc()?, &p.to_string_lossy()) {
|
||||
io.errln(format_args!("{message}"));
|
||||
}
|
||||
window
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let window = if cadcraft_io::is_image(p) { export_window(&s, framing, Some(&before))? } else { None };
|
||||
export_framed(&s, p, window, io)?;
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Image exports report how many model-space entities they can't draw, by type. The exit code
|
||||
//! stays 0 (#1208).
|
||||
//! `convert` to an image says how many model-space entities it can't draw, by type, instead of
|
||||
//! leaving them out silently (#1208). The exit code stays 0.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
@@ -70,28 +70,6 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() {
|
||||
assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_image_export_warns_about_undrawn_entities() {
|
||||
let scratch = Scratch::new("run-undrawn");
|
||||
let input = scratch.0.join("proxies.dxf");
|
||||
std::fs::write(&input, PROXIES).unwrap();
|
||||
let image = scratch.0.join("out.svg");
|
||||
let out = cli(&["run", input.to_str().unwrap(), "--export", image.to_str().unwrap()]);
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{:?}: {err}", out.status);
|
||||
assert!(image.is_file());
|
||||
assert!(out.stdout.is_empty(), "the warning belongs on stderr");
|
||||
let warnings: Vec<&str> = err.lines().filter(|l| l.contains("not drawn")).collect();
|
||||
assert_eq!(warnings, [format!("{}: 3 entities not drawn (PDFUNDERLAY: 1, REGION: 2)", image.display())], "{err}");
|
||||
|
||||
let copy = scratch.0.join("copy.dxf");
|
||||
let out = cli(&["run", input.to_str().unwrap(), "--export", copy.to_str().unwrap()]);
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{:?}: {err}", out.status);
|
||||
assert!(copy.is_file());
|
||||
assert!(!err.contains("not drawn"), "{err}");
|
||||
}
|
||||
|
||||
/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it an undrawn entity (#2422); it
|
||||
/// says once that the OLE content inside the frame is not drawn (review on #2587).
|
||||
#[test]
|
||||
|
||||
@@ -949,11 +949,3 @@ fn json_output_is_pretty_unless_compact() {
|
||||
assert_eq!(r.stdout.lines().count(), 2, "one line per --cmd result: {}", r.stdout);
|
||||
assert_eq!(invoke(&["run", "--sample", "--compact"]).code, 2, "run takes no --compact");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_progress_uses_the_requested_stderr() {
|
||||
run_cases(
|
||||
"roundtrip-progress",
|
||||
&[case("roundtrip progress", &["roundtrip", "{b}", "--same-format", "--no-census"], 0, Starts("b.dxf: opened;"), Line("[1/1] b.dxf"))],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -132,7 +132,6 @@ mod web {
|
||||
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);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_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,211 +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() {
|
||||
// Writing and opening the DWG here needs the converter in this process: each test is its own.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
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
|
||||
@@ -184,7 +176,6 @@ pub fn install_io() {
|
||||
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);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
@@ -446,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,
|
||||
@@ -515,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;
|
||||
@@ -550,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,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -144,10 +144,6 @@ impl NativeMenu {
|
||||
self.last_refresh = now;
|
||||
let typing = menus::text_field_window(ctx).is_some();
|
||||
for (cmd, _, item) in self.items.values() {
|
||||
// Open Recent rebuilds this item with the correct enabled state.
|
||||
if cmd == menus::RECENT_CLEAR {
|
||||
continue;
|
||||
}
|
||||
let en = (typing && menus::edits_text(cmd)) || cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
|
||||
item.set_enabled(en);
|
||||
}
|
||||
|
||||
+47
-246
@@ -22,7 +22,7 @@ use crate::{Drawing, Handle, RawTag};
|
||||
mod apply;
|
||||
mod grips;
|
||||
mod reference;
|
||||
pub use apply::{align_grip, drag_grip, grip_stops, set_property};
|
||||
pub use apply::{drag_grip, set_property};
|
||||
pub use grips::{DynGrip, GripPart, GripShape, grips};
|
||||
pub use reference::{CustomProperty, Reference, Value, custom_properties, reference};
|
||||
|
||||
@@ -52,13 +52,6 @@ pub struct DynamicBlock {
|
||||
/// the grips shown in them by object).
|
||||
#[serde(skip)]
|
||||
pub grip_objects: Vec<(i32, Handle)>,
|
||||
/// Where each grip object is in the dynamic block, by graph id (a flip grip's place along its
|
||||
/// reflection line).
|
||||
#[serde(skip)]
|
||||
pub grip_points: Vec<(i32, Vec3)>,
|
||||
/// The block's base point (where a base point parameter is in the block).
|
||||
#[serde(skip)]
|
||||
pub base: Vec3,
|
||||
}
|
||||
|
||||
/// One parameter: a property a reference to the block can change.
|
||||
@@ -94,41 +87,16 @@ pub enum ParameterKind {
|
||||
/// The value changes the end point (`false`) or both points from the midpoint (`true`).
|
||||
from_midpoint: bool,
|
||||
},
|
||||
/// A distance and an angle from a base point (Distance1, Angle1): the end point's distance
|
||||
/// from the base and its direction (counterclockwise from the X axis of the block).
|
||||
Polar {
|
||||
base: Vec3,
|
||||
end: Vec3,
|
||||
label: String,
|
||||
description: String,
|
||||
angle_label: String,
|
||||
angle_description: String,
|
||||
values: ValueSet,
|
||||
angle_values: ValueSet,
|
||||
},
|
||||
/// Horizontal and vertical distances from a base point (X Distance1, Y Distance1): how far
|
||||
/// the end point is from the base along the block's X and Y axes.
|
||||
Xy {
|
||||
base: Vec3,
|
||||
end: Vec3,
|
||||
x_label: String,
|
||||
y_label: String,
|
||||
x_description: String,
|
||||
y_description: String,
|
||||
x_values: ValueSet,
|
||||
y_values: ValueSet,
|
||||
},
|
||||
/// An angle about a base point (Angle1): the end point turns about the base. The angle is
|
||||
/// measured from the direction the dynamic block has from base to end.
|
||||
Rotation { base: Vec3, end: Vec3, label: String, description: String, values: ValueSet },
|
||||
/// Aligns the reference with nearby geometry: dragged next to an object, its base point lands
|
||||
/// on the object and the direction from base to end runs along it. `perpendicular` is the
|
||||
/// parameter's type (perpendicular, else tangent); AutoCAD aligned both types the same way in
|
||||
/// every case measured.
|
||||
Alignment { base: Vec3, end: Vec3, perpendicular: bool },
|
||||
/// Mirrors the objects about the reflection line from base to end (Flip state1); the names
|
||||
/// of its two states, not flipped and flipped.
|
||||
Flip { base: Vec3, end: Vec3, label: String, description: String, states: [String; 2] },
|
||||
/// A distance and an angle from a base point.
|
||||
Polar { base: Vec3, end: Vec3 },
|
||||
/// Horizontal and vertical distances from a base point.
|
||||
Xy { base: Vec3, end: Vec3 },
|
||||
/// An angle about a base point.
|
||||
Rotation { base: Vec3, end: Vec3 },
|
||||
/// Aligns the reference with nearby geometry.
|
||||
Alignment { base: Vec3, end: Vec3 },
|
||||
/// Mirrors the objects about a reflection line.
|
||||
Flip { base: Vec3, end: Vec3 },
|
||||
/// A position (Position1).
|
||||
Point { at: Vec3, label: String, description: String },
|
||||
/// Named sets of visible objects.
|
||||
@@ -142,9 +110,7 @@ pub enum ParameterKind {
|
||||
},
|
||||
/// A named value chosen from a lookup table.
|
||||
Lookup { at: Vec3, label: String, description: String },
|
||||
/// The block's base point: the reference's insertion point is here, and an action that moves
|
||||
/// it moves the reference's insertion point. `at` is where the block editor showed it; the
|
||||
/// block itself has it at its base point (AutoCAD moves the block's objects to put it there).
|
||||
/// Moves the block's base point.
|
||||
BasePoint { at: Vec3 },
|
||||
/// A parameter type not modelled yet.
|
||||
Other { dxf_type: String },
|
||||
@@ -156,23 +122,11 @@ impl ParameterKind {
|
||||
match self {
|
||||
ParameterKind::Linear { label, .. }
|
||||
| ParameterKind::Point { label, .. }
|
||||
| ParameterKind::Rotation { label, .. }
|
||||
| ParameterKind::Flip { label, .. }
|
||||
| ParameterKind::Visibility { label, .. }
|
||||
| ParameterKind::Lookup { label, .. } => Some(label),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every property name a reference shows for the parameter: a polar parameter's distance
|
||||
/// and angle, an XY parameter's two distances, else its one label.
|
||||
pub fn labels(&self) -> Vec<&str> {
|
||||
match self {
|
||||
ParameterKind::Polar { label, angle_label, .. } => vec![label, angle_label],
|
||||
ParameterKind::Xy { x_label, y_label, .. } => vec![x_label, y_label],
|
||||
other => other.label().into_iter().collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One visibility state: its name and the objects shown in it (the parameter's other controlled
|
||||
@@ -251,46 +205,24 @@ pub enum ActionKind {
|
||||
angle_offset: f64,
|
||||
},
|
||||
/// A table: each row sets the listed parameter values together.
|
||||
Lookup { columns: Vec<LookupColumn>, rows: Vec<Vec<String>> },
|
||||
Lookup {
|
||||
columns: Vec<LookupColumn>,
|
||||
rows: Vec<Vec<String>>,
|
||||
},
|
||||
/// Moves the objects by the change of the parameter values it follows.
|
||||
Move { multiplier: f64, angle_offset: f64 },
|
||||
/// Scales the objects about its base point by how much the distance it follows grew (a linear
|
||||
/// or polar parameter's distance, an XY parameter's diagonal). Its connections name what each
|
||||
/// reads ("Scale", "XScale", "YScale").
|
||||
Scale { base: ActionBase },
|
||||
/// Turns the objects about its base point by the change of a rotation parameter's angle.
|
||||
Rotate { base: ActionBase },
|
||||
/// Mirrors the objects across a flip parameter's reflection line when its state changes.
|
||||
Flip,
|
||||
/// Repeats the objects as far as the parameter it follows reaches: along a distance (linear
|
||||
/// or polar parameter) every `column` units, or in a grid of columns and rows across an XY
|
||||
/// parameter's distances. The objects follow the parameter's base point.
|
||||
Array { column: f64, row: f64 },
|
||||
/// Follows a polar parameter: turns its objects about the parameter's base point by the change
|
||||
/// of its angle, and moves the vertices inside `frame` of the objects listed (all of an object
|
||||
/// not listed) along the parameter's new direction by the change of its distance. The
|
||||
/// `rotate_only` objects (outside the selection) only turn.
|
||||
PolarStretch {
|
||||
frame: Vec<Vec2>,
|
||||
#[serde(serialize_with = "hex_vertices")]
|
||||
vertices: Vec<(Handle, Vec<i32>)>,
|
||||
#[serde(serialize_with = "hexes")]
|
||||
rotate_only: Vec<Handle>,
|
||||
Move {
|
||||
multiplier: f64,
|
||||
angle_offset: f64,
|
||||
},
|
||||
Scale,
|
||||
Rotate,
|
||||
Flip,
|
||||
Array,
|
||||
PolarStretch,
|
||||
/// An action type not modelled yet.
|
||||
Other { dxf_type: String },
|
||||
}
|
||||
|
||||
/// Where an action that turns or scales its objects has its base point.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ActionBase {
|
||||
/// It follows the parameter's base point, at `offset` from it; else it stays at `at`.
|
||||
pub dependent: bool,
|
||||
pub offset: Vec3,
|
||||
pub at: Vec3,
|
||||
Other {
|
||||
dxf_type: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// A lookup table column: the parameter value it reads or sets.
|
||||
@@ -451,7 +383,7 @@ pub fn is_dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -
|
||||
/// [`dynamic_block`] with the drawing's [`ObjectIndex`] already built.
|
||||
pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> Option<DynamicBlock> {
|
||||
let xdict = block_xdict(d, name)?;
|
||||
let mut out = DynamicBlock { base: d.block(name.trim()).map(|b| b.base).unwrap_or_default(), ..Default::default() };
|
||||
let mut out = DynamicBlock::default();
|
||||
for o in graph_members(&objects.0, xdict)? {
|
||||
let secs = sections(&o.tags);
|
||||
let node = Cursor::new(section(&secs, "AcDbEvalExpr")).int(90);
|
||||
@@ -466,7 +398,6 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
|
||||
} else {
|
||||
if kind.ends_with("GRIP") {
|
||||
out.grip_objects.push((node, o.handle));
|
||||
out.grip_points.push((node, Cursor::new(section(&secs, "AcDbBlockGrip")).point(1010)));
|
||||
}
|
||||
out.other.push(o.kind.clone());
|
||||
}
|
||||
@@ -475,21 +406,15 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
|
||||
}
|
||||
|
||||
/// A parameter's grip ids: after a two-point parameter's points, the grip count (170) and the
|
||||
/// base and end grips (91), then an XY parameter's corner grips (base X and end Y, base Y and end
|
||||
/// X); after a one-point parameter's point, its grip (93).
|
||||
/// base and end grips (91); after a one-point parameter's point, its grip (93).
|
||||
fn grip_ids(secs: &[(&str, &[RawTag])]) -> Vec<i32> {
|
||||
let two = section(secs, "AcDbBlock2PtParameter");
|
||||
if !two.is_empty() {
|
||||
let mut c = Cursor::new(two);
|
||||
c.point(1010);
|
||||
c.point(1011);
|
||||
let n = c.count(170).min(4);
|
||||
let mut ids: Vec<i32> = (0..n).map(|_| c.int(91)).collect();
|
||||
// Corner grips only an XY parameter has (the others write 0 for them).
|
||||
while ids.len() > 2 && ids.last() == Some(&0) {
|
||||
ids.pop();
|
||||
}
|
||||
return ids;
|
||||
let n = c.count(170).min(2);
|
||||
return (0..n).map(|_| c.int(91)).collect();
|
||||
}
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlock1PtParameter"));
|
||||
c.point(1010);
|
||||
@@ -521,49 +446,15 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
|
||||
ParameterKind::Lookup { at: one(), label: c.string(303), description: c.string(304) }
|
||||
}
|
||||
"BLOCKBASEPOINTPARAMETER" => ParameterKind::BasePoint { at: one() },
|
||||
// Its name and description (305, 306), the base angle point (1011) and angle (140), then
|
||||
// the value set.
|
||||
"BLOCKROTATIONPARAMETER" => {
|
||||
"BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKROTATIONPARAMETER" | "BLOCKALIGNMENTPARAMETER" | "BLOCKFLIPPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockRotationParameter"));
|
||||
let (label, description) = (c.string(305), c.string(306));
|
||||
ParameterKind::Rotation { base, end, label, description, values: value_set(&mut c) }
|
||||
}
|
||||
// Its name and description (305, 306) and its states' names (307 not flipped, 308 flipped).
|
||||
"BLOCKFLIPPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockFlipParameter"));
|
||||
let (label, description) = (c.string(305), c.string(306));
|
||||
let states = [c.string(307), c.string(308)];
|
||||
ParameterKind::Flip { base, end, label, description, states }
|
||||
}
|
||||
// The distance's name and description (305, 306), the angle's (307, 308), the label
|
||||
// offset (140), then the distance's value set (309, 96, 141–144, 175) and the angle's
|
||||
// (410, 97, 145–148, 176).
|
||||
"BLOCKPOLARPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockPolarParameter"));
|
||||
let (label, description, angle_label, angle_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
|
||||
let values = value_set_at(&mut c, [309, 96, 141, 175]);
|
||||
let angle_values = value_set_at(&mut c, [410, 97, 145, 176]);
|
||||
ParameterKind::Polar { base, end, label, description, angle_label, angle_description, values, angle_values }
|
||||
}
|
||||
// The vertical distance's name (305) before the horizontal's (306), then their
|
||||
// descriptions (307, 308), label offsets (141, 140), the vertical value set (309, 97,
|
||||
// 146–149, 176) and the horizontal one (410, 96, 142–145, 175).
|
||||
"BLOCKXYPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockXYParameter"));
|
||||
let (y_label, x_label, y_description, x_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
|
||||
let y_values = value_set_at(&mut c, [309, 97, 146, 176]);
|
||||
let x_values = value_set_at(&mut c, [410, 96, 142, 175]);
|
||||
ParameterKind::Xy { base, end, x_label, y_label, x_description, y_description, x_values, y_values }
|
||||
}
|
||||
// Its type (280): 1 perpendicular, 0 tangent.
|
||||
"BLOCKALIGNMENTPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
let perpendicular = Cursor::new(section(secs, "AcDbBlockAlignmentParameter")).int(280) != 0;
|
||||
ParameterKind::Alignment { base, end, perpendicular }
|
||||
match kind {
|
||||
"BLOCKPOLARPARAMETER" => ParameterKind::Polar { base, end },
|
||||
"BLOCKXYPARAMETER" => ParameterKind::Xy { base, end },
|
||||
"BLOCKROTATIONPARAMETER" => ParameterKind::Rotation { base, end },
|
||||
"BLOCKALIGNMENTPARAMETER" => ParameterKind::Alignment { base, end },
|
||||
_ => ParameterKind::Flip { base, end },
|
||||
}
|
||||
}
|
||||
other => ParameterKind::Other { dxf_type: other.to_string() },
|
||||
}
|
||||
@@ -572,17 +463,11 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
|
||||
/// A value set after a parameter's name and description: description (307), flags (96),
|
||||
/// minimum, maximum and increment (141–143), then the listed values (175 count, 144 each).
|
||||
fn value_set(c: &mut Cursor) -> ValueSet {
|
||||
value_set_at(c, [307, 96, 141, 175])
|
||||
}
|
||||
|
||||
/// A value set written with codes `[description, flags, minimum, count]`: the maximum and
|
||||
/// increment follow the minimum's code, each listed value is the code after the increment's.
|
||||
fn value_set_at(c: &mut Cursor, [description, flags, min, count]: [i32; 4]) -> ValueSet {
|
||||
c.next(description);
|
||||
let flags = c.int(flags);
|
||||
let (minimum, maximum, increment) = (c.real(min), c.real(min + 1), c.real(min + 2));
|
||||
let n = c.count(count);
|
||||
let list = (0..n).filter_map(|_| c.next(min + 3).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
|
||||
c.next(307);
|
||||
let flags = c.int(96);
|
||||
let (minimum, maximum, increment) = (c.real(141), c.real(142), c.real(143));
|
||||
let n = c.count(175);
|
||||
let list = (0..n).filter_map(|_| c.next(144).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
|
||||
ValueSet { flags, minimum, maximum, increment, list }
|
||||
}
|
||||
|
||||
@@ -622,56 +507,16 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[
|
||||
let (multiplier, angle_offset) = (c.real(140), c.real(141));
|
||||
(two_connections(tags), ActionKind::Move { multiplier, angle_offset })
|
||||
}
|
||||
// The base point's two connections (as a rotate action's), then the scale's three: the
|
||||
// parameters (94-96) and what each reads (303-305, "Scale", "XScale", "YScale").
|
||||
"BLOCKSCALEACTION" => {
|
||||
let with_base = section(secs, "AcDbBlockActionWithBasePt");
|
||||
let mut connections = two_connections(with_base);
|
||||
let tags = section(secs, "AcDbBlockScaleAction");
|
||||
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
|
||||
connections.extend((0..3).map(|i| (first(94 + i).trim().parse().unwrap_or(0), first(303 + i))));
|
||||
(connections, ActionKind::Scale { base: action_base(with_base) })
|
||||
}
|
||||
"BLOCKROTATEACTION" => {
|
||||
let mut connections = two_connections(section(secs, "AcDbBlockActionWithBasePt"));
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockRotationAction"));
|
||||
connections.push((c.int(94), c.string(303)));
|
||||
(connections, ActionKind::Rotate { base: action_base(section(secs, "AcDbBlockActionWithBasePt")) })
|
||||
}
|
||||
// Its four connections: the parameter (92-95) and the values it reads (301-304).
|
||||
"BLOCKFLIPACTION" => {
|
||||
let tags = section(secs, "AcDbBlockFlipAction");
|
||||
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
|
||||
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
|
||||
(connections, ActionKind::Flip)
|
||||
}
|
||||
// Its four connections (92-95 with 301-304, as a flip action's), then the row (140) and
|
||||
// column (141) offsets.
|
||||
"BLOCKARRAYACTION" => {
|
||||
let tags = section(secs, "AcDbBlockArrayAction");
|
||||
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
|
||||
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
|
||||
let mut c = Cursor::new(tags);
|
||||
let (row, column) = (c.real(140), c.real(141));
|
||||
(connections, ActionKind::Array { column, row })
|
||||
}
|
||||
"BLOCKPOLARSTRETCHACTION" => polar_stretch(section(secs, "AcDbBlockPolarStretchAction")),
|
||||
"BLOCKSCALEACTION" => (Vec::new(), ActionKind::Scale),
|
||||
"BLOCKROTATEACTION" => (Vec::new(), ActionKind::Rotate),
|
||||
"BLOCKFLIPACTION" => (Vec::new(), ActionKind::Flip),
|
||||
"BLOCKARRAYACTION" => (Vec::new(), ActionKind::Array),
|
||||
"BLOCKPOLARSTRETCHACTION" => (Vec::new(), ActionKind::PolarStretch),
|
||||
other => (Vec::new(), ActionKind::Other { dxf_type: other.to_string() }),
|
||||
};
|
||||
Action { node, handle, name, at, selection, connections, kind }
|
||||
}
|
||||
|
||||
/// The base point of an action that has one: after its two connections (92/93, 301/302), the
|
||||
/// offset from the parameter's base point (1011), whether it follows that point (280), and the
|
||||
/// point it stays at when it doesn't (1012).
|
||||
fn action_base(tags: &[RawTag]) -> ActionBase {
|
||||
let mut c = Cursor::new(tags);
|
||||
c.next(302);
|
||||
let offset = c.point(1011);
|
||||
let dependent = c.int(280) != 0;
|
||||
ActionBase { dependent, offset, at: c.point(1012) }
|
||||
}
|
||||
|
||||
/// Two connections: parameter ids (92, 93) and the values they read (301, 302). Writers order
|
||||
/// these groups differently (92 93 301 302, or 92 301 93 302), so each is read on its own.
|
||||
fn two_connections(tags: &[RawTag]) -> Vec<(i32, String)> {
|
||||
@@ -706,42 +551,6 @@ fn stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
|
||||
(connections, ActionKind::Stretch { frame, vertices, multiplier, angle_offset })
|
||||
}
|
||||
|
||||
/// A polar stretch action: its six connections (92-97 with 301-306), the frame (73 count,
|
||||
/// 1011/1021 points), the objects it only turns (72 count, 331 each), the objects whose vertices it
|
||||
/// moves (74 count; each a 332 handle, a 75 count and 76 vertex indices), more vertex lists (78
|
||||
/// count; each a 98 code, a 79 count and 76 indices), then the distance multiplier (141) and angle
|
||||
/// offset (140).
|
||||
fn polar_stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
|
||||
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
|
||||
let connections = (0..6).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
|
||||
let mut c = Cursor::new(tags);
|
||||
let n = c.count(73);
|
||||
let frame = (0..n)
|
||||
.map(|_| {
|
||||
let x = c.real(1011);
|
||||
Vec2::new(x, c.real(1021))
|
||||
})
|
||||
.collect();
|
||||
let n = c.count(72);
|
||||
let rotate_only = c.handles(331, n);
|
||||
let objects = c.count(74);
|
||||
let vertices = (0..objects)
|
||||
.filter_map(|_| {
|
||||
let h = c.handle(332)?;
|
||||
let n = c.count(75);
|
||||
Some((h, (0..n).map(|_| c.int(76)).collect()))
|
||||
})
|
||||
.collect();
|
||||
for _ in 0..c.count(78) {
|
||||
c.next(98);
|
||||
for _ in 0..c.count(79) {
|
||||
c.next(76);
|
||||
}
|
||||
}
|
||||
let (multiplier, angle_offset) = (c.real(141), c.real(140));
|
||||
(connections, ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, angle_offset })
|
||||
}
|
||||
|
||||
/// A lookup table: rows (92) and columns (93), the cells row by row (302, after a 301 header),
|
||||
/// then each column: unmatched name (303 then 305), parameter id (94), lookup flag (282) and the
|
||||
/// parameter value it stands for (304).
|
||||
@@ -789,13 +598,5 @@ mod tests {
|
||||
let (_, ActionKind::Stretch { vertices, .. }) = stretch(&tags) else { panic!("a stretch action") };
|
||||
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
|
||||
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
|
||||
|
||||
let mut tags = vec![tag(74, &n.to_string())];
|
||||
tags.extend((0..n).flat_map(|_| [tag(332, "1F"), tag(75, &n.to_string())]));
|
||||
tags.push(tag(78, &n.to_string()));
|
||||
tags.extend((0..n).map(|_| tag(79, &n.to_string())));
|
||||
let (_, ActionKind::PolarStretch { vertices, .. }) = polar_stretch(&tags) else { panic!("a polar stretch action") };
|
||||
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
|
||||
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
|
||||
}
|
||||
}
|
||||
|
||||
+161
-1081
File diff suppressed because it is too large
Load Diff
@@ -1,11 +1,7 @@
|
||||
//! The grips of a dynamic block reference, as AutoCAD shows them on a selected reference: an
|
||||
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter),
|
||||
//! a circle at the end of an angle (rotation parameter), a flip arrow across a reflection line
|
||||
//! (flip parameter), a down-pointing triangle for a list (visibility states, lookup values) and a
|
||||
//! pentagon pointing across the alignment direction at an alignment's base point (alignment
|
||||
//! parameter; dragged next to an object it aligns the reference with it, [`super::align_grip`]).
|
||||
//! Dragging an arrow, square or circle is [`super::drag_grip`]; a flip grip flips at a click; a
|
||||
//! list grip offers its property's choices.
|
||||
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter)
|
||||
//! and a down-pointing triangle for a list (visibility states, lookup values). Dragging an arrow
|
||||
//! or square is [`super::drag_grip`]; a list grip offers its property's choices.
|
||||
//!
|
||||
//! With a visibility parameter, a state lists the grips shown in it; the others are hidden.
|
||||
|
||||
@@ -30,13 +26,6 @@ pub enum GripPart {
|
||||
End,
|
||||
/// A one-point parameter's point (a position, a visibility or lookup grip).
|
||||
At,
|
||||
/// An XY parameter's corner at the base's X and the end's Y (listed as `blocks.reference.grip`
|
||||
/// takes it, as [`GripPart::name`] names it).
|
||||
#[serde(rename = "basex-endy")]
|
||||
BaseXEndY,
|
||||
/// An XY parameter's corner at the end's X and the base's Y.
|
||||
#[serde(rename = "basey-endx")]
|
||||
BaseYEndX,
|
||||
}
|
||||
|
||||
impl GripPart {
|
||||
@@ -45,8 +34,6 @@ impl GripPart {
|
||||
GripPart::Base => "base",
|
||||
GripPart::End => "end",
|
||||
GripPart::At => "at",
|
||||
GripPart::BaseXEndY => "basex-endy",
|
||||
GripPart::BaseYEndX => "basey-endx",
|
||||
}
|
||||
}
|
||||
pub fn from_name(s: &str) -> Option<GripPart> {
|
||||
@@ -54,28 +41,11 @@ impl GripPart {
|
||||
"base" => Some(GripPart::Base),
|
||||
"end" => Some(GripPart::End),
|
||||
"at" => Some(GripPart::At),
|
||||
"basex-endy" => Some(GripPart::BaseXEndY),
|
||||
"basey-endx" => Some(GripPart::BaseYEndX),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::GripPart;
|
||||
|
||||
/// A grip is listed with the part name `blocks.reference.grip` takes back.
|
||||
#[test]
|
||||
fn listed_part_names_are_the_names_a_drag_takes() {
|
||||
for p in [GripPart::Base, GripPart::End, GripPart::At, GripPart::BaseXEndY, GripPart::BaseYEndX] {
|
||||
let listed = serde_json::to_value(p).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
|
||||
assert_eq!(listed, p.name());
|
||||
assert_eq!(GripPart::from_name(&listed), Some(p));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a grip looks and what it does.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -86,13 +56,6 @@ pub enum GripShape {
|
||||
Point,
|
||||
/// A down-pointing triangle: click it for the property's choices.
|
||||
List,
|
||||
/// A circle at the end of an angle: drag it to turn the angle.
|
||||
Rotation,
|
||||
/// An arrow across a reflection line: click it to flip (its choices are the two states).
|
||||
Flip,
|
||||
/// A pentagon pointing to the left of an alignment's direction: drag it next to an object to
|
||||
/// align the reference with it.
|
||||
Alignment,
|
||||
}
|
||||
|
||||
/// One grip of a dynamic block reference.
|
||||
@@ -139,15 +102,6 @@ fn ends_used(m: &DynamicBlock, node: i32) -> Option<(bool, bool)> {
|
||||
used
|
||||
}
|
||||
|
||||
/// Where a grip object at `g` (from its parameter's base, in the dynamic block) is when the
|
||||
/// parameter's line `home` (base to end, in the block) is now `now` from `base`: kept along and
|
||||
/// across the line as it turns, moves or stretches. `home` and `now` aren't zero.
|
||||
fn carried(g: Vec2, home: Vec2, base: Vec2, now: Vec2) -> Vec2 {
|
||||
let (u0, u) = (home * (1.0 / home.len()), now * (1.0 / now.len()));
|
||||
let (along, across) = (g.dot(u0) / home.len(), u0.x * g.y - u0.y * g.x);
|
||||
base + now * along + u.perp() * across
|
||||
}
|
||||
|
||||
fn point<S: serde::Serializer>(p: &Vec2, s: S) -> Result<S::Ok, S::Error> {
|
||||
[p.x, p.y].serialize(s)
|
||||
}
|
||||
@@ -166,7 +120,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
|
||||
};
|
||||
// The grips the current visibility state shows (all of them without visibility states).
|
||||
let objects: HashMap<i32, Handle> = m.grip_objects.iter().copied().collect();
|
||||
let points: HashMap<i32, Vec3> = m.grip_points.iter().copied().collect();
|
||||
let mut shown_in_state: Option<HashSet<Handle>> = None;
|
||||
let mut visibility_node = None;
|
||||
for p in &m.parameters {
|
||||
@@ -218,87 +171,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
|
||||
}
|
||||
}
|
||||
}
|
||||
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
|
||||
let (b, e) = match r.values.get(&p.node) {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*hb, *he),
|
||||
};
|
||||
let id = grip(1);
|
||||
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
|
||||
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
|
||||
// The grip object's place (AutoCAD draws the circle there, not at the radius'
|
||||
// end), turned and moved with the radius.
|
||||
let at = carried(points.get(&id).copied().unwrap_or(*he).xy() - hb.xy(), home, b.xy(), now);
|
||||
let at = Vec3::new(at.x, at.y, b.z);
|
||||
let u = at - b;
|
||||
let u = if u.len() > 1e-12 { u * (1.0 / u.len()) } else { Vec3::new(1.0, 0.0, 0.0) };
|
||||
let (at, dir) = (world(at), toward(at, u));
|
||||
out.push(DynGrip {
|
||||
node: p.node,
|
||||
part: GripPart::End,
|
||||
shape: GripShape::Rotation,
|
||||
at,
|
||||
dir,
|
||||
property: label.clone(),
|
||||
choices: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
ParameterKind::Flip { base: hb, end: he, label, states, .. } => {
|
||||
let (b, e, flipped) = match r.values.get(&p.node) {
|
||||
Some(Value::Flip { base, end, flipped }) => (*base, *end, *flipped),
|
||||
_ => (*hb, *he, false),
|
||||
};
|
||||
let id = grip(0);
|
||||
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
|
||||
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
|
||||
// The grip object's place, kept along and across the reflection line as the
|
||||
// line turns or moves with other actions.
|
||||
let g = points.get(&id).copied().unwrap_or(*hb).xy() - hb.xy();
|
||||
let at = carried(g, home, b.xy(), now);
|
||||
let u = now * (1.0 / now.len());
|
||||
let across_dir = if flipped { -u.perp() } else { u.perp() };
|
||||
let (at3, dir) = (Vec3::new(at.x, at.y, b.z), toward(Vec3::new(at.x, at.y, b.z), across_dir.to3(0.0)));
|
||||
out.push(DynGrip {
|
||||
node: p.node,
|
||||
part: GripPart::Base,
|
||||
shape: GripShape::Flip,
|
||||
at: world(at3),
|
||||
dir,
|
||||
property: label.clone(),
|
||||
choices: states.to_vec(),
|
||||
});
|
||||
}
|
||||
}
|
||||
// Squares at the base and the end (a polar parameter), and at the two other corners of
|
||||
// the rectangle they span (an XY parameter), for the grips the parameter has; an end
|
||||
// no action follows has none.
|
||||
ParameterKind::Polar { base, end, label, .. } | ParameterKind::Xy { base, end, x_label: label, .. } => {
|
||||
let (b, e) = match r.values.get(&p.node) {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*base, *end),
|
||||
};
|
||||
let used = ends_used(&m, p.node).map_or([true, true], |(base, end)| [base, end]);
|
||||
let mut corners = vec![(0, GripPart::Base, b, used[0]), (1, GripPart::End, e, used[1])];
|
||||
if matches!(p.kind, ParameterKind::Xy { .. }) {
|
||||
let both = used[0] && used[1];
|
||||
corners.push((2, GripPart::BaseXEndY, Vec3::new(b.x, e.y, b.z), both));
|
||||
corners.push((3, GripPart::BaseYEndX, Vec3::new(e.x, b.y, b.z), both));
|
||||
}
|
||||
for (i, part, at, used) in corners {
|
||||
if used && shown(p.node, grip(i)) {
|
||||
out.push(DynGrip {
|
||||
node: p.node,
|
||||
part,
|
||||
shape: GripShape::Point,
|
||||
at: world(at),
|
||||
dir: Vec2::ZERO,
|
||||
property: label.clone(),
|
||||
choices: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
ParameterKind::Point { at, label, .. } => {
|
||||
let at = match r.values.get(&p.node) {
|
||||
Some(Value::Point { at }) => *at,
|
||||
@@ -317,26 +189,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
|
||||
});
|
||||
}
|
||||
}
|
||||
// At the base point, pointing to the left of the direction (as AutoCAD draws it).
|
||||
ParameterKind::Alignment { base, end, .. } => {
|
||||
let (b, e) = match r.values.get(&p.node) {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*base, *end),
|
||||
};
|
||||
let u = (e - b).xy();
|
||||
if shown(p.node, grip(0)) && u.len() > 1e-12 {
|
||||
let (at, dir) = (world(b), toward(b, u.perp().to3(0.0)));
|
||||
out.push(DynGrip {
|
||||
node: p.node,
|
||||
part: GripPart::Base,
|
||||
shape: GripShape::Alignment,
|
||||
at,
|
||||
dir,
|
||||
property: String::new(),
|
||||
choices: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
ParameterKind::Visibility { at, label, .. } | ParameterKind::Lookup { at, label, .. } => {
|
||||
let Some(list) = choices.get(&label.to_ascii_uppercase()).filter(|c| !c.is_empty()) else { continue };
|
||||
if shown(p.node, grip(0)) {
|
||||
|
||||
@@ -29,8 +29,6 @@ pub enum Value {
|
||||
Point { at: Vec3 },
|
||||
/// A two-point parameter's points.
|
||||
Points { base: Vec3, end: Vec3 },
|
||||
/// A flip parameter's reflection line and whether it is flipped.
|
||||
Flip { base: Vec3, end: Vec3, flipped: bool },
|
||||
}
|
||||
|
||||
/// A dynamic block reference.
|
||||
@@ -53,8 +51,8 @@ pub struct CustomProperty {
|
||||
/// The values it may be set to, when it is a choice (visibility states, lookup values, a
|
||||
/// distance's list).
|
||||
pub choices: Vec<String>,
|
||||
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, an angle,
|
||||
/// a position, a flip state, or a lookup whose tables set only those.
|
||||
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, a
|
||||
/// position, or a lookup whose tables set only those.
|
||||
pub editable: bool,
|
||||
}
|
||||
|
||||
@@ -93,9 +91,7 @@ fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(Stri
|
||||
out
|
||||
}
|
||||
|
||||
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip
|
||||
/// parameter's also has its state, a group 70 after its points (the header's `70 25`, `70 104`
|
||||
/// come before them).
|
||||
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30).
|
||||
fn value(o: &ForeignObject) -> Option<Value> {
|
||||
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
|
||||
return Some(Value::Text { value: t.value.clone() });
|
||||
@@ -104,10 +100,7 @@ fn value(o: &ForeignObject) -> Option<Value> {
|
||||
o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
|
||||
};
|
||||
let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0)));
|
||||
let first_point = o.tags.iter().position(|t| t.code == 10).unwrap_or(o.tags.len());
|
||||
let state = o.tags.get(first_point..).unwrap_or_default().iter().rev().find(|t| t.code == 70).map(|t| t.value.trim() == "1");
|
||||
match (point(0), point(1)) {
|
||||
(Some(base), Some(end)) if state.is_some() => Some(Value::Flip { base, end, flipped: state == Some(true) }),
|
||||
(Some(base), Some(end)) => Some(Value::Points { base, end }),
|
||||
(Some(at), None) => Some(Value::Point { at }),
|
||||
_ => None,
|
||||
@@ -129,52 +122,17 @@ pub fn reference(d: &Drawing, insert: Handle) -> Option<Reference> {
|
||||
let target = data.tags.iter().find(|t| t.code == 340).and_then(|t| Handle::parse_hex(&t.value))?;
|
||||
let (kind, name) = d.foreign.targets.get(&target)?;
|
||||
let definition = d.block(name).filter(|_| kind == "BLOCK_RECORD")?.name.clone();
|
||||
let m = dynamic_block(d, &definition)?;
|
||||
dynamic_block(d, &definition)?;
|
||||
let mut values = BTreeMap::new();
|
||||
let cache = entry(&objects, rep, "AppDataCache").and_then(|c| entry(&objects, c, "ACAD_ENHANCEDBLOCKDATA"));
|
||||
for (key, h) in cache.map(|c| entries(&objects, c)).unwrap_or_default().into_iter().take(MAX_VALUES) {
|
||||
if let (Ok(node), Some(v)) = (key.trim().parse::<i32>(), objects.get(&h).and_then(|o| value(o))) {
|
||||
// The record's groups alone can't tell a flip from another two-point parameter (a stray
|
||||
// 70, or a flip without its state): the parameter it belongs to decides.
|
||||
let flip = m.parameters.iter().any(|p| p.node == node && matches!(p.kind, ParameterKind::Flip { .. }));
|
||||
let v = match (flip, v) {
|
||||
(false, Value::Flip { base, end, .. }) => Value::Points { base, end },
|
||||
(true, Value::Points { base, end }) => Value::Flip { base, end, flipped: false },
|
||||
(_, v) => v,
|
||||
};
|
||||
values.insert(node, v);
|
||||
}
|
||||
}
|
||||
Some(Reference { definition, values })
|
||||
}
|
||||
|
||||
/// An angle (radians) as Properties shows it: degrees with AUPREC decimals.
|
||||
/// An angle parameter's value `a` (radians, counterclockwise) as the drawing shows angles: from
|
||||
/// ANGBASE, clockwise when ANGDIR is 1 (AutoCAD shows a 0 angle as 90 in a drawing measured
|
||||
/// clockwise from north, and 0.5 rad as 61.35).
|
||||
pub(super) fn angle_shown(d: &Drawing, a: f64) -> f64 {
|
||||
let base = d.header.f64("ANGBASE", 0.0);
|
||||
let shown = if d.header.i64("ANGDIR", 0) == 1 { base - a } else { a - base };
|
||||
shown.rem_euclid(std::f64::consts::TAU)
|
||||
}
|
||||
|
||||
/// The value of an angle parameter shown (or typed) as `v` (radians): the inverse of
|
||||
/// [`angle_shown`].
|
||||
pub(super) fn angle_from_shown(d: &Drawing, v: f64) -> f64 {
|
||||
let base = d.header.f64("ANGBASE", 0.0);
|
||||
let a = if d.header.i64("ANGDIR", 0) == 1 { base - v } else { v + base };
|
||||
a.rem_euclid(std::f64::consts::TAU)
|
||||
}
|
||||
|
||||
fn angle_text(d: &Drawing, a: f64) -> String {
|
||||
let prec = usize::try_from(d.header.i64("AUPREC", 0).clamp(0, 8)).unwrap_or(0);
|
||||
// Rounded to the shown decimals first: an angle just short of a full turn shows as 0, not 360.
|
||||
let step = 10f64.powi(i32::try_from(prec).unwrap_or(0));
|
||||
let shown = (angle_shown(d, a).to_degrees() * step).round() / step;
|
||||
let shown = if shown >= 360.0 { shown - 360.0 } else { shown };
|
||||
format!("{:.prec$}", shown + 0.0)
|
||||
}
|
||||
|
||||
/// A number as the drawing shows lengths (LUPREC decimals).
|
||||
fn number(d: &Drawing, v: f64) -> String {
|
||||
let prec = usize::try_from(d.header.i64("LUPREC", 4).clamp(0, 8)).unwrap_or(4);
|
||||
@@ -198,7 +156,26 @@ struct Current<'a> {
|
||||
impl Current<'_> {
|
||||
/// Parameter `node`'s value of property `property`, as table cells write it.
|
||||
fn property(&self, node: i32, property: &str) -> Option<String> {
|
||||
super::apply::property_text(self.m, self.values, node, property)
|
||||
let p = self.m.parameters.iter().find(|p| p.node == node)?;
|
||||
let v = self.values.get(&node);
|
||||
match (&p.kind, property.to_ascii_lowercase().as_str()) {
|
||||
(ParameterKind::Visibility { states, .. }, "visibilitystate") => match v {
|
||||
Some(Value::Text { value }) => Some(value.clone()),
|
||||
_ => states.first().map(|s| s.name.clone()),
|
||||
},
|
||||
(ParameterKind::Linear { base, end, .. }, "updateddistance" | "distance") => {
|
||||
let (b, e) = match v {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*base, *end),
|
||||
};
|
||||
Some(format!("{}", (e - b).len()))
|
||||
}
|
||||
(ParameterKind::Lookup { .. }, "lookupstring") => match v {
|
||||
Some(Value::Text { value }) => Some(value.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Lookup parameter `node`'s value: the value every lookup table that sets it gives for the
|
||||
@@ -262,27 +239,6 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
|
||||
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
|
||||
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
|
||||
}
|
||||
// The distance from the base to the end, and the end's direction (AutoCAD measures it
|
||||
// from the block's X axis, not from where the dynamic block has it).
|
||||
ParameterKind::Polar { base: b, end: e, label, angle_label, values, .. } => {
|
||||
let (b, e) = match v {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*b, *e),
|
||||
};
|
||||
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
|
||||
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
|
||||
let a = (e - b).xy().angle().rem_euclid(std::f64::consts::TAU);
|
||||
out.push(CustomProperty { name: angle_label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
|
||||
}
|
||||
// How far the end is from the base along X and along Y.
|
||||
ParameterKind::Xy { base: b, end: e, x_label, y_label, .. } => {
|
||||
let (b, e) = match v {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*b, *e),
|
||||
};
|
||||
out.push(CustomProperty { name: x_label.clone(), value: number(d, (e.x - b.x) * sx), choices: Vec::new(), editable: true });
|
||||
out.push(CustomProperty { name: y_label.clone(), value: number(d, (e.y - b.y) * sy), choices: Vec::new(), editable: true });
|
||||
}
|
||||
ParameterKind::Point { at, label, .. } => {
|
||||
let at = match v {
|
||||
Some(Value::Point { at }) => *at,
|
||||
@@ -291,21 +247,6 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
|
||||
out.push(CustomProperty { name: format!("{label} X"), value: number(d, (at.x - base.x) * sx), choices: Vec::new(), editable: true });
|
||||
out.push(CustomProperty { name: format!("{label} Y"), value: number(d, (at.y - base.y) * sy), choices: Vec::new(), editable: true });
|
||||
}
|
||||
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
|
||||
let (b, e) = match v {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*hb, *he),
|
||||
};
|
||||
let now = (e - b).xy();
|
||||
let zero = (*he - *hb).xy();
|
||||
let a = (now.y.atan2(now.x) - zero.y.atan2(zero.x)).rem_euclid(std::f64::consts::TAU);
|
||||
out.push(CustomProperty { name: label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
|
||||
}
|
||||
ParameterKind::Flip { label, states, .. } => {
|
||||
let flipped = matches!(v, Some(Value::Flip { flipped: true, .. }));
|
||||
let value = states[usize::from(flipped)].clone();
|
||||
out.push(CustomProperty { name: label.clone(), value, choices: states.to_vec(), editable: true });
|
||||
}
|
||||
ParameterKind::Visibility { label, states, .. } => {
|
||||
let value = cur.property(p.node, "VisibilityState").unwrap_or_default();
|
||||
out.push(CustomProperty { name: label.clone(), value, choices: states.iter().map(|s| s.name.clone()).collect(), editable: true });
|
||||
@@ -322,8 +263,7 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
|
||||
}
|
||||
|
||||
/// Whether every lookup table that sets lookup parameter `node` sets only what
|
||||
/// [`super::set_property`] can apply with it: visibility states, distances, angles, positions and
|
||||
/// flip states.
|
||||
/// [`super::set_property`] can apply with it: visibility states and distances.
|
||||
fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
|
||||
let mut any = false;
|
||||
for a in &m.actions {
|
||||
@@ -332,29 +272,12 @@ fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
let settable = |c: &super::LookupColumn| {
|
||||
m.parameters.iter().find(|p| p.node == c.node).is_some_and(|p| super::apply::column(&p.kind, &c.property).is_some())
|
||||
};
|
||||
if !columns.iter().all(settable) {
|
||||
if !columns
|
||||
.iter()
|
||||
.all(|c| matches!(c.property.to_ascii_lowercase().as_str(), "lookupstring" | "visibilitystate" | "updateddistance" | "distance"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::angle_text;
|
||||
use crate::Drawing;
|
||||
|
||||
#[test]
|
||||
fn an_angle_just_short_of_a_full_turn_shows_as_zero() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_i64("AUPREC", 0);
|
||||
assert_eq!(angle_text(&d, 359.7f64.to_radians()), "0");
|
||||
assert_eq!(angle_text(&d, 359.4f64.to_radians()), "359");
|
||||
d.header.set_i64("AUPREC", 2);
|
||||
assert_eq!(angle_text(&d, 359.996f64.to_radians()), "0.00");
|
||||
assert_eq!(angle_text(&d, 90f64.to_radians()), "90.00");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -617,7 +617,7 @@ impl EntityKind {
|
||||
EntityKind::Text(t) => vec![t.justify_point()],
|
||||
EntityKind::MText(t) => vec![t.insert.xy()],
|
||||
EntityKind::AttDef(a) => vec![a.text.justify_point()],
|
||||
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.grip_attribs().map(|(_, a)| a.text.justify_point())).collect(),
|
||||
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.attribs.iter().map(|a| a.text.justify_point())).collect(),
|
||||
EntityKind::Dimension(d) => vec![d.p13.xy(), d.p14.xy(), d.defpt.xy(), d.text_mid.xy()],
|
||||
EntityKind::MLine(m) => m.points(),
|
||||
EntityKind::Leader(l) => l.vertices.iter().map(|v| v.xy()).collect(),
|
||||
|
||||
@@ -191,12 +191,6 @@ fn one_u() -> u32 {
|
||||
}
|
||||
|
||||
impl Insert {
|
||||
/// The attributes that have a grip of their own (grips 1, 2… after the insertion point), with
|
||||
/// their index in `attribs`: those shown and not locked in position, as AutoCAD offers them.
|
||||
pub fn grip_attribs(&self) -> impl Iterator<Item = (usize, &Attrib)> {
|
||||
self.attribs.iter().enumerate().filter(|(_, a)| !a.invisible && !a.modes.lock_position)
|
||||
}
|
||||
|
||||
/// Block-to-world transform (2D part).
|
||||
pub fn transform(&self, base: Vec2) -> Mat3 {
|
||||
Mat3::translate(self.insert.xy())
|
||||
|
||||
@@ -7,11 +7,6 @@ pub struct HatchLoop {
|
||||
pub vertices: Vec<PolyVertex>,
|
||||
#[serde(default)]
|
||||
pub outer: bool,
|
||||
/// Original DXF group 92 bits. Writing keeps only Derived (4), Textbox (8) and
|
||||
/// Outermost (16), derives External (1) from `outer`, and sets Polyline (2).
|
||||
/// None uses the flags of a locally created loop.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub boundary_flags: Option<i64>,
|
||||
/// The objects the loop was made from (DXF group 97 count, 330 handles): an associative
|
||||
/// hatch re-fills the loop from them when they change.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
|
||||
@@ -37,7 +37,7 @@ pub struct RegionProps {
|
||||
impl Region {
|
||||
/// A region bounded by one closed loop.
|
||||
pub fn from_loop(vertices: Vec<PolyVertex>) -> Region {
|
||||
Region { loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }] }
|
||||
Region { loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }] }
|
||||
}
|
||||
|
||||
pub fn polylines(&self) -> Vec<Polyline> {
|
||||
@@ -170,7 +170,7 @@ mod tests {
|
||||
let mut vertices: Vec<PolyVertex> =
|
||||
(0..n).map(|k| PolyVertex::new(Vec2::new(c - half + 2.0 * half * k as f64 / n as f64, c - half))).collect();
|
||||
vertices.extend([Vec2::new(c + half, c - half), Vec2::new(c + half, c + half), Vec2::new(c - half, c + half)].map(PolyVertex::new));
|
||||
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
|
||||
HatchLoop { vertices, outer, sources: Vec::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -53,10 +53,6 @@ impl ForeignExtra {
|
||||
/// Everything of a file CADCraft keeps without modelling it.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Foreign {
|
||||
/// Original two-point text and style, by entity handle and attribute position.
|
||||
/// Kept with imported metadata so new entities never inherit another entity's fitting.
|
||||
pub text_fits: BTreeMap<Handle, Vec<(crate::Text, crate::TextStyle)>>,
|
||||
|
||||
/// CLASS records (groups after `0 CLASS`) of the kept objects' and entities' types.
|
||||
pub classes: Vec<Vec<RawTag>>,
|
||||
/// Classes retain every source position, including duplicate names.
|
||||
|
||||
@@ -39,7 +39,7 @@ pub use header::{HVal, Header};
|
||||
pub use plotstyle::*;
|
||||
pub use plotter::*;
|
||||
pub use raster::{Raster, Rasters};
|
||||
pub use refedit::{RefEdit, WorkItem};
|
||||
pub use refedit::{RefEdit, WorkItem, XrefSource};
|
||||
pub use store::EntityStore;
|
||||
pub use tables::*;
|
||||
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
|
||||
|
||||
@@ -42,6 +42,36 @@ pub struct RefEdit {
|
||||
/// Block objects taken out of the working set with their edits (block coordinates, the block
|
||||
/// object's handle).
|
||||
pub released: Vec<Entity>,
|
||||
/// The nested references picked through to reach the edited block: block references inside
|
||||
/// block definitions, outermost first. Empty when the picked reference's own block is edited.
|
||||
pub path: Vec<Handle>,
|
||||
/// Set when the edited block comes from an external reference: REFCLOSE Save writes it back
|
||||
/// into its source drawing.
|
||||
pub xref: Option<XrefSource>,
|
||||
}
|
||||
|
||||
/// Where an xref edited in place is written back to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct XrefSource {
|
||||
/// The xref (its block name in this drawing).
|
||||
pub xref: String,
|
||||
/// The source drawing file.
|
||||
pub file: String,
|
||||
/// `file` with every symbolic link resolved when the edit began: the file that is written.
|
||||
/// The save is refused when `file` leads somewhere else by then.
|
||||
pub real: String,
|
||||
/// The version the file was in when the edit began, as its `$ACADVER` code ("AC1015"): it
|
||||
/// is written back in that version (`None`: in the drawing's own).
|
||||
pub version: Option<String>,
|
||||
/// Whether the file is a binary DXF (written back as one).
|
||||
pub binary: bool,
|
||||
/// The block of the source drawing being edited; `None` for its model space.
|
||||
pub block: Option<String>,
|
||||
/// The file's size and modification time (nanoseconds since 1970) when the edit began.
|
||||
pub stamp: Option<(u64, u128)>,
|
||||
/// Edited block objects (their handles in this drawing) and the objects of the source
|
||||
/// drawing they were loaded from.
|
||||
pub sources: Vec<(Handle, Handle)>,
|
||||
}
|
||||
|
||||
impl RefEdit {
|
||||
|
||||
@@ -728,6 +728,11 @@ pub struct Block {
|
||||
/// The parameters of an associative array when this is an array block.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub array: Option<crate::ArrayParams>,
|
||||
/// An xref's file as its loaded objects were read from it: size and modification time
|
||||
/// (nanoseconds since 1970). Kept per drawing, so an edit in place (REFEDIT) can tell whether
|
||||
/// the file changed since this drawing loaded it (session state; not saved).
|
||||
#[serde(skip)]
|
||||
pub xref_stamp: Option<(u64, u128)>,
|
||||
}
|
||||
|
||||
/// The load state of an external reference.
|
||||
@@ -774,6 +779,7 @@ impl Block {
|
||||
explodable: true,
|
||||
units: 0,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,14 +70,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.enabled(has_doc)
|
||||
.noundo(),
|
||||
CommandSpec::new("blocks.reference.set", "Set Dynamic Property", run_reference_set)
|
||||
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance, \"Position1 X\", an angle or a flip state), value (lengths in drawing units, angles in degrees; a flip state by name or 0/1)} → {properties}")
|
||||
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance or \"Position1 X\"), value (lengths in drawing units)} → {properties}")
|
||||
.enabled(has_doc),
|
||||
CommandSpec::new("blocks.reference.grips", "Dynamic Block Grips", dyngrip::run_grips)
|
||||
.params("{handle} → [{node, part: base|end|at|basex-endy|basey-endx, shape: linear|point|list|rotation|flip, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
|
||||
.params("{handle} → [{node, part: base|end|at, shape: linear|point|list, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
|
||||
.enabled(has_doc)
|
||||
.noundo(),
|
||||
CommandSpec::new("blocks.reference.grip", "Drag Dynamic Grip", dyngrip::run_grip)
|
||||
.params("{handle, node (the parameter's graph id), part: base|end|at|basex-endy|basey-endx, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it, a rotation's circle turns its angle, a polar or XY parameter's squares move its base, end or corners")
|
||||
.params("{handle, node (the parameter's graph id), part: base|end|at, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it")
|
||||
.enabled(has_doc),
|
||||
CommandSpec::new("purge", "Purge", purge::run)
|
||||
.alias(&["pu", "-purge"])
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Grips of dynamic block references: `blocks.reference.grips` lists them, `blocks.reference.grip`
|
||||
//! drags one (one undo step), and [`Session::start_dyn_grip`] starts the drag the UI's click on a
|
||||
//! grip begins, with the reference re-evaluated under the cursor as its preview. Typing a number
|
||||
//! at a distance's grip sets the distance, at a rotation grip the angle (degrees).
|
||||
//! at a distance's grip sets the distance.
|
||||
|
||||
use cadcraft_doc::color::Color;
|
||||
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
|
||||
@@ -30,8 +30,7 @@ pub(super) fn run_grip(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.and_then(Value::as_i64)
|
||||
.and_then(|n| i32::try_from(n).ok())
|
||||
.ok_or_else(|| bad(cmd, "`node` (a parameter's graph id) is required"))?;
|
||||
let part =
|
||||
str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end, at, basex-endy or basey-endx"))?;
|
||||
let part = str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end or at"))?;
|
||||
let to = point_param(p, "to").ok_or_else(|| bad(cmd, "`to` [x, y] is required"))?;
|
||||
drag(s, h, node, part, to).map_err(|e| bad(cmd, e))?;
|
||||
let properties = dynblock::custom_properties(s.doc()?, h).map(|(_, p)| p).unwrap_or_default();
|
||||
@@ -47,25 +46,11 @@ fn drag(s: &mut Session, h: Handle, node: i32, part: GripPart, to: Vec2) -> std:
|
||||
return Err("the reference is on a locked layer".into());
|
||||
}
|
||||
let mut d = s.doc().map_err(|e| e.to_string())?.clone();
|
||||
drag_in(s, &mut d, h, node, part, to)?;
|
||||
dynblock::drag_grip(&mut d, h, node, part, to)?;
|
||||
*s.doc_mut().map_err(|e| e.to_string())? = d;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drag grip (`node`, `part`) of reference `h` to `to` in drawing `d`; an alignment grip aligns
|
||||
/// the reference with the object at the cursor (within the aperture), as AutoCAD does.
|
||||
fn drag_in(s: &Session, d: &mut Drawing, h: Handle, node: i32, part: GripPart, to: Vec2) -> std::result::Result<(), String> {
|
||||
let alignment = dynblock::reference(d, h)
|
||||
.and_then(|r| dynblock::dynamic_block(d, &r.definition))
|
||||
.is_some_and(|m| m.parameters.iter().any(|p| p.node == node && matches!(p.kind, dynblock::ParameterKind::Alignment { .. })));
|
||||
if !alignment {
|
||||
return dynblock::drag_grip(d, h, node, part, to);
|
||||
}
|
||||
let aperture = s.pixel_size() * s.settings.aperture.max(1.0);
|
||||
let near = crate::snap::nearest_with_direction(d, &s.space(), to, aperture, h);
|
||||
dynblock::align_grip(d, h, node, to, near)
|
||||
}
|
||||
|
||||
/// The properties an object of a block draws with in reference `r`: on layer 0 it is on the
|
||||
/// reference's layer, and its ByBlock colour, linetype, lineweight and transparency are the
|
||||
/// reference's (as the renderer draws a block's contents).
|
||||
@@ -117,11 +102,7 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
|
||||
_ => None,
|
||||
});
|
||||
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
|
||||
let kind = match a.multiline_text() {
|
||||
Some(m) => EntityKind::MText(m),
|
||||
None => EntityKind::Text(a.text.clone()),
|
||||
};
|
||||
Entity { handle: Handle(0), common, kind }
|
||||
Entity { handle: Handle(0), common, kind: EntityKind::Text(a.text.clone()) }
|
||||
}));
|
||||
out
|
||||
}
|
||||
@@ -133,16 +114,11 @@ struct DynGripEdit {
|
||||
part: GripPart,
|
||||
/// Where the grip is (the rubber band's start).
|
||||
from: Vec2,
|
||||
/// The property it changes, and the grip's shape (a typed number sets a distance or angle).
|
||||
/// The property it changes, and whether it is a distance (a typed number sets it).
|
||||
property: String,
|
||||
shape: GripShape,
|
||||
/// Where the grip can stop (a value list or increments): tick marks across its travel.
|
||||
stops: Vec<(Vec2, Vec2)>,
|
||||
distance: bool,
|
||||
}
|
||||
|
||||
/// Half a tick mark's length, in pixels.
|
||||
const TICK_PX: f64 = 6.0;
|
||||
|
||||
impl Interactive for DynGripEdit {
|
||||
fn name(&self) -> &'static str {
|
||||
"GRIP"
|
||||
@@ -153,22 +129,19 @@ impl Interactive for DynGripEdit {
|
||||
}
|
||||
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
let (msg, accept) = match self.shape {
|
||||
GripShape::Linear => ("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER),
|
||||
GripShape::Rotation => ("** ROTATE ** Specify rotation point or angle", Accept::POINT_OR_NUMBER),
|
||||
GripShape::Alignment => ("Specify point location", Accept::POINT),
|
||||
_ => ("** STRETCH ** Specify stretch point", Accept::POINT),
|
||||
let (msg, accept) = if self.distance {
|
||||
("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER)
|
||||
} else {
|
||||
("** STRETCH ** Specify stretch point", Accept::POINT)
|
||||
};
|
||||
let p = Prompt::new(msg, accept).kw(&["eXit"]).base(self.from);
|
||||
// A rotation grip asks for an angle: Dynamic Input shows one angle box.
|
||||
if self.shape == GripShape::Rotation { p.angle() } else { p }
|
||||
Prompt::new(msg, accept).kw(&["eXit"]).base(self.from)
|
||||
}
|
||||
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
let to = match i {
|
||||
Input::Point(p) => p,
|
||||
Input::Deferred(d) => d.at,
|
||||
Input::Text(t) if matches!(self.shape, GripShape::Linear | GripShape::Rotation) => {
|
||||
Input::Text(t) if self.distance => {
|
||||
let mut d = s.doc()?.clone();
|
||||
dynblock::set_property(&mut d, self.handle, &self.property, t.trim()).map_err(EngineError::Other)?;
|
||||
*s.doc_mut()? = d;
|
||||
@@ -182,30 +155,9 @@ impl Interactive for DynGripEdit {
|
||||
Ok(Step::Done)
|
||||
}
|
||||
|
||||
/// The rubber band from the grip, and ticks at the stops of a value list or increments.
|
||||
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
let half = TICK_PX * s.pixel_size();
|
||||
let mut out: Vec<EntityKind> = self
|
||||
.stops
|
||||
.iter()
|
||||
.map(|(at, way)| {
|
||||
let n = way.perp() * half;
|
||||
crate::cmd::helpers::line(*at - n, *at + n)
|
||||
})
|
||||
.collect();
|
||||
out.push(crate::cmd::helpers::line(self.from, c));
|
||||
out
|
||||
}
|
||||
|
||||
/// A rotation grip's angle at the cursor, as Properties will show it.
|
||||
fn live_value(&self, s: &Session, c: Vec2) -> Option<String> {
|
||||
if self.shape != GripShape::Rotation {
|
||||
return None;
|
||||
}
|
||||
let mut d = s.doc().ok()?.clone();
|
||||
dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c).ok()?;
|
||||
let (_, props) = dynblock::custom_properties(&d, self.handle)?;
|
||||
props.into_iter().find(|p| p.name.eq_ignore_ascii_case(&self.property)).map(|p| format!("{}°", p.value))
|
||||
/// The rubber band from the grip.
|
||||
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
vec![crate::cmd::helpers::line(self.from, c)]
|
||||
}
|
||||
|
||||
/// The reference re-evaluated at the cursor, drawn as it will look (its own colours, so
|
||||
@@ -213,7 +165,7 @@ impl Interactive for DynGripEdit {
|
||||
fn preview_objects(&self, s: &Session, c: Vec2) -> Vec<Entity> {
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
let mut d = d.clone();
|
||||
match drag_in(s, &mut d, self.handle, self.node, self.part, c) {
|
||||
match dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c) {
|
||||
Ok(()) => drawn(&d, self.handle),
|
||||
Err(_) => Vec::new(),
|
||||
}
|
||||
@@ -222,8 +174,8 @@ impl Interactive for DynGripEdit {
|
||||
|
||||
impl Session {
|
||||
/// Start dragging grip `part` of parameter `node` of dynamic block reference `handle` (the
|
||||
/// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no
|
||||
/// drag: the UI offers the choices, or flips, with `blocks.reference.set`.
|
||||
/// UI's click on a dynamic grip). A list grip (visibility, lookup) has no drag: the UI offers
|
||||
/// its choices and sets them with `blocks.reference.set`.
|
||||
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
|
||||
if self.running.is_some() {
|
||||
self.cancel();
|
||||
@@ -232,19 +184,17 @@ impl Session {
|
||||
.into_iter()
|
||||
.find(|g| g.node == node && g.part == part)
|
||||
.ok_or_else(|| EngineError::Other("no such grip".into()))?;
|
||||
if matches!(g.shape, GripShape::List | GripShape::Flip) {
|
||||
return Err(EngineError::Other("a list or flip grip is clicked, not dragged".into()));
|
||||
if g.shape == GripShape::List {
|
||||
return Err(EngineError::Other("a list grip is chosen from, not dragged".into()));
|
||||
}
|
||||
let label = if g.shape == GripShape::Rotation { "** ROTATE **" } else { "** STRETCH **" };
|
||||
let stops = dynblock::grip_stops(self.doc()?, handle, node, part);
|
||||
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, shape: g.shape, stops };
|
||||
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, distance: g.shape == GripShape::Linear };
|
||||
let machine = crate::guard::Guarded::wrap(Box::new(edit));
|
||||
let st = self.state()?;
|
||||
let (before, selection_before) = (st.doc.clone(), st.selection.clone());
|
||||
self.running = Some(Running { id: "grip".into(), machine, before, selection_before });
|
||||
self.pending_window = None;
|
||||
self.point_mods.clear();
|
||||
self.echo(label);
|
||||
self.echo("** STRETCH **");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,42 +1,60 @@
|
||||
//! REFEDIT, REFSET and REFCLOSE: edit a block reference in place.
|
||||
//! REFEDIT, REFSET and REFCLOSE: edit a block reference or an xref in place.
|
||||
//!
|
||||
//! REFEDIT hides the picked reference and puts the block's objects (all, or the ones named) into
|
||||
//! the drawing where the reference shows them: the *working set*, ordinary objects that every
|
||||
//! command edits. The rest of the block stands there as faded copies, and everything else in the
|
||||
//! drawing is locked ([`crate::cmd::curves::is_locked`], enforced by [`after_command`]). Objects
|
||||
//! drawn while editing join the working set. REFSET adds objects to or removes them from it.
|
||||
//! REFCLOSE writes the working set back into the block definition, so every reference to the
|
||||
//! block shows the change, or discards the edit.
|
||||
//! drawing is locked ([`crate::cmd::curves::is_locked`], enforced by [`after_command`]) and drawn
|
||||
//! faded (XFADECTL). Objects drawn while editing join the working set. REFSET adds objects to or
|
||||
//! removes them from it. REFCLOSE writes the working set back into the block definition, so every
|
||||
//! reference to the block shows the change, or discards the edit.
|
||||
//!
|
||||
//! A reference nested in another block is picked through its parents (`path`, or "Select nesting
|
||||
//! level [OK/Next]" at the command line): its own block is edited, the parents' other objects
|
||||
//! stand faded around it.
|
||||
//!
|
||||
//! An xref (or a block that came with one) is edited the same way, and REFCLOSE Save writes the
|
||||
//! change into its source drawing the way SAVE writes a drawing: the previous file is kept as its
|
||||
//! `.bak`, the new one replaces it atomically, and a symbolic link planted beside it or put at its
|
||||
//! path during the edit never redirects the write. The save is refused when the file is
|
||||
//! read-only, open in another program (or another drawing tab), or changed since it was loaded.
|
||||
//! The xref is then loaded again from the file it wrote.
|
||||
//!
|
||||
//! The state is [`Drawing::refedit`]: it travels with undo, is never written to a file (files
|
||||
//! are written from [`Drawing::committed`]) and ends with the drawing it belongs to.
|
||||
//!
|
||||
//! Not yet: external references (their source drawing would have to be written back), nested
|
||||
//! references picked at a depth, annotative scale contexts and attribute synchronisation.
|
||||
//! Not yet: annotative scale contexts, attribute synchronisation and xrefs nested in xrefs (open
|
||||
//! those with XOPEN).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::{Drawing, Entity, EntityStore, Handle, RefEdit, Transparency, WorkItem};
|
||||
use cadcraft_doc::{Block, Drawing, Entity, EntityKind, EntityStore, Handle, RefEdit, WorkItem, XrefSource, XrefStatus};
|
||||
use cadcraft_geom::Mat3;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::curves::handle_value;
|
||||
use super::super::machines::{SelOutcome, SelectPhase, SelectRun};
|
||||
use super::super::machines::{SelOutcome, SelectPhase};
|
||||
use super::references_block;
|
||||
use super::xref::load::{self, Sym};
|
||||
use crate::cmd::file::Version;
|
||||
use crate::cmd::{CommandSpec, bad, bool_or, has_doc, str_param, targets};
|
||||
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
/// Transparency of the faded copies of the block's other objects.
|
||||
const GHOST_FADE: u8 = 70;
|
||||
/// Most nesting levels offered for one picked reference.
|
||||
const MAX_LEVELS: usize = 256;
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("refedit", "Edit Reference In-Place", run_refedit)
|
||||
.menu(&["Tools", "Xref and Block In-place Editing", "Edit Reference In-Place"])
|
||||
.params("{handle? | handles? | name? (a block reference, default the selection), objects?: [block object handles] (default all)} → {block, insert, working: [handles], faded}")
|
||||
.alias(&["-refedit"])
|
||||
.params("{handle? | handles? | name? (a block or xref reference, default the selection), path?: [handles of nested block references, outermost first] | nested?: block name (the first nested reference to it), objects?: [block object handles] (default all)} → {block, insert, working: [handles], faded, path, xref?: {name, file, version: its $ACADVER, binary}}. Editing an xref writes its file back on REFCLOSE Save, in the version and form it was read in (refused for versions CADCraft does not write, such as R12).")
|
||||
.enabled(has_doc)
|
||||
.interactive(|_| Ok(Box::new(SelectRun::single("refedit", "REFEDIT", "Select reference")))),
|
||||
.interactive(|_| Ok(Box::new(RefeditM::default()))),
|
||||
CommandSpec::new("refedit.levels", "Reference Nesting Levels", run_levels)
|
||||
.params("{handle (a block or xref reference)} → {levels: [{name, path: [handles], xref}]} (the picked reference first, then the references nested in it)")
|
||||
.enabled(has_doc)
|
||||
.noundo(),
|
||||
CommandSpec::new("refset", "Working Set", run_refset)
|
||||
.menu(&["Tools", "Xref and Block In-place Editing", "Add to Working Set"])
|
||||
.params("{add?: [handles], remove?: [handles]} (or {handles, mode?: \"add\"|\"remove\"}); with neither: lists the working set → {working: [handles], added, removed}")
|
||||
@@ -44,7 +62,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
.interactive(|_| Ok(Box::new(RefsetM::default()))),
|
||||
CommandSpec::new("refclose", "Save Reference Edits", run_refclose)
|
||||
.menu(&["Tools", "Xref and Block In-place Editing", "Save Reference Edits"])
|
||||
.params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects}")
|
||||
.params("{option?: \"save\"|\"discard\" | save?: bool (default true)} → {block, saved, objects, file? (an xref's source drawing written), backup? (its previous file, as SAVE names it; null when none was kept), notSaved?: {type: count} (what the file couldn't keep, also echoed)}")
|
||||
.enabled(editing)
|
||||
.interactive(|_| Ok(Box::new(RefcloseM))),
|
||||
]
|
||||
@@ -59,14 +77,13 @@ fn active(s: &Session, cmd: &str) -> Result<RefEdit> {
|
||||
s.doc()?.refedit.clone().ok_or_else(|| bad(cmd, "no block reference is being edited (REFEDIT)"))
|
||||
}
|
||||
|
||||
/// A block object as the drawing shows it through the edited reference.
|
||||
fn to_host(to_world: &Mat3, e: &Entity, h: Handle, ghost: bool) -> Entity {
|
||||
/// A block object as the drawing shows it through the edited reference. The copy keeps the
|
||||
/// object's own transparency: the renderer fades what is outside the working set by the current
|
||||
/// XFADECTL, so changing XFADECTL during the edit shows at once.
|
||||
fn to_host(to_world: &Mat3, e: &Entity, h: Handle) -> Entity {
|
||||
let mut c = e.clone();
|
||||
c.handle = h;
|
||||
c.kind.transform(to_world);
|
||||
if ghost {
|
||||
c.common.transparency = Transparency::Percent(GHOST_FADE);
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
@@ -88,6 +105,219 @@ fn hexes(hs: impl IntoIterator<Item = Handle>) -> Vec<String> {
|
||||
hs.into_iter().map(|h| h.hex()).collect()
|
||||
}
|
||||
|
||||
// ---------------- nesting ----------------
|
||||
|
||||
/// One level of a picked reference: a block, how its objects show in the drawing, and the
|
||||
/// reference inside it that leads to the next level (none at the last).
|
||||
struct Level {
|
||||
block: Arc<Block>,
|
||||
to_world: Mat3,
|
||||
next: Option<Handle>,
|
||||
}
|
||||
|
||||
/// Whether a reference with transform `m` can be edited in place (finite, not flat, scaled the
|
||||
/// same in X and Y).
|
||||
fn editable_transform(m: &Mat3, sx: f64, sy: f64) -> bool {
|
||||
let finite = [m.a, m.b, m.c, m.d, m.e, m.f].iter().all(|v| v.is_finite());
|
||||
finite && m.det().abs() >= 1e-12 && (sx.abs() - sy.abs()).abs() <= 1e-9 * sx.abs().max(sy.abs())
|
||||
}
|
||||
|
||||
/// The levels from top reference `ins` down `path` (references inside the block definitions).
|
||||
fn levels(d: &Drawing, ins: &cadcraft_doc::Insert, path: &[Handle]) -> Result<Vec<Level>> {
|
||||
let mut block = d.block(&ins.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", ins.block)))?;
|
||||
let mut m = ins.transform(block.base.xy());
|
||||
if !editable_transform(&m, ins.scale.x, ins.scale.y) {
|
||||
return Err(bad("refedit", "the reference must be scaled equally in X and Y (and not flat) to be edited in place"));
|
||||
}
|
||||
if path.len() >= cadcraft_doc::MAX_BLOCK_DEPTH {
|
||||
return Err(bad("refedit", "the reference is nested too deeply"));
|
||||
}
|
||||
let mut out = Vec::with_capacity(path.len() + 1);
|
||||
for h in path {
|
||||
let e = block.entities.get(*h).ok_or_else(|| bad("refedit", format!("object {} is not a reference in block \"{}\"", h.hex(), block.name)))?;
|
||||
let EntityKind::Insert(child) = &e.kind else { return Err(bad("refedit", format!("object {} is not a block reference", h.hex()))) };
|
||||
let cb = d.block(&child.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", child.block)))?;
|
||||
let cm = m.then_before(child.transform(cb.base.xy()));
|
||||
if !editable_transform(&cm, child.scale.x, child.scale.y) {
|
||||
return Err(bad("refedit", format!("the nested reference to \"{}\" must be scaled equally in X and Y", cb.name)));
|
||||
}
|
||||
out.push(Level { block, to_world: m, next: Some(*h) });
|
||||
block = cb;
|
||||
m = cm;
|
||||
}
|
||||
out.push(Level { block, to_world: m, next: None });
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The references nested in block `name` (depth first): (path of handles, block name). `m` is how
|
||||
/// the block shows in the drawing: a reference is checked with everything above it, as [`levels`]
|
||||
/// checks it.
|
||||
fn nested(d: &Drawing, name: &str, m: &Mat3, path: &mut Vec<Handle>, out: &mut Vec<(Vec<Handle>, String)>) {
|
||||
if path.len() + 1 >= cadcraft_doc::MAX_BLOCK_DEPTH || out.len() >= MAX_LEVELS {
|
||||
return;
|
||||
}
|
||||
let Some(b) = d.block(name) else { return };
|
||||
for e in b.entities.iter() {
|
||||
let EntityKind::Insert(i) = &e.kind else { continue };
|
||||
// Generated geometry (dimensions, arrays) is not offered, nor a reference `levels` would
|
||||
// refuse (scaled differently in X and Y, flat): nothing below it can be edited either.
|
||||
let Some(c) = d.block(&i.block) else { continue };
|
||||
let cm = m.then_before(i.transform(c.base.xy()));
|
||||
let editable = editable_transform(&cm, i.scale.x, i.scale.y);
|
||||
if i.block.starts_with('*') || c.array.is_some() || out.len() >= MAX_LEVELS || !editable {
|
||||
continue;
|
||||
}
|
||||
path.push(e.handle);
|
||||
out.push((path.clone(), i.block.clone()));
|
||||
nested(d, &i.block, &cm, path, out);
|
||||
path.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// The nesting levels of reference `ih`: the reference itself, then every reference nested in it.
|
||||
fn level_list(d: &Drawing, ih: Handle) -> Result<Vec<(Vec<Handle>, String)>> {
|
||||
let Some(EntityKind::Insert(ins)) = d.entity(ih).map(|e| &e.kind) else { return Err(bad("refedit", "select a block reference")) };
|
||||
let mut out = vec![(Vec::new(), ins.block.clone())];
|
||||
let m = d.block(&ins.block).map_or(Mat3::IDENTITY, |b| ins.transform(b.base.xy()));
|
||||
nested(d, &ins.block, &m, &mut Vec::new(), &mut out);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn run_levels(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ih = targets(s, p)?.into_iter().next().ok_or_else(|| bad("refedit.levels", "select a block reference"))?;
|
||||
let d = s.doc()?;
|
||||
let levels: Vec<Value> = level_list(d, ih)?
|
||||
.into_iter()
|
||||
.map(|(path, name)| json!({ "name": name, "path": hexes(path), "xref": xref_of(d, &name).is_some() }))
|
||||
.collect();
|
||||
Ok(json!({ "levels": levels }))
|
||||
}
|
||||
|
||||
// ---------------- xrefs ----------------
|
||||
|
||||
/// The xref block `name` belongs to: (the xref's name, the block of its source drawing or `None`
|
||||
/// for its model space). `None` for a block of this drawing.
|
||||
fn xref_of(d: &Drawing, name: &str) -> Option<(String, Option<String>)> {
|
||||
let b = d.block(name)?;
|
||||
if b.xref_path.is_some() {
|
||||
return Some((b.name.clone(), None));
|
||||
}
|
||||
let (root, rest) = name.split_once('|')?;
|
||||
let x = d.block(root).filter(|x| x.xref_path.is_some())?;
|
||||
Some((x.name.clone(), Some(rest.to_string())))
|
||||
}
|
||||
|
||||
/// Whether a drawing tab other than the active one has `file` open.
|
||||
fn open_in_another_tab(s: &Session, file: &std::path::Path) -> bool {
|
||||
let canon = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
|
||||
let me = canon(file);
|
||||
s.docs.iter().enumerate().any(|(i, st)| i != s.active && st.path.as_deref().is_some_and(|p| canon(std::path::Path::new(p)) == me))
|
||||
}
|
||||
|
||||
/// The source file of xref `name`, checked for an edit in place: found, not open in another
|
||||
/// drawing tab, writable, not changed since this drawing loaded it. Also returns the
|
||||
/// [`load::Stamp`] it had then (this drawing's own baseline, [`Block::xref_stamp`]).
|
||||
fn xref_file(s: &Session, name: &str) -> Result<(std::path::PathBuf, load::Stamp)> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return Err(bad("refedit", "editing xrefs in place is not available on the web; open the xref's drawing instead"));
|
||||
}
|
||||
let d = s.doc()?;
|
||||
let b = d.block(name).ok_or_else(|| bad("refedit", format!("no xref \"{name}\"")))?;
|
||||
if b.xref_status != XrefStatus::Loaded {
|
||||
return Err(bad("refedit", format!("xref \"{}\" is not loaded ({}); reload it first", b.name, b.xref_status.label())));
|
||||
}
|
||||
let path = b.xref_path.clone().unwrap_or_default();
|
||||
let host = s.state().ok().and_then(|st| st.path.clone());
|
||||
let file = load::find(&path, host.as_deref().map(std::path::Path::new), false).map_err(|_| bad("refedit", format!("{path}: file not found")))?;
|
||||
// Under the automation roots: the file is read for the edit, and written by REFCLOSE Save, so
|
||||
// an edit that couldn't be saved doesn't begin.
|
||||
crate::file_access::check_read(&file).map_err(|e| bad("refedit", e))?;
|
||||
crate::file_access::check_write(&file).map_err(|e| bad("refedit", format!("{e}; open it with XOPEN instead")))?;
|
||||
if open_in_another_tab(s, &file) {
|
||||
return Err(bad("refedit", format!("{} is open in another drawing tab: edit it there, or close it first", file.display())));
|
||||
}
|
||||
writable(&file).map_err(|e| bad("refedit", e))?;
|
||||
// Unknown (the system can't tell, or the file changed while it was read) counts as changed.
|
||||
match (b.xref_stamp, load::stamp(&file)) {
|
||||
(Some(then), Some(now)) if then == now => Ok((file, then)),
|
||||
_ => Err(bad("refedit", format!("{} changed since xref \"{}\" was loaded; reload it first", file.display(), b.name))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `file` may be written: not read-only and not open in another program (AutoCAD's
|
||||
/// `.dwl` lock file beside it, or a file that can't be opened for writing).
|
||||
fn writable(file: &std::path::Path) -> std::result::Result<(), String> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = file;
|
||||
Err("files are not available on the web".into())
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let meta = std::fs::metadata(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
if meta.permissions().readonly() {
|
||||
return Err(format!("{} is read-only", file.display()));
|
||||
}
|
||||
let lock = file.with_extension("dwl");
|
||||
if lock.is_file() {
|
||||
return Err(format!("{} is open in another program (lock file {})", file.display(), lock.display()));
|
||||
}
|
||||
std::fs::OpenOptions::new().append(true).open(file).map(|_| ()).map_err(|e| format!("{} can't be written: {e}", file.display()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects of the source drawing a block of xref `x` came from, matched one to one with the
|
||||
/// block's objects (the order loading keeps). Refused when they no longer match.
|
||||
fn source_handles(blk: &Block, src: &Drawing, inner: Option<&str>) -> Result<Vec<(Handle, Handle)>> {
|
||||
let store = match inner {
|
||||
None => &src.model,
|
||||
Some(n) => {
|
||||
let b = src.block(n).ok_or_else(|| bad("refedit", format!("block \"{n}\" is no longer in the xref's drawing; reload the xref")))?;
|
||||
if b.xref_path.is_some() {
|
||||
return Err(bad("refedit", format!("\"{n}\" is an xref of the xref's drawing: open it with XOPEN to edit it")));
|
||||
}
|
||||
&b.entities
|
||||
}
|
||||
};
|
||||
let kind = |e: &Entity| std::mem::discriminant(&e.kind);
|
||||
if store.len() != blk.entities.len() || store.iter().zip(blk.entities.iter()).any(|(a, b)| kind(a) != kind(b)) {
|
||||
return Err(bad("refedit", "the xref's drawing no longer matches what was loaded; reload the xref first"));
|
||||
}
|
||||
Ok(blk.entities.iter().zip(store.iter()).map(|(a, b)| (a.handle, b.handle)).collect())
|
||||
}
|
||||
|
||||
/// The version (`$ACADVER` code) and form (binary DXF or not) of the xref's file `file`, read as
|
||||
/// `src`, so it is written back as it was: a DWG's version is its first bytes, a DXF's the
|
||||
/// `$ACADVER` it was read with. Refused when CADCraft can't write that version (an R12 DXF,
|
||||
/// AC1009): saving would change it, and the xref is often someone else's file.
|
||||
fn file_form(file: &std::path::Path, src: &Drawing) -> Result<(Option<String>, bool)> {
|
||||
use std::io::Read;
|
||||
let mut head = Vec::new();
|
||||
std::fs::File::open(file).and_then(|f| f.take(4096).read_to_end(&mut head)).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?;
|
||||
let dwg = head
|
||||
.get(..6)
|
||||
.filter(|t| t.starts_with(b"AC") && t.get(2..).is_some_and(|d| d.iter().all(u8::is_ascii_digit)))
|
||||
.map(|t| String::from_utf8_lossy(t).into_owned());
|
||||
let declared = || src.foreign.version.clone().or_else(|| src.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).map(str::to_string));
|
||||
let version = dwg.or_else(declared).map(|v| v.trim().to_ascii_uppercase());
|
||||
if let Some(code) = &version
|
||||
&& Version::parse(code).is_none_or(|v| v.code() != code)
|
||||
{
|
||||
return Err(bad(
|
||||
"refedit",
|
||||
format!(
|
||||
"{} is an {code} file, and CADCraft writes only 2000 to 2018 files, so the edit couldn't be saved in the file's own version; open it with XOPEN instead",
|
||||
file.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
let binary = craft_dxf::is_binary(&head);
|
||||
if (version.is_some() || binary) && crate::cmd::file::write_as().is_none() {
|
||||
return Err(bad("refedit", "saving an xref in its own version is not available in this build; open it with XOPEN instead"));
|
||||
}
|
||||
Ok((version, binary))
|
||||
}
|
||||
|
||||
// ---------------- REFEDIT ----------------
|
||||
|
||||
fn run_refedit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -100,34 +330,61 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.model
|
||||
.iter()
|
||||
.chain(d.layouts.iter().flat_map(|l| l.entities.iter()))
|
||||
.find(|e| matches!(&e.kind, cadcraft_doc::EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(n)))
|
||||
.find(|e| matches!(&e.kind, EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(n)))
|
||||
.map(|e| e.handle),
|
||||
None => targets(s, p)?.into_iter().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, cadcraft_doc::EntityKind::Insert(_)))),
|
||||
None => targets(s, p)?.into_iter().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Insert(_)))),
|
||||
};
|
||||
let ih = picked.ok_or_else(|| bad("refedit", "select a block reference"))?;
|
||||
let (ins, space) = match d.entity(ih).map(|e| &e.kind) {
|
||||
Some(cadcraft_doc::EntityKind::Insert(i)) => (i.clone(), d.space_of(ih).ok_or_else(|| bad("refedit", "the reference is in no space"))?),
|
||||
Some(EntityKind::Insert(i)) => (i.clone(), d.space_of(ih).ok_or_else(|| bad("refedit", "the reference is in no space"))?),
|
||||
_ => return Err(bad("refedit", "select a block reference")),
|
||||
};
|
||||
let blk = d.block(&ins.block).cloned().ok_or_else(|| bad("refedit", format!("block \"{}\" not found", ins.block)))?;
|
||||
if blk.xref_path.is_some() {
|
||||
return Err(bad(
|
||||
"refedit",
|
||||
format!(
|
||||
"\"{}\" is an external reference: editing it in place would write its source drawing, which is not available yet. Open it with XOPEN, edit and save it, then reload.",
|
||||
blk.name
|
||||
),
|
||||
));
|
||||
}
|
||||
let path: Vec<Handle> = match (p.get("path"), str_param(p, "nested")) {
|
||||
(Some(Value::Array(a)), _) => {
|
||||
a.iter().map(|v| handle_value(v).ok_or_else(|| bad("refedit", format!("`path`: {v} is not an object handle")))).collect::<Result<_>>()?
|
||||
}
|
||||
(Some(Value::Null) | None, Some(n)) => level_list(d, ih)?
|
||||
.into_iter()
|
||||
.find(|(path, name)| !path.is_empty() && name.eq_ignore_ascii_case(n))
|
||||
.map(|(path, _)| path)
|
||||
.ok_or_else(|| bad("refedit", format!("no reference to \"{n}\" is nested in this one")))?,
|
||||
(Some(Value::Null) | None, None) => Vec::new(),
|
||||
(Some(v), _) => return Err(bad("refedit", format!("`path` must be an array of object handles, got {v}"))),
|
||||
};
|
||||
let levels = levels(d, &ins, &path)?;
|
||||
let Some(edit) = levels.last() else { return Err(bad("refedit", "select a block reference")) };
|
||||
let blk = edit.block.clone();
|
||||
let to_world = edit.to_world;
|
||||
if blk.name.starts_with('*') || blk.array.is_some() {
|
||||
return Err(bad("refedit", format!("\"{}\" is generated geometry and can't be edited in place", blk.name)));
|
||||
}
|
||||
let to_world = ins.transform(blk.base.xy());
|
||||
let (sx, sy) = (ins.scale.x.abs(), ins.scale.y.abs());
|
||||
let finite = [to_world.a, to_world.b, to_world.c, to_world.d, to_world.e, to_world.f].iter().all(|v| v.is_finite());
|
||||
if !finite || to_world.det().abs() < 1e-12 || (sx - sy).abs() > 1e-9 * sx.max(sy) {
|
||||
return Err(bad("refedit", "the reference must be scaled equally in X and Y (and not flat) to be edited in place"));
|
||||
}
|
||||
// An xref's block: where it is written back.
|
||||
let xref = match xref_of(d, &blk.name) {
|
||||
Some((x, inner)) => {
|
||||
let (file, baseline) = xref_file(s, &x)?;
|
||||
let (src, read_as) = load::read_file(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?;
|
||||
// The handles, version and stamp all come from this one read, which must be of the
|
||||
// file this drawing loaded.
|
||||
if read_as != Some(baseline) {
|
||||
return Err(bad("refedit", format!("{} changed since xref \"{x}\" was loaded; reload it first", file.display())));
|
||||
}
|
||||
let sources = source_handles(&blk, &src, inner.as_deref())?;
|
||||
let real = std::fs::canonicalize(&file).map_err(|e| bad("refedit", format!("{}: {e}", file.display())))?;
|
||||
let (version, binary) = file_form(&file, &src)?;
|
||||
Some(XrefSource {
|
||||
xref: x,
|
||||
file: file.to_string_lossy().into_owned(),
|
||||
real: real.to_string_lossy().into_owned(),
|
||||
version,
|
||||
binary,
|
||||
block: inner,
|
||||
stamp: read_as,
|
||||
sources,
|
||||
})
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let d = s.doc()?;
|
||||
let chosen: Option<HashSet<Handle>> = match p.get("objects") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(a)) if a.eq_ignore_ascii_case("all") => None,
|
||||
@@ -157,20 +414,37 @@ fn run_refedit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
items: Vec::new(),
|
||||
ghosts: Vec::new(),
|
||||
released: Vec::new(),
|
||||
path: path.clone(),
|
||||
xref,
|
||||
};
|
||||
let doc = s.doc_mut()?;
|
||||
for e in blk.entities.iter() {
|
||||
let working = chosen.as_ref().is_none_or(|c| c.contains(&e.handle));
|
||||
let h = doc.new_handle();
|
||||
put(doc, &r, to_host(&to_world, e, h, !working))?;
|
||||
put(doc, &r, to_host(&to_world, e, h))?;
|
||||
if working {
|
||||
r.items.push(WorkItem { copy: h, source: Some(e.handle) });
|
||||
} else {
|
||||
r.ghosts.push((h, e.handle));
|
||||
}
|
||||
}
|
||||
// The parents' other objects stand faded around a nested block.
|
||||
for level in levels.iter().filter(|l| l.next.is_some()) {
|
||||
for e in level.block.entities.iter().filter(|e| Some(e.handle) != level.next && !matches!(e.kind, EntityKind::AttDef(_))) {
|
||||
let h = doc.new_handle();
|
||||
put(doc, &r, to_host(&level.to_world, e, h))?;
|
||||
r.ghosts.push((h, e.handle));
|
||||
}
|
||||
}
|
||||
doc.modify_entity(ih, |e| e.common.visible = false).map_err(|e| bad("refedit", e.to_string()))?;
|
||||
let out = json!({ "block": r.block, "insert": ih.hex(), "working": hexes(r.items.iter().map(|i| i.copy)), "faded": r.ghosts.len() });
|
||||
let out = json!({
|
||||
"block": r.block,
|
||||
"insert": ih.hex(),
|
||||
"working": hexes(r.items.iter().map(|i| i.copy)),
|
||||
"faded": r.ghosts.len(),
|
||||
"path": hexes(r.path.iter().copied()),
|
||||
"xref": r.xref.as_ref().map(|x| json!({ "name": x.xref, "file": x.file, "version": x.version, "binary": x.binary })),
|
||||
});
|
||||
let sel: Vec<Handle> = r.items.iter().map(|i| i.copy).collect();
|
||||
doc.refedit = Some(r);
|
||||
s.set_selection(sel);
|
||||
@@ -220,16 +494,19 @@ fn apply_refset(s: &mut Session, add: &[Handle], remove: &[Handle]) -> Result<Va
|
||||
continue;
|
||||
}
|
||||
if let Some(pos) = r.ghosts.iter().position(|(g, _)| g == h) {
|
||||
// A faded block object joins the working set (with the edits it had before).
|
||||
let (g, src) = r.ghosts.remove(pos);
|
||||
doc.remove_entity(g);
|
||||
// A faded object of the edited block joins the working set (with the edits it had
|
||||
// before); a parent's faded object (nested edits) can't.
|
||||
let src = r.ghosts.get(pos).map(|g| g.1);
|
||||
let Some(src) = src.filter(|src| blk.entities.get(*src).is_some()) else { continue };
|
||||
r.ghosts.remove(pos);
|
||||
doc.remove_entity(*h);
|
||||
let cur = match r.released.iter().position(|e| e.handle == src) {
|
||||
Some(i) => Some(r.released.remove(i)),
|
||||
None => blk.entities.get(src).map(|e| (**e).clone()),
|
||||
};
|
||||
if let Some(cur) = cur {
|
||||
let c = doc.new_handle();
|
||||
put(doc, &r, to_host(&r.to_world, &cur, c, false))?;
|
||||
put(doc, &r, to_host(&r.to_world, &cur, c))?;
|
||||
r.items.push(WorkItem { copy: c, source: Some(src) });
|
||||
added += 1;
|
||||
}
|
||||
@@ -248,7 +525,7 @@ fn apply_refset(s: &mut Session, add: &[Handle], remove: &[Handle]) -> Result<Va
|
||||
let kept = to_block(&inv, &e, src);
|
||||
doc.remove_entity(*h);
|
||||
let g = doc.new_handle();
|
||||
put(doc, &r, to_host(&r.to_world, &kept, g, true))?;
|
||||
put(doc, &r, to_host(&r.to_world, &kept, g))?;
|
||||
r.ghosts.push((g, src));
|
||||
r.released.push(kept);
|
||||
}
|
||||
@@ -276,15 +553,78 @@ fn close(s: &mut Session, save: bool) -> Result<Value> {
|
||||
// Work on a copy: the drawing changes only when everything went through.
|
||||
let mut nd: Drawing = s.doc()?.clone();
|
||||
let mut objects = 0;
|
||||
let mut written = None;
|
||||
if save {
|
||||
objects = commit_block(&mut nd, &r)?;
|
||||
if let Some(x) = &r.xref {
|
||||
// Opened in another tab since the edit began: that tab would hold a stale drawing.
|
||||
if open_in_another_tab(s, std::path::Path::new(&x.file)) {
|
||||
return Err(bad(
|
||||
"refclose",
|
||||
format!("{} is open in another drawing tab: close it there first; the edit stays open (REFCLOSE Discard ends it)", x.file),
|
||||
));
|
||||
}
|
||||
// The file first: when it can't be written the edit stays open (Discard ends it).
|
||||
written = Some(write_back(&nd, &r, x)?);
|
||||
}
|
||||
}
|
||||
nd.end_refedit_discard(&r);
|
||||
let mut notes = Vec::new();
|
||||
if let (Some(x), Some(_)) = (&r.xref, &written) {
|
||||
let host = s.state().ok().and_then(|st| st.path.clone());
|
||||
notes = load::load(&mut nd, &x.xref, host.as_deref(), false);
|
||||
}
|
||||
*s.doc_mut()? = nd;
|
||||
// The objects the edit managed were its own: OOPS doesn't bring them back after it.
|
||||
s.state_mut()?.erased.forget(|h| r.owns(h));
|
||||
s.set_selection(Vec::new());
|
||||
Ok(json!({ "block": r.block, "saved": save, "objects": objects }))
|
||||
for o in notes {
|
||||
s.echo(o.message());
|
||||
}
|
||||
let mut out = json!({ "block": r.block, "saved": save, "objects": objects });
|
||||
if let (Some(x), Some(w)) = (&r.xref, written) {
|
||||
out["file"] = json!(x.file);
|
||||
// `null` when the file didn't look like a whole drawing and the `.bak` there was kept.
|
||||
out["backup"] = json!(w.backup);
|
||||
// What the file couldn't keep, said as SAVE says it (nothing is dropped silently).
|
||||
let kept = w.backup.as_ref().map(|b| format!(" The previous file, with them, is kept as {b}.")).unwrap_or_default();
|
||||
let mut not_saved = w.lost.clone();
|
||||
if let Some(msg) = crate::cmd::file::lost_message(&x.file, w.version, &w.lost) {
|
||||
s.echo(format!("{}: {msg}.{kept}", x.file));
|
||||
}
|
||||
if w.associations > 0 {
|
||||
s.echo(format!(
|
||||
"{}: Not saved in the file: the dimension associations of {} dimension(s), which tie them to the objects they measure (an xref edited in place doesn't keep them yet).{kept}",
|
||||
x.file, w.associations
|
||||
));
|
||||
not_saved.insert("dimension associations".into(), w.associations);
|
||||
}
|
||||
if !not_saved.is_empty() {
|
||||
out["notSaved"] = json!(not_saved);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What writing an xref back did: the backup it kept, the version it was written at, what the
|
||||
/// file couldn't keep ([`crate::cmd::file::lost_writing`]), and how many dimensions were written
|
||||
/// without their associations ([`associations_dropped`]).
|
||||
struct Written {
|
||||
backup: Option<String>,
|
||||
version: Version,
|
||||
lost: std::collections::BTreeMap<String, usize>,
|
||||
associations: usize,
|
||||
}
|
||||
|
||||
/// The dimensions of the part of `src` (the xref's drawing as read) that the write-back replaces
|
||||
/// which are attached to objects: loading the xref dropped those associations, so the file is
|
||||
/// written without them.
|
||||
fn associations_dropped(src: &Drawing, x: &XrefSource) -> usize {
|
||||
let store = match &x.block {
|
||||
None => Some(&src.model),
|
||||
Some(n) => src.block(n).map(|b| &b.entities),
|
||||
};
|
||||
store.map_or(0, |st| st.iter().filter(|e| matches!(&e.kind, EntityKind::Dimension(dm) if !dm.assoc.is_empty())).count())
|
||||
}
|
||||
|
||||
/// Replace the block's objects by the working set (and move the drawing objects added to it
|
||||
@@ -333,6 +673,298 @@ fn commit_block(nd: &mut Drawing, r: &RefEdit) -> Result<usize> {
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
// ---------------- writing an xref back ----------------
|
||||
|
||||
/// Write the edited block of `nd` (committed) into xref source `x`.
|
||||
fn write_back(nd: &Drawing, r: &RefEdit, x: &XrefSource) -> Result<Written> {
|
||||
let file = std::path::Path::new(&x.file);
|
||||
let real = std::path::Path::new(&x.real);
|
||||
// Under the automation roots, the file written and its backup, before anything is read or
|
||||
// written: roots put in force since the edit began hold too.
|
||||
for target in [real.to_path_buf(), crate::cmd::file::backup_path(real)] {
|
||||
crate::file_access::check_write(&target).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?;
|
||||
}
|
||||
writable(file).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?;
|
||||
still_leads_to(file, real).map_err(|e| bad("refclose", format!("{e}; the edit stays open (REFCLOSE Discard ends it)")))?;
|
||||
unchanged(file, x, load::stamp(file))?;
|
||||
let hooks = crate::cmd::file::io().ok_or_else(|| bad("refclose", "file formats are not available in this build"))?;
|
||||
let (mut src, read_as) = load::read_file(file).map_err(|e| bad("refclose", format!("{}: {e}", file.display())))?;
|
||||
// What is written over is what was just read, and that is the file the edit began with.
|
||||
unchanged(file, x, read_as)?;
|
||||
let dropped = associations_dropped(&src, x);
|
||||
let cleared = put_edit(nd, r, x, &mut src)?;
|
||||
// The xref is loaded again from the file: one it could no longer load is not written.
|
||||
let objects = load::object_count(&src);
|
||||
if objects > load::MAX_XREF_OBJECTS {
|
||||
return Err(bad(
|
||||
"refclose",
|
||||
format!(
|
||||
"{} would hold {objects} objects, more than an xref loads ({}); it is not written (REFCLOSE Discard ends the edit)",
|
||||
file.display(),
|
||||
load::MAX_XREF_OBJECTS
|
||||
),
|
||||
));
|
||||
}
|
||||
// In the version and form the file was read in, not the writer's default (a DWG at 2004 or
|
||||
// later): a version change can lock out whoever made the file.
|
||||
let version = x.version.as_deref().and_then(Version::parse);
|
||||
let bytes = if version.is_none() && !x.binary {
|
||||
(hooks.write)(&src, &x.file)
|
||||
} else {
|
||||
let w = crate::cmd::file::write_as().ok_or_else(|| bad("refclose", "saving an xref in its own version is not available in this build"))?;
|
||||
w(&src, &x.file, &crate::cmd::file::SaveAs { version, binary: x.binary, portable_fonts: false })
|
||||
};
|
||||
let bytes = bytes.map_err(|e| bad("refclose", format!("writing {}: {e}", file.display())))?;
|
||||
let as_version =
|
||||
version.unwrap_or_else(|| src.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver).unwrap_or_default());
|
||||
let lost = crate::cmd::file::lost_writing(&src, &x.file, as_version);
|
||||
// Once more just before the file is replaced: another program may have saved it while the
|
||||
// new file was made. (Without a lock every writer honours, this narrows the window; it
|
||||
// can't close it.)
|
||||
unchanged(file, x, load::stamp(file))?;
|
||||
let backup = replace_file(file, real, &bytes).map_err(|e| bad("refclose", e))?;
|
||||
Ok(Written { backup, version: as_version, lost, associations: dropped.saturating_add(cleared) })
|
||||
}
|
||||
|
||||
/// Refuse when `now` (the xref's file as it is, or as just read) is not the file the edit began
|
||||
/// with; an unknown stamp counts as changed.
|
||||
fn unchanged(file: &std::path::Path, x: &XrefSource, now: Option<load::Stamp>) -> Result<()> {
|
||||
if x.stamp.is_none() || now != x.stamp {
|
||||
return Err(bad(
|
||||
"refclose",
|
||||
format!("{} changed since the edit began; it is not overwritten (REFCLOSE Discard ends the edit)", file.display()),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Put the edited block of `nd` (committed) into `src`, the xref's drawing as read: its objects
|
||||
/// with their source handles and names, and the host symbols they use. A dimension attached to
|
||||
/// objects of the host (drawn during the edit) is written without those associations: the
|
||||
/// host's handles mean nothing in the xref's file. Returns how many were.
|
||||
fn put_edit(nd: &Drawing, r: &RefEdit, x: &XrefSource, src: &mut Drawing) -> Result<usize> {
|
||||
let file = std::path::Path::new(&x.file);
|
||||
let blk = nd.block(&r.block).ok_or_else(|| bad("refclose", format!("block \"{}\" is gone", r.block)))?;
|
||||
let prefix = format!("{}|", x.xref);
|
||||
let map: HashMap<Handle, Handle> = x.sources.iter().copied().collect();
|
||||
let mut store = EntityStore::new();
|
||||
let mut wanted: Vec<(Sym, String)> = Vec::new();
|
||||
let mut cleared = 0usize;
|
||||
for e in blk.entities.iter() {
|
||||
let mut e = (**e).clone();
|
||||
e.handle = match map.get(&e.handle) {
|
||||
Some(h) => *h,
|
||||
None => src.new_handle(),
|
||||
};
|
||||
rename_into_source(&mut e, &prefix, &mut wanted);
|
||||
if let EntityKind::Dimension(dm) = &mut e.kind
|
||||
&& !dm.assoc.is_empty()
|
||||
{
|
||||
dm.assoc.clear();
|
||||
cleared = cleared.saturating_add(1);
|
||||
}
|
||||
store.push(e);
|
||||
}
|
||||
bring_symbols(nd, src, &prefix, wanted, MAX_SYMBOLS)?;
|
||||
match &x.block {
|
||||
None => src.model = store,
|
||||
Some(name) => {
|
||||
let key = src
|
||||
.blocks
|
||||
.keys()
|
||||
.find(|k| k.eq_ignore_ascii_case(name))
|
||||
.cloned()
|
||||
.ok_or_else(|| bad("refclose", format!("block \"{name}\" is gone from {}", file.display())))?;
|
||||
if let Some(b) = src.blocks.get_mut(&key) {
|
||||
Arc::make_mut(b).entities = store;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(cleared)
|
||||
}
|
||||
|
||||
/// Refuse a save when `file` no longer leads to `real` (the file the edit began with), or `real`
|
||||
/// is no longer a plain file: a symbolic link put at either since would send the edit to another
|
||||
/// file.
|
||||
fn still_leads_to(file: &std::path::Path, real: &std::path::Path) -> std::result::Result<(), String> {
|
||||
let now = std::fs::canonicalize(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
let plain = std::fs::symlink_metadata(real).is_ok_and(|m| m.is_file());
|
||||
if now != real || !plain {
|
||||
return Err(format!(
|
||||
"{} leads to another file than when the edit began (a symbolic link was put there); it is not overwritten",
|
||||
file.display()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Symbol names of a host object as the xref's drawing has them: `xref|name` loses its prefix;
|
||||
/// the host's own symbols keep their names and are noted in `wanted` (copied into the drawing).
|
||||
fn rename_into_source(e: &mut Entity, prefix: &str, wanted: &mut Vec<(Sym, String)>) {
|
||||
let found = std::cell::RefCell::new(Vec::new());
|
||||
load::rename_refs(e, &|sym, n| {
|
||||
if load::has_prefix(n, prefix) {
|
||||
return n.get(prefix.len()..).map(str::to_string);
|
||||
}
|
||||
found.borrow_mut().push((sym, n.to_string()));
|
||||
None
|
||||
});
|
||||
wanted.extend(found.into_inner());
|
||||
}
|
||||
|
||||
/// Most distinct symbols [`bring_symbols`] looks at for one save (hostile drawings: blocks naming
|
||||
/// blocks naming blocks…).
|
||||
const MAX_SYMBOLS: usize = 100_000;
|
||||
|
||||
/// Copy the host's symbols that objects written into `src` use and `src` lacks (layers,
|
||||
/// linetypes, text, dimension, multileader and table styles, and blocks with what they use in
|
||||
/// turn). Only distinct names count against `cap`; past it the save is refused rather than
|
||||
/// written with symbols missing.
|
||||
fn bring_symbols(host: &Drawing, src: &mut Drawing, prefix: &str, mut wanted: Vec<(Sym, String)>, cap: usize) -> Result<()> {
|
||||
let mut seen: HashSet<(Sym, String)> = HashSet::new();
|
||||
let mut blocks: Vec<String> = Vec::new();
|
||||
while let Some((sym, name)) = wanted.pop() {
|
||||
if name.is_empty() || !seen.insert((sym, name.to_ascii_uppercase())) {
|
||||
continue;
|
||||
}
|
||||
if seen.len() > cap {
|
||||
return Err(bad("refclose", format!("the edit uses more than {cap} symbols; the xref is not written (REFCLOSE Discard ends the edit)")));
|
||||
}
|
||||
if sym == Sym::Block {
|
||||
blocks.push(name.clone());
|
||||
}
|
||||
bring_symbol(host, src, prefix, sym, &name, &mut wanted);
|
||||
}
|
||||
// A block the written objects name that the drawing still lacks (an xref of the host, added
|
||||
// with REFSET) would leave a reference to nothing in the file: refused, nothing written.
|
||||
if let Some(name) = blocks.iter().find(|n| src.block(n).is_none()) {
|
||||
return Err(bad(
|
||||
"refclose",
|
||||
format!(
|
||||
"the edit uses block \"{name}\", which can't be written into the xref's drawing (an xref of this drawing, or a block it doesn't define); remove it from the working set (REFSET) or use REFCLOSE Discard"
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The blocks dimension style `t` of `host` draws its arrowheads with: the names `host` defines as
|
||||
/// blocks (a built-in arrowhead name is drawn in code, not a block), as the xref's drawing names
|
||||
/// them.
|
||||
fn arrow_blocks(host: &Drawing, t: &cadcraft_doc::DimStyle, prefix: &str) -> Vec<(Sym, String)> {
|
||||
[&t.arrow_block, &t.arrow_block1, &t.arrow_block2, &t.leader_arrow_block]
|
||||
.into_iter()
|
||||
.map(|n| n.trim())
|
||||
.filter(|n| !n.is_empty() && host.block(n).is_some())
|
||||
.map(|n| (Sym::Block, if load::has_prefix(n, prefix) { n.get(prefix.len()..).unwrap_or(n).to_string() } else { n.to_string() }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Copy host symbol `name` of kind `sym` into `src` when `src` lacks it, queueing what it uses.
|
||||
fn bring_symbol(host: &Drawing, src: &mut Drawing, prefix: &str, sym: Sym, name: &str, wanted: &mut Vec<(Sym, String)>) {
|
||||
let name = name.to_string();
|
||||
{
|
||||
match sym {
|
||||
Sym::Layer => {
|
||||
if name != "0"
|
||||
&& src.layer(&name).is_none()
|
||||
&& let Some(l) = host.layer(&name)
|
||||
{
|
||||
wanted.push((Sym::Linetype, l.linetype.clone()));
|
||||
src.layers.push(l.clone());
|
||||
}
|
||||
}
|
||||
Sym::Linetype => {
|
||||
let builtin = ["ByLayer", "ByBlock", "Continuous"].iter().any(|n| n.eq_ignore_ascii_case(&name));
|
||||
if !builtin
|
||||
&& src.linetype(&name).is_none()
|
||||
&& let Some(t) = host.linetype(&name)
|
||||
{
|
||||
src.linetypes.push(t.clone());
|
||||
}
|
||||
}
|
||||
Sym::Style => {
|
||||
if src.text_style(&name).is_none()
|
||||
&& let Some(t) = host.text_style(&name)
|
||||
{
|
||||
src.text_styles.push(t.clone());
|
||||
}
|
||||
}
|
||||
Sym::DimStyle => {
|
||||
if src.dim_style(&name).is_none()
|
||||
&& let Some(t) = host.dim_style(&name)
|
||||
{
|
||||
wanted.push((Sym::Style, t.text_style.clone()));
|
||||
wanted.extend(arrow_blocks(host, t, prefix));
|
||||
src.dim_styles.push(t.clone());
|
||||
}
|
||||
}
|
||||
Sym::Block => {
|
||||
if src.block(&name).is_none()
|
||||
&& let Some(b) = host.block(&name)
|
||||
&& b.xref_path.is_none()
|
||||
{
|
||||
let mut nb = (**b).clone();
|
||||
let mut store = EntityStore::new();
|
||||
for e in b.entities.iter() {
|
||||
let mut e = (**e).clone();
|
||||
e.handle = src.new_handle();
|
||||
rename_into_source(&mut e, prefix, wanted);
|
||||
store.push(e);
|
||||
}
|
||||
nb.entities = store;
|
||||
src.blocks.insert(nb.name.clone(), Arc::new(nb));
|
||||
}
|
||||
}
|
||||
Sym::MLeaderStyle => {
|
||||
let have = src.mleader_styles.iter().any(|t| t.name.eq_ignore_ascii_case(&name));
|
||||
if !have && let Some(t) = host.mleader_styles.iter().find(|t| t.name.eq_ignore_ascii_case(&name)) {
|
||||
wanted.push((Sym::Style, t.text_style.clone()));
|
||||
src.mleader_styles.push(t.clone());
|
||||
}
|
||||
}
|
||||
Sym::TableStyle => {
|
||||
let have = src.table_styles.iter().any(|t| t.name.eq_ignore_ascii_case(&name));
|
||||
if !have && let Some(t) = host.table_styles.iter().find(|t| t.name.eq_ignore_ascii_case(&name)) {
|
||||
wanted.extend(t.cell_styles.iter().map(|c| (Sym::Style, c.text_style.clone())));
|
||||
src.table_styles.push(t.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the xref's file (`file` as the xref names it, `real` the file it leads to) by `bytes`,
|
||||
/// the way SAVE replaces a drawing: the old file is kept as its `.bak` (when ISAVEBAK is on)
|
||||
/// ([`crate::cmd::file::backup_path`]: `site.dwg` as `site.bak`, `site.dxf` as `site.dxf.bak`),
|
||||
/// and the new one goes into a fresh, exclusively created temporary file that is renamed over
|
||||
/// `real` ([`crate::atomic_write`]). A symbolic link planted at the temporary or backup path is
|
||||
/// never written through, and a link at `real` is replaced, not followed. Returns the backup's
|
||||
/// path (`None` when none was kept).
|
||||
fn replace_file(file: &std::path::Path, real: &std::path::Path, bytes: &[u8]) -> std::result::Result<Option<String>, String> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = (file, real, bytes);
|
||||
Err("files are not available on the web".into())
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
// As SAVE: ISAVEBAK off keeps no backup.
|
||||
let kept = if crate::autosave::isavebak() {
|
||||
crate::cmd::file::backup(real)
|
||||
.map_err(|e| format!("the backup copy of {} could not be written ({e}); it is unchanged", file.display()))?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let permissions = std::fs::symlink_metadata(real).ok().filter(std::fs::Metadata::is_file).map(|m| m.permissions());
|
||||
crate::atomic_write::write_atomic_with(real, permissions, |f| std::io::Write::write_all(f, bytes))
|
||||
.map_err(|e| format!("{} can't be replaced: {e}; it is unchanged", file.display()))?;
|
||||
// Named beside the file as the xref names it, unless that name is itself a link.
|
||||
let shown = if std::fs::symlink_metadata(file).is_ok_and(|m| m.file_type().is_symlink()) { real } else { file };
|
||||
Ok(kept.then(|| crate::cmd::file::backup_path(shown).to_string_lossy().into_owned()))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- while editing ----------------
|
||||
|
||||
/// After a command ran: objects it created join the working set, and a command that changed
|
||||
@@ -376,6 +1008,94 @@ pub(crate) fn locked(d: &Drawing, h: Handle) -> bool {
|
||||
|
||||
// ---------------- interactive ----------------
|
||||
|
||||
/// REFEDIT at the command line: "Select reference", then "Select nesting level [OK/Next]" when
|
||||
/// the reference has others nested in it.
|
||||
#[derive(Default)]
|
||||
struct RefeditM {
|
||||
sel: SelectPhase,
|
||||
picked: Option<Handle>,
|
||||
levels: Vec<(Vec<Handle>, String)>,
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl RefeditM {
|
||||
fn picked(&mut self, s: &mut Session, hs: &[Handle]) -> Result<Step> {
|
||||
let d = s.doc()?;
|
||||
let Some(h) = hs.iter().copied().find(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Insert(_)))) else {
|
||||
s.echo("Select a block or xref reference.");
|
||||
self.sel = SelectPhase::single();
|
||||
return Ok(Step::Continue);
|
||||
};
|
||||
self.levels = level_list(d, h)?;
|
||||
self.picked = Some(h);
|
||||
if self.levels.len() > 1 {
|
||||
self.echo_level(s);
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
self.finish(s)
|
||||
}
|
||||
fn echo_level(&self, s: &mut Session) {
|
||||
if let Some((path, name)) = self.levels.get(self.at) {
|
||||
s.echo(format!("Reference name: {name}{}", if path.is_empty() { String::new() } else { format!(" (nested {} deep)", path.len()) }));
|
||||
}
|
||||
}
|
||||
fn finish(&mut self, s: &mut Session) -> Result<Step> {
|
||||
let Some(h) = self.picked else { return Ok(Step::Cancel) };
|
||||
let path = self.levels.get(self.at).map(|(p, _)| hexes(p.iter().copied())).unwrap_or_default();
|
||||
let r = run_refedit(s, &json!({ "handle": h.hex(), "path": path }))?;
|
||||
let n = r["working"].as_array().map_or(0, Vec::len);
|
||||
s.set_selection(Vec::new());
|
||||
s.echo(format!("{n} object(s) in the working set. Use REFCLOSE to save or discard the changes."));
|
||||
Ok(Step::Done)
|
||||
}
|
||||
}
|
||||
|
||||
impl Interactive for RefeditM {
|
||||
fn name(&self) -> &'static str {
|
||||
"REFEDIT"
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.sel = SelectPhase::begin(s);
|
||||
self.sel.single = true;
|
||||
if self.sel.done {
|
||||
let hs = self.sel.picked.clone();
|
||||
return self.picked(s, &hs);
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
if self.picked.is_none() {
|
||||
return Prompt::new("Select reference", Accept::SELECT);
|
||||
}
|
||||
Prompt::new("Select nesting level", Accept::TEXT).kw(&["OK", "Next"]).default("Next")
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
if matches!(i, Input::Cancel) {
|
||||
return Ok(Step::Cancel);
|
||||
}
|
||||
if self.picked.is_none() {
|
||||
return match self.sel.feed(s, &i)? {
|
||||
SelOutcome::More => Ok(Step::Continue),
|
||||
SelOutcome::Empty => Ok(Step::Done),
|
||||
SelOutcome::Done(hs) => self.picked(s, &hs),
|
||||
};
|
||||
}
|
||||
let k = match &i {
|
||||
Input::Keyword(k) | Input::Text(k) => k.trim().to_ascii_lowercase(),
|
||||
Input::Enter => "next".into(),
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
if k.starts_with('o') {
|
||||
return self.finish(s);
|
||||
}
|
||||
if k.starts_with('n') {
|
||||
self.at = (self.at + 1) % self.levels.len().max(1);
|
||||
self.echo_level(s);
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
enum RStage {
|
||||
#[default]
|
||||
@@ -464,8 +1184,39 @@ impl Interactive for RefcloseM {
|
||||
_ => return Ok(Step::Cancel),
|
||||
};
|
||||
let r = close(s, save)?;
|
||||
s.echo(if save { "Reference changes saved." } else { "Reference changes discarded." });
|
||||
let _ = r;
|
||||
s.echo(match (save, r.get("file").and_then(Value::as_str)) {
|
||||
(true, Some(f)) => match r["backup"].as_str() {
|
||||
Some(b) => format!("Reference changes saved to {f} (the previous file is kept as {b})."),
|
||||
None => format!("Reference changes saved to {f}."),
|
||||
},
|
||||
(true, None) => "Reference changes saved.".to_string(),
|
||||
(false, _) => "Reference changes discarded.".to_string(),
|
||||
});
|
||||
Ok(Step::Done)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Review of #2355: the budget counted every queued reference, so a host-only layer queued
|
||||
/// first was skipped once enough repeated ones followed it, and the file was written without
|
||||
/// it. Only distinct names count now, and running out refuses the save.
|
||||
#[test]
|
||||
fn repeated_symbols_do_not_use_up_the_budget() {
|
||||
let mut host = Drawing::new_metric();
|
||||
host.layers.push(cadcraft_doc::Layer { name: "Added".into(), ..cadcraft_doc::Layer::default() });
|
||||
let mut wanted = vec![(Sym::Layer, "Added".to_string())];
|
||||
for _ in 0..1000 {
|
||||
wanted.push((Sym::Layer, "0".into()));
|
||||
wanted.push((Sym::Linetype, "ByLayer".into()));
|
||||
}
|
||||
// Distinct: ByLayer, 0, Added and its linetype.
|
||||
let mut src = Drawing::new_metric();
|
||||
bring_symbols(&host, &mut src, "x|", wanted.clone(), 4).unwrap();
|
||||
assert!(src.layer("Added").is_some(), "the layer queued first is copied");
|
||||
let mut src = Drawing::new_metric();
|
||||
assert!(bring_symbols(&host, &mut src, "x|", wanted, 2).is_err(), "past the budget the save is refused");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +134,7 @@ struct Ctx {
|
||||
}
|
||||
|
||||
/// The folder of the host drawing at `host` (a file path).
|
||||
fn folder(host: Option<&Path>) -> Option<PathBuf> {
|
||||
pub(crate) fn folder(host: Option<&Path>) -> Option<PathBuf> {
|
||||
let p = host?.parent()?;
|
||||
Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() })
|
||||
}
|
||||
@@ -294,7 +294,10 @@ fn case_insensitive(p: &Path) -> Result<Option<PathBuf>, ()> {
|
||||
}
|
||||
|
||||
/// Read a drawing file through the host's io hooks, counting its bytes against the load's total.
|
||||
fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
|
||||
/// Also returns the [`Stamp`] of the bytes read: taken from the opened file, so it describes them
|
||||
/// even when the path is pointed at another file meanwhile; `None` when the file changed while it
|
||||
/// was read (or the system can't tell its time), so an edit in place refuses until it is reloaded.
|
||||
fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>), String> {
|
||||
let hooks = super::super::super::file::io().ok_or("file formats are not available in this build")?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
@@ -303,7 +306,9 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
|
||||
let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes);
|
||||
let limit = MAX_XREF_BYTES.min(left);
|
||||
let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?;
|
||||
let len = f.metadata().map_err(|e| e.to_string())?.len();
|
||||
let meta = f.metadata().map_err(|e| e.to_string())?;
|
||||
let len = meta.len();
|
||||
let before = stamp_of(&meta);
|
||||
let too_big = || {
|
||||
if limit < MAX_XREF_BYTES {
|
||||
format!("the referenced files are larger than {} MB together", MAX_XREF_TOTAL_BYTES >> 20)
|
||||
@@ -321,7 +326,9 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
|
||||
return Err(too_big());
|
||||
}
|
||||
cx.bytes = cx.bytes.saturating_add(n);
|
||||
(hooks.read)(&bytes, &file.to_string_lossy())
|
||||
let after = f.metadata().ok().as_ref().and_then(stamp_of);
|
||||
let read_as = before.filter(|b| Some(*b) == after);
|
||||
Ok(((hooks.read)(&bytes, &file.to_string_lossy())?, read_as))
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
@@ -330,6 +337,32 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A file's size and modification time (nanoseconds since 1970): how an edit in place (REFEDIT)
|
||||
/// tells whether an xref's file changed since it was read ([`cadcraft_doc::Block::xref_stamp`]).
|
||||
pub(crate) type Stamp = (u64, u128);
|
||||
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
fn stamp_of(m: &std::fs::Metadata) -> Option<Stamp> {
|
||||
let t = m.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos();
|
||||
Some((m.len(), t))
|
||||
}
|
||||
|
||||
/// The [`Stamp`] of the file at `file` now.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn stamp(file: &Path) -> Option<Stamp> {
|
||||
stamp_of(&std::fs::metadata(file).ok()?)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn stamp(_file: &Path) -> Option<Stamp> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Read the drawing file `file` (with the size limits of xref loading), with the [`Stamp`] of the
|
||||
/// bytes read (see [`read`]).
|
||||
pub(crate) fn read_file(file: &Path) -> Result<(Drawing, Option<Stamp>), String> {
|
||||
read(file, &mut Ctx::new(None))
|
||||
}
|
||||
|
||||
/// Load every xref of `d` that isn't unloaded from the paths saved in it; `host` is the drawing's
|
||||
/// own path.
|
||||
pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec<Outcome> {
|
||||
@@ -393,8 +426,14 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
|
||||
let Some(path) = b.xref_path.clone() else { return (XrefStatus::Unresolved, "not an xref".into()) };
|
||||
clear(d, &key);
|
||||
let (status, detail) = match fetch(&path, host, chosen, cx, depth) {
|
||||
Ok((x, file)) => match import(d, &key, &x, cx) {
|
||||
Ok(()) => (XrefStatus::Loaded, file.to_string_lossy().into_owned()),
|
||||
Ok((x, file, read_as)) => match import(d, &key, &x, cx) {
|
||||
Ok(()) => {
|
||||
// This drawing's own baseline: another drawing loading the file later doesn't move it.
|
||||
if let Some(b) = d.blocks.get_mut(&key) {
|
||||
Arc::make_mut(b).xref_stamp = read_as;
|
||||
}
|
||||
(XrefStatus::Loaded, file.to_string_lossy().into_owned())
|
||||
}
|
||||
Err(e) => {
|
||||
// Whatever made it in before the failure goes again. A fetch that failed imported
|
||||
// nothing, so it doesn't pay for a second scan of the block table.
|
||||
@@ -409,7 +448,13 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
|
||||
}
|
||||
|
||||
/// Read the drawing referenced as `path` and load its own attached xrefs into it.
|
||||
fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usize) -> Result<(Drawing, PathBuf), (XrefStatus, String)> {
|
||||
fn fetch(
|
||||
path: &str,
|
||||
host: Option<&Path>,
|
||||
chosen: bool,
|
||||
cx: &mut Ctx,
|
||||
depth: usize,
|
||||
) -> Result<(Drawing, PathBuf, Option<Stamp>), (XrefStatus, String)> {
|
||||
let unresolved = |m: &str| (XrefStatus::Unresolved, m.to_string());
|
||||
if depth >= MAX_BLOCK_DEPTH {
|
||||
return Err(unresolved("xrefs are nested too deeply"));
|
||||
@@ -423,7 +468,7 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi
|
||||
return Err(unresolved("too many referenced files"));
|
||||
}
|
||||
cx.files += 1;
|
||||
let mut x = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
|
||||
let (mut x, read_as) = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
|
||||
cx.chain.push(canon);
|
||||
let nested: Vec<String> =
|
||||
x.blocks.values().filter(|b| b.xref_path.is_some() && !b.xref_overlay && !b.name.contains('|')).map(|b| b.name.clone()).collect();
|
||||
@@ -434,15 +479,20 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi
|
||||
}
|
||||
}
|
||||
cx.chain.pop();
|
||||
Ok((x, file))
|
||||
Ok((x, file, read_as))
|
||||
}
|
||||
|
||||
/// The objects loading drawing `x` as an xref counts against [`MAX_XREF_OBJECTS`]: its model
|
||||
/// space and every block's.
|
||||
pub(crate) fn object_count(x: &Drawing) -> usize {
|
||||
x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()))
|
||||
}
|
||||
|
||||
/// Bring referenced drawing `x` into xref `key`: its model space becomes the block's objects, its
|
||||
/// symbols and blocks are added as `key|name` (dependent symbols the host already has keep the
|
||||
/// host's settings, so layer changes survive a reload).
|
||||
fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), String> {
|
||||
let count = x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()));
|
||||
cx.objects = cx.objects.saturating_add(count);
|
||||
cx.objects = cx.objects.saturating_add(object_count(x));
|
||||
if cx.objects > MAX_XREF_OBJECTS {
|
||||
return Err(format!("more than {MAX_XREF_OBJECTS} objects"));
|
||||
}
|
||||
|
||||
@@ -39,10 +39,6 @@ fn vertex_value(v: &Value) -> Option<PolyVertex> {
|
||||
Some(PolyVertex { p, bulge: f64_or(v, "bulge", 0.0), start_width: f64_or(v, "startWidth", 0.0), end_width: f64_or(v, "endWidth", 0.0) })
|
||||
}
|
||||
|
||||
fn current_elevation(s: &Session) -> Result<f64> {
|
||||
Ok(s.doc()?.header.f64("ELEVATION", 0.0))
|
||||
}
|
||||
|
||||
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
|
||||
for v in raw.into_iter().flatten() {
|
||||
@@ -57,7 +53,6 @@ pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut k = lwpoly(vs, bool_or(p, "closed", false));
|
||||
if let EntityKind::LwPolyline(pl) = &mut k {
|
||||
pl.const_width = width;
|
||||
pl.elevation = current_elevation(s)?;
|
||||
}
|
||||
added(s.add_entity(k)?)
|
||||
}
|
||||
@@ -179,7 +174,6 @@ impl Interactive for LineM {
|
||||
#[derive(Default)]
|
||||
pub(super) struct PlineM {
|
||||
verts: Vec<PolyVertex>,
|
||||
elevation: f64,
|
||||
arc_mode: bool,
|
||||
/// Total width at the start and end of the next segment (Width / Halfwidth answers).
|
||||
start_w: f64,
|
||||
@@ -197,7 +191,6 @@ impl PlineM {
|
||||
fn entity(&self, closed: bool) -> EntityKind {
|
||||
let mut k = lwpoly(self.verts.clone(), closed);
|
||||
if let EntityKind::LwPolyline(pl) = &mut k {
|
||||
pl.elevation = self.elevation;
|
||||
// Every segment the same uniform width: store it as the constant width, as before.
|
||||
let segs = if closed { pl.vertices.len() } else { pl.vertices.len().saturating_sub(1) };
|
||||
let w = pl.vertices.first().map_or(0.0, |v| v.start_width);
|
||||
@@ -266,10 +259,6 @@ impl Interactive for PlineM {
|
||||
fn name(&self) -> &'static str {
|
||||
"PLINE"
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.elevation = current_elevation(s)?;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
if self.asking_width > 0 {
|
||||
let unit = if self.half { "half-width" } else { "width" };
|
||||
|
||||
@@ -232,7 +232,7 @@ impl Interactive for MTextM {
|
||||
None => Prompt::new("Specify first corner", Accept::POINT),
|
||||
Some(a) if !self.boxed() => Prompt::new("Specify opposite corner", Accept::POINT)
|
||||
.kw(&["Height", "Justify", "Line spacing", "Rotation", "Style", "Width", "Columns"])
|
||||
.corner(a),
|
||||
.base(a),
|
||||
_ if self.lines.is_empty() => Prompt::new("Enter text (use \\P for new paragraphs)", Accept::TEXT),
|
||||
_ => Prompt::new("Enter next line of text (empty line to finish)", Accept::TEXT),
|
||||
}
|
||||
|
||||
@@ -95,15 +95,6 @@ pub fn set_proxies_lost(f: ProxiesLost) {
|
||||
let _ = PROXIES_LOST.set(f);
|
||||
}
|
||||
|
||||
/// Version-specific DWG compatibility omissions, counted by the host's actual writer.
|
||||
pub type DwgCompatLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
|
||||
|
||||
static DWG_COMPAT_LOST: OnceLock<DwgCompatLost> = OnceLock::new();
|
||||
|
||||
pub fn set_dwg_compat_lost(f: DwgCompatLost) {
|
||||
let _ = DWG_COMPAT_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> {
|
||||
@@ -730,12 +721,13 @@ fn adopt_source_group(out: &std::fs::File, src: &std::fs::Metadata) -> std::io::
|
||||
/// ([`crate::atomic_write::write_atomic_with`]). Nothing
|
||||
/// to keep when there is no file yet. A file that doesn't look like a drawing
|
||||
/// ([`looks_like_drawing`]) is not backed up, and the `.bak` already there is left alone.
|
||||
/// Returns whether the backup was written. Also used for an xref REFEDIT writes back.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn backup(path: &std::path::Path) -> std::io::Result<()> {
|
||||
pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
|
||||
let mut src = match std::fs::File::open(path) {
|
||||
Ok(f) if f.metadata()?.is_file() => f,
|
||||
Ok(_) => return Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Ok(_) => return Ok(false),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let (head, tail, len) = ends(&mut src)?;
|
||||
@@ -744,7 +736,7 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> {
|
||||
// the roots (or to another computer) isn't looked at.
|
||||
if !backup_replaced(&head, &tail, len, std::fs::symlink_metadata(&bak).is_ok()) {
|
||||
log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display());
|
||||
return Ok(());
|
||||
return Ok(false);
|
||||
}
|
||||
// The backup is no more readable than the drawing, nor than the .bak it replaces (a private
|
||||
// 0600 drawing or .bak stays private). The mode is set as the new file is created, so a
|
||||
@@ -770,7 +762,8 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> {
|
||||
}
|
||||
std::io::Write::write_all(out, &head)?;
|
||||
std::io::copy(&mut src, out).map(|_| ())
|
||||
})
|
||||
})?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Store the bytes, then mark the drawing saved under `path`. If storing fails the drawing keeps
|
||||
@@ -932,12 +925,6 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
}
|
||||
if let Some(compatibility) = DWG_COMPAT_LOST.get() {
|
||||
for (kind, count) in compatibility(d, version) {
|
||||
let total = out.entry(kind).or_default();
|
||||
*total = total.saturating_add(count);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -232,7 +232,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
let outer = found.outer;
|
||||
let ob = Bounds2::from_points(outer.iter().copied());
|
||||
let sources = handles_of(&owners, &found.outer_sources);
|
||||
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, sources }];
|
||||
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, sources }];
|
||||
// Islands: closed objects entirely inside the outer loop that don't contain the pick point.
|
||||
if let Some(store) = d.space(&space) {
|
||||
for e in store.iter() {
|
||||
@@ -248,7 +248,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
let inside = pts.iter().all(|q| point_in_polygon(&outer, *q) || outer.iter().any(|o| o.near(*q, tol * 10.0)));
|
||||
let same_as_outer = (cadcraft_geom::shoelace(&pts).abs() - cadcraft_geom::shoelace(&outer).abs()).abs() < tol.max(1e-6) * 1000.0;
|
||||
if inside && !same_as_outer && !point_in_polygon(&pts, p) {
|
||||
loops.push(HatchLoop { vertices: vs, outer: false, boundary_flags: None, sources: vec![e.handle] });
|
||||
loops.push(HatchLoop { vertices: vs, outer: false, sources: vec![e.handle] });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,12 +260,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
&& island.sources.iter().all(|&i| owners.get(i).and_then(|h| d.entity(*h)).is_some_and(|e| island_curve(d, e)));
|
||||
if open_curves {
|
||||
let sources = handles_of(&owners, &island.sources);
|
||||
loops.push(HatchLoop {
|
||||
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
|
||||
outer: false,
|
||||
boundary_flags: None,
|
||||
sources,
|
||||
});
|
||||
loops.push(HatchLoop { vertices: island.outline.into_iter().map(PolyVertex::new).collect(), outer: false, sources });
|
||||
}
|
||||
}
|
||||
Ok(loops)
|
||||
@@ -276,7 +271,7 @@ pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result<Vec<Hatch
|
||||
let mut loops = Vec::new();
|
||||
for h in hs {
|
||||
if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) {
|
||||
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, sources: vec![*h] });
|
||||
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), sources: vec![*h] });
|
||||
}
|
||||
}
|
||||
if loops.is_empty() {
|
||||
|
||||
@@ -197,7 +197,7 @@ fn follow(before: &Drawing, after: &Drawing, handle: Handle, h: &Hatch, checked:
|
||||
match refill(from, after, l) {
|
||||
Refill::Loop(vertices) => {
|
||||
let sources = l.sources.iter().copied().filter(|s| exists(after, *s)).take(MAX_SOURCES).collect();
|
||||
loops.push(HatchLoop { vertices, outer: l.outer, boundary_flags: l.boundary_flags, sources });
|
||||
loops.push(HatchLoop { vertices, outer: l.outer, sources });
|
||||
}
|
||||
// An erased island: the hatch fills its area.
|
||||
Refill::Erased if !l.outer => {}
|
||||
|
||||
@@ -48,6 +48,8 @@ pub const FILES: &[&str] = &[
|
||||
"publish",
|
||||
"qsave",
|
||||
"recover",
|
||||
"refclose",
|
||||
"refedit",
|
||||
"reinit",
|
||||
"saveas",
|
||||
"script",
|
||||
@@ -260,9 +262,8 @@ pub const NO_FILES: &[&str] = &[
|
||||
"attdisp.normal",
|
||||
"attdisp.on",
|
||||
"attdisp.off",
|
||||
"refedit",
|
||||
"refedit.levels",
|
||||
"refset",
|
||||
"refclose",
|
||||
"bedit",
|
||||
"bsave",
|
||||
"bsaveas",
|
||||
@@ -514,9 +515,9 @@ mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Words in a command's parameter doc that usually name a file. In these commands they don't:
|
||||
/// `array` and `arraypath` follow a path of objects, and `blocks.reference.grips` reports a
|
||||
/// direction.
|
||||
const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"];
|
||||
/// `array` and `arraypath` follow a path of objects, `refedit.levels` reports paths of nested
|
||||
/// references, and `blocks.reference.grips` reports a direction.
|
||||
const NOT_FILES: &[&str] = &["array", "arraypath", "refedit.levels", "blocks.reference.grips"];
|
||||
|
||||
/// The words of a command's documentation, lower case.
|
||||
fn words(doc: &str) -> BTreeSet<String> {
|
||||
|
||||
@@ -170,16 +170,13 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option<EntityK
|
||||
if index == 0 {
|
||||
return Some(translated(kind, delta));
|
||||
}
|
||||
let k = i.grip_attribs().nth(index - 1).map(|(k, _)| k)?;
|
||||
let a = i.attribs.get_mut(k)?;
|
||||
let a = i.attribs.get_mut(index - 1)?;
|
||||
let ip = a.text.insert.xy() + delta;
|
||||
set_xy(&mut a.text.insert, ip);
|
||||
if let Some(al) = &mut a.text.align_pt {
|
||||
let q = al.xy() + delta;
|
||||
set_xy(al, q);
|
||||
}
|
||||
// A multiline attribute is drawn from its multiline text: it moves too.
|
||||
a.transform_multiline(&Mat3::translate(delta));
|
||||
}
|
||||
EntityKind::Dimension(d) => {
|
||||
match index {
|
||||
|
||||
@@ -92,15 +92,6 @@ impl Interactive for Guarded {
|
||||
Vec::new()
|
||||
})
|
||||
}
|
||||
fn live_value(&self, s: &Session, cursor: Vec2) -> Option<String> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
}
|
||||
catch_unwind(AssertUnwindSafe(|| self.inner.live_value(s, cursor))).unwrap_or_else(|_| {
|
||||
self.broken.set(Some("panic in preview"));
|
||||
None
|
||||
})
|
||||
}
|
||||
fn drag(&self, s: &Session, cursor: Vec2) -> Option<crate::prompt::Drag> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
|
||||
@@ -454,19 +454,6 @@ fn printing_many_lines_is_linear() {
|
||||
assert_eq!(s.log.last().map(String::as_str), Some("a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lisp_pline_keeps_current_elevation() {
|
||||
let mut s = session();
|
||||
ok(&mut s, r#"(setvar "ELEVATION" 800.0)"#);
|
||||
ok(&mut s, r#"(command "_PLINE" '(0 0) '(1000 0) '(1000 100) "")"#);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "800.0");
|
||||
|
||||
ok(&mut s, r#"(setvar "ELEVATION" -2.5)"#);
|
||||
s.execute("pline", &serde_json::json!({"vertices": [[0, 0], [10, 0]], "width": 2})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "-2.5");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 43 (entget (entlast))))"), "2.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_draws_and_one_routine_is_one_undo_step() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -126,14 +126,23 @@ pub fn snap_name(m: u32) -> &'static str {
|
||||
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
|
||||
}
|
||||
|
||||
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
|
||||
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
|
||||
/// first, then deferred snaps, then Nearest), without repeats.
|
||||
/// 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.
|
||||
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 {
|
||||
return Vec::new();
|
||||
}
|
||||
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
|
||||
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)) {
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
|
||||
|
||||
@@ -79,7 +79,7 @@ pub struct Prompt {
|
||||
/// 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, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
||||
/// cell): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub corner: bool,
|
||||
/// The grip this prompt stretches (one hot grip at the STRETCH prompt), as (object, grip
|
||||
@@ -103,10 +103,6 @@ pub struct Prompt {
|
||||
/// the routine writes, so it cannot be read for the word "Select" (#1598).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub picks_one: bool,
|
||||
/// The value asked for is an angle about the base (a rotation grip): Dynamic Input shows one
|
||||
/// angle box, with the command's live value ([`Interactive::live_value`]).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub angle: bool,
|
||||
/// The prompt takes a block's name as well as its keywords: a Greek word that is an existing
|
||||
/// block's name is that block, not a keyword read from its Latin keys.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
@@ -158,11 +154,6 @@ impl Prompt {
|
||||
self.grip = Some(g);
|
||||
self
|
||||
}
|
||||
/// An angle about the base is asked for (the `angle` field).
|
||||
pub fn angle(mut self) -> Self {
|
||||
self.angle = true;
|
||||
self
|
||||
}
|
||||
/// The visual chooser the UI can show (the `picker` field).
|
||||
pub fn picker(mut self, p: Picker) -> Self {
|
||||
self.picker = Some(p);
|
||||
@@ -335,11 +326,6 @@ pub trait Interactive: Send {
|
||||
fn preview_objects(&self, _s: &Session, _cursor: Vec2) -> Vec<cadcraft_doc::Entity> {
|
||||
Vec::new()
|
||||
}
|
||||
/// The value the cursor would give, as the prompt asks for it (an angle as the drawing
|
||||
/// shows angles): what Dynamic Input shows in its box before anything is typed.
|
||||
fn live_value(&self, _s: &Session, _cursor: Vec2) -> Option<String> {
|
||||
None
|
||||
}
|
||||
/// The preview as existing objects under one transform, when it is that (MOVE, COPY,
|
||||
/// ROTATE, SCALE). The UI then draws them from geometry uploaded once instead of rebuilding
|
||||
/// the transformed copies every frame; `None` falls back to [`Interactive::preview`].
|
||||
|
||||
@@ -139,7 +139,7 @@ pub fn bracket() -> Drawing {
|
||||
EntityKind::Hatch(Hatch {
|
||||
pattern: "ANSI31".into(),
|
||||
solid: false,
|
||||
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, boundary_flags: None, sources: Vec::new() }],
|
||||
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, sources: Vec::new() }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: false,
|
||||
|
||||
@@ -722,7 +722,7 @@ mod hatch_pattern_pick_tests {
|
||||
|
||||
fn square(lo: f64, hi: f64, outer: bool) -> HatchLoop {
|
||||
let vertices = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
|
||||
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
|
||||
HatchLoop { vertices, outer, sources: Vec::new() }
|
||||
}
|
||||
|
||||
fn ansi31_hatch(loops: Vec<HatchLoop>) -> Drawing {
|
||||
@@ -788,7 +788,6 @@ mod hatch_pattern_pick_tests {
|
||||
let tri = HatchLoop {
|
||||
vertices: [(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(),
|
||||
outer: true,
|
||||
boundary_flags: None,
|
||||
sources: Vec::new(),
|
||||
};
|
||||
let d = solid_hatch(vec![tri], 0);
|
||||
|
||||
@@ -192,7 +192,6 @@ impl Session {
|
||||
}
|
||||
|
||||
fn script_lines(&mut self, text: &str) -> Result<()> {
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
|
||||
for line in text.lines() {
|
||||
// Trailing spaces are inputs (Enter); other trailing whitespace (`\r`) is not.
|
||||
let line = line.trim_end_matches(|c: char| c.is_whitespace() && c != ' ');
|
||||
|
||||
@@ -608,12 +608,6 @@ impl Session {
|
||||
out
|
||||
}
|
||||
|
||||
/// The value the cursor would give at the active command's prompt (see
|
||||
/// [`Interactive::live_value`]).
|
||||
pub fn live_value(&self, cursor: Vec2) -> Option<String> {
|
||||
self.running.as_ref()?.machine.live_value(self, cursor)
|
||||
}
|
||||
|
||||
/// What the drawing area shows in place of the drawing while a command runs (DVIEW's preview
|
||||
/// set, see [`Interactive::display_only`]), also while a transparent command interrupts it.
|
||||
/// `None`: the drawing.
|
||||
|
||||
+64
-190
@@ -7,7 +7,7 @@ mod viewport;
|
||||
|
||||
pub use viewport::ViewportPoint;
|
||||
|
||||
use cadcraft_doc::{Drawing, EntityKind, Handle, Insert, MAX_BLOCK_DEPTH, Prim, Space};
|
||||
use cadcraft_doc::{Drawing, EntityKind, Insert, MAX_BLOCK_DEPTH, Prim, Space};
|
||||
use cadcraft_geom::{Bounds2, Circle, EPS, Ellipse, Mat3, PI, Segment, Vec2, intersect_ext};
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -72,33 +72,6 @@ impl SnapHit {
|
||||
None => crate::Input::Point(self.point),
|
||||
}
|
||||
}
|
||||
|
||||
fn plain(mode: u32, point: Vec2) -> SnapHit {
|
||||
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
|
||||
}
|
||||
|
||||
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
|
||||
/// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest.
|
||||
fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) {
|
||||
let class = if self.deferred.is_some() {
|
||||
1
|
||||
} else if self.mode == mode::NEA {
|
||||
2
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(class, snap_score(self.mode, self.point, cursor, aperture))
|
||||
}
|
||||
|
||||
/// The same snap as `o`: mode and point, from the same source (paper 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.
|
||||
fn same(&self, o: &SnapHit) -> 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, 1e-9 * (1.0 + self.point.len()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The curve a deferred snap refers to.
|
||||
@@ -238,14 +211,6 @@ pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u3
|
||||
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
|
||||
}
|
||||
|
||||
/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest
|
||||
/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest.
|
||||
/// Snaps seen through layout viewports are included.
|
||||
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn osnap_with(
|
||||
d: &Drawing,
|
||||
@@ -272,39 +237,19 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
|
||||
let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred);
|
||||
(all.into_iter().next(), prims)
|
||||
}
|
||||
|
||||
/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_all_with_neighborhood(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> (Vec<SnapHit>, Option<Vec<Prim>>) {
|
||||
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
|
||||
return (Vec::new(), None);
|
||||
return (None, None);
|
||||
}
|
||||
let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
||||
Some((hits, prims)) => (hits, Some(prims)),
|
||||
None => (Vec::new(), None),
|
||||
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
||||
Some((hit, prims)) => (hit, Some(prims)),
|
||||
None => (None, None),
|
||||
};
|
||||
let views = viewport::near(d, space, cursor, aperture);
|
||||
if views.is_empty() {
|
||||
return (all, near_prims);
|
||||
return (best, near_prims);
|
||||
}
|
||||
let model = Space::Model;
|
||||
let model_ix = crate::spatial::index(d, &model);
|
||||
// What a click picks across spaces stays as it was: each space's best snap, and a viewport's
|
||||
// replaces the best so far only when it scores closer. A paper-space Nearest can therefore
|
||||
// beat an Endpoint seen through a viewport, which `ranked` alone would put first.
|
||||
let mut pick = all.first().copied();
|
||||
for view in views {
|
||||
let model_cursor = view.to_model(cursor);
|
||||
let model_aperture = aperture / view.scale;
|
||||
@@ -312,7 +257,7 @@ fn osnap_all_with_neighborhood(
|
||||
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let hits = osnap_in(
|
||||
let hit = osnap_in(
|
||||
d,
|
||||
&model,
|
||||
&model_ix,
|
||||
@@ -323,36 +268,15 @@ fn osnap_all_with_neighborhood(
|
||||
deferred,
|
||||
&view.viewport.frozen_layers,
|
||||
Some(view.model_clip),
|
||||
);
|
||||
if let Some(hit) = hits.first().and_then(|h| view.hit(*h))
|
||||
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
|
||||
)
|
||||
.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))
|
||||
{
|
||||
pick = Some(hit);
|
||||
}
|
||||
all.extend(hits.into_iter().filter_map(|h| view.hit(h)));
|
||||
}
|
||||
let mut out = ranked(all, cursor, aperture);
|
||||
if let Some(pick) = pick {
|
||||
out.retain(|h| !h.same(&pick));
|
||||
out.insert(0, pick);
|
||||
}
|
||||
(out, near_prims)
|
||||
}
|
||||
|
||||
/// `hits` best first ([`SnapHit::rank`]), without repeats.
|
||||
fn ranked(mut hits: Vec<SnapHit>, cursor: Vec2, aperture: f64) -> Vec<SnapHit> {
|
||||
hits.sort_by(|a, b| {
|
||||
let (ca, sa) = a.rank(cursor, aperture);
|
||||
let (cb, sb) = b.rank(cursor, aperture);
|
||||
ca.cmp(&cb).then(sa.total_cmp(&sb))
|
||||
});
|
||||
let mut out: Vec<SnapHit> = Vec::with_capacity(hits.len());
|
||||
for h in hits {
|
||||
if !out.iter().any(|o| o.same(&h)) {
|
||||
out.push(h);
|
||||
best = Some(hit);
|
||||
}
|
||||
}
|
||||
out
|
||||
(best, near_prims)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -367,11 +291,10 @@ fn osnap_in(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Vec<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
|
||||
) -> Option<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit)
|
||||
}
|
||||
|
||||
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_in_with_prims(
|
||||
d: &Drawing,
|
||||
@@ -384,8 +307,8 @@ fn osnap_in_with_prims(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
|
||||
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
|
||||
) -> Option<(Option<SnapHit>, 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
|
||||
// that don't reach each other).
|
||||
@@ -422,8 +345,8 @@ fn osnap_in_with_prims(
|
||||
}
|
||||
}
|
||||
}
|
||||
let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hits, near_prims))
|
||||
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hit, near_prims))
|
||||
}
|
||||
|
||||
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
|
||||
@@ -475,50 +398,9 @@ pub(crate) fn gather(
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
|
||||
gather_in(d, space, ix, cursor, aperture, osmode, &[], None)
|
||||
gather_in(d, space, ix, cursor, aperture, osmode, &[])
|
||||
}
|
||||
|
||||
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
|
||||
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
|
||||
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
|
||||
/// block reference with.
|
||||
pub(crate) fn nearest_with_direction(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, skip: Handle) -> Option<(Vec2, Vec2)> {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let (_, prims) = gather_in(d, space, &ix, cursor, aperture, 0, &[], Some(skip))?;
|
||||
let mut best: Option<(f64, Vec2, Vec2)> = None;
|
||||
let mut consider = |at: Vec2, dir: Vec2| {
|
||||
let dd = at.dist(cursor);
|
||||
if at.is_finite() && dir.len() > 1e-12 && dir.is_finite() && dd <= aperture && best.is_none_or(|(bd, _, _)| dd < bd) {
|
||||
best = Some((dd, at, dir * (1.0 / dir.len())));
|
||||
}
|
||||
};
|
||||
for p in prims.iter().take(2000) {
|
||||
if let Prim::Circle(c) = p {
|
||||
let at = c.closest(cursor);
|
||||
consider(at, (at - c.center).perp());
|
||||
continue;
|
||||
}
|
||||
if let Prim::Infinite { base, dir, .. } = p {
|
||||
let len = dir.len();
|
||||
if len > 1e-12 {
|
||||
let u = *dir * (1.0 / len);
|
||||
consider(*base + u * (cursor - *base).dot(u), u);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for seg in prim_segments(p) {
|
||||
let seg = fix_circle(&seg);
|
||||
let at = seg.closest(cursor);
|
||||
match seg {
|
||||
Segment::Line(l) => consider(at, l.b - l.a),
|
||||
Segment::Arc { arc, .. } => consider(at, (at - arc.center).perp()),
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(_, at, dir)| (at, dir))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn gather_in(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
@@ -527,7 +409,6 @@ fn gather_in(
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
frozen: &[String],
|
||||
skip: Option<Handle>,
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
|
||||
let probe = Bounds2::new(cursor, cursor).expand(aperture);
|
||||
let mut cands: Vec<(u32, Vec2)> = Vec::new();
|
||||
@@ -535,7 +416,7 @@ fn gather_in(
|
||||
let mut count = 0usize;
|
||||
let mut budget = MAX_BLOCK_LEAVES;
|
||||
for (e, known) in crate::select::candidates(d, space, ix, &probe.expand(aperture), true, false)? {
|
||||
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) || Some(e.handle) == skip {
|
||||
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) {
|
||||
continue;
|
||||
}
|
||||
let inf = crate::select::is_infinite(e);
|
||||
@@ -577,8 +458,7 @@ fn gather_in(
|
||||
Some((cands, near_prims))
|
||||
}
|
||||
|
||||
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
|
||||
/// snaps, the deferred snaps and Nearest.
|
||||
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish(
|
||||
mut cands: Vec<(u32, Vec2)>,
|
||||
@@ -589,7 +469,7 @@ fn finish(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
clip: Option<Bounds2>,
|
||||
) -> Vec<SnapHit> {
|
||||
) -> Option<SnapHit> {
|
||||
// Perpendicular / tangent from the base point.
|
||||
if let Some(bp) = base {
|
||||
for p in near_prims {
|
||||
@@ -627,10 +507,20 @@ fn finish(
|
||||
}
|
||||
}
|
||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||
let mut hits: Vec<SnapHit> =
|
||||
cands.into_iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).map(|(m, p)| SnapHit::plain(m, p)).collect();
|
||||
if base.is_none() && deferred {
|
||||
hits.extend(deferred_hits(near_prims, cursor, aperture, osmode, clip));
|
||||
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 });
|
||||
}
|
||||
if base.is_none()
|
||||
&& deferred
|
||||
&& let Some(h) = deferred_hit(near_prims, cursor, aperture, osmode, clip)
|
||||
{
|
||||
return Some(h);
|
||||
}
|
||||
if osmode & mode::NEA != 0 {
|
||||
// The closest point of all nearby objects, whatever their drawing order.
|
||||
@@ -650,13 +540,12 @@ fn finish(
|
||||
}
|
||||
}
|
||||
if let Some((_, p)) = nb {
|
||||
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
|
||||
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
|
||||
}
|
||||
}
|
||||
ranked(hits, cursor, aperture)
|
||||
None
|
||||
}
|
||||
|
||||
/// Prefer more specific modes when nearly equidistant.
|
||||
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 }
|
||||
}
|
||||
@@ -959,11 +848,9 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
|
||||
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
|
||||
/// perpendicular on the same circle.
|
||||
fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
|
||||
let mut hits = Vec::new();
|
||||
/// 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;
|
||||
for p in prims {
|
||||
let curve = match p {
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||
@@ -972,28 +859,32 @@ fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip:
|
||||
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) }
|
||||
let (m, name, at) = match curve {
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
|
||||
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
|
||||
let l = cadcraft_geom::Line::new(a, b);
|
||||
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
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 }) });
|
||||
let dd = at.dist(cursor);
|
||||
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
|
||||
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) }));
|
||||
}
|
||||
}
|
||||
hits
|
||||
best.map(|(_, h)| h)
|
||||
}
|
||||
|
||||
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
|
||||
@@ -1230,23 +1121,6 @@ mod tests {
|
||||
assert_eq!(h.name, "Intersection");
|
||||
}
|
||||
|
||||
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection
|
||||
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap`
|
||||
/// picks.
|
||||
#[test]
|
||||
fn osnap_all_ranks_every_candidate() {
|
||||
let d = drawing();
|
||||
let modes = mode::END | mode::MID | mode::INT | mode::NEA;
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false);
|
||||
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}");
|
||||
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point);
|
||||
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot.
|
||||
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, modes, None, false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn center_quadrant_tangent() {
|
||||
let d = drawing();
|
||||
|
||||
@@ -311,6 +311,7 @@ mod tests {
|
||||
explodable: true,
|
||||
units: 0,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
};
|
||||
blk.entities
|
||||
.push(Entity::new(cadcraft_doc::Handle(1_000_000), EntityKind::Circle(cadcraft_doc::Circle { center: v3(0.0, 0.0), radius: 1.0 })));
|
||||
|
||||
@@ -81,6 +81,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
|
||||
("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
|
||||
// XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted.
|
||||
("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)),
|
||||
// How much objects outside the working set fade while a reference is edited in place (REFEDIT).
|
||||
("XFADECTL", Kind::Int(0, 90), Def::Int(50)),
|
||||
];
|
||||
|
||||
/// The standard lineweights in hundredths of a millimetre.
|
||||
|
||||
@@ -746,15 +746,6 @@ fn script_runs_commands() {
|
||||
assert!(matches!(&t.kind, EntityKind::Text(t) if t.value == "Hello world"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripts_allow_one_leading_utf8_bom() {
|
||||
for text in ["\u{feff}LINE 0,0 10,10\n\n", "\u{feff}; first comment\r\nLINE 0,0 10,10\r\n\r\n"] {
|
||||
let mut s = Session::new();
|
||||
s.script(text).unwrap();
|
||||
assert_eq!(kinds(&s), vec!["Line"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_splits_line_at_keyword_prompt() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, MText, MultilineAttrib, Text};
|
||||
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, Text};
|
||||
use cadcraft_engine::geom::Vec3;
|
||||
use serde_json::json;
|
||||
|
||||
@@ -45,66 +45,3 @@ fn references_take_lock_position_from_the_definition() {
|
||||
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
|
||||
assert_eq!(i.attribs[0].modes, AttribModes { verify: false, preset: false, lock_position: true });
|
||||
}
|
||||
|
||||
/// A definition at `x` with `modes`, invisible or not, multiline or not.
|
||||
fn definition(tag: &str, x: f64, modes: AttribModes, invisible: bool, multiline: bool) -> Attrib {
|
||||
let text = Text {
|
||||
insert: Vec3::new(x, 0.0, 0.0),
|
||||
align_pt: None,
|
||||
height: 2.0,
|
||||
value: tag.into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: Default::default(),
|
||||
valign: Default::default(),
|
||||
};
|
||||
let multiline = multiline.then(|| {
|
||||
let mtext = MText {
|
||||
insert: Vec3::new(x, 0.0, 0.0),
|
||||
height: 2.0,
|
||||
width: 0.0,
|
||||
attach: 7,
|
||||
rotation: 0.0,
|
||||
style: "Standard".into(),
|
||||
contents: format!("{tag}\\PTWO"),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
};
|
||||
MultilineAttrib { mtext, read_as: format!("{tag}\nTWO") }
|
||||
});
|
||||
Attrib { tag: tag.into(), text, invisible, constant: false, prompt: tag.into(), props: Default::default(), multiline, modes }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_shown_unlocked_attributes_have_grips_and_a_multiline_one_moves_its_text() {
|
||||
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
|
||||
let locked = AttribModes { lock_position: true, ..AttribModes::default() };
|
||||
let mut b = Block::new("TAG");
|
||||
for a in [
|
||||
definition("FREE", 0.0, AttribModes::default(), false, false),
|
||||
definition("LOCKED", 10.0, locked, false, false),
|
||||
definition("HIDDEN", 20.0, AttribModes::default(), true, false),
|
||||
definition("NOTE", 30.0, AttribModes::default(), false, true),
|
||||
] {
|
||||
let h = d.new_handle();
|
||||
b.entities.push(Entity::new(h, EntityKind::AttDef(a)));
|
||||
}
|
||||
d.blocks.insert("TAG".into(), Arc::new(b));
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "tags", None);
|
||||
let r = s.execute("insert", &json!({ "name": "TAG", "at": [100, 0] })).unwrap();
|
||||
let h = cadcraft_engine::doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
// The insertion point, FREE and NOTE: no grip for the locked or the invisible attribute.
|
||||
let g = s.grips_of(h).unwrap();
|
||||
assert_eq!(g.iter().map(|p| p.x).collect::<Vec<_>>(), [100.0, 100.0, 130.0]);
|
||||
// NOTE's grip (index 2) dragged up 5: its multiline text moves with it.
|
||||
s.execute("grip.stretch", &json!({ "handle": h.hex(), "index": 2, "to": [130, 5] })).unwrap();
|
||||
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
|
||||
let note = i.attribs.iter().find(|a| a.tag == "NOTE").unwrap();
|
||||
assert_eq!((note.text.insert.y, note.multiline.as_ref().unwrap().mtext.insert.y), (5.0, 5.0));
|
||||
let free = i.attribs.iter().find(|a| a.tag == "FREE").unwrap();
|
||||
assert_eq!(free.text.insert.y, 0.0, "the others stay");
|
||||
}
|
||||
|
||||
@@ -145,56 +145,3 @@ fn a_grip_drag_previews_the_reference_in_its_own_colours() {
|
||||
let blue = cadcraft_engine::doc::color::Color::True(cadcraft_engine::doc::color::Rgb(0x2f, 0x6b, 0xff));
|
||||
assert!(preview[n..].iter().all(|e| e.common.color == blue));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grip_with_a_value_list_marks_its_stops_while_dragged() {
|
||||
let (mut s, h) = session();
|
||||
// Width is a list (30, 32, 36) from (0, -4): its end can stop 30, 32 or 36 along it.
|
||||
let stops = cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 2, GripPart::End);
|
||||
let at: Vec<(f64, f64)> = stops.iter().map(|(p, _)| (p.x, p.y)).collect();
|
||||
assert_eq!(at, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
|
||||
assert!(stops.iter().all(|(_, way)| (way.x - 1.0).abs() < 1e-12 && way.y.abs() < 1e-12));
|
||||
// A grip that isn't on a list or increments has none; nor a list grip.
|
||||
assert!(cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 1, GripPart::At).is_empty());
|
||||
|
||||
// The preview marks each stop with a tick across the travel, a few pixels long.
|
||||
s.start_dyn_grip(h, 2, GripPart::End).unwrap();
|
||||
let half = 6.0 * s.pixel_size();
|
||||
let ticks: Vec<(f64, f64)> = s
|
||||
.preview(Vec2::new(133.0, 0.0))
|
||||
.into_iter()
|
||||
.filter_map(|e| match e.kind {
|
||||
cadcraft_engine::doc::EntityKind::Line(l) if (l.a.x - l.b.x).abs() < 1e-9 && ((l.b.y - l.a.y).abs() - 2.0 * half).abs() < 1e-9 => {
|
||||
Some((l.a.x, (l.a.y + l.b.y) / 2.0))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(ticks, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
|
||||
}
|
||||
|
||||
/// An alignment grip dragged onto a line (the synthetic Align block of the io tests, a line at
|
||||
/// 30° from (120, 100)): the reference moves onto the line and turns along it, as AutoCAD does;
|
||||
/// away from objects it only moves.
|
||||
#[test]
|
||||
fn an_alignment_grip_aligns_with_the_line_at_the_cursor() {
|
||||
let src = include_str!("../../../io/tests/data/dynblock_params.txt").replace("\r\n", "\n");
|
||||
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "params", None);
|
||||
let r = s.execute("insert", &json!({ "name": "Align", "at": [100, 100] })).unwrap();
|
||||
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let g = s.execute("blocks.reference.grips", &json!({ "handle": h.hex() })).unwrap();
|
||||
assert_eq!(g[0]["shape"], "alignment");
|
||||
// A point on the line, a little below it.
|
||||
let (c, sn) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
|
||||
let to = [120.0 + 10.0 * c + 0.01 * sn, 100.0 + 10.0 * sn - 0.01 * c];
|
||||
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": to })).unwrap();
|
||||
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
|
||||
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6, "{}", i.rotation.to_degrees());
|
||||
assert!((i.insert.x - (120.0 + 10.0 * c)).abs() < 1e-6 && (i.insert.y - (100.0 + 10.0 * sn)).abs() < 1e-6, "{:?}", i.insert);
|
||||
// Far from anything: it only moves.
|
||||
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": [0, -50] })).unwrap();
|
||||
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
|
||||
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6 && i.insert.x.abs() < 1e-9 && (i.insert.y + 50.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
@@ -144,26 +144,6 @@ fn moving_or_copying_the_hatch_alone_ends_the_link() {
|
||||
assert!(!hatch(&s, &h).associative);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_boundary_flags_survive_refill_and_copy() {
|
||||
let mut session = Session::new();
|
||||
let boundary = handle(&session.execute("rectang", &json!({ "p1": [0, 0], "p2": [4, 2] })).unwrap());
|
||||
let hatch_handle = handle(&session.execute("hatch", &json!({ "handles": [boundary.clone()] })).unwrap());
|
||||
session.doc_mut().unwrap().model.modify(Handle::parse_hex(&hatch_handle).unwrap(), |entity| {
|
||||
if let EntityKind::Hatch(hatch) = &mut entity.kind {
|
||||
hatch.loops[0].boundary_flags = Some(7);
|
||||
}
|
||||
});
|
||||
let expected = hatch(&session, &hatch_handle).loops[0].boundary_flags;
|
||||
session.execute("move", &json!({ "handles": [boundary], "delta": [10, 0] })).unwrap();
|
||||
assert_eq!(hatch(&session, &hatch_handle).loops[0].boundary_flags, expected);
|
||||
let count = session.doc().unwrap().model.len();
|
||||
session.execute("copy", &json!({ "handles": [hatch_handle], "delta": [30, 0] })).unwrap();
|
||||
let copy = session.doc().unwrap().model.iter().skip(count).find(|entity| matches!(entity.kind, EntityKind::Hatch(_))).unwrap();
|
||||
let EntityKind::Hatch(copied) = ©.kind else { panic!("not a hatch") };
|
||||
assert_eq!(copied.loops[0].boundary_flags, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_associative_hatch_keeps_no_sources() {
|
||||
let mut s = Session::new();
|
||||
@@ -186,10 +166,7 @@ fn hostile_sources_never_panic() {
|
||||
let k = EntityKind::Hatch(Hatch {
|
||||
pattern: "ANSI31".into(),
|
||||
solid: false,
|
||||
loops: vec![
|
||||
HatchLoop { vertices: sq, outer: true, boundary_flags: None, sources: sources.clone() },
|
||||
HatchLoop { vertices: nan, outer: false, boundary_flags: None, sources },
|
||||
],
|
||||
loops: vec![HatchLoop { vertices: sq, outer: true, sources: sources.clone() }, HatchLoop { vertices: nan, outer: false, sources }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: true,
|
||||
|
||||
@@ -106,7 +106,6 @@ mod mocoro;
|
||||
mod modify_curves;
|
||||
mod mtext_columns;
|
||||
mod mtext_options;
|
||||
mod mtext_ortho;
|
||||
mod multiline_attributes;
|
||||
mod named_viewports;
|
||||
mod named_views;
|
||||
@@ -144,10 +143,10 @@ mod recent_commands;
|
||||
mod rectang_ortho;
|
||||
mod rectang_polygon_order;
|
||||
mod refedit;
|
||||
mod refedit_xref;
|
||||
mod region;
|
||||
mod rename_cmdline;
|
||||
mod rotate_reference;
|
||||
mod rotation_grip_input;
|
||||
mod scale_offset_z;
|
||||
mod select_keywords;
|
||||
mod select_similar;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -278,46 +278,6 @@ 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 keeps the snap it had before Tab cycling: a viewport's best snap
|
||||
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
|
||||
#[test]
|
||||
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
|
||||
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_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
|
||||
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
|
||||
let all = osnap_all(&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::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
|
||||
"Tab reaches the viewport's endpoint: {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();
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
//! MTEXT's opposite corner ignores ortho: the text box keeps its width and proportion (#3388).
|
||||
|
||||
use cadcraft_doc::{EntityKind, MText};
|
||||
use cadcraft_engine::snap::tracking::CursorQuery;
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use cadcraft_geom::{Bounds2, Vec2};
|
||||
use serde_json::json;
|
||||
|
||||
/// Move the cursor to `raw` at the current prompt, as the canvas does.
|
||||
fn hover(s: &mut Session, raw: Vec2) -> Vec2 {
|
||||
let p = s.current_prompt().unwrap();
|
||||
let q = CursorQuery { base: p.base, deferred: p.deferred, corner: p.corner, aperture: 1e-6, tol: 1e-6, now: 0.0, shift: false };
|
||||
let c = s.snap_cursor(raw, &q).point;
|
||||
s.cursor = c;
|
||||
c
|
||||
}
|
||||
|
||||
fn session(ortho: bool) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("setvar", &json!({ "name": "OSMODE", "value": 0 })).unwrap();
|
||||
s.execute("setvar", &json!({ "name": "ORTHOMODE", "value": i32::from(ortho) })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn last_mtext(s: &Session) -> MText {
|
||||
match s.doc().unwrap().model.last().map(|e| e.kind.clone()) {
|
||||
Some(EntityKind::MText(t)) => t,
|
||||
k => panic!("no mtext: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Place an MTEXT from `first` to a cursor click at `second`, returning the preview bounds,
|
||||
/// in-place editor box `(insert, width)` and created entity `(insert, width)`.
|
||||
fn click_mtext(ortho: bool, first: Vec2, second: Vec2) -> ((Vec2, Vec2), (Vec2, f64), (Vec2, f64)) {
|
||||
let mut s = session(ortho);
|
||||
s.cmdline(&format!("mtext {},{}", first.x, first.y)).unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert_eq!(p.message, "Specify opposite corner");
|
||||
assert!(p.corner, "MTEXT opposite corner ignores ortho");
|
||||
let c = hover(&mut s, second);
|
||||
assert!(c.near(second, 1e-9), "opposite corner stays under the cursor: {c:?}");
|
||||
let mut pv = Bounds2::EMPTY;
|
||||
for e in s.preview(c) {
|
||||
pv = pv.union(&cadcraft_doc::entity_bounds(s.doc().unwrap(), &e, 0));
|
||||
}
|
||||
s.input(Input::Point(c)).unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
s.input(Input::Text("Hello".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.current_prompt().is_none(), "MTEXT is done, still at {:?}", s.current_prompt().map(|p| p.message));
|
||||
let t = last_mtext(&s);
|
||||
assert_eq!(t.contents, "Hello");
|
||||
((pv.min, pv.max), (ed.insert.xy(), ed.width), (t.insert.xy(), t.width))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_opposite_corner_ignores_ortho() {
|
||||
let cases = [
|
||||
// Wide box (dx > dy)
|
||||
(Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::new(0.0, 3.0), 10.0),
|
||||
// Tall box (dy > dx)
|
||||
(Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::new(0.0, 10.0), 3.0),
|
||||
// Opposite quadrant (negative dx and dy)
|
||||
(Vec2::new(10.0, 10.0), Vec2::new(2.0, 4.0), Vec2::new(2.0, 4.0), Vec2::new(10.0, 10.0), Vec2::new(2.0, 10.0), 8.0),
|
||||
];
|
||||
for (first, second, min, max, insert, width) in cases {
|
||||
let on = click_mtext(true, first, second);
|
||||
assert!(on.0.0.near(min, 1e-9) && on.0.1.near(max, 1e-9), "preview bounds with ortho on: {:?}", on.0);
|
||||
assert!(on.1.0.near(insert, 1e-9) && (on.1.1 - width).abs() < 1e-9, "editor box with ortho on: {:?}", on.1);
|
||||
assert!(on.2.0.near(insert, 1e-9) && (on.2.1 - width).abs() < 1e-9, "entity box with ortho on: {:?}", on.2);
|
||||
let off = click_mtext(false, first, second);
|
||||
assert_eq!(off, on, "ortho changes nothing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_coordinate_and_direct_distance_input_with_ortho() {
|
||||
let mut s = session(true);
|
||||
// Absolute coordinate input for the opposite corner.
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
s.cmdline("10,3").unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
assert!(ed.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
|
||||
assert!((ed.width - 10.0).abs() < 1e-9);
|
||||
s.input(Input::Text("Abs".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let t = last_mtext(&s);
|
||||
assert!(t.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
|
||||
assert!((t.width - 10.0).abs() < 1e-9);
|
||||
|
||||
// Relative coordinate input for the opposite corner.
|
||||
s.cmdline("mtext 2,3").unwrap();
|
||||
s.cmdline("@4,9").unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
assert!(ed.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
|
||||
assert!((ed.width - 4.0).abs() < 1e-9);
|
||||
s.input(Input::Text("Rel".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let t = last_mtext(&s);
|
||||
assert!(t.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
|
||||
assert!((t.width - 4.0).abs() < 1e-9);
|
||||
|
||||
// Direct distance entry goes toward the cursor rather than along an axis.
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
let c = hover(&mut s, Vec2::new(3.0, 4.0));
|
||||
assert!(c.near(Vec2::new(3.0, 4.0), 1e-9));
|
||||
s.cmdline("5").unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
assert!(ed.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
|
||||
assert!((ed.width - 3.0).abs() < 1e-9);
|
||||
s.input(Input::Text("Dir".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let t = last_mtext(&s);
|
||||
assert!(t.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
|
||||
assert!((t.width - 3.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_escape_cancels_cleanly_with_ortho() {
|
||||
let mut s = session(true);
|
||||
// Cancel at the opposite-corner prompt.
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
let c = hover(&mut s, Vec2::new(10.0, 3.0));
|
||||
assert!(c.near(Vec2::new(10.0, 3.0), 1e-9));
|
||||
s.cancel();
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert!(s.editing_mtext().is_none());
|
||||
assert!(s.doc().unwrap().model.is_empty());
|
||||
|
||||
// Cancel after picking the opposite corner (at the text prompt).
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
let c = hover(&mut s, Vec2::new(10.0, 3.0));
|
||||
s.input(Input::Point(c)).unwrap();
|
||||
assert!(s.editing_mtext().is_some());
|
||||
s.cancel();
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert!(s.editing_mtext().is_none());
|
||||
assert!(s.doc().unwrap().model.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_and_pline_still_obey_ortho() {
|
||||
let mut s = session(true);
|
||||
s.cmdline("line 0,0").unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert!(!p.corner, "LINE next point is constrained by ortho");
|
||||
let c = hover(&mut s, Vec2::new(10.0, 3.0));
|
||||
assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps LINE horizontal: {c:?}");
|
||||
s.cancel();
|
||||
|
||||
s.cmdline("pline 0,0").unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert!(!p.corner, "PLINE next point is constrained by ortho");
|
||||
let c = hover(&mut s, Vec2::new(3.0, 10.0));
|
||||
assert!(c.near(Vec2::new(0.0, 10.0), 1e-9), "ortho keeps PLINE vertical: {c:?}");
|
||||
s.cancel();
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
//! OFFSET Erase/Layer/Multiple/Undo and the MOVE/COPY Displacement option at the command line.
|
||||
|
||||
use cadcraft_engine::Input;
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use serde_json::json;
|
||||
|
||||
/// Every line as ((ax, ay), (bx, by), layer), sorted by the first y.
|
||||
@@ -64,27 +62,6 @@ fn offset_multiple_and_undo() {
|
||||
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.0), (10.0, 2.0), "0"), l((0.0, 4.0), (10.0, 4.0), "0")]);
|
||||
}
|
||||
|
||||
// Regression test for #618: OFFSET's distance prompt took only a typed number; clicking two points
|
||||
// (the distance between them) was rejected, and the second click had no distance guide.
|
||||
#[test]
|
||||
fn offset_distance_from_two_clicked_points() {
|
||||
let mut s = one_line();
|
||||
s.start("offset").unwrap();
|
||||
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert!(p.message.contains("second point"), "{}", s.prompt_text());
|
||||
assert!(p.base.is_some_and(|b| b.near(Vec2::new(20.0, 20.0), 1e-9)), "the second click is measured from the first");
|
||||
// The guide from the first click to the cursor is the previewed distance.
|
||||
let guide = s.preview(Vec2::new(20.0, 22.5));
|
||||
assert!(matches!(guide.first().map(|e| &e.kind), Some(EntityKind::Line(g)) if g.a.xy().near(Vec2::new(20.0, 20.0), 1e-9)), "{guide:?}");
|
||||
s.input(Input::Point(Vec2::new(20.0, 22.5))).unwrap();
|
||||
assert!(s.current_prompt().unwrap().message.contains("Select object"), "{}", s.prompt_text());
|
||||
assert_eq!(s.doc().unwrap().header.f64("OFFSETDIST", -1.0), 2.5);
|
||||
s.script("5,0 5,1\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.5), (10.0, 2.5), "0")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_json_erase_and_layer() {
|
||||
let mut s = one_line();
|
||||
|
||||
@@ -104,6 +104,7 @@ fn a_dimension_drawn_from_its_block_is_picked_on_the_block_text() {
|
||||
explodable: true,
|
||||
units: 0,
|
||||
array: None,
|
||||
xref_stamp: None,
|
||||
};
|
||||
d.blocks.insert("*D1".into(), std::sync::Arc::new(block));
|
||||
d.model.modify(dim, |e| {
|
||||
|
||||
@@ -279,7 +279,7 @@ fn interactive_refedit_refset_and_refclose() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xrefs_are_refused_with_a_message() {
|
||||
fn an_xref_that_is_not_loaded_is_refused_with_a_message() {
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().blocks.insert(
|
||||
"X".into(),
|
||||
@@ -291,5 +291,6 @@ fn xrefs_are_refused_with_a_message() {
|
||||
);
|
||||
let x = insert(&mut s, "X", (0.0, 0.0), 1.0, 0.0);
|
||||
let e = s.execute("refedit", &json!({ "handle": x })).unwrap_err();
|
||||
assert!(e.to_string().contains("external reference"), "{e}");
|
||||
// Xrefs are edited in place and written back (refedit_xref.rs); one not loaded can't be.
|
||||
assert!(e.to_string().contains("not loaded"), "{e}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,794 @@
|
||||
//! REFEDIT on xrefs and nested references (gap F2): the source drawing written back on REFCLOSE
|
||||
//! Save (with a backup; refused for read-only, locked or changed files) and nesting levels.
|
||||
//! Files go in a folder under Cargo's temporary directory for integration tests.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_engine::cmd::file::{IoHooks, Version, set_io, set_write_as};
|
||||
use cadcraft_engine::doc::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, Insert, Layer, Line, XrefStatus};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn hooks() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
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())
|
||||
});
|
||||
}
|
||||
|
||||
/// A fresh folder for one test, removed when the test ends however it ends (a skip, a failed
|
||||
/// assertion).
|
||||
struct Folder(PathBuf);
|
||||
|
||||
impl std::ops::Deref for Folder {
|
||||
type Target = Path;
|
||||
fn deref(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Folder {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn folder(tag: &str) -> Folder {
|
||||
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("refedit-xref").join(format!("{}-{tag}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Folder(dir)
|
||||
}
|
||||
|
||||
fn save(d: &Drawing, path: &Path) {
|
||||
std::fs::write(path, cadcraft_io::write(d, path).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Drawing {
|
||||
cadcraft_io::read(&std::fs::read(path).unwrap(), path).unwrap()
|
||||
}
|
||||
|
||||
fn line(d: &mut Drawing, layer: &str, a: (f64, f64), b: (f64, f64)) -> Handle {
|
||||
let h = d.new_handle();
|
||||
let mut e = Entity::new(h, EntityKind::Line(Line { a: Vec3::new(a.0, a.1, 0.0), b: Vec3::new(b.0, b.1, 0.0) }));
|
||||
e.common.layer = layer.into();
|
||||
d.model.push(e);
|
||||
h
|
||||
}
|
||||
|
||||
fn insert(block: &str, at: Vec3) -> Insert {
|
||||
Insert {
|
||||
block: block.into(),
|
||||
insert: at,
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A site plan: a line on layer Walls and a reference to its block Tree (a circle).
|
||||
fn site() -> (Drawing, Handle) {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.layers.push(Layer { name: "Walls".into(), ..Layer::default() });
|
||||
let wall = line(&mut d, "Walls", (0.0, 0.0), (10.0, 0.0));
|
||||
let mut tree = Block::new("Tree");
|
||||
let c = d.new_handle();
|
||||
tree.entities.push(Entity::new(c, EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 1.0 })));
|
||||
d.blocks.insert("Tree".into(), Arc::new(tree));
|
||||
let h = d.new_handle();
|
||||
d.model.push(Entity::new(h, EntityKind::Insert(insert("Tree", Vec3::new(5.0, 0.0, 0.0)))));
|
||||
(d, wall)
|
||||
}
|
||||
|
||||
/// A host drawing (saved as host.dxf) with site.dxf attached at (100, 0).
|
||||
fn attached(tag: &str) -> (Session, Folder, Handle, String) {
|
||||
hooks();
|
||||
let dir = folder(tag);
|
||||
let (d, wall) = site();
|
||||
save(&d, &dir.join("site.dxf"));
|
||||
let host = dir.join("host.dxf");
|
||||
save(&Drawing::new_metric(), &host);
|
||||
let mut s = Session::new();
|
||||
s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap();
|
||||
let r = s.execute("xattach", &json!({ "path": "site.dxf", "at": [100, 0] })).unwrap();
|
||||
let insert = r["handle"].as_str().unwrap().to_string();
|
||||
(s, dir, wall, insert)
|
||||
}
|
||||
|
||||
fn hx(v: Value) -> String {
|
||||
v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn working(r: &Value) -> Vec<String> {
|
||||
r["working"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
fn find_line(s: &Session, hs: &[String]) -> String {
|
||||
let d = s.doc().unwrap();
|
||||
hs.iter().find(|h| matches!(d.entity(Handle::parse_hex(h).unwrap()).unwrap().kind, EntityKind::Line(_))).unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_an_xref_writes_its_drawing_back_with_a_backup() {
|
||||
let (mut s, dir, wall, insert) = attached("save");
|
||||
let file = dir.join("site.dxf");
|
||||
// A layer of the host only, current for what is drawn during the edit.
|
||||
s.execute("layer.new", &json!({ "name": "Added", "current": true })).unwrap();
|
||||
let r = s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
assert_eq!(r["xref"]["name"], "site");
|
||||
let work = working(&r);
|
||||
assert_eq!(work.len(), 2);
|
||||
// Everything but the working set is locked while editing, and drawn faded.
|
||||
let l = find_line(&s, &work);
|
||||
s.execute("move", &json!({ "handles": [l], "delta": [0, 5] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap();
|
||||
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
assert_eq!(out["objects"], 3);
|
||||
assert!(out.get("notSaved").is_none() && !s.log.iter().any(|m| m.contains("Not saved")), "the file keeps everything: no warning");
|
||||
assert!(out["file"].as_str().unwrap().ends_with("site.dxf"));
|
||||
let bak = dir.join("site.dxf.bak");
|
||||
assert!(out["backup"].as_str().unwrap().ends_with("site.dxf.bak"), "{out}");
|
||||
assert_eq!(read(&bak).model.len(), 2, "the previous file is kept");
|
||||
// The file holds the edit, in its own coordinates, with the line's own handle.
|
||||
let back = read(&file);
|
||||
assert_eq!(back.model.len(), 3);
|
||||
let moved = back.entity(wall).expect("the edited line keeps its handle");
|
||||
let EntityKind::Line(ln) = &moved.kind else { panic!() };
|
||||
assert!((ln.a.y - 5.0).abs() < 1e-9 && (ln.a.x).abs() < 1e-9, "{ln:?}");
|
||||
assert_eq!(moved.common.layer, "Walls", "the xref's layer loses its prefix");
|
||||
let new_line = back.model.iter().find(|e| matches!(&e.kind, EntityKind::Line(l) if (l.a.y - 20.0).abs() < 1e-9)).unwrap();
|
||||
assert_eq!(new_line.common.layer, "Added");
|
||||
assert!(back.layer("Added").is_some(), "a host layer the new line uses comes along");
|
||||
// The host shows the xref as written (loaded again), and nothing of the edit is left.
|
||||
let d = s.doc().unwrap();
|
||||
assert!(d.refedit.is_none());
|
||||
assert_eq!(d.block("site").unwrap().entities.len(), 3);
|
||||
assert_eq!(d.block("site").unwrap().xref_status, XrefStatus::Loaded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_of_the_xref_is_written_into_that_block() {
|
||||
let (mut s, dir, _, insert) = attached("nested");
|
||||
let levels = s.execute("refedit.levels", &json!({ "handle": insert })).unwrap();
|
||||
let names: Vec<&str> = levels["levels"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["site", "site|Tree"]);
|
||||
let r = s.execute("refedit", &json!({ "handle": insert, "nested": "site|Tree" })).unwrap();
|
||||
assert_eq!(r["block"], "site|Tree");
|
||||
assert_eq!(r["path"].as_array().unwrap().len(), 1);
|
||||
assert!(r["faded"].as_u64().unwrap() >= 1, "the site's other objects stand faded around it");
|
||||
let c = working(&r)[0].clone();
|
||||
// The circle shows at the tree's place in the drawing: (100 + 5, 0).
|
||||
let EntityKind::Circle(circle) = &s.doc().unwrap().entity(Handle::parse_hex(&c).unwrap()).unwrap().kind else { panic!() };
|
||||
assert!((circle.center.x - 105.0).abs() < 1e-9);
|
||||
s.execute("scale", &json!({ "handles": [c], "base": [105, 0], "factor": 2 })).unwrap();
|
||||
s.execute("refclose", &json!({})).unwrap();
|
||||
let back = read(&dir.join("site.dxf"));
|
||||
let EntityKind::Circle(c) = &back.block("Tree").unwrap().entities.iter().next().unwrap().kind else { panic!() };
|
||||
assert!((c.radius - 2.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_read_only_or_changed_files_are_not_overwritten() {
|
||||
// A lock file of another program: refused at the start.
|
||||
let (mut s, dir, _, insert) = attached("locked");
|
||||
let file = dir.join("site.dxf");
|
||||
std::fs::write(dir.join("site.dwl"), b"lock").unwrap();
|
||||
let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string();
|
||||
assert!(e.contains("open in another program"), "{e}");
|
||||
std::fs::remove_file(dir.join("site.dwl")).unwrap();
|
||||
|
||||
// Changed on disk while editing: the save is refused, the edit stays, Discard ends it.
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
let mut other = read(&file);
|
||||
line(&mut other, "0", (0.0, 50.0), (1.0, 50.0));
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
save(&other, &file);
|
||||
let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string();
|
||||
assert!(e.contains("changed since"), "{e}");
|
||||
assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open");
|
||||
s.execute("refclose", &json!({ "option": "discard" })).unwrap();
|
||||
assert_eq!(read(&file).model.len(), 3, "the other program's change is kept");
|
||||
|
||||
// Changed since it was loaded: reload first.
|
||||
let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string();
|
||||
assert!(e.contains("since") && e.contains("reload"), "{e}");
|
||||
s.execute("-xref", &json!({ "option": "reload", "names": "site" })).unwrap();
|
||||
|
||||
// Read-only: refused.
|
||||
let mut perm = std::fs::metadata(&file).unwrap().permissions();
|
||||
perm.set_readonly(true);
|
||||
std::fs::set_permissions(&file, perm.clone()).unwrap();
|
||||
let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "{e}");
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perm.set_readonly(false);
|
||||
std::fs::set_permissions(&file, perm).unwrap();
|
||||
|
||||
// Open in another drawing tab of this session: refused.
|
||||
s.execute("qsave", &json!({})).unwrap();
|
||||
let host = s.state().unwrap().path.clone().unwrap();
|
||||
s.execute("open", &json!({ "path": file.to_string_lossy() })).unwrap();
|
||||
s.execute("open", &json!({ "path": host })).unwrap();
|
||||
let ih = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Insert(_))).unwrap().handle;
|
||||
let e = s.execute("refedit", &json!({ "handle": ih.hex() })).unwrap_err().to_string();
|
||||
assert!(e.contains("another drawing tab"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_block_references_are_picked_through_their_parents() {
|
||||
let mut s = Session::new();
|
||||
let c = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap());
|
||||
s.execute("block", &json!({ "name": "Inner", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap();
|
||||
let i = hx(s.execute("insert", &json!({ "name": "Inner", "at": [10, 0] })).unwrap());
|
||||
let l = hx(s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap());
|
||||
s.execute("block", &json!({ "name": "Outer", "base": [0, 0], "handles": [i, l], "keep": "delete" })).unwrap();
|
||||
let o = hx(s.execute("insert", &json!({ "name": "Outer", "at": [100, 100] })).unwrap());
|
||||
|
||||
// At the command line: pick, Next to the nested level, OK.
|
||||
s.start("refedit").unwrap();
|
||||
s.input(Input::Pick(vec![Handle::parse_hex(&o).unwrap()])).unwrap();
|
||||
assert!(s.prompt_text().contains("Select nesting level"), "{}", s.prompt_text());
|
||||
assert!(s.log.iter().any(|m| m.contains("Reference name: Outer")));
|
||||
s.input(Input::Enter).unwrap(); // Next
|
||||
assert!(s.log.iter().any(|m| m.contains("Reference name: Inner")));
|
||||
s.cmdline("o").unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let r = d.refedit.clone().unwrap();
|
||||
assert_eq!(r.block, "Inner");
|
||||
assert_eq!(r.items.len(), 1);
|
||||
assert_eq!(r.ghosts.len(), 1, "Outer's line stands faded");
|
||||
let EntityKind::Circle(circle) = &d.entity(r.items[0].copy).unwrap().kind else { panic!() };
|
||||
assert!(circle.center.xy().near(Vec2::new(110.0, 100.0), 1e-9));
|
||||
// Only the working set can change: Outer's faded line is locked.
|
||||
s.execute("move", &json!({ "handles": [r.items[0].copy.hex()], "delta": [0, 3] })).unwrap();
|
||||
s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let EntityKind::Circle(c) = &d.block("Inner").unwrap().entities.iter().next().unwrap().kind else { panic!() };
|
||||
assert!(c.center.xy().near(Vec2::new(0.0, 3.0), 1e-9), "{c:?}");
|
||||
assert_eq!(d.block("Outer").unwrap().entities.len(), 2, "the parent is untouched");
|
||||
// Bad paths are refused.
|
||||
assert!(s.execute("refedit", &json!({ "handle": o, "path": ["FFFFF"] })).is_err());
|
||||
assert!(s.execute("refedit", &json!({ "handle": o, "path": "x" })).is_err());
|
||||
assert!(s.execute("refedit", &json!({ "handle": o, "nested": "Nope" })).is_err());
|
||||
let _ = Vec2::ZERO;
|
||||
}
|
||||
|
||||
/// A symbolic link at `link` to `target`; `None` where the system doesn't let a test make one
|
||||
/// (Windows without the privilege), and the test is skipped there. CI runs it on Linux.
|
||||
fn symlink(target: &Path, link: &Path) -> Option<()> {
|
||||
#[cfg(unix)]
|
||||
let made = std::os::unix::fs::symlink(target, link);
|
||||
#[cfg(windows)]
|
||||
let made = std::os::windows::fs::symlink_file(target, link);
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let made: std::io::Result<()> = Err(std::io::Error::other("no symbolic links"));
|
||||
match made {
|
||||
Ok(()) => Some(()),
|
||||
Err(e) => {
|
||||
eprintln!("skipped: symbolic links can't be made here ({e})");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_plain_file(p: &Path) -> bool {
|
||||
std::fs::symlink_metadata(p).is_ok_and(|m| m.is_file())
|
||||
}
|
||||
|
||||
/// Review of #2355: a link planted at the temporary or backup path beside the xref must not take
|
||||
/// the write (CWE-59). Before, the new bytes went into `victim.txt` through `site.dxf.cadcraft-tmp`
|
||||
/// and `site.dxf` itself became that link.
|
||||
#[test]
|
||||
fn links_planted_beside_the_xref_are_not_written_through() {
|
||||
let (mut s, dir, _, insert) = attached("planted");
|
||||
let file = dir.join("site.dxf");
|
||||
let (victim, other) = (dir.join("victim.txt"), dir.join("other.txt"));
|
||||
std::fs::write(&victim, b"victim").unwrap();
|
||||
std::fs::write(&other, b"other").unwrap();
|
||||
if symlink(&victim, &dir.join("site.dxf.cadcraft-tmp")).is_none() {
|
||||
return;
|
||||
}
|
||||
symlink(&other, &dir.join("site.dxf.bak")).unwrap();
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap();
|
||||
s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
assert_eq!(std::fs::read(&victim).unwrap(), b"victim", "nothing is written through the planted link");
|
||||
assert_eq!(std::fs::read(&other).unwrap(), b"other", "nor through a link at the backup");
|
||||
assert!(is_plain_file(&file), "the xref's file is still a file, not a link");
|
||||
assert_eq!(read(&file).model.len(), 3, "and holds the edit");
|
||||
assert!(is_plain_file(&dir.join("site.dxf.bak")), "the link at the backup is replaced by the backup");
|
||||
assert_eq!(read(&dir.join("site.dxf.bak")).model.len(), 2);
|
||||
}
|
||||
|
||||
/// Review of #2355: the xref's own path turned into a link to another file during the edit (here
|
||||
/// a byte-identical copy with the same time, so the change check can't tell) is not written.
|
||||
#[test]
|
||||
fn an_xref_path_turned_into_a_link_during_the_edit_is_not_written() {
|
||||
let (mut s, dir, _, insert) = attached("swapped");
|
||||
let file = dir.join("site.dxf");
|
||||
let elsewhere = dir.join("elsewhere");
|
||||
std::fs::create_dir_all(&elsewhere).unwrap();
|
||||
let target = elsewhere.join("victim.dxf");
|
||||
if symlink(&file, &dir.join("probe")).is_none() {
|
||||
return;
|
||||
}
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap();
|
||||
let modified = std::fs::metadata(&file).unwrap().modified().unwrap();
|
||||
std::fs::copy(&file, &target).unwrap();
|
||||
std::fs::OpenOptions::new().write(true).open(&target).unwrap().set_modified(modified).unwrap();
|
||||
std::fs::rename(&file, dir.join("moved.dxf")).unwrap();
|
||||
symlink(&target, &file).unwrap();
|
||||
let before = std::fs::read(&target).unwrap();
|
||||
let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string();
|
||||
assert!(e.contains("leads to another file"), "{e}");
|
||||
assert_eq!(std::fs::read(&target).unwrap(), before, "the link's target is untouched");
|
||||
assert!(!elsewhere.join("victim.dxf.bak").exists() && !dir.join("site.dxf.bak").exists(), "no backup either");
|
||||
assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open");
|
||||
s.execute("refclose", &json!({ "option": "discard" })).unwrap();
|
||||
}
|
||||
|
||||
/// Review of #2355: `site.dxf` and `site.dwg` in one folder both used to back up to `site.bak`,
|
||||
/// so editing one and then the other lost the first one's old copy. They keep their own now, named
|
||||
/// as SAVE names them (`site.dxf.bak`, `site.bak`).
|
||||
#[test]
|
||||
fn xrefs_of_one_name_in_one_folder_keep_their_own_backups() {
|
||||
// These files are our own: DWG is read and written in this process.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
hooks();
|
||||
let dir = folder("two-backups");
|
||||
let (d, _) = site();
|
||||
let (dxf, dwg) = (dir.join("site.dxf"), dir.join("site.dwg"));
|
||||
save(&d, &dxf);
|
||||
save(&d, &dwg);
|
||||
let (old_dxf, old_dwg) = (std::fs::read(&dxf).unwrap(), std::fs::read(&dwg).unwrap());
|
||||
let host = dir.join("host.dxf");
|
||||
save(&Drawing::new_metric(), &host);
|
||||
let mut s = Session::new();
|
||||
s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap();
|
||||
for (path, name, x) in [("site.dxf", "a", 0), ("site.dwg", "b", 100)] {
|
||||
let r = s.execute("xattach", &json!({ "path": path, "name": name, "at": [x, 0] })).unwrap();
|
||||
s.execute("refedit", &json!({ "handle": r["handle"] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[x, 20], [x + 10, 20]] })).unwrap();
|
||||
s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
}
|
||||
assert_eq!(std::fs::read(dir.join("site.dxf.bak")).unwrap(), old_dxf, "the DXF's previous file");
|
||||
assert_eq!(std::fs::read(dir.join("site.bak")).unwrap(), old_dwg, "the DWG's previous file");
|
||||
assert_eq!((read(&dxf).model.len(), read(&dwg).model.len()), (3, 3), "both hold their edit");
|
||||
}
|
||||
|
||||
/// A host drawing (host.dxf in `dir`) with `file` of `dir` attached as xref `name` at (100, 0).
|
||||
fn host_with(dir: &Path, file: &str, name: &str) -> (Session, String) {
|
||||
let host = dir.join("host.dxf");
|
||||
save(&Drawing::new_metric(), &host);
|
||||
let mut s = Session::new();
|
||||
s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap();
|
||||
let r = s.execute("xattach", &json!({ "path": file, "name": name, "at": [100, 0] })).unwrap();
|
||||
(s, r["handle"].as_str().unwrap().to_string())
|
||||
}
|
||||
|
||||
/// The `$ACADVER` an ASCII DXF declares.
|
||||
fn dxf_version(bytes: &[u8]) -> Option<String> {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
lines.windows(3).find(|w| w[0] == "$ACADVER" && w[1] == "1").map(|w| w[2].to_string())
|
||||
}
|
||||
|
||||
/// Review of #2355: the xref was saved in the writer's default version (an R2000 DWG came back
|
||||
/// as 2004, AC1018). It is written back in the version, and form, it was read in.
|
||||
#[test]
|
||||
fn an_xref_is_written_back_in_the_version_it_was_read_in() {
|
||||
// These files are our own: DWG is read and written in this process.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
hooks();
|
||||
let dir = folder("versions");
|
||||
let (d, _) = site();
|
||||
let write = |name: &str, version: Version, binary: bool| {
|
||||
let p = dir.join(name);
|
||||
let opts = cadcraft_io::SaveOptions { version: Some(version), binary };
|
||||
std::fs::write(&p, cadcraft_io::write_with(&d, &p, &opts).unwrap()).unwrap();
|
||||
p
|
||||
};
|
||||
let dwg = write("old.dwg", Version::R2000, false);
|
||||
let dxf = write("old.dxf", Version::R2004, false);
|
||||
let bin = write("bin.dxf", Version::R2010, true);
|
||||
assert_eq!((&std::fs::read(&dwg).unwrap()[..6], dxf_version(&std::fs::read(&dxf).unwrap()).as_deref()), (&b"AC1015"[..], Some("AC1018")));
|
||||
for (file, name) in [("old.dwg", "a"), ("old.dxf", "b"), ("bin.dxf", "c")] {
|
||||
let (mut s, insert) = host_with(&dir, file, name);
|
||||
let r = s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
assert_eq!(r["xref"]["binary"], file == "bin.dxf", "{r}");
|
||||
s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap();
|
||||
s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
}
|
||||
let (dwg_bytes, dxf_bytes, bin_bytes) = (std::fs::read(&dwg).unwrap(), std::fs::read(&dxf).unwrap(), std::fs::read(&bin).unwrap());
|
||||
assert_eq!(&dwg_bytes[..6], b"AC1015", "the R2000 DWG stays R2000");
|
||||
assert_eq!(dxf_version(&dxf_bytes).as_deref(), Some("AC1018"), "the 2004 DXF stays 2004");
|
||||
assert!(bin_bytes.starts_with(b"AutoCAD Binary DXF"), "the binary DXF stays binary");
|
||||
assert_eq!(read(&bin).header.get("ACADVER").and_then(cadcraft_engine::doc::HVal::as_str), Some("AC1024"), "and 2010");
|
||||
assert_eq!((read(&dwg).model.len(), read(&dxf).model.len(), read(&bin).model.len()), (3, 3, 3), "each holds its edit");
|
||||
}
|
||||
|
||||
/// Review of #2355: an R12 DXF xref came back as an R2000 one. CADCraft doesn't write R12, so the
|
||||
/// edit is refused before it begins (no work lost), and the file is left as it is.
|
||||
#[test]
|
||||
fn an_xref_in_a_version_cadcraft_cannot_write_is_not_edited_in_place() {
|
||||
hooks();
|
||||
let dir = folder("r12");
|
||||
let r12 = "0
|
||||
SECTION
|
||||
2
|
||||
HEADER
|
||||
9
|
||||
$ACADVER
|
||||
1
|
||||
AC1009
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
ENTITIES
|
||||
0
|
||||
LINE
|
||||
8
|
||||
0
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
11
|
||||
1
|
||||
21
|
||||
1
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
EOF
|
||||
";
|
||||
std::fs::write(dir.join("r12.dxf"), r12).unwrap();
|
||||
let (mut s, insert) = host_with(&dir, "r12.dxf", "old");
|
||||
let e = s.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string();
|
||||
assert!(e.contains("AC1009") && e.contains("XOPEN"), "{e}");
|
||||
assert!(s.doc().unwrap().refedit.is_none());
|
||||
assert_eq!(std::fs::read_to_string(dir.join("r12.dxf")).unwrap(), r12, "the file is untouched");
|
||||
}
|
||||
|
||||
/// Review of #2355: SAVE says what a file can't keep; the write-back said nothing. A 2013 DXF xref
|
||||
/// holding a solid whose ACIS geometry is SAT text (no data store record) loses it when written:
|
||||
/// the save says so, names it in `notSaved`, and points at the backup that still has it.
|
||||
#[test]
|
||||
fn what_the_xref_file_cannot_keep_is_reported() {
|
||||
hooks();
|
||||
let dir = folder("lost");
|
||||
let dxf = "0
|
||||
SECTION
|
||||
2
|
||||
HEADER
|
||||
9
|
||||
$ACADVER
|
||||
1
|
||||
AC1027
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
ENTITIES
|
||||
0
|
||||
LINE
|
||||
5
|
||||
20
|
||||
8
|
||||
0
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
11
|
||||
1
|
||||
21
|
||||
1
|
||||
0
|
||||
3DSOLID
|
||||
5
|
||||
21
|
||||
100
|
||||
AcDbEntity
|
||||
8
|
||||
0
|
||||
100
|
||||
AcDbModelerGeometry
|
||||
70
|
||||
1
|
||||
1
|
||||
400 0 1 0
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
EOF
|
||||
";
|
||||
std::fs::write(dir.join("solid.dxf"), dxf).unwrap();
|
||||
let (mut s, insert) = host_with(&dir, "solid.dxf", "solid");
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap();
|
||||
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
assert_eq!(out["notSaved"], json!({ "3DSOLID": 1 }), "{out}");
|
||||
let warning = s.log.iter().find(|m| m.contains("Not saved in the DXF file")).expect("a warning on the command line");
|
||||
assert!(warning.contains("1 3DSOLID") && warning.contains("solid.dxf.bak"), "{warning}");
|
||||
assert!(std::fs::read_to_string(dir.join("solid.dxf.bak")).unwrap().contains("3DSOLID"), "the backup still has it");
|
||||
}
|
||||
|
||||
/// Review of #2355: a reference nested with different X and Y scales was offered as a level, and
|
||||
/// OK then refused it. It isn't offered (nor anything below it); a uniformly scaled one is.
|
||||
#[test]
|
||||
fn nested_references_refedit_cannot_open_are_not_offered() {
|
||||
let mut s = Session::new();
|
||||
let c = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap());
|
||||
s.execute("block", &json!({ "name": "Leaf", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap();
|
||||
let uniform = hx(s.execute("insert", &json!({ "name": "Leaf", "at": [10, 0], "scale": 2 })).unwrap());
|
||||
let stretched = hx(s.execute("insert", &json!({ "name": "Leaf", "at": [20, 0], "scale": [2, 1] })).unwrap());
|
||||
s.execute("block", &json!({ "name": "Holder", "base": [0, 0], "handles": [uniform, stretched], "keep": "delete" })).unwrap();
|
||||
let o = hx(s.execute("insert", &json!({ "name": "Holder", "at": [0, 0] })).unwrap());
|
||||
let levels = s.execute("refedit.levels", &json!({ "handle": o })).unwrap();
|
||||
let names: Vec<&str> = levels["levels"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Holder", "Leaf"], "{levels}");
|
||||
// The one offered opens.
|
||||
let path = levels["levels"][1]["path"].clone();
|
||||
s.execute("refedit", &json!({ "handle": o, "path": path })).unwrap();
|
||||
}
|
||||
|
||||
/// Review of #2355: the faded copies carried XFADECTL in their own transparency, so lowering
|
||||
/// XFADECTL during the edit left them faded. They keep the object's own transparency now; the
|
||||
/// fade is drawn from the current XFADECTL.
|
||||
#[test]
|
||||
fn faded_copies_keep_their_own_transparency() {
|
||||
let mut s = Session::new();
|
||||
let a = hx(s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap());
|
||||
let b = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap());
|
||||
s.execute("block", &json!({ "name": "Pair", "base": [0, 0], "handles": [a, b], "keep": "delete" })).unwrap();
|
||||
let i = hx(s.execute("insert", &json!({ "name": "Pair", "at": [0, 0] })).unwrap());
|
||||
let d = s.doc().unwrap();
|
||||
let blk = d.block("Pair").unwrap();
|
||||
let line = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::Line(_))).unwrap().handle;
|
||||
let own = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::Circle(_))).unwrap().common.transparency;
|
||||
s.execute("refedit", &json!({ "handle": i, "objects": [line.hex()] })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let r = d.refedit.clone().unwrap();
|
||||
let ghost = d.entity(r.ghosts[0].0).unwrap();
|
||||
assert_eq!(ghost.common.transparency, own, "the circle's copy is faded by the renderer, not by its own transparency");
|
||||
s.execute("refclose", &json!({ "option": "discard" })).unwrap();
|
||||
}
|
||||
|
||||
/// Review of #2355: the xref's file opened in another tab after the edit began was overwritten
|
||||
/// by REFCLOSE Save; the save is refused while it is open there.
|
||||
#[test]
|
||||
fn an_xref_opened_in_another_tab_during_the_edit_is_not_written() {
|
||||
let (mut s, dir, _, insert) = attached("tab-later");
|
||||
let file = dir.join("site.dxf");
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap();
|
||||
let host = s.active;
|
||||
s.execute("open", &json!({ "path": file.to_string_lossy() })).unwrap();
|
||||
s.execute("document.switch", &json!({ "index": host })).unwrap();
|
||||
let before = std::fs::read(&file).unwrap();
|
||||
let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string();
|
||||
assert!(e.contains("another drawing tab"), "{e}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), before, "the file is untouched");
|
||||
assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open");
|
||||
}
|
||||
|
||||
/// Review of #2355: the "loaded" stamp was one per file for the whole process, so a second drawing
|
||||
/// loading the xref later moved the first drawing's baseline. Here the file changes (same objects,
|
||||
/// moved) after the first drawing loaded it: that drawing still shows the old geometry, and REFEDIT
|
||||
/// there must refuse rather than pair the old geometry with the new file.
|
||||
#[test]
|
||||
fn each_drawing_keeps_its_own_xref_baseline() {
|
||||
let (mut first, dir, _, insert) = attached("baseline");
|
||||
let file = dir.join("site.dxf");
|
||||
let mut moved = read(&file);
|
||||
let h = moved.model.iter().find(|e| matches!(e.kind, EntityKind::Line(_))).unwrap().handle;
|
||||
moved
|
||||
.modify_entity(h, |e| {
|
||||
if let EntityKind::Line(l) = &mut e.kind {
|
||||
l.b.y += 1.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
save(&moved, &file);
|
||||
// Another drawing loads the changed file.
|
||||
let other_host = dir.join("other.dxf");
|
||||
save(&Drawing::new_metric(), &other_host);
|
||||
let mut second = Session::new();
|
||||
second.execute("open", &json!({ "path": other_host.to_string_lossy() })).unwrap();
|
||||
let r = second.execute("xattach", &json!({ "path": "site.dxf", "at": [0, 0] })).unwrap();
|
||||
second.execute("refedit", &json!({ "handle": r["handle"] })).unwrap();
|
||||
second.execute("refclose", &json!({ "option": "discard" })).unwrap();
|
||||
// The first drawing loaded the earlier file.
|
||||
let e = first.execute("refedit", &json!({ "handle": insert })).unwrap_err().to_string();
|
||||
assert!(e.contains("changed since") && e.contains("reload"), "{e}");
|
||||
}
|
||||
|
||||
/// Review of #2355: multileader and table styles of the host that objects drawn during the edit
|
||||
/// use were not copied into the xref's file, so they lost their style there.
|
||||
#[test]
|
||||
fn host_multileader_and_table_styles_come_along() {
|
||||
let (mut s, dir, _, insert) = attached("styles");
|
||||
s.execute("mleaderstyle", &json!({ "name": "Callout", "textHeight": 7, "current": true })).unwrap();
|
||||
s.execute("tablestyle", &json!({ "name": "Schedule", "textHeight": 4, "current": true })).unwrap();
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
s.execute("mleader", &json!({ "points": [[100, 30], [110, 40]], "text": "A" })).unwrap();
|
||||
s.execute("table", &json!({ "at": [120, 30], "rows": 1, "cols": 1 })).unwrap();
|
||||
s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
let back = read(&dir.join("site.dxf"));
|
||||
let mleader = back.model.iter().find_map(|e| if let EntityKind::MLeader(m) = &e.kind { Some(m.style.clone()) } else { None }).unwrap();
|
||||
let table = back.model.iter().find_map(|e| if let EntityKind::Table(t) = &e.kind { Some(t.style.clone()) } else { None }).unwrap();
|
||||
assert_eq!((mleader.as_str(), table.as_str()), ("Callout", "Schedule"));
|
||||
let ml = back.mleader_styles.iter().find(|t| t.name == "Callout").expect("the multileader style is in the file");
|
||||
assert!((ml.text_height - 7.0).abs() < 1e-9);
|
||||
let ts = back.table_styles.iter().find(|t| t.name == "Schedule").expect("the table style is in the file");
|
||||
assert!((ts.text_height - 4.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// Automation roots (#1472): an agent confined to its folders can't have REFCLOSE write an xref, or
|
||||
/// the xref's `.bak`, outside its write root, and can't start an edit in place of one it may not
|
||||
/// write. The refusals leave the xref, its backup and the host as they were.
|
||||
#[test]
|
||||
fn a_confined_session_does_not_write_an_xref_outside_its_write_root() {
|
||||
use cadcraft_engine::file_access::{AutomationRoots, confine};
|
||||
let (mut s, dir, _, insert) = attached("confined");
|
||||
let file = dir.join("site.dxf");
|
||||
let before = std::fs::read(&file).unwrap();
|
||||
let out = dir.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
// The xref's folder may be read but not written.
|
||||
let roots = AutomationRoots::new(Some(&dir), Some(&out)).unwrap();
|
||||
|
||||
// REFEDIT of an xref it couldn't save is refused before the edit begins.
|
||||
let e = confine(roots.as_ref(), || s.execute("refedit", &json!({ "handle": insert }))).unwrap_err().to_string();
|
||||
assert!(e.contains("outside") || e.contains("write"), "{e}");
|
||||
assert!(s.doc().unwrap().refedit.is_none(), "no edit began");
|
||||
|
||||
// An edit begun without the roots isn't written once they are in force.
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap();
|
||||
let e = confine(roots.as_ref(), || s.execute("refclose", &json!({ "option": "save" }))).unwrap_err().to_string();
|
||||
assert!(e.contains("outside") || e.contains("write"), "{e}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), before, "the xref is unchanged");
|
||||
assert!(std::fs::symlink_metadata(dir.join("site.dxf.bak")).is_err(), "no backup was written");
|
||||
assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open");
|
||||
assert_eq!(s.doc().unwrap().block("site").unwrap().entities.len(), 2, "the host still shows the xref as it was");
|
||||
s.execute("refclose", &json!({ "option": "discard" })).unwrap();
|
||||
|
||||
// Roots that don't reach the xref's folder: it isn't read for an edit either.
|
||||
let elsewhere = dir.join("elsewhere");
|
||||
std::fs::create_dir_all(elsewhere.join("out")).unwrap();
|
||||
let roots = AutomationRoots::new(Some(&elsewhere), Some(&elsewhere.join("out"))).unwrap();
|
||||
let e = confine(roots.as_ref(), || s.execute("refedit", &json!({ "handle": insert }))).unwrap_err().to_string();
|
||||
assert!(s.doc().unwrap().refedit.is_none(), "no edit began: {e}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), before);
|
||||
}
|
||||
|
||||
/// The write-back reports what a file can't keep as SAVE does (`lost_writing`), not only solids
|
||||
/// in a 2013 DXF: an R2000 DXF xref has no place for a proxy's separate strings (#3229), so the
|
||||
/// save names the proxy it leaves out, with the DXF's reason and the backup that keeps it.
|
||||
#[test]
|
||||
fn a_proxy_an_r2000_dxf_xref_cannot_keep_is_reported() {
|
||||
hooks();
|
||||
let dir = folder("proxy");
|
||||
let dxf = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n20\n8\n0\n10\n0\n20\n0\n11\n1\n21\n1\n0\nACAD_PROXY_ENTITY\n5\n21\n100\nAcDbEntity\n8\n0\n100\nAcDbProxyEntity\n90\n498\n91\n500\n162\n8\n161\n16\n310\nAABB\n0\nENDSEC\n0\nEOF\n";
|
||||
std::fs::write(dir.join("proxy.dxf"), dxf).unwrap();
|
||||
let (mut s, insert) = host_with(&dir, "proxy.dxf", "proxy");
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[100, 20], [110, 20]] })).unwrap();
|
||||
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
assert_eq!(out["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "{out}");
|
||||
let warning = s.log.iter().find(|m| m.contains("Not saved in the DXF file")).expect("a warning on the command line");
|
||||
assert!(warning.contains("before 2007") && warning.contains("1 ACAD_PROXY_ENTITY") && warning.contains("proxy.dxf.bak"), "{warning}");
|
||||
}
|
||||
|
||||
/// Review of #2355: a reference to another xref of the host, added to the working set with
|
||||
/// REFSET, would be written into the xref's drawing naming a block that drawing doesn't define.
|
||||
/// The save is refused instead; the file, its backup and the edit stay as they were.
|
||||
#[test]
|
||||
fn a_reference_to_another_xref_of_the_host_is_not_written_into_the_xref() {
|
||||
let (mut s, dir, _, insert) = attached("other-xref");
|
||||
let (other, _) = site();
|
||||
save(&other, &dir.join("other.dxf"));
|
||||
let r = s.execute("xattach", &json!({ "path": "other.dxf", "at": [0, 100] })).unwrap();
|
||||
let other_insert = r["handle"].as_str().unwrap().to_string();
|
||||
let file = dir.join("site.dxf");
|
||||
let before = std::fs::read(&file).unwrap();
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
s.execute("refset", &json!({ "add": [other_insert] })).unwrap();
|
||||
let e = s.execute("refclose", &json!({ "option": "save" })).unwrap_err().to_string();
|
||||
assert!(e.contains("\"other\""), "{e}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), before, "the xref is unchanged");
|
||||
assert!(std::fs::symlink_metadata(dir.join("site.dxf.bak")).is_err(), "no backup was written");
|
||||
assert!(s.doc().unwrap().refedit.is_some(), "the edit stays open");
|
||||
s.execute("refclose", &json!({ "option": "discard" })).unwrap();
|
||||
}
|
||||
|
||||
/// A dimension drawn during the edit with a host dimension style whose arrowhead is a block of
|
||||
/// the host: the block comes along with the style, so the xref's drawing defines what it names.
|
||||
#[test]
|
||||
fn a_host_dimension_styles_arrow_block_comes_along() {
|
||||
let (mut s, dir, _, insert) = attached("arrow-block");
|
||||
{
|
||||
let d = s.doc_mut().unwrap();
|
||||
let mut pin = Block::new("Pin");
|
||||
let h = d.new_handle();
|
||||
pin.entities.push(Entity::new(h, EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 0.5 })));
|
||||
d.blocks.insert("Pin".into(), Arc::new(pin));
|
||||
d.dim_styles.push(cadcraft_engine::doc::DimStyle { name: "Pinned".into(), arrow_block: "Pin".into(), ..Default::default() });
|
||||
d.header.set_str("DIMSTYLE", "Pinned");
|
||||
}
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
s.execute("dimlinear", &json!({ "p1": [100, 30], "p2": [110, 30], "at": [105, 40] })).unwrap();
|
||||
s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
let back = read(&dir.join("site.dxf"));
|
||||
assert_eq!(back.dim_style("Pinned").expect("the style comes along").arrow_block, "Pin");
|
||||
assert!(back.block("Pin").is_some(), "and the block its arrowheads are");
|
||||
}
|
||||
|
||||
/// Whether `d`'s model holds a dimension attached to the objects it measures.
|
||||
fn associative_dimensions(d: &Drawing) -> usize {
|
||||
d.model.iter().filter(|e| matches!(&e.kind, EntityKind::Dimension(dm) if !dm.assoc.is_empty())).count()
|
||||
}
|
||||
|
||||
/// Review of #2355: loading an xref drops its dimensions' associations, so the write-back leaves
|
||||
/// them out of the file. Until that is kept, the save says so, as for anything else the file
|
||||
/// can't keep, and names the backup that still has them. A dimension drawn during the edit
|
||||
/// attaches to the host's copies, whose handles mean nothing in the xref's file: it is written
|
||||
/// without them, and counted too.
|
||||
#[test]
|
||||
fn dimension_associations_the_write_back_drops_are_reported() {
|
||||
hooks();
|
||||
let dir = folder("assoc");
|
||||
let mut src = Session::new();
|
||||
src.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
src.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 5] })).unwrap();
|
||||
let file = dir.join("dims.dxf");
|
||||
src.execute("saveas", &json!({ "path": file.to_string_lossy() })).unwrap();
|
||||
assert_eq!(associative_dimensions(&read(&file)), 1, "the file has an associative dimension");
|
||||
|
||||
let (mut s, insert) = host_with(&dir, "dims.dxf", "dims");
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
// On the copy of the line, at (100, 0)..(110, 0) in the host.
|
||||
s.execute("dimlinear", &json!({ "p1": [100, 0], "p2": [110, 0], "at": [105, -5] })).unwrap();
|
||||
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
assert_eq!(out["notSaved"]["dimension associations"], 2, "{out}");
|
||||
let warning = s.log.iter().find(|m| m.contains("dimension associations")).expect("a warning on the command line");
|
||||
assert!(warning.contains("dims.dxf.bak"), "{warning}");
|
||||
let back = read(&file);
|
||||
assert_eq!(associative_dimensions(&back), 0, "{:?}", back.model.iter().map(|e| &e.kind).collect::<Vec<_>>());
|
||||
assert_eq!(associative_dimensions(&read(&dir.join("dims.dxf.bak"))), 1, "the backup keeps them");
|
||||
}
|
||||
|
||||
/// Review of #2355 (follow-up): a nested reference is offered only when the reference with
|
||||
/// everything above it can be opened. Each of two uniform scales of 0.0001 is fine alone, but
|
||||
/// together they flatten the inner block past what REFEDIT opens, so it isn't offered.
|
||||
#[test]
|
||||
fn a_nested_reference_too_small_with_its_parents_is_not_offered() {
|
||||
let mut s = Session::new();
|
||||
let c = hx(s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap());
|
||||
s.execute("block", &json!({ "name": "Leaf", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap();
|
||||
let tiny = hx(s.execute("insert", &json!({ "name": "Leaf", "at": [0, 0], "scale": 0.0001 })).unwrap());
|
||||
let l = hx(s.execute("line", &json!({ "points": [[0, 0], [1, 0]] })).unwrap());
|
||||
s.execute("block", &json!({ "name": "Holder", "base": [0, 0], "handles": [tiny, l], "keep": "delete" })).unwrap();
|
||||
let o = hx(s.execute("insert", &json!({ "name": "Holder", "at": [0, 0], "scale": 0.0001 })).unwrap());
|
||||
let levels = s.execute("refedit.levels", &json!({ "handle": o })).unwrap();
|
||||
let names: Vec<&str> = levels["levels"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Holder"], "{levels}");
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
//! The rotation grip of a dynamic block asks for an angle: Dynamic Input shows one angle box,
|
||||
//! holding the angle the cursor would give as Properties will show it. The drawing is the
|
||||
//! synthetic Symbol block of the io tests (Angle1 about its base, its grip at the radius' end).
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Handle;
|
||||
use cadcraft_engine::doc::dynblock::GripPart;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use serde_json::json;
|
||||
|
||||
fn dxf(src: &str) -> String {
|
||||
src.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(|l| {
|
||||
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
|
||||
format!("{code}\n{value}\n")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A session with Symbol and a reference to it at (100, 100).
|
||||
fn session() -> (Session, Handle) {
|
||||
let src = include_str!("../../../io/tests/data/dynblock_symbol.txt").replace("\r\n", "\n");
|
||||
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "symbol", None);
|
||||
let r = s.execute("insert", &json!({ "name": "Symbol", "at": [100, 100] })).unwrap();
|
||||
(s, Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rotation_grip_asks_for_an_angle_and_shows_it_live() {
|
||||
let (mut s, h) = session();
|
||||
s.start_dyn_grip(h, 15, GripPart::End).unwrap();
|
||||
assert!(s.current_prompt().is_some_and(|p| p.angle), "{:?}", s.current_prompt());
|
||||
// The grip is at (102, 100); straight above the base is a quarter turn.
|
||||
assert_eq!(s.live_value(Vec2::new(100.0, 102.0)).as_deref(), Some("90°"));
|
||||
assert_eq!(s.live_value(Vec2::new(98.0, 100.0)).as_deref(), Some("180°"));
|
||||
// Nothing is changed by looking.
|
||||
let props = s.execute("blocks.reference", &json!({ "handle": h.hex() })).unwrap();
|
||||
let angle = props["properties"].as_array().unwrap().iter().find(|p| p["name"] == "Angle1").unwrap()["value"].clone();
|
||||
assert_eq!(angle, json!("0"));
|
||||
}
|
||||
@@ -22,7 +22,6 @@ fn install() {
|
||||
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);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
}
|
||||
|
||||
/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes.
|
||||
@@ -88,35 +87,6 @@ fn not_saved(r: &Value) -> Value {
|
||||
r.get("notSaved").cloned().unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
fn legacy_visualstyles_warn_only_for_2007_dwg() {
|
||||
install();
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let source = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1021\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic\n350\n21\n\
|
||||
0\nVISUALSTYLE\n5\n21\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic\n70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\
|
||||
74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n\
|
||||
170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n0\nENDSEC\n0\nEOF\n";
|
||||
let drawing = cadcraft_io::read_dxf(source.as_bytes()).unwrap();
|
||||
let mut session = Session::empty();
|
||||
session.open_drawing(drawing, "styles.dxf", None);
|
||||
assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&session, "styles.dwg").get("VISUALSTYLE"), Some(&1));
|
||||
for (format, version) in [("dwg", 2007), ("dwg", 2013), ("dxf", 2007)] {
|
||||
let start = session.log.len();
|
||||
let result = session.execute("document.bytes", &json!({"format": format, "version": version})).unwrap();
|
||||
if format == "dwg" && version == 2007 {
|
||||
assert_eq!(not_saved(&result), json!({"VISUALSTYLE": 1}));
|
||||
assert!(session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
|
||||
} else {
|
||||
assert_eq!(not_saved(&result), Value::Null);
|
||||
assert!(!session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_no_version_writes_is_not_reported() {
|
||||
install();
|
||||
|
||||
@@ -305,3 +305,36 @@ fn drawings_sharing_a_name_keep_their_own_backups() {
|
||||
assert_eq!(name("x/plan.dxf"), "x/plan.dxf.bak");
|
||||
assert_eq!(name("x/plan.dwt"), "x/plan.dwt.bak");
|
||||
}
|
||||
|
||||
/// REFCLOSE Save writes an xref back the way SAVE writes a drawing: with ISAVEBAK off it keeps
|
||||
/// no `.bak` (and reports none), with it on it keeps the previous file.
|
||||
#[test]
|
||||
fn an_xref_written_back_by_refclose_keeps_a_backup_as_save_does() {
|
||||
let _g = saving();
|
||||
hooks();
|
||||
let dir = temp_dir("refclose");
|
||||
let site = dir.join("site.dxf");
|
||||
let mut x = Session::new();
|
||||
add_circle(&mut x, 0.0);
|
||||
x.execute("saveas", &json!({ "path": site.to_string_lossy() })).unwrap();
|
||||
let host = dir.join("host.dxf");
|
||||
let mut s = Session::new();
|
||||
s.execute("saveas", &json!({ "path": host.to_string_lossy() })).unwrap();
|
||||
let insert = s.execute("xattach", &json!({ "path": "site.dxf", "at": [100, 0] })).unwrap()["handle"].as_str().unwrap().to_string();
|
||||
let bak = backup_path(&site);
|
||||
|
||||
cadcraft_engine::autosave::set_isavebak(false);
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
add_circle(&mut s, 110.0);
|
||||
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
assert_eq!(circles(&site), 2, "the edit is written");
|
||||
assert!(out["backup"].is_null() && !bak.exists(), "ISAVEBAK off keeps no backup: {out}");
|
||||
|
||||
cadcraft_engine::autosave::set_isavebak(true);
|
||||
s.execute("refedit", &json!({ "handle": insert })).unwrap();
|
||||
add_circle(&mut s, 120.0);
|
||||
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
|
||||
assert_eq!((circles(&site), circles(&bak)), (3, 2), "{out}");
|
||||
assert_eq!(files(&dir), ["host.dxf", "site.dxf", "site.dxf.bak"], "no staging files are left");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
+21
-40
@@ -649,41 +649,31 @@ fn frame(font: &TextFont, s: &str, p: &TextParams) -> (Vec2, Vec2, f64, Vec2) {
|
||||
(origin, justify_offset(font, &sh, height, p.h, p.v), rot, mirror)
|
||||
}
|
||||
|
||||
/// Resolve Aligned/Fit dimensions with the same shaping direction as [`place`].
|
||||
/// Missing, coincident or nonfinite points leave the parameters unchanged.
|
||||
pub fn fit_params(font: &TextFont, s: &str, p: &TextParams) -> TextParams {
|
||||
let mut fitted = *p;
|
||||
if !matches!(p.h, Align::Aligned | Align::Fit) {
|
||||
return fitted;
|
||||
}
|
||||
let Some(second) = p.align_pt else { return fitted };
|
||||
let distance = p.insert.dist(second);
|
||||
if !distance.is_finite() || distance <= 1e-12 {
|
||||
return fitted;
|
||||
}
|
||||
fitted.rotation = p.insert.angle_to(second);
|
||||
let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
|
||||
let width = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL).width;
|
||||
if width.is_finite() && width > 1e-12 {
|
||||
let scale = distance / width;
|
||||
if p.h == Align::Aligned {
|
||||
fitted.height = height * scale;
|
||||
} else {
|
||||
fitted.width_factor *= scale;
|
||||
}
|
||||
}
|
||||
fitted
|
||||
}
|
||||
|
||||
/// Place a single-line TEXT in world coordinates with any font. Returns the shaped text and its
|
||||
/// bounding box.
|
||||
pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) {
|
||||
let fitted = fit_params(font, s, p);
|
||||
let p = &fitted;
|
||||
let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
|
||||
let rot = if p.rotation.is_finite() { p.rotation } else { 0.0 };
|
||||
let mut height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
|
||||
let mut wf = p.width_factor;
|
||||
let mut rot = if p.rotation.is_finite() { p.rotation } else { 0.0 };
|
||||
let insert = p.insert;
|
||||
let mut sh = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL);
|
||||
if matches!(p.h, Align::Aligned | Align::Fit)
|
||||
&& let Some(p2) = p.align_pt
|
||||
{
|
||||
let len = insert.dist(p2);
|
||||
rot = insert.angle_to(p2);
|
||||
// Measured as it is placed, left to right: the stroke font's trailing gap follows the
|
||||
// glyph that ends the line.
|
||||
let w = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL).width;
|
||||
if w > 1e-12 && len > 1e-12 {
|
||||
let k = len / w;
|
||||
if p.h == Align::Aligned {
|
||||
height *= k;
|
||||
} else {
|
||||
wf *= k;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut sh = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL);
|
||||
let width = sh.width;
|
||||
// Every justification but baseline-left (and aligned/fit, which span both points) is placed by
|
||||
// its alignment point (DXF group 11); the insertion point (group 10) is then a computed point.
|
||||
@@ -750,15 +740,6 @@ mod tests {
|
||||
assert!((text.width - 10.0).abs() < 1e-9, "{}", text.width);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_middle_vertical_spans_points() {
|
||||
for h in [Align::Aligned, Align::Fit] {
|
||||
let p = TextParams { h, v: VAlign::Middle, align_pt: Some(Vec2::new(12.0, 5.0)), ..TextParams::new(Vec2::ZERO, 2.0) };
|
||||
let (shaped, _) = place(&TextFont::Stroke, "SYNTHETIC", &p);
|
||||
assert!((shaped.width - p.insert.dist(p.align_pt.unwrap())).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_ascii_printable_has_a_glyph() {
|
||||
for c in ' '..='~' {
|
||||
|
||||
@@ -102,9 +102,6 @@ pub struct MTextLayout {
|
||||
/// Geometry by colour run (strokes plus fillable glyph outlines).
|
||||
pub pieces: Vec<MTextPiece>,
|
||||
pub bounds: Bounds2,
|
||||
/// The box of each column, in the order the text flows through them, measured like `bounds`
|
||||
/// but without the gutters and to each column's own height. One column: `bounds`.
|
||||
pub column_bounds: Vec<Bounds2>,
|
||||
/// Plain text of each laid-out line.
|
||||
pub lines: Vec<String>,
|
||||
/// Whether the geometry stops short: the layout reached its allowance of retained points
|
||||
@@ -734,7 +731,6 @@ pub fn layout_mtext_with(contents: &str, p: &MTextParams) -> MTextLayout {
|
||||
out.bounds = Bounds2::from_points(
|
||||
[Vec2::new(x0, top), Vec2::new(x0 + block_w, top), Vec2::new(x0 + block_w, top - block_h), Vec2::new(x0, top - block_h)].map(xf),
|
||||
);
|
||||
out.column_bounds = vec![out.bounds];
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -700,14 +700,6 @@ pub(super) fn layout(contents: &str, params: &MTextParams, base: &Fmt) -> MTextL
|
||||
[Vec2::new(box_x0, top), Vec2::new(box_x0 + total_w, top), Vec2::new(box_x0 + total_w, top - block_h), Vec2::new(box_x0, top - block_h)]
|
||||
.map(xf),
|
||||
);
|
||||
out.column_bounds = (0..n_cols)
|
||||
.map(|column| {
|
||||
let h = col_bottom.get(column).copied().unwrap_or(0.0).max(col_height(column));
|
||||
let slot = if reversed { n_cols.saturating_sub(1).saturating_sub(column) } else { column };
|
||||
let x0 = box_x0 + slot as f64 * (col_w + gutter);
|
||||
Bounds2::from_points([Vec2::new(x0, top), Vec2::new(x0 + col_w, top), Vec2::new(x0 + col_w, top - h), Vec2::new(x0, top - h)].map(xf))
|
||||
})
|
||||
.collect();
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -109,66 +109,6 @@ fn reversed_columns_run_right_to_left() {
|
||||
assert!(first > 0 && second > 0 && min_x(&l) >= 0.0);
|
||||
}
|
||||
|
||||
/// The geometry points inside `b`.
|
||||
fn points_in(l: &MTextLayout, b: &cadcraft_geom::Bounds2) -> usize {
|
||||
l.strokes.iter().flatten().filter(|p| b.contains(**p)).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_column_has_its_own_box_without_the_gutter() {
|
||||
let two = lay(&"word ".repeat(12), 10.0, Some(MTextColumnSpec { count: 2, gutter: 2.0, height: 6.0, ..Default::default() }));
|
||||
let [a, b] = two.column_bounds.as_slice() else { panic!("{:?}", two.column_bounds) };
|
||||
assert!(two.bounds.contains_box(a) && two.bounds.contains_box(b));
|
||||
assert!(a.max.x < b.min.x, "the gutter lies between the columns: {a:?} {b:?}");
|
||||
assert!(a.width() + b.width() < two.bounds.width());
|
||||
let total = two.strokes.iter().map(Vec::len).sum::<usize>();
|
||||
assert!(points_in(&two, a) > 0 && points_in(&two, b) > 0);
|
||||
assert_eq!(points_in(&two, a) + points_in(&two, b), total, "every point is in its column's box");
|
||||
|
||||
// Three static columns, the text filling two and a half: the half-full column keeps the
|
||||
// column height; text past the last column lengthens only that one.
|
||||
let spec = MTextColumnSpec { count: 3, gutter: 2.0, height: 6.0, ..Default::default() };
|
||||
let three = lay(&"word ".repeat(20), 10.0, Some(spec.clone()));
|
||||
assert_eq!(three.column_bounds.len(), 3);
|
||||
assert!(three.column_bounds.windows(2).all(|w| w[0].max.x < w[1].min.x && (w[0].height() - w[1].height()).abs() < 1e-9));
|
||||
let over = lay(&"word ".repeat(40), 10.0, Some(spec));
|
||||
let [first, .., last] = over.column_bounds.as_slice() else { panic!("{:?}", over.column_bounds) };
|
||||
assert!(last.height() > first.height() && (last.height() - over.bounds.height()).abs() < 1e-9);
|
||||
|
||||
// Manual heights: each column as tall as its own height.
|
||||
let manual = lay("one\\Ntwo", 5.0, Some(MTextColumnSpec { dynamic: true, heights: vec![3.0, 5.0], ..Default::default() }));
|
||||
let [a, b] = manual.column_bounds.as_slice() else { panic!("{:?}", manual.column_bounds) };
|
||||
assert!(a.height() < b.height());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_column_keeps_its_place() {
|
||||
let l = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 3, gutter: 1.0, height: 4.0, ..Default::default() }));
|
||||
let [a, b, c] = l.column_bounds.as_slice() else { panic!("{:?}", l.column_bounds) };
|
||||
assert!(a.max.x < b.min.x && b.max.x < c.min.x);
|
||||
assert!(points_in(&l, a) > 0 && points_in(&l, b) > 0 && points_in(&l, c) == 0);
|
||||
assert!((c.max.x - l.bounds.max.x).abs() < 1e-9 && (c.height() - a.height()).abs() < 1e-9);
|
||||
// Reversed: the column the text starts in is the rightmost.
|
||||
let r = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 2, height: 1.0, reversed: true, ..Default::default() }));
|
||||
let [a, b] = r.column_bounds.as_slice() else { panic!("{:?}", r.column_bounds) };
|
||||
assert!(a.min.x > b.max.x - 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_column_is_the_whole_box() {
|
||||
let rotated = |p: MTextParams| MTextParams { rotation: 0.4, attach: 5, insert: Vec2::new(3.0, -2.0), ..p };
|
||||
for (s, width, columns) in [
|
||||
("plain text that wraps a few times", 6.0, None),
|
||||
("\\pxl1;paragraph text that wraps\\Pagain", 6.0, None),
|
||||
("no width\\Pat all", 0.0, None),
|
||||
(&*"word ".repeat(30), 10.0, Some(MTextColumnSpec { count: 1, gutter: 5.0, height: 3.0, ..Default::default() })),
|
||||
("one\\Ptwo", 10.0, Some(MTextColumnSpec { dynamic: true, gutter: 5.0, height: 30.0, ..Default::default() })),
|
||||
] {
|
||||
let l = layout_mtext_with(s, &rotated(MTextParams { width, columns, ..MTextParams::new(Vec2::ZERO, 1.0) }));
|
||||
assert_eq!(l.column_bounds, vec![l.bounds], "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_paragraph_codes_do_not_panic() {
|
||||
let huge_tabs = format!("\\pt{};a\tb", (0..100_000).map(|i| i.to_string()).collect::<Vec<_>>().join(","));
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
//! A synthetic TrueType (sfnt) font file, built in code for tests that need a real font without a
|
||||
//! font file in the repository or one installed on the machine: `head`, `hhea`, `maxp`, `hmtx`,
|
||||
//! `glyf`, `loca`, a format-4 `cmap` and `OS/2`, laid out in a sorted table directory.
|
||||
//!
|
||||
//! Test-only, and shared: `crates/render/src/tests.rs` (the level-of-detail fixture) and
|
||||
//! `crates/io/tests/pdf_text.rs` (the PDF writer's embedding fixtures) build their fonts with it,
|
||||
//! each including this file with `#[path]`, so neither needs a published API, a dependency or a
|
||||
//! copy of the other's tables. `crates/fonts` is the layer that reads those tables
|
||||
//! (`crates/fonts/src/ttf.rs`), which is why the skeleton lives beside its tests; the glyph shapes,
|
||||
//! the character map ranges and the metrics a font records stay at the caller that needs them.
|
||||
|
||||
fn be16(v: &mut Vec<u8>, x: u16) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
|
||||
fn be32(v: &mut Vec<u8>, x: u32) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
|
||||
/// A simple glyph, with the point and contour counts `maxp` records for the font.
|
||||
pub struct Glyph {
|
||||
bytes: Vec<u8>,
|
||||
points: usize,
|
||||
contours: usize,
|
||||
}
|
||||
|
||||
/// `.notdef`: no contours, no bytes.
|
||||
pub fn notdef() -> Glyph {
|
||||
Glyph { bytes: Vec::new(), points: 0, contours: 0 }
|
||||
}
|
||||
|
||||
/// One simple glyph: closed contours of on-curve points, with the box the file records for it.
|
||||
pub fn glyph(contours: &[Vec<(i16, i16)>]) -> Glyph {
|
||||
let points: Vec<(i16, i16)> = contours.iter().flatten().copied().collect();
|
||||
let mut g = Vec::new();
|
||||
be16(&mut g, contours.len() as u16);
|
||||
let box_ = points.iter().fold((i16::MAX, i16::MAX, i16::MIN, i16::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));
|
||||
for v in [box_.0, box_.1, box_.2, box_.3] {
|
||||
be16(&mut g, v as u16);
|
||||
}
|
||||
let mut end = 0u16;
|
||||
for c in contours {
|
||||
end = end.saturating_add(c.len() as u16);
|
||||
be16(&mut g, end.saturating_sub(1));
|
||||
}
|
||||
be16(&mut g, 0);
|
||||
g.extend(std::iter::repeat_n(1u8, points.len()));
|
||||
let (mut px, mut py) = (0i16, 0i16);
|
||||
for (x, _) in &points {
|
||||
be16(&mut g, x.wrapping_sub(px) as u16);
|
||||
px = *x;
|
||||
}
|
||||
for (_, y) in &points {
|
||||
be16(&mut g, y.wrapping_sub(py) as u16);
|
||||
py = *y;
|
||||
}
|
||||
while g.len() % 4 != 0 {
|
||||
g.push(0);
|
||||
}
|
||||
Glyph { bytes: g, points: points.len(), contours: contours.len() }
|
||||
}
|
||||
|
||||
/// What the callers differ in; every other table field is the same in each font this builds.
|
||||
pub struct Sfnt<'a> {
|
||||
/// `glyf` entries, `.notdef` first.
|
||||
pub glyphs: &'a [Glyph],
|
||||
/// `cmap` format-4 segments: first character code, last character code, and glyph id minus
|
||||
/// code. The `0xFFFF` segment that ends the map is added here.
|
||||
pub cmap: &'a [(u16, u16, i16)],
|
||||
/// The advance width every glyph shares, in em units.
|
||||
pub advance: u16,
|
||||
/// The left side bearing every glyph shares.
|
||||
pub lsb: i16,
|
||||
/// `hmtx` entries written. Fewer than the glyphs `hhea` declares is a deliberately short
|
||||
/// table: that font is malformed on purpose, and a reader must cope with it, not repair it.
|
||||
pub metrics: usize,
|
||||
/// `OS/2` `fsType`: the embedding permissions, `0` for any use.
|
||||
pub fs_type: u16,
|
||||
/// `head`'s ink box: xMin, yMin, xMax, yMax.
|
||||
pub ink_box: [i16; 4],
|
||||
}
|
||||
|
||||
/// Em units per em: with a 700-unit cap height, one em is 1000 units, so a text height of one unit
|
||||
/// is a cap height of one unit.
|
||||
const UNITS_PER_EM: u16 = 1000;
|
||||
|
||||
/// The font file `f` describes, as a TrueType file.
|
||||
pub fn bytes(f: &Sfnt<'_>) -> Vec<u8> {
|
||||
let mut glyf = Vec::new();
|
||||
let mut loca = Vec::new();
|
||||
for g in f.glyphs {
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
glyf.extend_from_slice(&g.bytes);
|
||||
}
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
let mut head = Vec::new();
|
||||
be32(&mut head, 0x0001_0000); // version
|
||||
be32(&mut head, 0x0001_0000); // fontRevision
|
||||
be32(&mut head, 0); // checkSumAdjustment
|
||||
be32(&mut head, 0x5F0F_3CF5); // magic
|
||||
be16(&mut head, 0); // flags
|
||||
be16(&mut head, UNITS_PER_EM);
|
||||
head.extend_from_slice(&[0; 16]); // created, modified
|
||||
for v in f.ink_box {
|
||||
be16(&mut head, v as u16);
|
||||
}
|
||||
// macStyle, lowestRecPPEM, fontDirectionHint, indexToLocFormat 1 = long offsets (`loca` holds
|
||||
// `u32`), glyphDataFormat.
|
||||
for v in [0u16, 8, 2, 1, 0] {
|
||||
be16(&mut head, v);
|
||||
}
|
||||
let mut hhea = Vec::new();
|
||||
be32(&mut hhea, 0x0001_0000);
|
||||
// ascender, descender, lineGap, advanceWidthMax, minLeftSideBearing, minRightSideBearing,
|
||||
// xMaxExtent, caretSlopeRise, caretSlopeRun, caretOffset, four reserved, metricDataFormat.
|
||||
for v in [800i16, -200, 0, f.advance as i16, 0, 0, f.advance as i16, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut hhea, v as u16);
|
||||
}
|
||||
be16(&mut hhea, f.glyphs.len() as u16); // numberOfHMetrics
|
||||
let max_points = f.glyphs.iter().map(|g| g.points).max().unwrap_or(0);
|
||||
let max_contours = f.glyphs.iter().map(|g| g.contours).max().unwrap_or(0);
|
||||
let mut maxp = Vec::new();
|
||||
be32(&mut maxp, 0x0001_0000);
|
||||
// numGlyphs, maxPoints, maxContours, maxCompositePoints, maxCompositeContours, maxZones, and
|
||||
// the composite and instruction maxima after them.
|
||||
for v in [f.glyphs.len() as u16, max_points as u16, max_contours as u16, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut maxp, v);
|
||||
}
|
||||
let mut hmtx = Vec::new();
|
||||
for _ in 0..f.metrics {
|
||||
be16(&mut hmtx, f.advance);
|
||||
be16(&mut hmtx, f.lsb as u16);
|
||||
}
|
||||
// cmap: version 0 with one encoding record (Windows, Unicode BMP), a format-4 subtable over
|
||||
// the caller's segments and the `0xFFFF` one that ends it.
|
||||
let segs: Vec<(u16, u16, i16)> = f.cmap.iter().copied().chain([(0xFFFF, 0xFFFF, 1)]).collect();
|
||||
let seg_count = segs.len() as u32;
|
||||
let seg_selector = seg_count.ilog2();
|
||||
let seg_search_range = 2 * (1 << seg_selector);
|
||||
let mut sub = Vec::new();
|
||||
be16(&mut sub, 4); // format
|
||||
be16(&mut sub, (16 + segs.len() * 8) as u16); // length
|
||||
be16(&mut sub, 0); // language
|
||||
be16(&mut sub, (segs.len() * 2) as u16); // segCountX2
|
||||
for v in [seg_search_range as u16, seg_selector as u16, (2 * seg_count - seg_search_range) as u16] {
|
||||
be16(&mut sub, v);
|
||||
}
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.1);
|
||||
}
|
||||
be16(&mut sub, 0); // reservedPad
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.0);
|
||||
}
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.2 as u16);
|
||||
}
|
||||
for _ in &segs {
|
||||
be16(&mut sub, 0); // idRangeOffset
|
||||
}
|
||||
let mut cmap = Vec::new();
|
||||
for v in [0u16, 1, 3, 1] {
|
||||
be16(&mut cmap, v);
|
||||
}
|
||||
be32(&mut cmap, 12); // the subtable, straight after the records
|
||||
cmap.extend_from_slice(&sub);
|
||||
let mut os2 = vec![0u8; 78];
|
||||
os2[8..10].copy_from_slice(&f.fs_type.to_be_bytes());
|
||||
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
|
||||
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
|
||||
tables.sort_by_key(|t| *t.0);
|
||||
let mut out = Vec::new();
|
||||
be32(&mut out, 0x0001_0000); // sfnt version 1.0
|
||||
let num_tables = tables.len() as u32;
|
||||
let table_selector = num_tables.ilog2();
|
||||
let dir_search_range = 16 * (1 << table_selector);
|
||||
// numTables, searchRange, entrySelector, rangeShift: 16-byte records, largest power of two first.
|
||||
for v in [num_tables as u16, dir_search_range as u16, table_selector as u16, (16 * num_tables - dir_search_range) as u16] {
|
||||
be16(&mut out, v);
|
||||
}
|
||||
let mut off = 12 + 16 * tables.len();
|
||||
for (t, d) in &tables {
|
||||
out.extend_from_slice(*t);
|
||||
be32(&mut out, 0); // checkSum: the readers here do not verify it
|
||||
be32(&mut out, off as u32);
|
||||
be32(&mut out, d.len() as u32);
|
||||
off += d.len().div_ceil(4) * 4;
|
||||
}
|
||||
for (_, d) in &tables {
|
||||
out.extend_from_slice(d);
|
||||
while out.len() % 4 != 0 {
|
||||
out.push(0);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -212,7 +212,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
||||
// Every record is placed now, and an object holding a reserved handle keeps it from new
|
||||
// objects by itself. Kept, the set would be copied with every undo step of the drawing.
|
||||
d.reserved_handles.clear();
|
||||
remember_text_fits(&mut d);
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
@@ -245,23 +244,6 @@ fn number_unknown_viewport_ids(d: &mut Drawing, sheet_dropped: &std::collections
|
||||
}
|
||||
}
|
||||
|
||||
/// Capture after all tables and entity fixups, including files whose tables follow entities.
|
||||
fn remember_text_fits(d: &mut Drawing) {
|
||||
let mut fits = std::collections::BTreeMap::new();
|
||||
for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())) {
|
||||
let texts: Vec<&Text> = match &e.kind {
|
||||
EntityKind::Text(t) => vec![t],
|
||||
EntityKind::AttDef(a) => vec![&a.text],
|
||||
EntityKind::Insert(i) => i.attribs.iter().map(|a| &a.text).collect(),
|
||||
_ => continue,
|
||||
};
|
||||
if texts.iter().any(|t| matches!(t.halign, HAlign::Aligned | HAlign::Fit)) {
|
||||
fits.insert(e.handle, texts.into_iter().map(|t| (t.clone(), d.text_style(&t.style).cloned().unwrap_or_default())).collect());
|
||||
}
|
||||
}
|
||||
std::sync::Arc::make_mut(&mut d.foreign).text_fits = fits;
|
||||
}
|
||||
|
||||
/// An entity from the groups of a DXF record of type `kind` (without its `0` group), as the
|
||||
/// reader makes it, with plain strings as [`crate::entity_groups`] gives them (not the file's
|
||||
/// `^ ` escapes). AutoLISP's `entmake` and `entmod` are built on it.
|
||||
|
||||
@@ -73,7 +73,7 @@ pub(super) fn hatch(tags: &[Tag], t: &T, curves: &mut CurvePoints) -> Option<Ent
|
||||
verts.pop();
|
||||
}
|
||||
let sources = boundary_sources(tags, &mut i);
|
||||
loops.push(HatchLoop { vertices: verts, outer, boundary_flags: Some(flags), sources });
|
||||
loops.push(HatchLoop { vertices: verts, outer, sources });
|
||||
}
|
||||
curves.left = curves.left.saturating_sub(start_left.saturating_sub(budget.left));
|
||||
if budget.cut {
|
||||
|
||||
@@ -70,8 +70,7 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option<EntityKind>
|
||||
let list = xdata_list(x, "REGION");
|
||||
let fin = |v: &PolyVertex| v.p.is_finite() && v.bulge.is_finite();
|
||||
let first_outer = list.iter().find(|t| t.code == 1070).is_none_or(|t| t.i64() != 0);
|
||||
let mut loops =
|
||||
vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, boundary_flags: None, sources: Vec::new() }];
|
||||
let mut loops = vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, sources: Vec::new() }];
|
||||
let mut total = 0usize;
|
||||
let mut cur: Option<HatchLoop> = None;
|
||||
let mut expect_flag = false;
|
||||
@@ -82,7 +81,7 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option<EntityKind>
|
||||
if loops.len() >= MAX_REGION_LOOPS {
|
||||
break;
|
||||
}
|
||||
cur = Some(HatchLoop { vertices: Vec::new(), outer: false, boundary_flags: None, sources: Vec::new() });
|
||||
cur = Some(HatchLoop { vertices: Vec::new(), outer: false, sources: Vec::new() });
|
||||
expect_flag = true;
|
||||
}
|
||||
1070 if expect_flag => {
|
||||
|
||||
@@ -165,56 +165,10 @@ fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::Hash
|
||||
|
||||
/// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG
|
||||
/// version's (MULTILEADER from 2007).
|
||||
pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> (String, craft_dwg::Unwritten) {
|
||||
let (mut tags, kept) = sections::tags_kept_for(d, Version::R2000, dwg, false, true);
|
||||
let mut unwritten = craft_dwg::Unwritten::new();
|
||||
if dwg == Version::R2007 {
|
||||
let omitted = legacy_visualstyles_kept(d, &kept);
|
||||
if omitted != 0 {
|
||||
let mut source = d.clone();
|
||||
std::sync::Arc::make_mut(&mut source.foreign).objects.retain(|object| !legacy_visual_style(object));
|
||||
tags = tags_for(&source, Version::R2000, dwg, false);
|
||||
unwritten.insert("VISUALSTYLE".into(), omitted);
|
||||
}
|
||||
}
|
||||
pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> String {
|
||||
let mut tags = tags_for(d, Version::R2000, dwg, false);
|
||||
bridge_markers(&mut tags);
|
||||
(craft_dxf::write_ascii(&tags), unwritten)
|
||||
}
|
||||
|
||||
/// Version-specific DWG compatibility omissions, counted from the actual saved view.
|
||||
/// Hosts use this before saving and when reporting saves through their byte-only I/O hooks.
|
||||
pub fn dwg_compat_lost(d: &Drawing, version: Version) -> craft_dwg::Unwritten {
|
||||
let mut lost = craft_dwg::Unwritten::new();
|
||||
if version == Version::R2007 && d.foreign.objects.iter().any(legacy_visual_style) {
|
||||
let (_, kept) = sections::tags_kept_for(d, Version::R2000, version, false, true);
|
||||
let omitted = legacy_visualstyles_kept(d, &kept);
|
||||
if omitted != 0 {
|
||||
lost.insert("VISUALSTYLE".into(), omitted);
|
||||
}
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
fn legacy_visualstyles_kept(d: &Drawing, kept: &HashSet<cadcraft_doc::Handle>) -> usize {
|
||||
d.foreign.objects.iter().filter(|object| kept.contains(&object.handle) && legacy_visual_style(object)).count()
|
||||
}
|
||||
|
||||
/// The fixed-property VISUALSTYLE layout in the 2007/2010 DXF Reference has no 176/177
|
||||
/// property pairs. The bridge cannot faithfully save this layout as a 2007 DWG.
|
||||
fn legacy_visual_style(object: &cadcraft_doc::foreign::ForeignObject) -> bool {
|
||||
if !object.kind.trim().eq_ignore_ascii_case("VISUALSTYLE") {
|
||||
return false;
|
||||
}
|
||||
let mut properties = object.tags.iter().skip_while(|tag| tag.code != 100 || tag.value.trim() != "AcDbVisualStyle");
|
||||
properties.next();
|
||||
let mut fixed = false;
|
||||
for tag in properties.take_while(|tag| tag.code != 100 && tag.code < 1000) {
|
||||
if matches!(tag.code, 176 | 177) {
|
||||
return false;
|
||||
}
|
||||
fixed |= matches!(tag.code, 40 | 71);
|
||||
}
|
||||
fixed
|
||||
craft_dxf::write_ascii(&tags)
|
||||
}
|
||||
|
||||
/// Proxy type names and lookup-parameter subclass names must match the bridge reader's spelling.
|
||||
|
||||
@@ -254,69 +254,8 @@ fn computed_text_insert(d: &Drawing, t: &Text) -> Vec3 {
|
||||
if q.is_finite() { Vec3::new(q.x, q.y, t.insert.z) } else { t.insert }
|
||||
}
|
||||
|
||||
fn relative_match(a: f64, b: f64) -> bool {
|
||||
a.is_finite() && b.is_finite() && (a - b).abs() <= 1e-9 * a.abs().max(b.abs())
|
||||
}
|
||||
|
||||
// A fitted dimension depends on the point distance, independently of position and direction.
|
||||
fn imported_fit_scale(original: &Text, current: &Text) -> Option<f64> {
|
||||
let (Some(first), Some(second)) = (original.align_pt, current.align_pt) else {
|
||||
return None;
|
||||
};
|
||||
let before = original.insert.xy().dist(first.xy());
|
||||
let after = current.insert.xy().dist(second.xy());
|
||||
if !before.is_finite() || !after.is_finite() || before <= 0.0 || after <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
if relative_match(before, after) {
|
||||
return Some(1.0);
|
||||
}
|
||||
let scale = after / before;
|
||||
(scale.is_finite() && scale > 0.0).then_some(scale)
|
||||
}
|
||||
|
||||
/// `attdef_prompt` is `Some` for an ATTDEF (its prompt, which may be empty) and `None` for an ATTRIB.
|
||||
pub(super) fn text_tags(
|
||||
w: &mut W,
|
||||
d: &Drawing,
|
||||
t: &Text,
|
||||
attrib: Option<(&Attrib, Version)>,
|
||||
attdef_prompt: Option<&str>,
|
||||
source: (cadcraft_doc::Handle, usize),
|
||||
) {
|
||||
let fitted;
|
||||
let t = if matches!(t.halign, HAlign::Aligned | HAlign::Fit) {
|
||||
let mut resolved = t.clone();
|
||||
// Imported dimensions use the originating font's measurements. A substituted font
|
||||
// must not replace them while the fitting inputs still match the read-time snapshot.
|
||||
if let Some((original, style)) = d.foreign.text_fits.get(&source.0).and_then(|texts| texts.get(source.1))
|
||||
&& original.value == t.value
|
||||
&& let Some(scale) = imported_fit_scale(original, t)
|
||||
&& original.style == t.style
|
||||
&& *style == d.text_style(&t.style).cloned().unwrap_or_default()
|
||||
&& original.halign == t.halign
|
||||
&& original.valign == t.valign
|
||||
&& original.oblique == t.oblique
|
||||
&& original.width_factor == t.width_factor
|
||||
&& (t.halign != HAlign::Fit || relative_match(t.height, original.height * scale))
|
||||
{
|
||||
if t.halign == HAlign::Aligned && !t.value.is_empty() {
|
||||
resolved.height = original.height * scale;
|
||||
}
|
||||
if let Some(second) = t.align_pt {
|
||||
let distance = t.insert.xy().dist(second.xy());
|
||||
if distance.is_finite() && distance > 1e-12 {
|
||||
resolved.rotation = t.insert.xy().angle_to(second.xy());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
resolved = cadcraft_render::fitted_text_entity(d, t, &t.value);
|
||||
}
|
||||
fitted = resolved;
|
||||
&fitted
|
||||
} else {
|
||||
t
|
||||
};
|
||||
pub(super) fn text_tags(w: &mut W, d: &Drawing, t: &Text, attrib: Option<(&Attrib, Version)>, attdef_prompt: Option<&str>) {
|
||||
let attdef = attdef_prompt.is_some();
|
||||
// An attribute definition with no default value is drawn as its tag, whatever its prompt: the
|
||||
// baseline start AutoCAD stored is judged against the tag's width too. A stored point that is
|
||||
|
||||
@@ -292,7 +292,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo
|
||||
w.s(0, "TEXT");
|
||||
common(w, e, owner, paper, "AcDbText");
|
||||
thickness(w, e);
|
||||
text_tags(w, d, t, None, None, (e.handle, 0));
|
||||
text_tags(w, d, t, None, None);
|
||||
}
|
||||
// Closed polylines, one per loop (`dxf_region`): REGION's own data is ACIS.
|
||||
EntityKind::Region(r) => {
|
||||
@@ -312,7 +312,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo
|
||||
EntityKind::AttDef(a) => {
|
||||
w.s(0, "ATTDEF");
|
||||
common(w, e, owner, paper, "AcDbText");
|
||||
text_tags(w, d, &a.text, Some((a, cx.target)), Some(&a.prompt), (e.handle, 0));
|
||||
text_tags(w, d, &a.text, Some((a, cx.target)), Some(&a.prompt));
|
||||
if cx.target >= Version::R2007 {
|
||||
multiline_tags(w, a, true);
|
||||
}
|
||||
@@ -372,7 +372,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
|
||||
w.f(45, i.row_spacing);
|
||||
}
|
||||
if !i.attribs.is_empty() {
|
||||
for (index, a) in i.attribs.iter().enumerate() {
|
||||
for a in &i.attribs {
|
||||
let ah = w.h();
|
||||
w.s(0, "ATTRIB");
|
||||
w.s(5, ah);
|
||||
@@ -385,7 +385,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
|
||||
w.i(60, 1);
|
||||
}
|
||||
w.s(100, "AcDbText");
|
||||
text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index));
|
||||
text_tags(w, d, &a.text, Some((a, cx.target)), None);
|
||||
if cx.target >= Version::R2007 {
|
||||
multiline_tags(w, a, false);
|
||||
}
|
||||
@@ -627,7 +627,7 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
w.i(71, i64::from(h.associative));
|
||||
w.i(91, h.loops.len() as i64);
|
||||
for l in &h.loops {
|
||||
w.i(92, 2 | i64::from(l.outer) | (l.boundary_flags.unwrap_or(0) & (4 | 8 | 16)));
|
||||
w.i(92, 2 | if l.outer { 1 } else { 0 });
|
||||
let has_bulge = l.vertices.iter().any(|v| v.bulge != 0.0);
|
||||
w.i(72, i64::from(has_bulge));
|
||||
w.i(73, 1);
|
||||
|
||||
@@ -26,7 +26,6 @@ const HEADER_VARS: &[(&str, i32)] = &[
|
||||
("CELTSCALE", 40),
|
||||
("DIMSCALE", 40),
|
||||
("DIMSTYLE", 2),
|
||||
("DIMASSOC", 280),
|
||||
("LUNITS", 70),
|
||||
("LUPREC", 70),
|
||||
("AUNITS", 70),
|
||||
@@ -125,7 +124,6 @@ fn dim_header_vars(w: &mut W, d: &Drawing) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Write modelled HEADER variables with their declared DXF group types, then dimension style variables.
|
||||
pub(super) fn header_vars(w: &mut W, d: &Drawing) {
|
||||
for (name, code) in HEADER_VARS {
|
||||
let Some(v) = d.header.get(name) else { continue };
|
||||
@@ -155,7 +153,7 @@ pub(super) fn header_vars(w: &mut W, d: &Drawing) {
|
||||
w.f(c, f);
|
||||
}
|
||||
}
|
||||
(c @ (62 | 70 | 280 | 290 | 370), v) => {
|
||||
(c @ (62 | 70 | 290 | 370), v) => {
|
||||
if let Some(i) = v.as_i64() {
|
||||
w.s(9, format!("${name}"));
|
||||
w.i(c, i);
|
||||
|
||||
@@ -411,28 +411,22 @@ struct LayoutWriteData<'a> {
|
||||
ucs: Option<&'a Ucs>,
|
||||
/// The layout's limits as read (`None`: the default 0,0 to 12,9).
|
||||
limits: Option<(Vec2, Vec2)>,
|
||||
/// Whether this is the Model layout (block record *Model_Space).
|
||||
model: bool,
|
||||
}
|
||||
|
||||
/// 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. 1024 ("ModelType", DXF Reference, PLOTSETTINGS
|
||||
/// group 70) follows the layout: set for the Model layout, cleared for a paper-space layout even
|
||||
/// when the file had it, since it would mark that layout as model space.
|
||||
fn plot_layout_flags(page: &PageSetup, standard: bool, model: bool) -> i64 {
|
||||
/// 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;
|
||||
const MODEL_TYPE: i64 = 1024;
|
||||
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 },
|
||||
};
|
||||
let kept = if model { kept | MODEL_TYPE } else { kept & !MODEL_TYPE };
|
||||
kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 }
|
||||
}
|
||||
|
||||
@@ -452,7 +446,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
|
||||
// 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, data.model);
|
||||
let plot_flags = plot_layout_flags(page, standard);
|
||||
let plot_type = match page.plot_area.as_str() {
|
||||
"display" => 0,
|
||||
"extents" => 1,
|
||||
@@ -616,7 +610,6 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
|
||||
view: None,
|
||||
ucs: None,
|
||||
limits: None,
|
||||
model: true,
|
||||
},
|
||||
);
|
||||
for (i, (_, brh, l)) in ps_brs.iter().enumerate() {
|
||||
@@ -634,7 +627,6 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
|
||||
view: l.view,
|
||||
ucs: l.ucs.as_ref(),
|
||||
limits: l.limits,
|
||||
model: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -37,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::{dwg_compat_lost, entity_groups, proxies_lost};
|
||||
pub use dxf_write::{entity_groups, proxies_lost};
|
||||
pub use pdf::{PdfOptions, pdf, plot};
|
||||
|
||||
/// How a drawing is saved as DXF or DWG.
|
||||
@@ -164,13 +164,8 @@ pub fn write_noted(d: &Drawing, name: impl AsRef<Path>, opts: &SaveOptions) -> R
|
||||
/// file they came from (`Foreign::version`, not `$ACADVER`, which SAVEAS changes), and the bridge
|
||||
/// reads them as that version.
|
||||
fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec<u8>, craft_dwg::Unwritten)> {
|
||||
let (bridge, omitted) = dxf_write::dwg_bridge(d, version);
|
||||
let (bytes, mut unwritten) = craft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(dwg_error)?;
|
||||
for (kind, omitted) in omitted {
|
||||
let count = unwritten.entry(kind).or_default();
|
||||
*count = count.saturating_add(omitted);
|
||||
}
|
||||
Ok((bytes, unwritten))
|
||||
let bridge = dxf_write::dwg_bridge(d, version);
|
||||
craft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(dwg_error)
|
||||
}
|
||||
|
||||
/// Like [`write`], but image formats (PNG, SVG, PDF) show `window` (a model-space rectangle in
|
||||
|
||||
+1
-534
@@ -111,7 +111,6 @@ fn sample() -> Drawing {
|
||||
loops: vec![HatchLoop {
|
||||
vertices: vec![PolyVertex::new(Vec2::ZERO), PolyVertex::new(Vec2::new(2.0, 0.0)), PolyVertex::new(Vec2::new(2.0, 2.0))],
|
||||
outer: true,
|
||||
boundary_flags: Some(3),
|
||||
sources: Vec::new(),
|
||||
}],
|
||||
scale: 1.0,
|
||||
@@ -423,30 +422,6 @@ fn hostile_dxf_does_not_panic() {
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for #1336: the LAYER table of a DXF had no record cap, so a hostile file could
|
||||
// grow the layer list without bound (its VIEW/UCS/VPORT peers stop at one million records).
|
||||
#[test]
|
||||
fn dxf_layer_table_stops_at_the_record_cap() {
|
||||
use std::fmt::Write as _;
|
||||
let records = 1_000_100;
|
||||
let mut text = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n");
|
||||
for i in 0..records {
|
||||
let _ = write!(text, "0\nLAYER\n2\nL{i}\n");
|
||||
}
|
||||
text.push_str("0\nENDTAB\n0\nENDSEC\n0\nEOF\n");
|
||||
let d = read(text.as_bytes(), "layers.dxf").unwrap();
|
||||
// The exact total, not a range: the layer list stops at 1,000,000 layers, the drawing's own
|
||||
// default layers counted among them, so a cap that truncates early or late fails as loudly as
|
||||
// none at all. The count is a literal on purpose -- if the constant changes, this test must fail
|
||||
// rather than follow it.
|
||||
assert_eq!(
|
||||
d.layers.len(),
|
||||
1_000_000,
|
||||
"the LAYER table must stop at exactly 1,000,000 layers in total, defaults included, reading {records} records, but kept {}",
|
||||
d.layers.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_and_png_export() {
|
||||
let d = sample();
|
||||
@@ -2030,514 +2005,6 @@ fn intl_text(value: &str) -> Text {
|
||||
}
|
||||
}
|
||||
|
||||
fn two_point_text_sample() -> Drawing {
|
||||
let mut drawing = Drawing::new_metric();
|
||||
let mut block = Block::new("Labels");
|
||||
let mut attribs = Vec::new();
|
||||
for (index, halign) in [HAlign::Aligned, HAlign::Fit].into_iter().enumerate() {
|
||||
for multiplier in [1.0, 2.0] {
|
||||
let text =
|
||||
Text { insert: Vec3::ZERO, align_pt: Some(Vec3::new(30.0 * multiplier, 4.0 * multiplier, 0.0)), halign, ..intl_text("SYNTHETIC") };
|
||||
drawing.add(&Space::Model, Common::default(), EntityKind::Text(text.clone())).unwrap();
|
||||
let attribute = Attrib {
|
||||
tag: format!("LABEL{index}_{multiplier}"),
|
||||
text,
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: Default::default(),
|
||||
multiline: None,
|
||||
modes: Default::default(),
|
||||
};
|
||||
block.entities.push(Entity::new(Handle(0x500 + attribs.len() as u64), EntityKind::AttDef(attribute.clone())));
|
||||
attribs.push(attribute);
|
||||
}
|
||||
}
|
||||
drawing.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
|
||||
drawing
|
||||
.add(
|
||||
&Space::Model,
|
||||
Common::default(),
|
||||
EntityKind::Insert(Insert {
|
||||
block: "Labels".into(),
|
||||
insert: Vec3::ZERO,
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs,
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
drawing
|
||||
}
|
||||
|
||||
fn two_point_texts(drawing: &Drawing) -> Vec<&Text> {
|
||||
let mut texts = Vec::new();
|
||||
for entity in drawing.model.iter() {
|
||||
match &entity.kind {
|
||||
EntityKind::Text(text) => texts.push(text),
|
||||
EntityKind::Insert(insert) => texts.extend(insert.attribs.iter().map(|attribute| &attribute.text)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
texts.extend(
|
||||
drawing
|
||||
.block("Labels")
|
||||
.unwrap()
|
||||
.entities
|
||||
.iter()
|
||||
.filter_map(|entity| if let EntityKind::AttDef(attribute) = &entity.kind { Some(&attribute.text) } else { None }),
|
||||
);
|
||||
texts
|
||||
}
|
||||
|
||||
fn edit_two_point_texts(d: &mut Drawing, edit: impl Fn(&mut Text)) {
|
||||
fn store(store: &mut EntityStore, edit: &impl Fn(&mut Text)) {
|
||||
for handle in store.handles() {
|
||||
store.modify(handle, |e| match &mut e.kind {
|
||||
EntityKind::Text(t) => edit(t),
|
||||
EntityKind::AttDef(a) => edit(&mut a.text),
|
||||
EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| edit(&mut a.text)),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
}
|
||||
store(&mut d.model, &edit);
|
||||
for block in d.blocks.values_mut() {
|
||||
store(&mut std::sync::Arc::make_mut(block).entities, &edit);
|
||||
}
|
||||
}
|
||||
|
||||
// Original synthetic DXF records with measurements deliberately different from our stroke font.
|
||||
fn imported_two_point_text_sample() -> Drawing {
|
||||
let tags = craft_dxf::parse(write_dxf(&two_point_text_sample()).as_bytes()).unwrap();
|
||||
let mut altered = tags.clone();
|
||||
// Work on complete records, including their leading group 0.
|
||||
let starts: Vec<usize> = tags.iter().enumerate().filter_map(|(i, t)| (t.code == 0).then_some(i)).chain([tags.len()]).collect();
|
||||
for pair in starts.windows(2) {
|
||||
let record = &tags[pair[0]..pair[1]];
|
||||
if !matches!(record[0].str().as_ref(), "TEXT" | "ATTDEF" | "ATTRIB") {
|
||||
continue;
|
||||
}
|
||||
let number = |code| record.iter().find(|t| t.code == code).map(|t| t.str().parse::<f64>().unwrap()).unwrap_or(0.0);
|
||||
let distance = Vec2::new(number(10), number(20)).dist(Vec2::new(number(11), number(21)));
|
||||
let width = cadcraft_fonts::shape_stroke("SYNTHETIC", 2.5, 1.0, 0.0).width;
|
||||
let aligned = number(72) == 3.0;
|
||||
let code = if aligned { 40 } else { 41 };
|
||||
let dimension = if aligned { 2.5 } else { 1.0 } * distance / width * 1.15;
|
||||
for tag in &mut altered[pair[0]..pair[1]] {
|
||||
if tag.code == code {
|
||||
*tag = craft_dxf::Tag::new(code, craft_dxf::Value::Real(dimension));
|
||||
}
|
||||
if tag.code == 50 {
|
||||
*tag = craft_dxf::Tag::new(50, craft_dxf::Value::Real(0.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
read_dxf(craft_dxf::write_ascii(&altered).as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
fn check_two_point_save(d: &Drawing, name: &str, recompute: bool, rotation: bool) {
|
||||
let saved = read(&write(d, name).unwrap(), name).unwrap();
|
||||
let before = two_point_texts(d);
|
||||
let after = two_point_texts(&saved);
|
||||
assert_eq!(after.len(), before.len());
|
||||
for (original, text) in before.into_iter().zip(&after) {
|
||||
if rotation {
|
||||
assert!((text.rotation - text.insert.xy().angle_to(text.align_pt.unwrap().xy())).abs() < 1e-10, "{name}: {text:?}");
|
||||
}
|
||||
if recompute {
|
||||
let width =
|
||||
cadcraft_fonts::shape_stroke_dir(&original.value, original.height, original.width_factor, original.oblique, Some(false)).width;
|
||||
let scale = original.insert.xy().dist(original.align_pt.unwrap().xy()) / width;
|
||||
let (height, factor) = if original.halign == HAlign::Aligned {
|
||||
(original.height * scale, original.width_factor)
|
||||
} else {
|
||||
(original.height, original.width_factor * scale)
|
||||
};
|
||||
assert!((text.height / height - 1.0).abs() < 1e-12, "height: {name}");
|
||||
assert!((text.width_factor / factor - 1.0).abs() < 1e-12, "width factor: {name}");
|
||||
} else {
|
||||
assert!((text.height - original.height).abs() < 1e-10, "{name}");
|
||||
assert!((text.width_factor - original.width_factor).abs() < 1e-10, "{name}");
|
||||
}
|
||||
}
|
||||
let again = read(&write(&saved, name).unwrap(), name).unwrap();
|
||||
for (first, second) in after.into_iter().zip(two_point_texts(&again)) {
|
||||
assert!((first.rotation - second.rotation).abs() < 1e-10, "{name}");
|
||||
assert!((first.height - second.height).abs() < 1e-10, "{name}");
|
||||
assert!((first.width_factor - second.width_factor).abs() < 1e-10, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
fn two_point_formats() -> [&'static str; 2] {
|
||||
crate::dwg_worker::allow_in_process();
|
||||
["fit.dxf", "fit.dwg"]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_imported_measurements_survive_save() {
|
||||
for name in two_point_formats() {
|
||||
check_two_point_save(&imported_two_point_text_sample(), name, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_imported_rotation_follows_points() {
|
||||
for name in two_point_formats() {
|
||||
check_two_point_save(&imported_two_point_text_sample(), name, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
fn transform_two_point_sample(d: &mut Drawing, matrix: cadcraft_geom::Mat3) {
|
||||
// Transform the reference itself so attached attributes follow the production path.
|
||||
for handle in d.model.handles() {
|
||||
d.model.modify(handle, |entity| entity.kind.transform(&matrix));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_imported_measurements_survive_move() {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::translate(Vec2::new(47.0, -19.0)));
|
||||
for name in two_point_formats() {
|
||||
check_two_point_save(&d, name, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_imported_measurements_survive_rotate() {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::rotate_about(Vec2::new(7.0, -3.0), 0.73));
|
||||
for name in two_point_formats() {
|
||||
check_two_point_save(&d, name, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_imported_measurements_follow_uniform_scale() {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
let imported = d.clone();
|
||||
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::scale_about(Vec2::new(7.0, -3.0), 2.0));
|
||||
for (before, scaled) in two_point_texts(&imported).into_iter().zip(two_point_texts(&d)).take(8) {
|
||||
assert!((scaled.height - before.height * 2.0).abs() < 1e-10);
|
||||
assert!((scaled.width_factor - before.width_factor).abs() < 1e-10);
|
||||
}
|
||||
for name in two_point_formats() {
|
||||
check_two_point_save(&d, name, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_changed_fit_height_recomputes_measurements() {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
edit_two_point_texts(&mut d, |t| t.height *= 1.4);
|
||||
for name in two_point_formats() {
|
||||
// Aligned height is derived from distance, so editing it alone preserves the import.
|
||||
let saved = read(&write(&d, name).unwrap(), name).unwrap();
|
||||
for (before, after) in two_point_texts(&d).into_iter().zip(two_point_texts(&saved)) {
|
||||
if before.halign == HAlign::Fit {
|
||||
let expected = cadcraft_render::fitted_text_entity(&d, before, &before.value);
|
||||
assert!((after.width_factor / expected.width_factor - 1.0).abs() < 1e-12);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_imported_distance_uses_relative_tolerance() {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
edit_two_point_texts(&mut d, |t| {
|
||||
let point = t.align_pt.as_mut().unwrap();
|
||||
point.x *= 1.0 + 0.5e-9;
|
||||
point.y *= 1.0 + 0.5e-9;
|
||||
});
|
||||
for name in two_point_formats() {
|
||||
check_two_point_save(&d, name, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_changed_fitting_inputs_recompute_measurements() {
|
||||
for input in ["style", "oblique", "width factor"] {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
edit_two_point_texts(&mut d, |t| match input {
|
||||
"style" => t.style = "Replacement".into(),
|
||||
"oblique" => t.oblique += 0.2,
|
||||
_ => t.width_factor *= 1.2,
|
||||
});
|
||||
for name in two_point_formats() {
|
||||
check_two_point_save(&d, name, true, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_changed_string_recomputes_measurements() {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
edit_two_point_texts(&mut d, |t| t.value.push_str(" EDITED"));
|
||||
for name in two_point_formats() {
|
||||
check_two_point_save(&d, name, true, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_changed_distance_scales_aligned_and_recomputes_fit() {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
let imported = d.clone();
|
||||
edit_two_point_texts(&mut d, |t| t.align_pt.as_mut().unwrap().x *= 1.8);
|
||||
for name in two_point_formats() {
|
||||
let saved = read(&write(&d, name).unwrap(), name).unwrap();
|
||||
for ((before, edited), after) in two_point_texts(&imported).into_iter().zip(two_point_texts(&d)).zip(two_point_texts(&saved)) {
|
||||
if before.halign == HAlign::Aligned {
|
||||
let ratio = edited.insert.xy().dist(edited.align_pt.unwrap().xy()) / before.insert.xy().dist(before.align_pt.unwrap().xy());
|
||||
assert!((after.height / (before.height * ratio) - 1.0).abs() < 1e-12, "{name}");
|
||||
} else {
|
||||
let expected = cadcraft_render::fitted_text_entity(&d, edited, &edited.value);
|
||||
assert!((after.width_factor / expected.width_factor - 1.0).abs() < 1e-12, "{name}");
|
||||
}
|
||||
}
|
||||
check_two_point_save(&saved, name, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_authored_text_recomputes_measurements() {
|
||||
for name in two_point_formats() {
|
||||
check_two_point_save(&two_point_text_sample(), name, true, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_text_save_keeps_degenerate_and_unrelated_values() {
|
||||
for halign in [HAlign::Left, HAlign::Center, HAlign::Right, HAlign::Middle, HAlign::Aligned, HAlign::Fit] {
|
||||
for valign in [VAlign::Baseline, VAlign::Bottom] {
|
||||
for align_pt in [None, Some(Vec3::ZERO), Some(Vec3::new(30.0, 4.0, 0.0))] {
|
||||
if matches!(halign, HAlign::Aligned | HAlign::Fit) && align_pt.is_some_and(|point| point != Vec3::ZERO) {
|
||||
continue;
|
||||
}
|
||||
let text = Text { insert: Vec3::ZERO, align_pt, halign, valign, rotation: 0.7, width_factor: 0.8, ..intl_text("SYNTHETIC") };
|
||||
let mut drawing = Drawing::new_metric();
|
||||
drawing.add(&Space::Model, Common::default(), EntityKind::Text(text.clone())).unwrap();
|
||||
let saved = read(&write(&drawing, "edge.dxf").unwrap(), "edge.dxf").unwrap();
|
||||
let back = first(&saved, |kind| if let EntityKind::Text(text) = kind { Some(text.clone()) } else { None });
|
||||
assert!((text.rotation - back.rotation).abs() < 1e-12);
|
||||
assert!((text.height - back.height).abs() < 1e-10);
|
||||
assert!((text.width_factor - back.width_factor).abs() < 1e-10);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_imported_degenerate_geometry_keeps_edited_height() {
|
||||
for missing in [false, true] {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
let handle = d.model.handles()[0];
|
||||
d.model.modify(handle, |entity| {
|
||||
if let EntityKind::Text(t) = &mut entity.kind {
|
||||
t.insert = Vec3::ZERO;
|
||||
t.align_pt = if missing { None } else { Some(Vec3::ZERO) };
|
||||
t.height = 2.0;
|
||||
}
|
||||
});
|
||||
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
|
||||
snapshot.insert = Vec3::ZERO;
|
||||
snapshot.align_pt = if missing { None } else { Some(Vec3::ZERO) };
|
||||
snapshot.height = 2.0;
|
||||
let mut d = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
|
||||
let handle = d.model.handles()[0];
|
||||
let imported = first(&d, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
|
||||
assert_eq!(imported.align_pt, if missing { None } else { Some(Vec3::ZERO) });
|
||||
d.model.modify(handle, |entity| {
|
||||
if let EntityKind::Text(t) = &mut entity.kind {
|
||||
t.height = 4.0;
|
||||
}
|
||||
});
|
||||
let saved = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
|
||||
let text = first(&saved, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
|
||||
assert!((text.height - 4.0).abs() < 1e-10, "missing: {missing}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_imported_nonfinite_geometry_keeps_edited_height() {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
let handle = d.model.handles()[0];
|
||||
d.model.modify(handle, |entity| {
|
||||
if let EntityKind::Text(t) = &mut entity.kind {
|
||||
assert_eq!(t.halign, HAlign::Aligned);
|
||||
t.insert = Vec3::ZERO;
|
||||
t.align_pt = Some(Vec3::new(f64::INFINITY, 0.0, 0.0));
|
||||
t.height = 4.0;
|
||||
}
|
||||
});
|
||||
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
|
||||
snapshot.insert = Vec3::ZERO;
|
||||
snapshot.align_pt = Some(Vec3::new(f64::INFINITY, 0.0, 0.0));
|
||||
snapshot.height = 2.0;
|
||||
let saved = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
|
||||
let text = first(&saved, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
|
||||
assert!((text.height - 4.0).abs() < 1e-10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_imported_empty_attdef_keeps_dimensions_when_points_move() {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
let block = std::sync::Arc::make_mut(d.blocks.get_mut("Labels").unwrap());
|
||||
let handle = block.entities.handles()[0];
|
||||
block.entities.modify(handle, |entity| {
|
||||
if let EntityKind::AttDef(a) = &mut entity.kind {
|
||||
a.text.value.clear();
|
||||
a.text.insert = Vec3::ZERO;
|
||||
a.text.align_pt = Some(Vec3::new(10.0, 0.0, 0.0));
|
||||
a.text.height = 2.0;
|
||||
a.text.width_factor = 0.8;
|
||||
}
|
||||
});
|
||||
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
|
||||
snapshot.value.clear();
|
||||
snapshot.insert = Vec3::ZERO;
|
||||
snapshot.align_pt = Some(Vec3::new(10.0, 0.0, 0.0));
|
||||
snapshot.height = 2.0;
|
||||
snapshot.width_factor = 0.8;
|
||||
let mut d = read(&write(&d, "empty.dxf").unwrap(), "empty.dxf").unwrap();
|
||||
let block = std::sync::Arc::make_mut(d.blocks.get_mut("Labels").unwrap());
|
||||
let handle = block.entities.handles()[0];
|
||||
block.entities.modify(handle, |entity| {
|
||||
if let EntityKind::AttDef(a) = &mut entity.kind {
|
||||
a.text.align_pt = Some(Vec3::new(0.0, 20.0, 0.0));
|
||||
}
|
||||
});
|
||||
let saved = read(&write(&d, "empty.dxf").unwrap(), "empty.dxf").unwrap();
|
||||
let entity = saved.block("Labels").unwrap().entities.iter().next().unwrap();
|
||||
let EntityKind::AttDef(a) = &entity.kind else { panic!("expected ATTDEF") };
|
||||
assert!((a.text.height - 2.0).abs() < 1e-10);
|
||||
assert!((a.text.width_factor - 0.8).abs() < 1e-10);
|
||||
assert!((a.text.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_changed_style_definition_recomputes_measurements() {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
d.text_styles.iter_mut().find(|style| style.name.eq_ignore_ascii_case("Standard")).unwrap().backwards = true;
|
||||
for name in two_point_formats() {
|
||||
let saved = read(&write(&d, name).unwrap(), name).unwrap();
|
||||
for (before, after) in two_point_texts(&d).into_iter().zip(two_point_texts(&saved)) {
|
||||
let expected = cadcraft_render::fitted_text_entity(&d, before, &before.value);
|
||||
assert!((after.height - expected.height).abs() < 1e-9, "{name}");
|
||||
assert!((after.width_factor - expected.width_factor).abs() < 1e-9, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_changed_justification_recomputes_measurements() {
|
||||
for horizontal in [true, false] {
|
||||
let mut d = imported_two_point_text_sample();
|
||||
edit_two_point_texts(&mut d, |t| {
|
||||
if horizontal {
|
||||
t.halign = if t.halign == HAlign::Fit { HAlign::Aligned } else { HAlign::Fit };
|
||||
} else {
|
||||
t.valign = VAlign::Middle;
|
||||
}
|
||||
});
|
||||
for name in two_point_formats() {
|
||||
check_two_point_save(&d, name, true, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_dwg_source_preserves_imported_measurements() {
|
||||
let imported = imported_two_point_text_sample();
|
||||
crate::dwg_worker::allow_in_process();
|
||||
let dwg = write(&imported, "source.dwg").unwrap();
|
||||
let reopened = read(&dwg, "source.dwg").unwrap();
|
||||
assert!(!reopened.foreign.text_fits.is_empty());
|
||||
for name in two_point_formats() {
|
||||
check_two_point_save(&reopened, name, false, true);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_block_layout_and_empty_default() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let mut block = Block::new("Labels");
|
||||
for (index, halign) in [HAlign::Aligned, HAlign::Fit].into_iter().enumerate() {
|
||||
let text = Text { halign, valign: VAlign::Middle, align_pt: Some(Vec3::new(30.0, 4.0, 0.0)), ..intl_text("SYNTHETIC") };
|
||||
block.entities.push(Entity::new(Handle(0x500 + index as u64), EntityKind::Text(text.clone())));
|
||||
d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Text(text)).unwrap();
|
||||
let empty = Text { halign, align_pt: Some(Vec3::new(30.0, 4.0, 0.0)), ..intl_text("") };
|
||||
block.entities.push(Entity::new(
|
||||
Handle(0x510 + index as u64),
|
||||
EntityKind::AttDef(Attrib {
|
||||
tag: "LABEL".into(),
|
||||
text: empty,
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: Default::default(),
|
||||
multiline: None,
|
||||
modes: Default::default(),
|
||||
}),
|
||||
));
|
||||
}
|
||||
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
|
||||
for name in two_point_formats() {
|
||||
let saved = read(&write(&d, name).unwrap(), name).unwrap();
|
||||
for (before, after) in d.block("Labels").unwrap().entities.iter().zip(saved.block("Labels").unwrap().entities.iter()) {
|
||||
match (&before.kind, &after.kind) {
|
||||
(EntityKind::Text(a), EntityKind::Text(b)) => {
|
||||
let expected = cadcraft_render::fitted_text_entity(&d, a, &a.value);
|
||||
assert!((b.height - expected.height).abs() < 1e-9);
|
||||
assert!((b.width_factor - expected.width_factor).abs() < 1e-9);
|
||||
}
|
||||
(EntityKind::AttDef(a), EntityKind::AttDef(b)) => {
|
||||
assert!((a.text.height - b.text.height).abs() < 1e-9);
|
||||
assert!((a.text.width_factor - b.text.width_factor).abs() < 1e-9);
|
||||
assert!((b.text.rotation - b.text.insert.xy().angle_to(b.text.align_pt.unwrap().xy())).abs() < 1e-9);
|
||||
}
|
||||
_ => panic!("unexpected block entity"),
|
||||
}
|
||||
}
|
||||
let before = &d.layout("Layout1").unwrap().entities;
|
||||
let after = &saved.layout("Layout1").unwrap().entities;
|
||||
for (a, b) in before.iter().zip(after.iter()) {
|
||||
if let (EntityKind::Text(a), EntityKind::Text(b)) = (&a.kind, &b.kind) {
|
||||
let expected = cadcraft_render::fitted_text_entity(&d, a, &a.value);
|
||||
assert!((b.height - expected.height).abs() < 1e-9);
|
||||
assert!((b.width_factor - expected.width_factor).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
assert_eq!(before.len(), after.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_nonuniform_insert_keeps_attribute_fit_in_its_stored_coordinates() {
|
||||
let mut d = two_point_text_sample();
|
||||
for h in d.model.handles() {
|
||||
d.model.modify(h, |e| {
|
||||
if let EntityKind::Insert(i) = &mut e.kind {
|
||||
i.scale = Vec3::new(2.0, 0.5, 1.0);
|
||||
}
|
||||
});
|
||||
}
|
||||
for name in two_point_formats() {
|
||||
let saved = read(&write(&d, name).unwrap(), name).unwrap();
|
||||
let insert = saved.model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i) } else { None }).unwrap();
|
||||
let fit = insert.attribs.iter().find(|a| a.text.halign == HAlign::Fit).unwrap();
|
||||
let width = cadcraft_fonts::shape_stroke_dir(&fit.text.value, fit.text.height, fit.text.width_factor, fit.text.oblique, Some(false)).width;
|
||||
assert!((width - fit.text.insert.xy().dist(fit.text.align_pt.unwrap().xy())).abs() < 1e-9);
|
||||
assert!((insert.scale.x - 2.0).abs() < 1e-9 && (insert.scale.y - 0.5).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
fn intl_sample() -> Drawing {
|
||||
let mut d = Drawing::new_metric();
|
||||
let layer = format!("层 {INTL}");
|
||||
@@ -2952,7 +2419,7 @@ fn gradient_sample() -> (Drawing, Vec<Option<Gradient>>) {
|
||||
let h = Hatch {
|
||||
pattern: "SOLID".into(),
|
||||
solid: true,
|
||||
loops: vec![HatchLoop { vertices: square.clone(), outer: true, boundary_flags: Some(3), sources: Vec::new() }],
|
||||
loops: vec![HatchLoop { vertices: square.clone(), outer: true, sources: Vec::new() }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: false,
|
||||
|
||||
@@ -1,508 +0,0 @@
|
||||
0 SECTION
|
||||
2 HEADER
|
||||
9 $ACADVER
|
||||
1 AC1032
|
||||
9 $HANDSEED
|
||||
5 200
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 TABLES
|
||||
0 TABLE
|
||||
2 BLOCK_RECORD
|
||||
5 1
|
||||
330 0
|
||||
100 AcDbSymbolTable
|
||||
70 5
|
||||
0 BLOCK_RECORD
|
||||
5 1F
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 *Model_Space
|
||||
340 0
|
||||
0 BLOCK_RECORD
|
||||
5 1E
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 *Paper_Space
|
||||
340 0
|
||||
0 BLOCK_RECORD
|
||||
5 1D
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 60
|
||||
102 }
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 Row
|
||||
340 0
|
||||
70 0
|
||||
280 1
|
||||
281 1
|
||||
0 BLOCK_RECORD
|
||||
5 1C
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 70
|
||||
102 }
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 Fan
|
||||
340 0
|
||||
70 0
|
||||
280 1
|
||||
281 1
|
||||
0 BLOCK_RECORD
|
||||
5 1B
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 80
|
||||
102 }
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 Grid
|
||||
340 0
|
||||
70 0
|
||||
280 1
|
||||
281 1
|
||||
0 ENDTAB
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 BLOCKS
|
||||
0 BLOCK
|
||||
5 20
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 *Model_Space
|
||||
70 0
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 *Model_Space
|
||||
1
|
||||
0 ENDBLK
|
||||
5 21
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 BLOCK
|
||||
5 24
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 Row
|
||||
70 2
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 Row
|
||||
1
|
||||
0 LWPOLYLINE
|
||||
5 30
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbPolyline
|
||||
90 4
|
||||
70 1
|
||||
10 0
|
||||
20 0
|
||||
10 2
|
||||
20 0
|
||||
10 2
|
||||
20 2
|
||||
10 0
|
||||
20 2
|
||||
1001 AcDbBlockRepETag
|
||||
1070 1
|
||||
1071 0
|
||||
1005 30
|
||||
0 ENDBLK
|
||||
5 25
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 BLOCK
|
||||
5 26
|
||||
330 1C
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 Fan
|
||||
70 2
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 Fan
|
||||
1
|
||||
0 CIRCLE
|
||||
5 40
|
||||
330 1C
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbCircle
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
40 1
|
||||
1001 AcDbBlockRepETag
|
||||
1070 1
|
||||
1071 0
|
||||
1005 40
|
||||
0 ENDBLK
|
||||
5 27
|
||||
330 1C
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 BLOCK
|
||||
5 28
|
||||
330 1B
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 Grid
|
||||
70 2
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 Grid
|
||||
1
|
||||
0 CIRCLE
|
||||
5 50
|
||||
330 1B
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbCircle
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
40 1
|
||||
1001 AcDbBlockRepETag
|
||||
1070 1
|
||||
1071 0
|
||||
1005 50
|
||||
0 ENDBLK
|
||||
5 29
|
||||
330 1B
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 ENTITIES
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 OBJECTS
|
||||
0 DICTIONARY
|
||||
5 C
|
||||
330 0
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
0 DICTIONARY
|
||||
5 60
|
||||
330 1D
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 ACAD_ENHANCEDBLOCK
|
||||
360 61
|
||||
0 ACAD_EVALUATION_GRAPH
|
||||
5 61
|
||||
330 60
|
||||
100 AcDbEvalGraph
|
||||
96 4
|
||||
97 4
|
||||
91 0
|
||||
93 32
|
||||
95 1
|
||||
360 62
|
||||
91 1
|
||||
93 32
|
||||
95 4
|
||||
360 63
|
||||
0 BLOCKLINEARPARAMETER
|
||||
5 62
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 1
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Linear
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock2PtParameter
|
||||
1010 0
|
||||
1020 0
|
||||
1030 0
|
||||
1011 2
|
||||
1021 0
|
||||
1031 0
|
||||
170 4
|
||||
91 3
|
||||
91 2
|
||||
91 0
|
||||
91 0
|
||||
171 0
|
||||
172 0
|
||||
173 0
|
||||
174 0
|
||||
177 0
|
||||
100 AcDbBlockLinearParameter
|
||||
305 Distance1
|
||||
306
|
||||
140 0
|
||||
307
|
||||
96 0
|
||||
141 0
|
||||
142 0
|
||||
143 0
|
||||
175 0
|
||||
0 BLOCKARRAYACTION
|
||||
5 63
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 4
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Array
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockAction
|
||||
70 0
|
||||
71 1
|
||||
330 30
|
||||
1010 4
|
||||
1020 3
|
||||
1030 0
|
||||
100 AcDbBlockArrayAction
|
||||
92 1
|
||||
93 1
|
||||
94 1
|
||||
95 1
|
||||
301 Base
|
||||
302 End
|
||||
303 UpdatedBase
|
||||
304 UpdatedEnd
|
||||
140 1
|
||||
141 3
|
||||
0 DICTIONARY
|
||||
5 70
|
||||
330 1C
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 ACAD_ENHANCEDBLOCK
|
||||
360 71
|
||||
0 ACAD_EVALUATION_GRAPH
|
||||
5 71
|
||||
330 70
|
||||
100 AcDbEvalGraph
|
||||
96 4
|
||||
97 4
|
||||
91 0
|
||||
93 32
|
||||
95 1
|
||||
360 72
|
||||
91 1
|
||||
93 32
|
||||
95 4
|
||||
360 73
|
||||
0 BLOCKPOLARPARAMETER
|
||||
5 72
|
||||
330 71
|
||||
100 AcDbEvalExpr
|
||||
90 1
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Polar
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock2PtParameter
|
||||
1010 0
|
||||
1020 0
|
||||
1030 0
|
||||
1011 3
|
||||
1021 4
|
||||
1031 0
|
||||
170 4
|
||||
91 3
|
||||
91 2
|
||||
91 0
|
||||
91 0
|
||||
171 0
|
||||
172 0
|
||||
173 0
|
||||
174 0
|
||||
177 0
|
||||
100 AcDbBlockPolarParameter
|
||||
305 Distance1
|
||||
306
|
||||
307 Angle1
|
||||
308
|
||||
140 0
|
||||
309
|
||||
96 0
|
||||
141 0
|
||||
142 0
|
||||
143 0
|
||||
175 0
|
||||
410
|
||||
97 0
|
||||
145 0
|
||||
146 0
|
||||
147 0
|
||||
176 0
|
||||
0 BLOCKARRAYACTION
|
||||
5 73
|
||||
330 71
|
||||
100 AcDbEvalExpr
|
||||
90 4
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Array
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockAction
|
||||
70 0
|
||||
71 1
|
||||
330 40
|
||||
1010 4
|
||||
1020 5
|
||||
1030 0
|
||||
100 AcDbBlockArrayAction
|
||||
92 1
|
||||
93 1
|
||||
94 1
|
||||
95 1
|
||||
301 Base
|
||||
302 End
|
||||
303 UpdatedBase
|
||||
304 UpdatedEnd
|
||||
140 1
|
||||
141 2
|
||||
0 DICTIONARY
|
||||
5 80
|
||||
330 1B
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 ACAD_ENHANCEDBLOCK
|
||||
360 81
|
||||
0 ACAD_EVALUATION_GRAPH
|
||||
5 81
|
||||
330 80
|
||||
100 AcDbEvalGraph
|
||||
96 4
|
||||
97 4
|
||||
91 0
|
||||
93 32
|
||||
95 1
|
||||
360 82
|
||||
91 1
|
||||
93 32
|
||||
95 6
|
||||
360 83
|
||||
0 BLOCKXYPARAMETER
|
||||
5 82
|
||||
330 81
|
||||
100 AcDbEvalExpr
|
||||
90 1
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 XY
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock2PtParameter
|
||||
1010 0
|
||||
1020 0
|
||||
1030 0
|
||||
1011 10
|
||||
1021 10
|
||||
1031 0
|
||||
170 4
|
||||
91 3
|
||||
91 2
|
||||
91 4
|
||||
91 5
|
||||
171 0
|
||||
172 0
|
||||
173 0
|
||||
174 0
|
||||
177 0
|
||||
100 AcDbBlockXYParameter
|
||||
305 Y Distance1
|
||||
306 X Distance1
|
||||
307
|
||||
308
|
||||
141 0
|
||||
140 0
|
||||
309
|
||||
97 1
|
||||
146 0
|
||||
147 0
|
||||
148 0
|
||||
176 0
|
||||
410
|
||||
96 1
|
||||
142 0
|
||||
143 0
|
||||
144 0
|
||||
175 0
|
||||
0 BLOCKARRAYACTION
|
||||
5 83
|
||||
330 81
|
||||
100 AcDbEvalExpr
|
||||
90 6
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Array
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockAction
|
||||
70 0
|
||||
71 1
|
||||
330 50
|
||||
1010 12
|
||||
1020 12
|
||||
1030 0
|
||||
100 AcDbBlockArrayAction
|
||||
92 1
|
||||
93 1
|
||||
94 1
|
||||
95 1
|
||||
301 Base
|
||||
302 End
|
||||
303 UpdatedBase
|
||||
304 UpdatedEnd
|
||||
140 4
|
||||
141 5
|
||||
0 ENDSEC
|
||||
0 EOF
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,813 +0,0 @@
|
||||
0 SECTION
|
||||
2 HEADER
|
||||
9 $ACADVER
|
||||
1 AC1032
|
||||
9 $HANDSEED
|
||||
5 200
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 TABLES
|
||||
0 TABLE
|
||||
2 BLOCK_RECORD
|
||||
5 1
|
||||
330 0
|
||||
100 AcDbSymbolTable
|
||||
70 6
|
||||
0 BLOCK_RECORD
|
||||
5 1F
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 *Model_Space
|
||||
340 0
|
||||
0 BLOCK_RECORD
|
||||
5 1E
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 *Paper_Space
|
||||
340 0
|
||||
0 BLOCK_RECORD
|
||||
5 1D
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 60
|
||||
102 }
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 Grow
|
||||
340 0
|
||||
70 0
|
||||
280 1
|
||||
281 1
|
||||
0 BLOCK_RECORD
|
||||
5 1C
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 70
|
||||
102 }
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 Pinned
|
||||
340 0
|
||||
70 0
|
||||
280 1
|
||||
281 1
|
||||
0 BLOCK_RECORD
|
||||
5 1B
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 80
|
||||
102 }
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 Sheet
|
||||
340 0
|
||||
70 0
|
||||
280 1
|
||||
281 1
|
||||
0 BLOCK_RECORD
|
||||
5 1A
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 90
|
||||
102 }
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 Tag
|
||||
340 0
|
||||
70 0
|
||||
280 1
|
||||
281 1
|
||||
0 ENDTAB
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 BLOCKS
|
||||
0 BLOCK
|
||||
5 20
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 *Model_Space
|
||||
70 0
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 *Model_Space
|
||||
1
|
||||
0 ENDBLK
|
||||
5 21
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 BLOCK
|
||||
5 24
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 Grow
|
||||
70 2
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 Grow
|
||||
1
|
||||
0 LWPOLYLINE
|
||||
5 30
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbPolyline
|
||||
90 4
|
||||
70 1
|
||||
10 0
|
||||
20 0
|
||||
10 2
|
||||
20 0
|
||||
10 2
|
||||
20 2
|
||||
10 0
|
||||
20 2
|
||||
1001 AcDbBlockRepETag
|
||||
1070 1
|
||||
1071 1
|
||||
1005 30
|
||||
0 CIRCLE
|
||||
5 31
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbCircle
|
||||
10 1
|
||||
20 1
|
||||
30 0
|
||||
40 0.5
|
||||
1001 AcDbBlockRepETag
|
||||
1070 1
|
||||
1071 2
|
||||
1005 31
|
||||
0 ENDBLK
|
||||
5 25
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 BLOCK
|
||||
5 26
|
||||
330 1C
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 Pinned
|
||||
70 2
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 Pinned
|
||||
1
|
||||
0 LWPOLYLINE
|
||||
5 40
|
||||
330 1C
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbPolyline
|
||||
90 4
|
||||
70 1
|
||||
10 0
|
||||
20 0
|
||||
10 2
|
||||
20 0
|
||||
10 2
|
||||
20 2
|
||||
10 0
|
||||
20 2
|
||||
1001 AcDbBlockRepETag
|
||||
1070 1
|
||||
1071 1
|
||||
1005 40
|
||||
0 ENDBLK
|
||||
5 27
|
||||
330 1C
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 BLOCK
|
||||
5 28
|
||||
330 1B
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 Sheet
|
||||
70 2
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 Sheet
|
||||
1
|
||||
0 LWPOLYLINE
|
||||
5 50
|
||||
330 1B
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbPolyline
|
||||
90 4
|
||||
70 1
|
||||
10 0
|
||||
20 0
|
||||
10 2
|
||||
20 0
|
||||
10 2
|
||||
20 2
|
||||
10 0
|
||||
20 2
|
||||
1001 AcDbBlockRepETag
|
||||
1070 1
|
||||
1071 1
|
||||
1005 50
|
||||
0 ENDBLK
|
||||
5 29
|
||||
330 1B
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 BLOCK
|
||||
5 2A
|
||||
330 1A
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 Tag
|
||||
70 2
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 Tag
|
||||
1
|
||||
0 LINE
|
||||
5 B0
|
||||
330 1A
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbLine
|
||||
10 1
|
||||
20 0
|
||||
30 0
|
||||
11 4
|
||||
21 0
|
||||
31 0
|
||||
1001 AcDbBlockRepETag
|
||||
1070 1
|
||||
1071 1
|
||||
1005 B0
|
||||
0 CIRCLE
|
||||
5 B1
|
||||
330 1A
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbCircle
|
||||
10 4
|
||||
20 0
|
||||
30 0
|
||||
40 0.25
|
||||
1001 AcDbBlockRepETag
|
||||
1070 1
|
||||
1071 2
|
||||
1005 B1
|
||||
0 CIRCLE
|
||||
5 B2
|
||||
330 1A
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbCircle
|
||||
10 2
|
||||
20 2
|
||||
30 0
|
||||
40 0.5
|
||||
1001 AcDbBlockRepETag
|
||||
1070 1
|
||||
1071 3
|
||||
1005 B2
|
||||
0 ENDBLK
|
||||
5 2B
|
||||
330 1A
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 ENTITIES
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 OBJECTS
|
||||
0 DICTIONARY
|
||||
5 C
|
||||
330 0
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
0 DICTIONARY
|
||||
5 60
|
||||
330 1D
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 ACAD_ENHANCEDBLOCK
|
||||
360 61
|
||||
0 ACAD_EVALUATION_GRAPH
|
||||
5 61
|
||||
330 60
|
||||
100 AcDbEvalGraph
|
||||
96 3
|
||||
97 3
|
||||
91 0
|
||||
93 32
|
||||
95 1
|
||||
360 62
|
||||
91 1
|
||||
93 32
|
||||
95 2
|
||||
360 63
|
||||
91 2
|
||||
93 32
|
||||
95 3
|
||||
360 64
|
||||
0 BLOCKLINEARPARAMETER
|
||||
5 62
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 1
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Linear
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock2PtParameter
|
||||
1010 0
|
||||
1020 0
|
||||
1030 0
|
||||
1011 2
|
||||
1021 0
|
||||
1031 0
|
||||
170 4
|
||||
91 3
|
||||
91 2
|
||||
91 0
|
||||
91 0
|
||||
171 0
|
||||
172 0
|
||||
173 0
|
||||
174 0
|
||||
177 0
|
||||
100 AcDbBlockLinearParameter
|
||||
305 Distance1
|
||||
306
|
||||
140 0
|
||||
307
|
||||
96 1
|
||||
141 0
|
||||
142 0
|
||||
143 0
|
||||
175 0
|
||||
0 BLOCKPOINTPARAMETER
|
||||
5 63
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 2
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Point
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock1PtParameter
|
||||
1010 2
|
||||
1020 2
|
||||
1030 0
|
||||
93 0
|
||||
170 0
|
||||
171 0
|
||||
100 AcDbBlockPointParameter
|
||||
303 Position1
|
||||
304
|
||||
1011 2
|
||||
1021 2
|
||||
1031 0
|
||||
0 BLOCKSCALEACTION
|
||||
5 64
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 3
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Scale
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockAction
|
||||
70 0
|
||||
71 3
|
||||
330 30
|
||||
330 31
|
||||
330 63
|
||||
1010 4
|
||||
1020 3
|
||||
1030 0
|
||||
100 AcDbBlockActionWithBasePt
|
||||
92 1
|
||||
93 1
|
||||
301 UpdatedBaseX
|
||||
302 UpdatedBaseY
|
||||
1011 0
|
||||
1021 0
|
||||
1031 0
|
||||
280 1
|
||||
1012 0
|
||||
1022 0
|
||||
1032 0
|
||||
100 AcDbBlockScaleAction
|
||||
94 1
|
||||
95 1
|
||||
96 1
|
||||
303 Scale
|
||||
304 XScale
|
||||
305 YScale
|
||||
0 DICTIONARY
|
||||
5 70
|
||||
330 1C
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 ACAD_ENHANCEDBLOCK
|
||||
360 71
|
||||
0 ACAD_EVALUATION_GRAPH
|
||||
5 71
|
||||
330 70
|
||||
100 AcDbEvalGraph
|
||||
96 2
|
||||
97 2
|
||||
91 0
|
||||
93 32
|
||||
95 1
|
||||
360 72
|
||||
91 1
|
||||
93 32
|
||||
95 2
|
||||
360 73
|
||||
0 BLOCKLINEARPARAMETER
|
||||
5 72
|
||||
330 71
|
||||
100 AcDbEvalExpr
|
||||
90 1
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Linear
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock2PtParameter
|
||||
1010 0
|
||||
1020 0
|
||||
1030 0
|
||||
1011 2
|
||||
1021 0
|
||||
1031 0
|
||||
170 4
|
||||
91 3
|
||||
91 2
|
||||
91 0
|
||||
91 0
|
||||
171 0
|
||||
172 0
|
||||
173 0
|
||||
174 0
|
||||
177 0
|
||||
100 AcDbBlockLinearParameter
|
||||
305 Distance1
|
||||
306
|
||||
140 0
|
||||
307
|
||||
96 0
|
||||
141 0
|
||||
142 0
|
||||
143 0
|
||||
175 0
|
||||
0 BLOCKSCALEACTION
|
||||
5 73
|
||||
330 71
|
||||
100 AcDbEvalExpr
|
||||
90 2
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Scale
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockAction
|
||||
70 0
|
||||
71 1
|
||||
330 40
|
||||
1010 4
|
||||
1020 3
|
||||
1030 0
|
||||
100 AcDbBlockActionWithBasePt
|
||||
92 1
|
||||
93 1
|
||||
301 UpdatedBaseX
|
||||
302 UpdatedBaseY
|
||||
1011 0
|
||||
1021 0
|
||||
1031 0
|
||||
280 0
|
||||
1012 2
|
||||
1022 2
|
||||
1032 0
|
||||
100 AcDbBlockScaleAction
|
||||
94 1
|
||||
95 1
|
||||
96 1
|
||||
303 Scale
|
||||
304 XScale
|
||||
305 YScale
|
||||
0 DICTIONARY
|
||||
5 80
|
||||
330 1B
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 ACAD_ENHANCEDBLOCK
|
||||
360 81
|
||||
0 ACAD_EVALUATION_GRAPH
|
||||
5 81
|
||||
330 80
|
||||
100 AcDbEvalGraph
|
||||
96 2
|
||||
97 2
|
||||
91 0
|
||||
93 32
|
||||
95 1
|
||||
360 82
|
||||
91 1
|
||||
93 32
|
||||
95 2
|
||||
360 83
|
||||
0 BLOCKXYPARAMETER
|
||||
5 82
|
||||
330 81
|
||||
100 AcDbEvalExpr
|
||||
90 1
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 XY
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock2PtParameter
|
||||
1010 0
|
||||
1020 0
|
||||
1030 0
|
||||
1011 2
|
||||
1021 2
|
||||
1031 0
|
||||
170 4
|
||||
91 3
|
||||
91 2
|
||||
91 4
|
||||
91 5
|
||||
171 0
|
||||
172 0
|
||||
173 0
|
||||
174 0
|
||||
177 0
|
||||
100 AcDbBlockXYParameter
|
||||
305 Y Distance1
|
||||
306 X Distance1
|
||||
307
|
||||
308
|
||||
141 0
|
||||
140 0
|
||||
309
|
||||
97 0
|
||||
146 0
|
||||
147 0
|
||||
148 0
|
||||
176 0
|
||||
410
|
||||
96 0
|
||||
142 0
|
||||
143 0
|
||||
144 0
|
||||
175 0
|
||||
0 BLOCKSCALEACTION
|
||||
5 83
|
||||
330 81
|
||||
100 AcDbEvalExpr
|
||||
90 2
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Scale
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockAction
|
||||
70 0
|
||||
71 1
|
||||
330 50
|
||||
1010 4
|
||||
1020 3
|
||||
1030 0
|
||||
100 AcDbBlockActionWithBasePt
|
||||
92 1
|
||||
93 1
|
||||
301 UpdatedBaseX
|
||||
302 UpdatedBaseY
|
||||
1011 0
|
||||
1021 0
|
||||
1031 0
|
||||
280 1
|
||||
1012 0
|
||||
1022 0
|
||||
1032 0
|
||||
100 AcDbBlockScaleAction
|
||||
94 1
|
||||
95 1
|
||||
96 1
|
||||
303 Scale
|
||||
304 XScale
|
||||
305 YScale
|
||||
0 DICTIONARY
|
||||
5 90
|
||||
330 1A
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 ACAD_ENHANCEDBLOCK
|
||||
360 91
|
||||
0 ACAD_EVALUATION_GRAPH
|
||||
5 91
|
||||
330 90
|
||||
100 AcDbEvalGraph
|
||||
96 3
|
||||
97 3
|
||||
91 0
|
||||
93 32
|
||||
95 1
|
||||
360 92
|
||||
91 1
|
||||
93 32
|
||||
95 2
|
||||
360 93
|
||||
91 2
|
||||
93 32
|
||||
95 3
|
||||
360 94
|
||||
0 BLOCKPOLARPARAMETER
|
||||
5 92
|
||||
330 91
|
||||
100 AcDbEvalExpr
|
||||
90 1
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Polar
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock2PtParameter
|
||||
1010 0
|
||||
1020 0
|
||||
1030 0
|
||||
1011 4
|
||||
1021 0
|
||||
1031 0
|
||||
170 4
|
||||
91 3
|
||||
91 2
|
||||
91 0
|
||||
91 0
|
||||
171 0
|
||||
172 0
|
||||
173 0
|
||||
174 0
|
||||
177 0
|
||||
100 AcDbBlockPolarParameter
|
||||
305 Distance1
|
||||
306
|
||||
307 Angle1
|
||||
308
|
||||
140 0
|
||||
309
|
||||
96 0
|
||||
141 0
|
||||
142 0
|
||||
143 0
|
||||
175 0
|
||||
410
|
||||
97 0
|
||||
145 0
|
||||
146 0
|
||||
147 0
|
||||
176 0
|
||||
0 BLOCKPOINTPARAMETER
|
||||
5 93
|
||||
330 91
|
||||
100 AcDbEvalExpr
|
||||
90 2
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Point
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock1PtParameter
|
||||
1010 4
|
||||
1020 1
|
||||
1030 0
|
||||
93 0
|
||||
170 0
|
||||
171 0
|
||||
100 AcDbBlockPointParameter
|
||||
303 Position1
|
||||
304
|
||||
1011 4
|
||||
1021 1
|
||||
1031 0
|
||||
0 BLOCKPOLARSTRETCHACTION
|
||||
5 94
|
||||
330 91
|
||||
100 AcDbEvalExpr
|
||||
90 3
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Polar Stretch
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockAction
|
||||
70 0
|
||||
71 3
|
||||
330 B0
|
||||
330 B1
|
||||
330 93
|
||||
1010 5
|
||||
1020 -1
|
||||
1030 0
|
||||
100 AcDbBlockPolarStretchAction
|
||||
92 1
|
||||
301 EndXDelta
|
||||
93 1
|
||||
302 EndYDelta
|
||||
94 1
|
||||
303 Base
|
||||
95 1
|
||||
304 End
|
||||
96 1
|
||||
305 UpdatedBase
|
||||
97 1
|
||||
306 UpdatedEnd
|
||||
73 2
|
||||
1011 3.5
|
||||
1021 -0.5
|
||||
1011 4.5
|
||||
1021 1.5
|
||||
72 1
|
||||
331 B2
|
||||
74 1
|
||||
332 B0
|
||||
75 1
|
||||
76 1
|
||||
78 0
|
||||
141 1
|
||||
140 0
|
||||
77 0
|
||||
0 ENDSEC
|
||||
0 EOF
|
||||
@@ -1,469 +0,0 @@
|
||||
0 SECTION
|
||||
2 HEADER
|
||||
9 $ACADVER
|
||||
1 AC1032
|
||||
9 $HANDSEED
|
||||
5 200
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 TABLES
|
||||
0 TABLE
|
||||
2 BLOCK_RECORD
|
||||
5 1
|
||||
330 0
|
||||
100 AcDbSymbolTable
|
||||
70 3
|
||||
0 BLOCK_RECORD
|
||||
5 1F
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 *Model_Space
|
||||
340 0
|
||||
0 BLOCK_RECORD
|
||||
5 1E
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 *Paper_Space
|
||||
340 0
|
||||
0 BLOCK_RECORD
|
||||
5 1D
|
||||
102 {ACAD_XDICTIONARY
|
||||
360 60
|
||||
102 }
|
||||
330 1
|
||||
100 AcDbSymbolTableRecord
|
||||
100 AcDbBlockTableRecord
|
||||
2 Symbol
|
||||
340 0
|
||||
70 0
|
||||
280 1
|
||||
281 1
|
||||
0 ENDTAB
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 BLOCKS
|
||||
0 BLOCK
|
||||
5 20
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 *Model_Space
|
||||
70 0
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 *Model_Space
|
||||
1
|
||||
0 ENDBLK
|
||||
5 21
|
||||
330 1F
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 BLOCK
|
||||
5 24
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockBegin
|
||||
2 Symbol
|
||||
70 2
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
3 Symbol
|
||||
1
|
||||
0 CIRCLE
|
||||
5 30
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbCircle
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
40 1
|
||||
0 LINE
|
||||
5 31
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbLine
|
||||
10 0
|
||||
20 0
|
||||
30 0
|
||||
11 0
|
||||
21 3
|
||||
31 0
|
||||
0 ATTDEF
|
||||
5 32
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbText
|
||||
10 1
|
||||
20 2
|
||||
30 0
|
||||
40 1
|
||||
1 X
|
||||
50 90
|
||||
7 Standard
|
||||
100 AcDbAttributeDefinition
|
||||
3 Tag
|
||||
2 TAG
|
||||
70 0
|
||||
0 ENDBLK
|
||||
5 25
|
||||
330 1D
|
||||
100 AcDbEntity
|
||||
8 0
|
||||
100 AcDbBlockEnd
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 ENTITIES
|
||||
0 ENDSEC
|
||||
0 SECTION
|
||||
2 OBJECTS
|
||||
0 DICTIONARY
|
||||
5 C
|
||||
330 0
|
||||
100 AcDbDictionary
|
||||
281 1
|
||||
0 DICTIONARY
|
||||
5 60
|
||||
330 1D
|
||||
100 AcDbDictionary
|
||||
280 1
|
||||
281 1
|
||||
3 ACAD_ENHANCEDBLOCK
|
||||
360 61
|
||||
0 ACAD_EVALUATION_GRAPH
|
||||
5 61
|
||||
102 {ACAD_REACTORS
|
||||
330 60
|
||||
102 }
|
||||
330 60
|
||||
100 AcDbEvalGraph
|
||||
96 8
|
||||
97 8
|
||||
91 0
|
||||
93 32
|
||||
95 15
|
||||
360 62
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
91 1
|
||||
93 32
|
||||
95 16
|
||||
360 63
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
91 2
|
||||
93 32
|
||||
95 19
|
||||
360 64
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
91 3
|
||||
93 32
|
||||
95 20
|
||||
360 65
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
91 4
|
||||
93 32
|
||||
95 21
|
||||
360 66
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
91 5
|
||||
93 32
|
||||
95 25
|
||||
360 67
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
91 6
|
||||
93 32
|
||||
95 26
|
||||
360 68
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
92 -1
|
||||
91 7
|
||||
93 32
|
||||
95 30
|
||||
360 69
|
||||
0 BLOCKROTATIONPARAMETER
|
||||
5 62
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 15
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Rotation
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock2PtParameter
|
||||
1010 0
|
||||
1020 0
|
||||
1030 0
|
||||
1011 2
|
||||
1021 0
|
||||
1031 0
|
||||
170 4
|
||||
91 0
|
||||
91 16
|
||||
91 0
|
||||
91 0
|
||||
171 0
|
||||
172 0
|
||||
173 0
|
||||
174 0
|
||||
177 0
|
||||
100 AcDbBlockRotationParameter
|
||||
305 Angle1
|
||||
306
|
||||
1011 2
|
||||
1021 0
|
||||
1031 0
|
||||
140 0
|
||||
307
|
||||
96 3
|
||||
141 0
|
||||
142 6.283185307179586
|
||||
143 0
|
||||
175 0
|
||||
0 BLOCKROTATIONGRIP
|
||||
5 63
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 16
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Grip
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockGrip
|
||||
91 0
|
||||
92 0
|
||||
1010 2
|
||||
1020 0
|
||||
1030 0
|
||||
280 0
|
||||
93 -1
|
||||
100 AcDbBlockRotationGrip
|
||||
0 BLOCKROTATEACTION
|
||||
5 64
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 19
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Rotate
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockAction
|
||||
70 2
|
||||
91 0
|
||||
91 0
|
||||
71 4
|
||||
330 31
|
||||
330 32
|
||||
330 65
|
||||
330 68
|
||||
1010 1
|
||||
1020 1
|
||||
1030 0
|
||||
100 AcDbBlockActionWithBasePt
|
||||
92 15
|
||||
93 15
|
||||
301 UpdatedBaseX
|
||||
302 UpdatedBaseY
|
||||
1011 0
|
||||
1021 0
|
||||
1031 0
|
||||
280 1
|
||||
1012 0
|
||||
1022 0
|
||||
1032 0
|
||||
100 AcDbBlockRotationAction
|
||||
94 15
|
||||
303 AngleDelta
|
||||
0 BLOCKFLIPPARAMETER
|
||||
5 65
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 20
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Flip
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock2PtParameter
|
||||
1010 0
|
||||
1020 0
|
||||
1030 0
|
||||
1011 -10
|
||||
1021 0
|
||||
1031 0
|
||||
170 4
|
||||
91 21
|
||||
91 0
|
||||
91 0
|
||||
91 0
|
||||
171 0
|
||||
172 0
|
||||
173 0
|
||||
174 0
|
||||
177 0
|
||||
100 AcDbBlockFlipParameter
|
||||
305 Flip state1
|
||||
306
|
||||
307 Not flipped
|
||||
308 Flipped
|
||||
1012 -12
|
||||
1022 0
|
||||
1032 0
|
||||
309 UpdatedFlip
|
||||
96 21
|
||||
0 BLOCKFLIPGRIP
|
||||
5 66
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 21
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Grip
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockGrip
|
||||
91 0
|
||||
92 0
|
||||
1010 -2
|
||||
1020 0
|
||||
1030 0
|
||||
280 0
|
||||
93 -1
|
||||
100 AcDbBlockFlipGrip
|
||||
0 BLOCKFLIPACTION
|
||||
5 67
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 25
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Flip1
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockAction
|
||||
70 2
|
||||
91 0
|
||||
91 0
|
||||
71 3
|
||||
330 31
|
||||
330 32
|
||||
330 68
|
||||
1010 -6
|
||||
1020 0
|
||||
1030 0
|
||||
100 AcDbBlockFlipAction
|
||||
92 20
|
||||
93 20
|
||||
94 20
|
||||
95 20
|
||||
301 Flip
|
||||
302 UpdatedFlip
|
||||
303 UpdatedBase
|
||||
304 UpdatedEnd
|
||||
0 BLOCKPOINTPARAMETER
|
||||
5 68
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 26
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Point
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockParameter
|
||||
280 1
|
||||
281 0
|
||||
100 AcDbBlock1PtParameter
|
||||
1010 0
|
||||
1020 3
|
||||
1030 0
|
||||
93 0
|
||||
170 0
|
||||
171 0
|
||||
100 AcDbBlockPointParameter
|
||||
303 Position1
|
||||
304
|
||||
1011 0
|
||||
1021 4
|
||||
1031 0
|
||||
0 BLOCKMOVEACTION
|
||||
5 69
|
||||
330 61
|
||||
100 AcDbEvalExpr
|
||||
90 30
|
||||
98 33
|
||||
99 232
|
||||
100 AcDbBlockElement
|
||||
300 Move
|
||||
98 33
|
||||
99 232
|
||||
1071 0
|
||||
100 AcDbBlockAction
|
||||
70 2
|
||||
91 0
|
||||
91 0
|
||||
71 1
|
||||
330 32
|
||||
1010 0
|
||||
1020 4
|
||||
1030 0
|
||||
100 AcDbBlockMoveAction
|
||||
92 26
|
||||
93 26
|
||||
301 XDelta
|
||||
302 YDelta
|
||||
140 1
|
||||
141 0
|
||||
0 ENDSEC
|
||||
0 EOF
|
||||
@@ -1,48 +0,0 @@
|
||||
//! DIMASSOC is a drawing variable, written as HEADER group 280, independently of DIMSTYLE.
|
||||
use cadcraft_doc::Drawing;
|
||||
use cadcraft_io::{SaveOptions, Version, read_dxf, write, write_with};
|
||||
|
||||
/// Extract every DIMASSOC HEADER entry so duplicate or mistyped values fail the assertions.
|
||||
fn dimassoc_groups(bytes: &[u8]) -> Vec<(i32, i64)> {
|
||||
let tags = craft_dxf::parse(bytes).unwrap();
|
||||
let header = craft_dxf::sections(&tags).into_iter().find(|s| s.name == "HEADER").unwrap();
|
||||
let mut found = Vec::new();
|
||||
for pair in header.tags.windows(2) {
|
||||
if pair[0].code == 9 && pair[0].str() == "$DIMASSOC" {
|
||||
found.push((pair[1].code, pair[1].i64()));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// All supported modes use group 280 and survive each tested DXF version and encoding.
|
||||
#[test]
|
||||
fn new_drawing_modes_use_group_280_in_ascii_and_binary_dxf() {
|
||||
for mode in [0, 1, 2] {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.header.set_i64("DIMASSOC", mode);
|
||||
for version in [Version::R2000, Version::R2004, Version::R2007, Version::R2018] {
|
||||
for binary in [false, true] {
|
||||
let bytes = write_with(&d, "setting.dxf", &SaveOptions { version: Some(version), binary }).unwrap();
|
||||
assert_eq!(dimassoc_groups(&bytes), [(280, mode)], "{version:?}, binary{binary}");
|
||||
let back = read_dxf(&bytes).unwrap();
|
||||
assert_eq!(back.header.i64("DIMASSOC", -1), mode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Editing an imported mode replaces its stored value without emitting a second HEADER entry.
|
||||
#[test]
|
||||
fn an_imported_mode_can_be_changed_without_a_stale_or_duplicate_header() {
|
||||
let source = b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$DIMASSOC\n280\n1\n0\nENDSEC\n0\nEOF\n";
|
||||
let mut d = read_dxf(source).unwrap();
|
||||
assert_eq!(d.header.i64("DIMASSOC", -1), 1);
|
||||
for mode in [1, 0, 2] {
|
||||
d.header.set_i64("DIMASSOC", mode);
|
||||
let bytes = write(&d, "edited.dxf").unwrap();
|
||||
assert_eq!(dimassoc_groups(&bytes), [(280, mode)]);
|
||||
d = read_dxf(&bytes).unwrap();
|
||||
assert_eq!(d.header.i64("DIMASSOC", -1), mode);
|
||||
}
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
//! Array actions of dynamic blocks: a reference repeats the arrayed objects as far as its linear,
|
||||
//! polar or XY parameter reaches, as AutoCAD does (one copy per whole column along a distance; a
|
||||
//! whole number of columns by rows across an XY parameter, or just the object when either is
|
||||
//! short of one), marks the copies as AutoCAD marks them, and keeps the right number of copies
|
||||
//! through later changes and a save.
|
||||
//!
|
||||
//! The fixture is synthetic: block Row (a 2×2 square, Distance1 from the origin to (2, 0), copies
|
||||
//! every 3), Fan (a circle, Distance1/Angle1 from the origin to (3, 4), copies every 2) and Grid
|
||||
//! (a circle, X Distance1/Y Distance1 from the origin to (10, 10), columns every 5 and rows every
|
||||
//! 4, distances at least 0).
|
||||
|
||||
use cadcraft_doc::dynblock::{ActionKind, GripPart, GripShape, ParameterKind, custom_properties, drag_grip, dynamic_block, grips, set_property};
|
||||
use cadcraft_doc::geom::{Vec2, Vec3};
|
||||
use cadcraft_doc::{Drawing, EntityKind, Handle};
|
||||
use cadcraft_io::{read_dxf, write_dxf};
|
||||
|
||||
fn dxf(src: &str) -> String {
|
||||
src.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(|l| {
|
||||
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
|
||||
format!("{code}\n{value}\n")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The fixture with a reference to `block` at (100, 100).
|
||||
fn reference(block: &str) -> (Drawing, Handle) {
|
||||
let mut d = read_dxf(dxf(&include_str!("../data/dynblock_arrays.txt").replace("\r\n", "\n")).as_bytes()).unwrap();
|
||||
let ins = cadcraft_doc::Insert {
|
||||
block: block.into(),
|
||||
insert: Vec3::new(100.0, 100.0, 0.0),
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
};
|
||||
let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
(d, r)
|
||||
}
|
||||
|
||||
fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> {
|
||||
custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect()
|
||||
}
|
||||
|
||||
fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> {
|
||||
v.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect()
|
||||
}
|
||||
|
||||
/// Where each object of the reference's block is (a circle's centre, a polyline's first vertex).
|
||||
fn places(d: &Drawing, r: Handle) -> Vec<(f64, f64)> {
|
||||
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") };
|
||||
let round = |v: f64| (v * 1000.0).round() / 1000.0;
|
||||
d.block(&i.block)
|
||||
.unwrap()
|
||||
.entities
|
||||
.iter()
|
||||
.map(|e| match &e.kind {
|
||||
EntityKind::Circle(c) => (round(c.center.x), round(c.center.y)),
|
||||
EntityKind::LwPolyline(p) => (round(p.vertices[0].p.x), round(p.vertices[0].p.y)),
|
||||
k => panic!("unexpected {k:?}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether each object of the reference's block is marked as an array's copy.
|
||||
fn marked(d: &Drawing, r: Handle) -> Vec<bool> {
|
||||
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") };
|
||||
let mark = |e: &cadcraft_doc::Entity| e.common.xdata.iter().any(|t| t.code == 1001 && t.value == "AcDbBlockArrayActionTag");
|
||||
d.block(&i.block).unwrap().entities.iter().map(|e| mark(e)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_array_actions_and_polar_and_xy_parameters() {
|
||||
let (d, _) = reference("Row");
|
||||
let m = dynamic_block(&d, "Row").unwrap();
|
||||
assert!(matches!(m.actions[0].kind, ActionKind::Array { column: 3.0, row: 1.0 }));
|
||||
assert_eq!(m.actions[0].connections.len(), 4);
|
||||
let m = dynamic_block(&d, "Fan").unwrap();
|
||||
let ParameterKind::Polar { label, angle_label, .. } = &m.parameters[0].kind else { panic!("a polar parameter") };
|
||||
assert_eq!((label.as_str(), angle_label.as_str()), ("Distance1", "Angle1"));
|
||||
let m = dynamic_block(&d, "Grid").unwrap();
|
||||
let ParameterKind::Xy { x_label, y_label, x_values, y_values, .. } = &m.parameters[0].kind else { panic!("an XY parameter") };
|
||||
assert_eq!((x_label.as_str(), y_label.as_str()), ("X Distance1", "Y Distance1"));
|
||||
assert!(x_values.has_minimum() && y_values.has_minimum());
|
||||
assert_eq!(m.parameters[0].grips, vec![3, 2, 4, 5], "base, end and the two corner grips");
|
||||
assert!(matches!(m.actions[0].kind, ActionKind::Array { column: 5.0, row: 4.0 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polar_and_xy_parameters_show_their_two_properties() {
|
||||
let (d, r) = reference("Fan");
|
||||
assert_eq!(props(&d, r), pairs(&[("Distance1", "5.0000"), ("Angle1", "53")]));
|
||||
let (d, r) = reference("Grid");
|
||||
assert_eq!(props(&d, r), pairs(&[("X Distance1", "10.0000"), ("Y Distance1", "10.0000")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_distance_repeats_the_objects_once_per_whole_column() {
|
||||
let (mut d, r) = reference("Row");
|
||||
set_property(&mut d, r, "Distance1", "9").unwrap();
|
||||
assert_eq!(places(&d, r), vec![(0.0, 0.0), (3.0, 0.0), (6.0, 0.0)]);
|
||||
assert_eq!(marked(&d, r), vec![false, true, true], "AutoCAD marks every copy but the first");
|
||||
// Short of a whole column: one fewer; short of one: the object alone.
|
||||
set_property(&mut d, r, "Distance1", "8.9").unwrap();
|
||||
assert_eq!(places(&d, r), vec![(0.0, 0.0), (3.0, 0.0)]);
|
||||
set_property(&mut d, r, "Distance1", "2.5").unwrap();
|
||||
assert_eq!(places(&d, r), vec![(0.0, 0.0)]);
|
||||
assert_eq!(marked(&d, r), vec![false]);
|
||||
set_property(&mut d, r, "Distance1", "12").unwrap();
|
||||
assert_eq!(places(&d, r).len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polar_parameter_repeats_along_its_angle() {
|
||||
let (mut d, r) = reference("Fan");
|
||||
set_property(&mut d, r, "Distance1", "7").unwrap();
|
||||
assert_eq!(places(&d, r), vec![(0.0, 0.0), (1.2, 1.6), (2.4, 3.2)]);
|
||||
set_property(&mut d, r, "Angle1", "90").unwrap();
|
||||
assert_eq!(places(&d, r), vec![(0.0, 0.0), (0.0, 2.0), (0.0, 4.0)]);
|
||||
assert_eq!(props(&d, r), pairs(&[("Distance1", "7.0000"), ("Angle1", "90")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_xy_parameter_repeats_in_columns_and_rows() {
|
||||
let (mut d, r) = reference("Grid");
|
||||
// 10 × 10 with columns every 5 and rows every 4: 2 by 2.
|
||||
set_property(&mut d, r, "Y Distance1", "10").unwrap();
|
||||
assert_eq!(places(&d, r), vec![(0.0, 0.0), (5.0, 0.0), (0.0, 4.0), (5.0, 4.0)]);
|
||||
set_property(&mut d, r, "Y Distance1", "13").unwrap();
|
||||
assert_eq!(places(&d, r).len(), 6, "2 columns by 3 rows, the earlier copies replaced");
|
||||
assert_eq!(marked(&d, r), vec![false, true, true, true, true, true]);
|
||||
// Short of one column: the object alone, however many rows fit.
|
||||
set_property(&mut d, r, "X Distance1", "4").unwrap();
|
||||
assert_eq!(places(&d, r), vec![(0.0, 0.0)]);
|
||||
// Below the value set's minimum: refused, as AutoCAD refuses it.
|
||||
assert!(set_property(&mut d, r, "X Distance1", "-10").is_err());
|
||||
assert_eq!(props(&d, r), pairs(&[("X Distance1", "4.0000"), ("Y Distance1", "13.0000")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xy_grips_move_the_base_end_and_corners() {
|
||||
let (mut d, r) = reference("Grid");
|
||||
let gs = grips(&d, r);
|
||||
let summary: Vec<(GripPart, GripShape, (f64, f64))> = gs.iter().map(|g| (g.part, g.shape, (g.at.x, g.at.y))).collect();
|
||||
assert_eq!(
|
||||
summary,
|
||||
vec![
|
||||
(GripPart::Base, GripShape::Point, (100.0, 100.0)),
|
||||
(GripPart::End, GripShape::Point, (110.0, 110.0)),
|
||||
(GripPart::BaseXEndY, GripShape::Point, (100.0, 110.0)),
|
||||
(GripPart::BaseYEndX, GripShape::Point, (110.0, 100.0)),
|
||||
]
|
||||
);
|
||||
// The base X and end Y corner, dragged left and up: the base moves left (the circle with
|
||||
// it, as AutoCAD's arrays follow the base), the end up.
|
||||
drag_grip(&mut d, r, 1, GripPart::BaseXEndY, Vec2::new(95.0, 112.0)).unwrap();
|
||||
assert_eq!(props(&d, r), pairs(&[("X Distance1", "15.0000"), ("Y Distance1", "12.0000")]));
|
||||
assert_eq!(places(&d, r), vec![(-5.0, 0.0), (0.0, 0.0), (5.0, 0.0), (-5.0, 4.0), (0.0, 4.0), (5.0, 4.0), (-5.0, 8.0), (0.0, 8.0), (5.0, 8.0)]);
|
||||
// A corner past the base: below the minimum, refused.
|
||||
assert!(drag_grip(&mut d, r, 1, GripPart::BaseYEndX, Vec2::new(90.0, 100.0)).is_err());
|
||||
assert!(drag_grip(&mut d, r, 1, GripPart::At, Vec2::new(90.0, 100.0)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polar_grips_move_the_end_and_the_base() {
|
||||
let (mut d, r) = reference("Fan");
|
||||
let parts: Vec<GripPart> = grips(&d, r).into_iter().map(|g| g.part).collect();
|
||||
assert_eq!(parts, vec![GripPart::Base, GripPart::End]);
|
||||
drag_grip(&mut d, r, 1, GripPart::End, Vec2::new(100.0, 106.0)).unwrap();
|
||||
assert_eq!(props(&d, r), pairs(&[("Distance1", "6.0000"), ("Angle1", "90")]));
|
||||
assert_eq!(places(&d, r), vec![(0.0, 0.0), (0.0, 2.0), (0.0, 4.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_and_values_survive_a_save() {
|
||||
let (mut d, r) = reference("Grid");
|
||||
set_property(&mut d, r, "X Distance1", "12").unwrap();
|
||||
let back = read_dxf(write_dxf(&d).as_bytes()).unwrap();
|
||||
assert_eq!(props(&back, r), props(&d, r));
|
||||
assert_eq!(places(&back, r), places(&d, r));
|
||||
// Changed again after the save: still one set of copies.
|
||||
let mut back = back;
|
||||
set_property(&mut back, r, "Y Distance1", "5").unwrap();
|
||||
assert_eq!(places(&back, r), vec![(0.0, 0.0), (5.0, 0.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_arrays_are_refused_not_built() {
|
||||
let (mut d, r) = reference("Grid");
|
||||
// A billion columns: refused before any copy is made.
|
||||
assert!(set_property(&mut d, r, "X Distance1", "1e10").is_err());
|
||||
assert!(set_property(&mut d, r, "X Distance1", "NaN").is_err());
|
||||
assert!(set_property(&mut d, r, "X Distance1", "inf").is_err());
|
||||
assert_eq!(places(&d, r), vec![(0.0, 0.0)]);
|
||||
let (mut d, r) = reference("Row");
|
||||
assert!(set_property(&mut d, r, "Distance1", "1e300").is_err());
|
||||
let (mut d, r) = reference("Fan");
|
||||
assert!(set_property(&mut d, r, "Angle1", "nan").is_err());
|
||||
assert!(set_property(&mut d, r, "Distance1", "0").is_err());
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
//! Base point and alignment parameters of dynamic blocks, and lookup tables that set angles, flip
|
||||
//! states, XY distances and positions, as AutoCAD applies them:
|
||||
//! - an action that moves a base point parameter moves the reference's insertion point with it,
|
||||
//! and the block's objects move back so the parameter stays at the block's base point;
|
||||
//! - an alignment grip dragged next to an object moves the reference so the alignment's base is on
|
||||
//! the object and turns it so the alignment runs along the object, its right side toward the
|
||||
//! cursor;
|
||||
//! - lookup tables set and read rotation angles (`UpdatedAngle`, radians), flip states
|
||||
//! (`UpdatedFlip`), XY distances (`UpdatedDistanceX`/`Y`), polar distances and angles and
|
||||
//! positions (`UpdatedX`/`Y`, from the block's base point).
|
||||
//!
|
||||
//! The fixture is synthetic, laid out as AutoCAD writes these blocks: Shift (a 10×5 rectangle left
|
||||
//! of the origin, Distance1 along its bottom, a stretch of its right side holding the base point
|
||||
//! parameter, an attribute TAG at (-8, 0); a reference at (100, 100) with its attribute at (92, 100)),
|
||||
//! Align (a 4×2 rectangle, a perpendicular alignment from the origin along X), Turn (a 4×2
|
||||
//! rectangle turned by Angle1 about the origin; Lookup1 gives Up 90°, Left 180°, Zero 0°) and Many
|
||||
//! (Flip state1, X/Y Distance1, polar Distance1/Angle1 and Position1, all set by Lookup1's rows A
|
||||
//! and B, B being the block's own values). A line at 30° runs from (120, 100) to (140, 111.547).
|
||||
|
||||
use cadcraft_doc::dynblock::{GripShape, ParameterKind, Value, align_grip, custom_properties, dynamic_block, grips, reference, set_property};
|
||||
use cadcraft_doc::geom::{Vec2, Vec3};
|
||||
use cadcraft_doc::{Drawing, EntityKind, Handle};
|
||||
use cadcraft_io::{read_dxf, write_dxf};
|
||||
|
||||
fn dxf(src: &str) -> String {
|
||||
src.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(|l| {
|
||||
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
|
||||
format!("{code}\n{value}\n")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn fixture() -> Drawing {
|
||||
read_dxf(dxf(&include_str!("../data/dynblock_params.txt").replace("\r\n", "\n")).as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
/// The fixture with a reference to `block` at (100, 100) turned by `rotation`.
|
||||
fn reference_to(block: &str, rotation: f64) -> (Drawing, Handle) {
|
||||
let mut d = fixture();
|
||||
let ins = cadcraft_doc::Insert {
|
||||
block: block.into(),
|
||||
insert: Vec3::new(100.0, 100.0, 0.0),
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
};
|
||||
let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
(d, r)
|
||||
}
|
||||
|
||||
fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> {
|
||||
custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect()
|
||||
}
|
||||
|
||||
fn prop(d: &Drawing, r: Handle, name: &str) -> String {
|
||||
props(d, r).into_iter().find(|(n, _)| n == name).map(|(_, v)| v).unwrap_or_else(|| panic!("no {name}"))
|
||||
}
|
||||
|
||||
fn round(v: f64) -> f64 {
|
||||
(v * 1000.0).round() / 1000.0 + 0.0
|
||||
}
|
||||
|
||||
fn insert(d: &Drawing, r: Handle) -> &cadcraft_doc::Insert {
|
||||
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") };
|
||||
i
|
||||
}
|
||||
|
||||
/// The reference's polyline corners (lowest and highest) in block coordinates.
|
||||
fn outline(d: &Drawing, r: Handle) -> [f64; 4] {
|
||||
let b = d.block(&insert(d, r).block).unwrap();
|
||||
let pl = b
|
||||
.entities
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
EntityKind::LwPolyline(p) => Some(p),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let xs = pl.vertices.iter().map(|v| v.p.x);
|
||||
let ys = pl.vertices.iter().map(|v| v.p.y);
|
||||
[
|
||||
round(xs.clone().fold(f64::MAX, f64::min)),
|
||||
round(ys.clone().fold(f64::MAX, f64::min)),
|
||||
round(xs.fold(f64::MIN, f64::max)),
|
||||
round(ys.fold(f64::MIN, f64::max)),
|
||||
]
|
||||
}
|
||||
|
||||
fn at(d: &Drawing, r: Handle) -> (f64, f64) {
|
||||
let i = insert(d, r);
|
||||
(round(i.insert.x), round(i.insert.y))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_alignment_type_and_shows_its_grip() {
|
||||
let (d, r) = reference_to("Align", 0.0);
|
||||
let m = dynamic_block(&d, "Align").unwrap();
|
||||
assert!(matches!(m.parameters[0].kind, ParameterKind::Alignment { perpendicular: true, .. }));
|
||||
let g = grips(&d, r);
|
||||
let a = g.iter().find(|g| g.shape == GripShape::Alignment).expect("an alignment grip");
|
||||
// At the base point, pointing to the left of the alignment's direction (as AutoCAD draws it).
|
||||
assert_eq!((round(a.at.x), round(a.at.y)), (100.0, 100.0));
|
||||
assert_eq!((round(a.dir.x), round(a.dir.y)), (0.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_base_point_moves_the_insertion_point() {
|
||||
let mut d = fixture();
|
||||
let r = Handle(0xE0);
|
||||
set_property(&mut d, r, "Distance1", "15").unwrap();
|
||||
// Measured in AutoCAD: the reference moves to (105, 100) and its block runs from -15 to 0.
|
||||
assert_eq!(at(&d, r), (105.0, 100.0));
|
||||
assert_eq!(outline(&d, r), [-15.0, -2.5, 0.0, 2.5]);
|
||||
assert_eq!(prop(&d, r, "Distance1"), "15.0000");
|
||||
// The values as AutoCAD records them: the base point at the block's base, the distance moved back.
|
||||
let v = reference(&d, r).unwrap().values;
|
||||
assert_eq!(v.get(&1), Some(&Value::Point { at: Vec3::new(0.0, 0.0, 0.0) }));
|
||||
assert_eq!(v.get(&2), Some(&Value::Points { base: Vec3::new(-15.0, -2.5, 0.0), end: Vec3::new(0.0, -2.5, 0.0) }));
|
||||
// The attribute stays where it was in the drawing (its definition didn't move).
|
||||
let a = &insert(&d, r).attribs[0];
|
||||
assert_eq!((round(a.text.insert.x), round(a.text.insert.y)), (92.0, 100.0));
|
||||
// And back, from there.
|
||||
set_property(&mut d, r, "Distance1", "12").unwrap();
|
||||
assert_eq!(at(&d, r), (102.0, 100.0));
|
||||
assert_eq!(outline(&d, r), [-12.0, -2.5, 0.0, 2.5]);
|
||||
// A save keeps it.
|
||||
let back = read_dxf(write_dxf(&d).as_bytes()).unwrap();
|
||||
assert_eq!(at(&back, r), (102.0, 100.0));
|
||||
assert_eq!(prop(&back, r, "Distance1"), "12.0000");
|
||||
}
|
||||
|
||||
/// AutoCAD takes a distance of 0 (title block value lists offer it); the distance keeps its
|
||||
/// direction for the next change.
|
||||
#[test]
|
||||
fn a_distance_of_0_keeps_its_direction() {
|
||||
let mut d = fixture();
|
||||
let r = Handle(0xE0);
|
||||
set_property(&mut d, r, "Distance1", "0").unwrap();
|
||||
assert_eq!(prop(&d, r, "Distance1"), "0.0000");
|
||||
assert_eq!(at(&d, r), (90.0, 100.0));
|
||||
set_property(&mut d, r, "Distance1", "15").unwrap();
|
||||
assert_eq!(at(&d, r), (105.0, 100.0));
|
||||
assert_eq!(outline(&d, r), [-15.0, -2.5, 0.0, 2.5]);
|
||||
assert!(set_property(&mut d, r, "Distance1", "-1").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_turned_reference_moves_along_its_own_axis() {
|
||||
let (mut d, r) = reference_to("Shift", std::f64::consts::FRAC_PI_2);
|
||||
set_property(&mut d, r, "Distance1", "15").unwrap();
|
||||
assert_eq!(at(&d, r), (100.0, 105.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alignment_follows_a_line() {
|
||||
let line = Vec2::new(30f64.to_radians().cos(), 30f64.to_radians().sin());
|
||||
let foot = Vec2::new(120.0, 100.0) + line * 10.0;
|
||||
// Measured in AutoCAD: from below the line the reference turns to 30°, from above to 210°, its
|
||||
// alignment's base on the line.
|
||||
for (side, rotation) in [(-0.5, 30.0), (0.5, 210.0)] {
|
||||
let (mut d, r) = reference_to("Align", 0.0);
|
||||
let cursor = foot + line.perp() * side;
|
||||
align_grip(&mut d, r, 1, cursor, Some((foot, line))).unwrap();
|
||||
assert_eq!(round(insert(&d, r).rotation.to_degrees()), rotation);
|
||||
assert_eq!(at(&d, r), (round(foot.x), round(foot.y)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alignment_follows_a_circle() {
|
||||
// A circle about (150, 150), its nearest point at 225°: outside, the reference turns to 315°
|
||||
// (counterclockwise along the circle), inside to 135°, as in AutoCAD.
|
||||
let c = Vec2::new(150.0, 150.0);
|
||||
let out = Vec2::new(225f64.to_radians().cos(), 225f64.to_radians().sin());
|
||||
let foot = c + out * 10.0;
|
||||
for (r_cursor, rotation) in [(10.5, 315.0), (9.5, 135.0)] {
|
||||
let (mut d, r) = reference_to("Align", 0.0);
|
||||
align_grip(&mut d, r, 1, c + out * r_cursor, Some((foot, out.perp()))).unwrap();
|
||||
assert_eq!(round(insert(&d, r).rotation.to_degrees()), rotation);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alignment_grip_away_from_objects_only_moves() {
|
||||
let (mut d, r) = reference_to("Align", 0.5);
|
||||
align_grip(&mut d, r, 1, Vec2::new(90.0, 80.0), None).unwrap();
|
||||
assert_eq!(at(&d, r), (90.0, 80.0));
|
||||
assert_eq!(insert(&d, r).rotation, 0.5);
|
||||
// On the object itself, the side the grip came from decides.
|
||||
let (mut d, r) = reference_to("Align", 0.0);
|
||||
let line = Vec2::new(1.0, 0.0);
|
||||
align_grip(&mut d, r, 1, Vec2::new(110.0, 90.0), Some((Vec2::new(110.0, 90.0), line))).unwrap();
|
||||
// The grip was above the line (y = 90): its right side faces up, so the alignment runs to -X.
|
||||
assert_eq!(round(insert(&d, r).rotation.to_degrees()), 180.0);
|
||||
assert!(align_grip(&mut d, r, 1, Vec2::new(f64::NAN, 0.0), None).is_err());
|
||||
assert!(align_grip(&mut d, r, 7, Vec2::new(0.0, 0.0), None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lookup_sets_and_reads_an_angle() {
|
||||
let (mut d, r) = reference_to("Turn", 0.0);
|
||||
assert_eq!(prop(&d, r, "Lookup1"), "Zero");
|
||||
set_property(&mut d, r, "Lookup1", "Up").unwrap();
|
||||
assert_eq!(prop(&d, r, "Angle1"), "90");
|
||||
assert_eq!(outline(&d, r), [-2.0, 0.0, 0.0, 4.0]);
|
||||
// Reverse: an angle in the table gives its row.
|
||||
set_property(&mut d, r, "Angle1", "180").unwrap();
|
||||
assert_eq!(prop(&d, r, "Lookup1"), "Left");
|
||||
set_property(&mut d, r, "Angle1", "45").unwrap();
|
||||
assert_eq!(prop(&d, r, "Lookup1"), "Custom");
|
||||
assert!(custom_properties(&d, r).unwrap().1.iter().any(|p| p.name == "Lookup1" && p.editable));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lookup_sets_flips_xy_polar_and_positions() {
|
||||
let (mut d, r) = reference_to("Many", 0.0);
|
||||
// The block's own values are row B.
|
||||
assert_eq!(prop(&d, r, "Lookup1"), "B");
|
||||
set_property(&mut d, r, "Lookup1", "A").unwrap();
|
||||
// As AutoCAD sets them.
|
||||
for (name, value) in [
|
||||
("Flip state1", "Flipped"),
|
||||
("X Distance1", "6.0000"),
|
||||
("Y Distance1", "3.0000"),
|
||||
("Distance1", "5.0000"),
|
||||
("Angle1", "30"),
|
||||
("Position1 X", "1.0000"),
|
||||
("Position1 Y", "0.5000"),
|
||||
("Lookup1", "A"),
|
||||
] {
|
||||
assert_eq!(prop(&d, r, name), value, "{name}");
|
||||
}
|
||||
// The values are recorded as AutoCAD lays them out (it doesn't take the reference otherwise): a
|
||||
// flip state after its points, and the flip grip's state on its own after two header groups.
|
||||
let codes: Vec<Vec<i32>> = d
|
||||
.foreign
|
||||
.objects
|
||||
.iter()
|
||||
.filter(|o| o.kind == "XRECORD")
|
||||
.map(|o| o.tags.iter().map(|t| t.code).filter(|c| [10, 70].contains(c)).collect())
|
||||
.collect();
|
||||
assert!(codes.contains(&vec![10, 10, 70]), "{codes:?}");
|
||||
assert!(codes.contains(&vec![70, 70, 70, 70]), "{codes:?}");
|
||||
// A save keeps it, and the reverse lookup reads it back.
|
||||
let back = read_dxf(write_dxf(&d).as_bytes()).unwrap();
|
||||
assert_eq!(prop(&back, r, "Lookup1"), "A");
|
||||
assert_eq!(prop(&back, r, "Flip state1"), "Flipped");
|
||||
// One input off the table's rows: no row matches.
|
||||
set_property(&mut d, r, "Flip state1", "Not flipped").unwrap();
|
||||
assert_eq!(prop(&d, r, "Lookup1"), "Custom");
|
||||
set_property(&mut d, r, "Lookup1", "B").unwrap();
|
||||
assert_eq!(prop(&d, r, "X Distance1"), "4.0000");
|
||||
assert_eq!(prop(&d, r, "Position1 X"), "2.0000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lookup_cell_that_isnt_a_number_is_refused() {
|
||||
let src = include_str!("../data/dynblock_params.txt").replace("\r\n", "\n").replace("302 1.570796326794896", "302 up-ish");
|
||||
let mut d = read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
let ins = cadcraft_doc::Insert {
|
||||
block: "Turn".into(),
|
||||
insert: Vec3::new(0.0, 0.0, 0.0),
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
};
|
||||
let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
let before = insert(&d, r).block.clone();
|
||||
assert!(set_property(&mut d, r, "Lookup1", "Up").is_err());
|
||||
assert_eq!(insert(&d, r).block, before);
|
||||
// The other rows still work, and reading the table doesn't trip on the bad cell.
|
||||
set_property(&mut d, r, "Lookup1", "Left").unwrap();
|
||||
assert_eq!(prop(&d, r, "Angle1"), "180");
|
||||
}
|
||||
@@ -114,7 +114,7 @@ fn a_scale_action_survives_a_dwg_save() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = read_dxf(dxf(&with_scale_action()).as_bytes()).unwrap();
|
||||
let before = dynamic_block(&d, "Door").unwrap();
|
||||
assert!(before.actions.iter().any(|a| a.node == 7 && matches!(a.kind, ActionKind::Scale { .. })), "{:?}", before.actions);
|
||||
assert!(before.actions.iter().any(|a| a.node == 7 && matches!(a.kind, ActionKind::Scale)), "{:?}", before.actions);
|
||||
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
|
||||
|
||||
let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap();
|
||||
@@ -347,7 +347,9 @@ fn bad_values_are_refused_and_change_nothing() {
|
||||
let ps = cadcraft_doc::dynblock::custom_properties(&d, h("80")).unwrap().1;
|
||||
let editable: Vec<(&str, bool)> = ps.iter().map(|p| (p.name.as_str(), p.editable)).collect();
|
||||
assert_eq!(editable, [("Visibility1", true), ("Width", true), ("Size", true)]);
|
||||
for (name, value) in [("Visibility1", "Ajar"), ("Size", "Huge"), ("Width", "wide"), ("Width", "-3"), ("Width", "inf"), ("Nope", "x"), ("", "")] {
|
||||
for (name, value) in
|
||||
[("Visibility1", "Ajar"), ("Size", "Huge"), ("Width", "wide"), ("Width", "0"), ("Width", "-3"), ("Width", "inf"), ("Nope", "x"), ("", "")]
|
||||
{
|
||||
assert!(cadcraft_doc::dynblock::set_property(&mut d, h("80"), name, value).is_err(), "{name}={value}");
|
||||
}
|
||||
assert!(cadcraft_doc::dynblock::set_property(&mut d, h("30"), "Visibility1", "Open").is_err(), "not a reference");
|
||||
@@ -798,55 +800,3 @@ fn a_dynamic_block_with_handles_above_2_pow_48_is_kept() {
|
||||
let again = read_dxf(write_dxf(&d).as_bytes()).unwrap();
|
||||
assert_eq!(by_node(dynamic_block(&again, "Door").unwrap()), by_node(before));
|
||||
}
|
||||
|
||||
/// A multiline attribute (LABEL, two lines) in the stretch's selection: when Width changes, the
|
||||
/// reference's attribute moves with its definition, its multiline text too.
|
||||
#[test]
|
||||
fn a_stretch_moves_a_multiline_attributes_text() {
|
||||
let attdef = "0 ATTDEF\n5 3A\n330 1D\n100 AcDbEntity\n8 0\n100 AcDbText\n10 35\n20 0\n30 0\n40 1\n1 SITE\n7 Standard\n100 AcDbAttributeDefinition\n280 0\n3 Label\n2 LABEL\n70 0\n280 1\n71 4\n72 0\n11 35\n21 0\n31 0\n101 Embedded Object\n10 35\n20 0\n30 0\n40 1\n41 0\n46 0\n71 1\n72 5\n1 SITE\\PNAME\n7 Standard\n73 1\n44 1\n";
|
||||
let src = fixture().replace("71 1\n330 30\n1010 40", "71 2\n330 30\n330 3A\n1010 40");
|
||||
// Into Door's block, before its end.
|
||||
let door = src.find("2 Door\n70 0").unwrap();
|
||||
let end = door + src[door..].find("0 ENDBLK").unwrap();
|
||||
let src = format!("{}{attdef}{}", &src[..end], &src[end..]);
|
||||
let mut d = read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
let def = d
|
||||
.block("Door")
|
||||
.unwrap()
|
||||
.entities
|
||||
.iter()
|
||||
.find_map(|e| if let cadcraft_doc::EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None })
|
||||
.expect("the attribute definition");
|
||||
assert!(def.multiline.is_some(), "a multiline definition");
|
||||
// A reference at (100, 0) with its attribute where the definition puts it.
|
||||
let r = door_at_100(&mut d);
|
||||
d.modify_entity(r, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
let mut a = def.clone();
|
||||
let m = cadcraft_doc::geom::Mat3::translate(cadcraft_doc::geom::Vec2::new(100.0, 0.0));
|
||||
let mut k = cadcraft_doc::EntityKind::Text(a.text.clone());
|
||||
k.transform(&m);
|
||||
if let cadcraft_doc::EntityKind::Text(t) = k {
|
||||
a.text = t;
|
||||
}
|
||||
a.transform_multiline(&m);
|
||||
i.attribs.push(a);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
// Width 36 → 30: the attribute moves 6 to the left, its multiline text with it.
|
||||
cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap();
|
||||
let Some(cadcraft_doc::EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") };
|
||||
let a = &i.attribs[0];
|
||||
assert_eq!(a.text.insert.x, 129.0);
|
||||
assert_eq!(a.multiline.as_ref().unwrap().mtext.insert.x, 129.0);
|
||||
// Saved (in the drawing's version, 2018: R2000 DXF has no multiline attributes) and reopened:
|
||||
// the moved attribute and its multiline text stay where they went.
|
||||
let again = cadcraft_io::read(&cadcraft_io::write(&d, "door.dxf").unwrap(), "door.dxf").unwrap();
|
||||
let Some(cadcraft_doc::EntityKind::Insert(i)) = again.entity(r).map(|e| &e.kind) else { panic!("no reference after reopening") };
|
||||
let a = &i.attribs[0];
|
||||
assert_eq!((a.text.insert.x, a.text.insert.y), (129.0, 0.0));
|
||||
let m = &a.multiline.as_ref().expect("still multiline").mtext;
|
||||
assert_eq!((m.insert.x, m.insert.y), (129.0, 0.0));
|
||||
assert_eq!(m.contents, r"SITE\PNAME");
|
||||
}
|
||||
|
||||
@@ -1,285 +0,0 @@
|
||||
//! Rotation and flip parameters of dynamic blocks: their rotate and flip actions turn and mirror
|
||||
//! the objects (text stays readable), carry the parameters in their selection, record the
|
||||
//! change as AutoCAD does, and give the reference a rotation grip and a flip grip.
|
||||
//!
|
||||
//! The fixture is synthetic: block Symbol (a circle, a line from the origin to (0, 3) and an
|
||||
//! attribute TAG at (1, 2) turned 90°) with Angle1 (base at the origin, radius to (2, 0)) and its
|
||||
//! rotate action, Flip state1 (reflection line from the origin to (-10, 0)) and its flip action,
|
||||
//! and Position1 at (0, 3) with a move action.
|
||||
|
||||
use cadcraft_doc::dynblock::{
|
||||
ActionKind, GripPart, GripShape, ParameterKind, Value, custom_properties, drag_grip, dynamic_block, grip_stops, grips, reference, set_property,
|
||||
};
|
||||
use cadcraft_doc::geom::{Vec2, Vec3};
|
||||
use cadcraft_doc::{Drawing, EntityKind, Handle, RawTag};
|
||||
use cadcraft_io::{read_dxf, write_dxf};
|
||||
|
||||
fn dxf(src: &str) -> String {
|
||||
src.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(|l| {
|
||||
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
|
||||
format!("{code}\n{value}\n")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Symbol and a reference to it at (100, 100) with its attribute.
|
||||
fn symbol() -> (Drawing, Handle) {
|
||||
symbol_from(&include_str!("../data/dynblock_symbol.txt").replace("\r\n", "\n"))
|
||||
}
|
||||
|
||||
/// As [`symbol`], from the fixture's text `src` (changed by a test).
|
||||
fn symbol_from(src: &str) -> (Drawing, Handle) {
|
||||
let mut d = read_dxf(dxf(src).as_bytes()).unwrap();
|
||||
let def =
|
||||
d.block("Symbol").unwrap().entities.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None }).unwrap();
|
||||
let mut a = def.clone();
|
||||
a.text.insert = a.text.insert + Vec3::new(100.0, 100.0, 0.0);
|
||||
let ins = cadcraft_doc::Insert {
|
||||
block: "Symbol".into(),
|
||||
insert: Vec3::new(100.0, 100.0, 0.0),
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: vec![a],
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
};
|
||||
let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
(d, r)
|
||||
}
|
||||
|
||||
fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> {
|
||||
custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect()
|
||||
}
|
||||
|
||||
fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> {
|
||||
v.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect()
|
||||
}
|
||||
|
||||
/// The reference's block: its line's end and attribute definition (insertion, rotation in degrees).
|
||||
fn shown(d: &Drawing, r: Handle) -> (Vec2, Vec2, f64) {
|
||||
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") };
|
||||
let b = d.block(&i.block).unwrap();
|
||||
let line = b.entities.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.b.xy()) } else { None }).unwrap();
|
||||
let (at, rot) =
|
||||
b.entities.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some((a.text.insert.xy(), a.text.rotation)) } else { None }).unwrap();
|
||||
(line, at, rot.to_degrees())
|
||||
}
|
||||
|
||||
fn near(a: Vec2, b: (f64, f64)) -> bool {
|
||||
(a.x - b.0).abs() < 1e-6 && (a.y - b.1).abs() < 1e-6
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_and_flip_are_read() {
|
||||
let (d, _) = symbol();
|
||||
let m = dynamic_block(&d, "Symbol").unwrap();
|
||||
let p = |node: i32| &m.parameters.iter().find(|p| p.node == node).unwrap().kind;
|
||||
assert!(matches!(p(15), ParameterKind::Rotation { label, values, .. } if label == "Angle1" && values.maximum > 6.0));
|
||||
assert!(
|
||||
matches!(p(20), ParameterKind::Flip { label, states, .. } if label == "Flip state1" && states == &["Not flipped".to_string(), "Flipped".to_string()])
|
||||
);
|
||||
let a = |node: i32| m.actions.iter().find(|a| a.node == node).unwrap();
|
||||
assert!(matches!(&a(19).kind, ActionKind::Rotate { base } if base.dependent));
|
||||
assert_eq!(a(19).connections.last(), Some(&(15, "AngleDelta".to_string())));
|
||||
assert!(matches!(a(25).kind, ActionKind::Flip));
|
||||
assert_eq!(a(25).connections.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_angle_turns_and_a_flip_mirrors_what_their_actions_hold() {
|
||||
let (mut d, r) = symbol();
|
||||
assert_eq!(props(&d, r), pairs(&[("Angle1", "0"), ("Flip state1", "Not flipped"), ("Position1 X", "0.0000"), ("Position1 Y", "3.0000")]));
|
||||
|
||||
// 30°: the line, the attribute and Position1 turn about the origin; the text turns with them.
|
||||
set_property(&mut d, r, "angle1", "30").unwrap();
|
||||
let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
|
||||
let (line, at, rot) = shown(&d, r);
|
||||
assert!(near(line, (-3.0 * s, 3.0 * c)), "{line:?}");
|
||||
assert!(near(at, (c - 2.0 * s, s + 2.0 * c)), "{at:?}");
|
||||
assert!((rot - 120.0).abs() < 1e-9);
|
||||
assert_eq!(props(&d, r), pairs(&[("Angle1", "30"), ("Flip state1", "Not flipped"), ("Position1 X", "-1.5000"), ("Position1 Y", "2.5981")]));
|
||||
// The reference's attribute follows its definition.
|
||||
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") };
|
||||
assert!(near(i.attribs[0].text.insert.xy(), (100.0 + at.x, 100.0 + at.y)));
|
||||
|
||||
// Flipped: mirrored across the reflection line, which turned with them (now at 30°); the
|
||||
// text keeps reading left to right.
|
||||
set_property(&mut d, r, "Flip state1", "Flipped").unwrap();
|
||||
let (s2, c2) = (60f64.to_radians().sin(), 60f64.to_radians().cos());
|
||||
let mirror = |p: Vec2| (p.x * c2 + p.y * s2, p.x * s2 - p.y * c2);
|
||||
let (line2, at2, rot) = shown(&d, r);
|
||||
assert!(near(line2, mirror(line)), "{line2:?}");
|
||||
assert!(near(at2, mirror(at)), "{at2:?}");
|
||||
assert!((rot - 120.0).abs() < 1e-9, "readable");
|
||||
assert_eq!(props(&d, r)[1..], pairs(&[("Flip state1", "Flipped"), ("Position1 X", "1.5000"), ("Position1 Y", "-2.5981")]));
|
||||
|
||||
// Both survive a save.
|
||||
let again = read_dxf(write_dxf(&d).as_bytes()).unwrap();
|
||||
assert_eq!(props(&again, r), props(&d, r));
|
||||
// Back to not flipped: back to the turned geometry.
|
||||
set_property(&mut d, r, "Flip state1", "0").unwrap();
|
||||
assert!(near(shown(&d, r).1, (at.x, at.y)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_and_flip_grips() {
|
||||
let (mut d, r) = symbol();
|
||||
set_property(&mut d, r, "Angle1", "30").unwrap();
|
||||
let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
|
||||
let g = grips(&d, r);
|
||||
let rot = g.iter().find(|g| g.shape == GripShape::Rotation).unwrap();
|
||||
assert_eq!((rot.node, rot.part), (15, GripPart::End));
|
||||
assert!(near(rot.at, (100.0 + 2.0 * c, 100.0 + 2.0 * s)), "at the radius' end: {:?}", rot.at);
|
||||
let flip = g.iter().find(|g| g.shape == GripShape::Flip).unwrap();
|
||||
assert_eq!((flip.node, flip.part, flip.choices.len()), (20, GripPart::Base, 2));
|
||||
// The flip grip object at (-2, 0) turned with the reflection line.
|
||||
assert!(near(flip.at, (100.0 - 2.0 * c, 100.0 - 2.0 * s)), "{:?}", flip.at);
|
||||
|
||||
// Dragging the rotation grip straight up from the base: 90°.
|
||||
drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 105.0)).unwrap();
|
||||
assert_eq!(props(&d, r)[0].1, "90");
|
||||
// A flip grip is clicked, not dragged; the base of the angle is not a point to aim at.
|
||||
assert!(drag_grip(&mut d, r, 20, GripPart::Base, Vec2::new(90.0, 90.0)).is_err());
|
||||
assert!(drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 100.0)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotation_grip_off_the_radius_stays_where_its_grip_object_is() {
|
||||
// The grip object a quarter turn round from the radius' end (as AutoCAD saves blocks whose
|
||||
// grip was moved there): the circle is drawn there and turns with the angle, and dragging
|
||||
// it turns the block by the cursor's turn, not to the cursor's direction.
|
||||
let src = include_str!("../data/dynblock_symbol.txt")
|
||||
.replace("\r\n", "\n")
|
||||
.replace("100 AcDbBlockGrip\n91 0\n92 0\n1010 2\n1020 0\n", "100 AcDbBlockGrip\n91 0\n92 0\n1010 0\n1020 2\n");
|
||||
let (mut d, r) = symbol_from(&src);
|
||||
let at = |d: &Drawing| grips(d, r).into_iter().find(|g| g.shape == GripShape::Rotation).map(|g| g.at).unwrap();
|
||||
assert!(near(at(&d), (100.0, 102.0)), "{:?}", at(&d));
|
||||
// Dropped where it is: no turn.
|
||||
drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 102.0)).unwrap();
|
||||
assert!(props(&d, r).contains(&("Angle1".to_string(), "0".to_string())), "{:?}", props(&d, r));
|
||||
// A quarter turn further round: Angle1 90, and the grip is there.
|
||||
drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(98.0, 100.0)).unwrap();
|
||||
assert!(props(&d, r).contains(&("Angle1".to_string(), "90".to_string())), "{:?}", props(&d, r));
|
||||
assert!(near(at(&d), (98.0, 100.0)), "{:?}", at(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_angle_shows_and_is_typed_as_the_drawing_measures_angles() {
|
||||
// Angles measured clockwise from north (ANGBASE 90°, ANGDIR 1): AutoCAD shows Angle1 0 as
|
||||
// 90 and 0.5 rad as 61.35, and a typed angle is read the same way.
|
||||
let (mut d, r) = symbol();
|
||||
d.header.set_f64("ANGBASE", std::f64::consts::FRAC_PI_2);
|
||||
d.header.set_i64("ANGDIR", 1);
|
||||
assert!(props(&d, r).contains(&("Angle1".to_string(), "90".to_string())), "{:?}", props(&d, r));
|
||||
// 60 shown is 30° counterclockwise: the grip turns from (102, 100) to there.
|
||||
set_property(&mut d, r, "Angle1", "60").unwrap();
|
||||
assert!(props(&d, r).contains(&("Angle1".to_string(), "60".to_string())), "{:?}", props(&d, r));
|
||||
let at = grips(&d, r).into_iter().find(|g| g.shape == GripShape::Rotation).map(|g| g.at).unwrap();
|
||||
let want = (100.0 + 2.0 * 30f64.to_radians().cos(), 100.0 + 2.0 * 30f64.to_radians().sin());
|
||||
assert!(near(at, want), "{at:?} vs {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_angle_by_increments_marks_its_stops_round_the_circle() {
|
||||
// Angle1 by 90° from 0 to a full turn: its grip stops at four points round the base, the
|
||||
// full turn being no turn; the way it travels there is round the circle.
|
||||
let src = include_str!("../data/dynblock_symbol.txt")
|
||||
.replace("\r\n", "\n")
|
||||
.replace("96 3\n141 0\n142 6.283185307179586\n143 0\n", "96 7\n141 0\n142 6.283185307179586\n143 1.5707963267948966\n");
|
||||
let (d, r) = symbol_from(&src);
|
||||
let stops = grip_stops(&d, r, 15, GripPart::End);
|
||||
let at: Vec<Vec2> = stops.iter().map(|(p, _)| *p).collect();
|
||||
assert_eq!(at.len(), 4, "{at:?}");
|
||||
for (p, want) in at.iter().zip([(102.0, 100.0), (100.0, 102.0), (98.0, 100.0), (100.0, 98.0)]) {
|
||||
assert!(near(*p, want), "{p:?} vs {want:?}");
|
||||
}
|
||||
for (p, way) in &stops {
|
||||
assert!((*p - Vec2::new(100.0, 100.0)).dot(*way).abs() < 1e-9, "across the radius");
|
||||
}
|
||||
// The block as it comes (any angle) marks nothing; nor does a flip grip.
|
||||
let (d, r) = symbol();
|
||||
assert!(grip_stops(&d, r, 15, GripPart::End).is_empty());
|
||||
assert!(grip_stops(&d, r, 20, GripPart::Base).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_angle_s_stops_follow_a_grip_off_the_radius() {
|
||||
// The grip object a quarter turn round and 90° increments: each stop is where the grip is
|
||||
// at that angle, the first (0) where it is now.
|
||||
let src = include_str!("../data/dynblock_symbol.txt")
|
||||
.replace("\r\n", "\n")
|
||||
.replace("96 3\n141 0\n142 6.283185307179586\n143 0\n", "96 7\n141 0\n142 6.283185307179586\n143 1.5707963267948966\n")
|
||||
.replace("100 AcDbBlockGrip\n91 0\n92 0\n1010 2\n1020 0\n", "100 AcDbBlockGrip\n91 0\n92 0\n1010 0\n1020 2\n");
|
||||
let (d, r) = symbol_from(&src);
|
||||
let at: Vec<Vec2> = grip_stops(&d, r, 15, GripPart::End).into_iter().map(|(p, _)| p).collect();
|
||||
assert_eq!(at.len(), 4, "{at:?}");
|
||||
for (p, want) in at.iter().zip([(100.0, 102.0), (98.0, 100.0), (100.0, 98.0), (102.0, 100.0)]) {
|
||||
assert!(near(*p, want), "{p:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_angles_and_states_change_nothing() {
|
||||
let (mut d, r) = symbol();
|
||||
let before = d.clone();
|
||||
for (name, value) in [("Angle1", "steep"), ("Angle1", "inf"), ("Flip state1", "Sideways"), ("Flip state1", "2")] {
|
||||
assert!(set_property(&mut d, r, name, value).is_err(), "{name}={value}");
|
||||
}
|
||||
assert_eq!(d, before);
|
||||
}
|
||||
|
||||
/// The saved value record of parameter `node` on the reference (the XRECORD its
|
||||
/// `ACAD_ENHANCEDBLOCKDATA` entry names), as its index in the drawing's kept objects.
|
||||
fn record(d: &Drawing, node: i32) -> usize {
|
||||
let objects = &d.foreign.objects;
|
||||
let after = |o: &cadcraft_doc::foreign::ForeignObject, key: &str| {
|
||||
let i = o.tags.iter().position(|t| t.code == 3 && t.value == key)?;
|
||||
Handle::parse_hex(&o.tags.get(i + 1)?.value)
|
||||
};
|
||||
let cache = objects.iter().find_map(|o| after(o, "ACAD_ENHANCEDBLOCKDATA")).unwrap();
|
||||
let dict = objects.iter().find(|o| o.handle == cache).unwrap();
|
||||
let h = after(dict, &node.to_string()).unwrap();
|
||||
objects.iter().position(|o| o.handle == h).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_record_takes_its_shape_from_its_parameter() {
|
||||
let (mut d, r) = symbol();
|
||||
set_property(&mut d, r, "Angle1", "30").unwrap();
|
||||
set_property(&mut d, r, "Flip state1", "Flipped").unwrap();
|
||||
let mut again = read_dxf(write_dxf(&d).as_bytes()).unwrap();
|
||||
// A stray group 70 after the rotation's points, and a flip record without its state.
|
||||
let rot = record(&again, 15);
|
||||
std::sync::Arc::make_mut(&mut again.foreign).objects[rot].tags.push(RawTag { code: 70, value: "1".into() });
|
||||
let flip = record(&again, 20);
|
||||
let tags = &mut std::sync::Arc::make_mut(&mut again.foreign).objects[flip].tags;
|
||||
let last70 = tags.iter().rposition(|t| t.code == 70).unwrap();
|
||||
tags.remove(last70);
|
||||
let values = reference(&again, r).unwrap().values;
|
||||
assert!(matches!(values.get(&15), Some(Value::Points { .. })), "{:?}", values.get(&15));
|
||||
assert!(matches!(values.get(&20), Some(Value::Flip { flipped: false, .. })), "{:?}", values.get(&20));
|
||||
assert_eq!(props(&again, r)[..2], pairs(&[("Angle1", "30"), ("Flip state1", "Not flipped")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flip_selection_that_repeats_its_objects_mirrors_them_once() {
|
||||
// The flip action's selection lists the line, the circle and Position1 twice: each is mirrored
|
||||
// once, as with the selection listing them once (twice would mirror them back).
|
||||
let src = include_str!("../data/dynblock_symbol.txt").replace("\r\n", "\n");
|
||||
let once = "71 3\n330 31\n330 32\n330 68\n1010 -6";
|
||||
assert_eq!(src.matches(once).count(), 1);
|
||||
let (mut twice, r) = symbol_from(&src.replace(once, "71 6\n330 31\n330 32\n330 68\n330 31\n330 32\n330 68\n1010 -6"));
|
||||
let (mut plain, _) = symbol();
|
||||
for d in [&mut twice, &mut plain] {
|
||||
set_property(d, r, "Flip state1", "Flipped").unwrap();
|
||||
}
|
||||
let ((l1, a1, r1), (l2, a2, r2)) = (shown(&twice, r), shown(&plain, r));
|
||||
assert!(near(l1, (l2.x, l2.y)) && near(a1, (a2.x, a2.y)) && (r1 - r2).abs() < 1e-9, "{l1:?} {l2:?}");
|
||||
assert_eq!(props(&twice, r), props(&plain, r));
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
//! Scale and polar stretch actions of dynamic blocks, as AutoCAD applies them: a scale action
|
||||
//! scales its objects about its base point by how much the distance it follows grew (a 2×2 square
|
||||
//! scaled by a distance going from 2 to 4 is 4×4); a polar stretch turns its objects about the
|
||||
//! polar parameter's base by the change of its angle and moves the vertices in its frame (and the
|
||||
//! objects it doesn't stretch) with the end, while its rotate-only objects just turn. Both carry
|
||||
//! the parameters in their selection, and the results survive a save.
|
||||
//!
|
||||
//! The fixture is synthetic: block Grow (a 2×2 square and a circle at (1, 1), Distance1 from the
|
||||
//! origin to (2, 0), scaled about the distance's base; Position1 at (2, 2) is in the selection),
|
||||
//! Pinned (the square, scaled about the fixed point (2, 2)) and Sheet (the square, scaled by the
|
||||
//! diagonal of X Distance1 and Y Distance1, from the origin to (2, 2), as AutoCAD scales by an XY
|
||||
//! parameter); Tag (a line from (1, 0) to (4, 0), a circle at its end and one at (2, 2), a polar
|
||||
//! Distance1/Angle1 from the origin to (4, 0); the polar stretch's frame holds the line's end and
|
||||
//! Position1 at (4, 1); the circle at (2, 2) only turns).
|
||||
|
||||
use cadcraft_doc::dynblock::{ActionKind, custom_properties, dynamic_block, set_property};
|
||||
use cadcraft_doc::geom::Vec3;
|
||||
use cadcraft_doc::{Drawing, EntityKind, Handle};
|
||||
use cadcraft_io::{read_dxf, write_dxf};
|
||||
|
||||
fn dxf(src: &str) -> String {
|
||||
src.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(|l| {
|
||||
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
|
||||
format!("{code}\n{value}\n")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The fixture with a reference to `block` at (100, 100).
|
||||
fn reference(block: &str) -> (Drawing, Handle) {
|
||||
let mut d = read_dxf(dxf(&include_str!("../data/dynblock_scale_polar.txt").replace("\r\n", "\n")).as_bytes()).unwrap();
|
||||
let ins = cadcraft_doc::Insert {
|
||||
block: block.into(),
|
||||
insert: Vec3::new(100.0, 100.0, 0.0),
|
||||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
};
|
||||
let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
(d, r)
|
||||
}
|
||||
|
||||
fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> {
|
||||
custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect()
|
||||
}
|
||||
|
||||
/// Each object of the reference's block, in block coordinates: a polyline's corners (lowest and
|
||||
/// highest), a circle's centre and radius, a line's ends.
|
||||
fn shapes(d: &Drawing, r: Handle) -> Vec<[f64; 4]> {
|
||||
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") };
|
||||
let round = |v: f64| (v * 1000.0).round() / 1000.0 + 0.0;
|
||||
d.block(&i.block)
|
||||
.unwrap()
|
||||
.entities
|
||||
.iter()
|
||||
.map(|e| match &e.kind {
|
||||
EntityKind::LwPolyline(p) => {
|
||||
let xs = p.vertices.iter().map(|v| v.p.x);
|
||||
let ys = p.vertices.iter().map(|v| v.p.y);
|
||||
[
|
||||
round(xs.clone().fold(f64::MAX, f64::min)),
|
||||
round(ys.clone().fold(f64::MAX, f64::min)),
|
||||
round(xs.fold(f64::MIN, f64::max)),
|
||||
round(ys.fold(f64::MIN, f64::max)),
|
||||
]
|
||||
}
|
||||
EntityKind::Circle(c) => [round(c.center.x), round(c.center.y), round(c.radius), 0.0],
|
||||
EntityKind::Line(l) => [round(l.a.x), round(l.a.y), round(l.b.x), round(l.b.y)],
|
||||
k => panic!("unexpected {k:?}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_scale_actions_base_and_connections() {
|
||||
let (d, _) = reference("Grow");
|
||||
let m = dynamic_block(&d, "Grow").unwrap();
|
||||
let a = m.actions.iter().find(|a| matches!(a.kind, ActionKind::Scale { .. })).unwrap();
|
||||
let ActionKind::Scale { base } = a.kind else { unreachable!() };
|
||||
assert!(base.dependent);
|
||||
let names: Vec<&str> = a.connections.iter().map(|(_, c)| c.as_str()).collect();
|
||||
assert_eq!(names, ["UpdatedBaseX", "UpdatedBaseY", "Scale", "XScale", "YScale"]);
|
||||
let m = dynamic_block(&d, "Pinned").unwrap();
|
||||
let ActionKind::Scale { base } = m.actions[0].kind else { panic!("a scale action") };
|
||||
assert!(!base.dependent);
|
||||
assert_eq!((base.at.x, base.at.y), (2.0, 2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_distance_scales_its_objects_about_the_base() {
|
||||
let (mut d, r) = reference("Grow");
|
||||
set_property(&mut d, r, "Distance1", "4").unwrap();
|
||||
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 4.0, 4.0], [2.0, 2.0, 1.0, 0.0]]);
|
||||
// The point parameter in the selection is scaled with them.
|
||||
let p = props(&d, r);
|
||||
assert!(p.contains(&("Position1 X".into(), "4.0000".into())), "{p:?}");
|
||||
assert!(p.contains(&("Position1 Y".into(), "4.0000".into())), "{p:?}");
|
||||
// From there, by the ratio of the new distance to the one it has now.
|
||||
set_property(&mut d, r, "Distance1", "1").unwrap();
|
||||
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 1.0, 1.0], [0.5, 0.5, 0.25, 0.0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fixed_base_point_stays() {
|
||||
let (mut d, r) = reference("Pinned");
|
||||
set_property(&mut d, r, "Distance1", "4").unwrap();
|
||||
assert_eq!(shapes(&d, r), vec![[-2.0, -2.0, 2.0, 2.0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_xy_parameter_scales_by_its_diagonal() {
|
||||
let (mut d, r) = reference("Sheet");
|
||||
// From (2, 2) to (4, 2): the diagonal grows from √8 to √20.
|
||||
set_property(&mut d, r, "X Distance1", "4").unwrap();
|
||||
let s = (20.0f64 / 8.0).sqrt() * 2.0;
|
||||
let round = |v: f64| (v * 1000.0).round() / 1000.0;
|
||||
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, round(s), round(s)]]);
|
||||
// A distance of 0 along one axis still leaves a diagonal: 4 long, twice the square's √8 / 2.
|
||||
set_property(&mut d, r, "Y Distance1", "0").unwrap();
|
||||
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2.828, 2.828]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scaled_objects_and_values_survive_a_save() {
|
||||
let (mut d, r) = reference("Grow");
|
||||
set_property(&mut d, r, "Distance1", "3").unwrap();
|
||||
let mut back = read_dxf(write_dxf(&d).as_bytes()).unwrap();
|
||||
assert_eq!(props(&back, r), props(&d, r));
|
||||
assert_eq!(shapes(&back, r), shapes(&d, r));
|
||||
set_property(&mut back, r, "Distance1", "6").unwrap();
|
||||
assert_eq!(shapes(&back, r), vec![[0.0, 0.0, 6.0, 6.0], [3.0, 3.0, 1.5, 0.0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_scales_are_refused_and_change_nothing() {
|
||||
let (mut d, r) = reference("Grow");
|
||||
for v in ["0", "-3", "NaN", "inf", "1e-300", "1e200"] {
|
||||
assert!(set_property(&mut d, r, "Distance1", v).is_err(), "{v}");
|
||||
}
|
||||
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2.0, 2.0], [1.0, 1.0, 0.5, 0.0]]);
|
||||
// A large factor within the limit is a large block.
|
||||
set_property(&mut d, r, "Distance1", "2e6").unwrap();
|
||||
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2e6, 2e6], [1e6, 1e6, 5e5, 0.0]]);
|
||||
// Both XY distances 0 would scale the objects to nothing; from there no ratio is known.
|
||||
let (mut d, r) = reference("Sheet");
|
||||
set_property(&mut d, r, "X Distance1", "0").unwrap();
|
||||
assert!(set_property(&mut d, r, "Y Distance1", "0").is_err());
|
||||
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 1.414, 1.414]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_polar_stretch_action() {
|
||||
let (d, _) = reference("Tag");
|
||||
let m = dynamic_block(&d, "Tag").unwrap();
|
||||
let ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, .. } = &m.actions[0].kind else { panic!("a polar stretch") };
|
||||
assert_eq!(frame.len(), 2);
|
||||
assert_eq!(vertices, &vec![(Handle(0xB0), vec![1])]);
|
||||
assert_eq!(rotate_only, &vec![Handle(0xB2)]);
|
||||
assert_eq!(*multiplier, 1.0);
|
||||
assert_eq!(m.actions[0].connections.len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polar_distance_stretches_the_frame_along_it() {
|
||||
let (mut d, r) = reference("Tag");
|
||||
set_property(&mut d, r, "Distance1", "6").unwrap();
|
||||
// The line's end and the head follow the end; the rotate-only circle stays.
|
||||
assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 6.0, 0.0], [6.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]);
|
||||
let p = props(&d, r);
|
||||
assert!(p.contains(&("Position1 X".into(), "6.0000".into())), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polar_angle_turns_everything_about_the_base() {
|
||||
let (mut d, r) = reference("Tag");
|
||||
set_property(&mut d, r, "Angle1", "90").unwrap();
|
||||
assert_eq!(shapes(&d, r), vec![[0.0, 1.0, 0.0, 4.0], [0.0, 4.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]);
|
||||
let p = props(&d, r);
|
||||
assert!(p.contains(&("Position1 X".into(), "-1.0000".into())) && p.contains(&("Position1 Y".into(), "4.0000".into())), "{p:?}");
|
||||
// Then a distance along the new direction, and back to the start.
|
||||
set_property(&mut d, r, "Distance1", "6").unwrap();
|
||||
assert_eq!(shapes(&d, r), vec![[0.0, 1.0, 0.0, 6.0], [0.0, 6.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]);
|
||||
set_property(&mut d, r, "Angle1", "0").unwrap();
|
||||
set_property(&mut d, r, "Distance1", "4").unwrap();
|
||||
assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 4.0, 0.0], [4.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polar_stretched_objects_survive_a_save() {
|
||||
let (mut d, r) = reference("Tag");
|
||||
set_property(&mut d, r, "Angle1", "90").unwrap();
|
||||
let mut back = read_dxf(write_dxf(&d).as_bytes()).unwrap();
|
||||
assert_eq!(props(&back, r), props(&d, r));
|
||||
assert_eq!(shapes(&back, r), shapes(&d, r));
|
||||
set_property(&mut back, r, "Distance1", "2").unwrap();
|
||||
assert_eq!(shapes(&back, r), vec![[0.0, 1.0, 0.0, 2.0], [0.0, 2.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_polar_values_are_refused() {
|
||||
let (mut d, r) = reference("Tag");
|
||||
for (n, v) in [("Distance1", "0"), ("Distance1", "NaN"), ("Distance1", "-inf"), ("Angle1", "nan"), ("Angle1", "1e400")] {
|
||||
assert!(set_property(&mut d, r, n, v).is_err(), "{n} {v}");
|
||||
}
|
||||
assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 4.0, 0.0], [4.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]);
|
||||
}
|
||||
@@ -118,7 +118,7 @@ fn hatch(pattern: &str, gradient: Option<Gradient>) -> Hatch {
|
||||
Hatch {
|
||||
pattern: pattern.into(),
|
||||
solid: pattern == "SOLID",
|
||||
loops: vec![HatchLoop { vertices: square(10.0), outer: true, boundary_flags: None, sources: Vec::new() }],
|
||||
loops: vec![HatchLoop { vertices: square(10.0), outer: true, sources: Vec::new() }],
|
||||
scale: 2.0,
|
||||
angle: 0.25,
|
||||
associative: false,
|
||||
|
||||
@@ -41,8 +41,8 @@ fn source_boundary_objects_roundtrip() {
|
||||
let outer = poly(&mut d, square(0.0, 20.0));
|
||||
let island = poly(&mut d, square(5.0, 5.0));
|
||||
let loops = vec![
|
||||
HatchLoop { vertices: square(0.0, 20.0), outer: true, boundary_flags: None, sources: vec![outer] },
|
||||
HatchLoop { vertices: square(5.0, 5.0), outer: false, boundary_flags: None, sources: vec![island] },
|
||||
HatchLoop { vertices: square(0.0, 20.0), outer: true, sources: vec![outer] },
|
||||
HatchLoop { vertices: square(5.0, 5.0), outer: false, sources: vec![island] },
|
||||
];
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(loops.clone(), true))).expect("add");
|
||||
// A non-associative hatch writes no sources; a source that is gone isn't written.
|
||||
@@ -79,7 +79,7 @@ fn join(p: &[(i32, String)]) -> String {
|
||||
fn sources_after_spline_fit_data_and_hostile_counts() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
let outer = poly(&mut d, square(0.0, 20.0));
|
||||
let loops = vec![HatchLoop { vertices: square(0.0, 20.0), outer: true, boundary_flags: None, sources: vec![outer] }];
|
||||
let loops = vec![HatchLoop { vertices: square(0.0, 20.0), outer: true, sources: vec![outer] }];
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(loops, true))).expect("add");
|
||||
let p = pairs(&write_dxf(&d));
|
||||
let start = p.iter().position(|(c, v)| *c == 0 && v == "HATCH").expect("HATCH");
|
||||
@@ -127,11 +127,11 @@ fn a_hatch_in_a_block_keeps_its_boundary_and_the_boundary_its_reactor() {
|
||||
let fill = d.new_handle();
|
||||
let k = EntityKind::LwPolyline(LwPolyline { vertices: square(0.0, 10.0), closed: true, const_width: 0.0, elevation: 0.0, plinegen: false });
|
||||
b.entities.push(Entity::new(outline, k));
|
||||
let loops = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, boundary_flags: None, sources: vec![outline] }];
|
||||
let loops = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, sources: vec![outline] }];
|
||||
b.entities.push(Entity::new(fill, EntityKind::Hatch(hatch(loops, true))));
|
||||
d.blocks.insert("Tag".into(), std::sync::Arc::new(b));
|
||||
// A model-space hatch whose source is in the block is not linked to it.
|
||||
let stray = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, boundary_flags: None, sources: vec![outline] }];
|
||||
let stray = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, sources: vec![outline] }];
|
||||
let other = d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(stray, true))).expect("add");
|
||||
let p = pairs(&write_dxf(&d));
|
||||
let poly = record(&p, "LWPOLYLINE", outline);
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
use cadcraft_doc::{Drawing, EntityKind, HatchLoop, Region};
|
||||
use cadcraft_io::{read_dxf, write_dxf};
|
||||
|
||||
fn boundary(points: &[(f64, f64)], flags: i64) -> String {
|
||||
let mut text = format!("92\n{flags}\n");
|
||||
if flags & 2 != 0 {
|
||||
text.push_str(&format!("72\n0\n73\n1\n93\n{}\n", points.len()));
|
||||
for (point_x, point_y) in points {
|
||||
text.push_str(&format!("10\n{point_x}\n20\n{point_y}\n"));
|
||||
}
|
||||
} else {
|
||||
text.push_str(&format!("93\n{}\n", points.len()));
|
||||
for (start, end) in points.iter().zip(points.iter().cycle().skip(1)) {
|
||||
text.push_str(&format!("72\n1\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n", start.0, start.1, end.0, end.1));
|
||||
}
|
||||
}
|
||||
text.push_str("97\n0\n");
|
||||
text
|
||||
}
|
||||
|
||||
fn logo(flags: [i64; 4]) -> String {
|
||||
let hexagon = [(-10.0, 0.0), (-5.0, -8.0), (5.0, -8.0), (10.0, 0.0), (5.0, 8.0), (-5.0, 8.0)];
|
||||
let letter = [(-3.0, -4.0), (3.0, -4.0), (3.0, -2.0), (-1.0, -2.0), (-1.0, 4.0), (-3.0, 4.0)];
|
||||
let right: Vec<_> = hexagon.iter().map(|(point_x, point_y)| (point_x + 28.0, *point_y)).collect();
|
||||
let hole: Vec<_> = hexagon.iter().map(|(point_x, point_y)| (point_x * 0.6 + 28.0, point_y * 0.6)).collect();
|
||||
let mut text = String::from("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n");
|
||||
for (index, loops) in
|
||||
[[(&hexagon[..], flags[0]), (&letter[..], flags[1])], [(&right[..], flags[2]), (&hole[..], flags[3])]].into_iter().enumerate()
|
||||
{
|
||||
text.push_str(&format!(
|
||||
"0\nHATCH\n5\n{:X}\n100\nAcDbEntity\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n1\n2\nSOLID\n70\n1\n71\n0\n91\n2\n",
|
||||
0x100 + index
|
||||
));
|
||||
for (points, flags) in loops {
|
||||
text.push_str(&boundary(points, flags));
|
||||
}
|
||||
text.push_str("75\n1\n76\n1\n98\n0\n");
|
||||
}
|
||||
text.push_str("0\nENDSEC\n0\nEOF\n");
|
||||
text
|
||||
}
|
||||
|
||||
fn flags_written(drawing: &Drawing) -> Vec<i64> {
|
||||
let text = write_dxf(drawing);
|
||||
let lines: Vec<_> = text.lines().collect();
|
||||
let mut hatch = false;
|
||||
lines
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.filter_map(|pair| {
|
||||
let code: i32 = pair[0].trim().parse().unwrap();
|
||||
if code == 0 {
|
||||
hatch = pair[1].trim() == "HATCH";
|
||||
}
|
||||
if hatch && code == 92 { Some(pair[1].trim().parse().unwrap()) } else { None }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boundary_flags_survive_dxf_open_and_save() {
|
||||
for flags in [[7, 22, 7, 6], [7, 22, 6, 20], [0, 9, 16, 31]] {
|
||||
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
|
||||
let expected = flags.map(|flag| flag | 2);
|
||||
assert_eq!(flags_written(&drawing), expected);
|
||||
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
|
||||
assert_eq!(flags_written(&back), expected);
|
||||
for entity in back.model.iter() {
|
||||
if let EntityKind::Hatch(hatch) = &entity.kind {
|
||||
let json = serde_json::to_vec(&hatch.loops).unwrap();
|
||||
let restored: Vec<HatchLoop> = serde_json::from_slice(&json).unwrap();
|
||||
assert_eq!(restored, hatch.loops);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reclassified_loops_write_current_external_bit() {
|
||||
for imported in [7, 23] {
|
||||
let mut drawing = read_dxf(logo([7, imported, 7, 6]).as_bytes()).unwrap();
|
||||
let handle = drawing.model.iter().next().unwrap().handle;
|
||||
drawing.model.modify(handle, |entity| {
|
||||
let EntityKind::Hatch(hatch) = &mut entity.kind else { panic!("expected hatch") };
|
||||
assert!(hatch.loops[1].outer);
|
||||
let mut region = Region { loops: hatch.loops.clone() };
|
||||
assert!(region.renest());
|
||||
hatch.loops = region.loops;
|
||||
assert!(!hatch.loops[1].outer);
|
||||
assert_eq!(hatch.loops[1].boundary_flags, Some(imported));
|
||||
});
|
||||
let written = flags_written(&drawing)[1];
|
||||
assert_eq!(written & 1, 0);
|
||||
assert_eq!(written & (4 | 16), imported & (4 | 16));
|
||||
assert_ne!(written & 2, 0);
|
||||
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
|
||||
assert_eq!(flags_written(&back), flags_written(&drawing));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undocumented_boundary_bits_are_not_written_back() {
|
||||
let flags = [i64::MAX, -1, 32 | 7, i64::MIN | 22];
|
||||
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
|
||||
let expected = flags.map(|flag| (flag & 31) | 2);
|
||||
assert_eq!(flags_written(&drawing), expected);
|
||||
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
|
||||
assert_eq!(flags_written(&back), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
fn boundary_flags_survive_dwg_open_and_both_save_formats() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
for flags in [[7, 22, 7, 6], [7, 22, 6, 20]] {
|
||||
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
|
||||
let bytes = cadcraft_io::write(&drawing, "logo.dwg").unwrap();
|
||||
let back = cadcraft_io::read(&bytes, "logo.dwg").unwrap();
|
||||
let expected = flags.map(|flag| flag | 2);
|
||||
assert_eq!(flags_written(&back), expected);
|
||||
let again = cadcraft_io::write(&back, "logo.dwg").unwrap();
|
||||
assert_eq!(flags_written(&cadcraft_io::read(&again, "logo.dwg").unwrap()), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_serialized_loops_keep_locally_created_flags() {
|
||||
let mut drawing = read_dxf(logo([7, 22, 6, 20]).as_bytes()).unwrap();
|
||||
let mut expected = Vec::new();
|
||||
let handles: Vec<_> = drawing.model.iter().map(|entity| entity.handle).collect();
|
||||
for handle in handles {
|
||||
drawing.model.modify(handle, |entity| {
|
||||
if let EntityKind::Hatch(hatch) = &mut entity.kind {
|
||||
for boundary in &mut hatch.loops {
|
||||
let mut json = serde_json::to_value(&*boundary).unwrap();
|
||||
json.as_object_mut().unwrap().remove("boundary_flags");
|
||||
*boundary = serde_json::from_value::<HatchLoop>(json).unwrap();
|
||||
expected.push(2 | i64::from(boundary.outer));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
assert_eq!(flags_written(&drawing), expected);
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use cadcraft_io::{read_dxf, write_dxf};
|
||||
|
||||
fn square() -> HatchLoop {
|
||||
let v = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].into_iter().map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
|
||||
HatchLoop { vertices: v, outer: true, boundary_flags: None, sources: Vec::new() }
|
||||
HatchLoop { vertices: v, outer: true, sources: Vec::new() }
|
||||
}
|
||||
|
||||
fn hatch(pattern: &str, scale: f64, angle: f64, origin: Vec2, lines: Vec<PatternLine>) -> Hatch {
|
||||
|
||||
@@ -72,41 +72,3 @@ fn the_page_still_decides_the_bits_cadcraft_models() {
|
||||
d.layouts.last_mut().unwrap().page = PageSetup::default();
|
||||
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128 | 32 | 16));
|
||||
}
|
||||
|
||||
/// Each LAYOUT object's name and plot layout flags (the AcDbLayout group 1 and the
|
||||
/// AcDbPlotSettings group 70) in DXF text.
|
||||
fn layout_plot_flags(text: &str) -> Vec<(String, i64)> {
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut out = Vec::new();
|
||||
let (mut inside, mut subclass, mut name, mut flags) = (false, "", None, None);
|
||||
for pair in lines.chunks(2) {
|
||||
let [code, value] = pair else { break };
|
||||
match *code {
|
||||
"0" => {
|
||||
if let (true, Some(n), Some(f)) = (inside, name.take(), flags.take()) {
|
||||
out.push((n, f));
|
||||
}
|
||||
(inside, subclass, name, flags) = (*value == "LAYOUT", "", None, None);
|
||||
}
|
||||
"100" if inside => subclass = value,
|
||||
"70" if inside && subclass == "AcDbPlotSettings" => flags = value.parse().ok(),
|
||||
"1" if inside && subclass == "AcDbLayout" => name = Some(value.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_model_layout_carries_the_model_type_flag() {
|
||||
// 1024 is "ModelType" (DXF Reference, PLOTSETTINGS group 70): the plot settings of model space.
|
||||
// The Model layout carries it; a paper layout does not, even when it was read with it.
|
||||
for read in [688, 688 | 1024] {
|
||||
let bytes = write(&drawing(read), "sheet.dxf").unwrap();
|
||||
let layouts = layout_plot_flags(&String::from_utf8_lossy(&bytes));
|
||||
let flags = |name: &str| layouts.iter().find(|(n, _)| n == name).map(|&(_, f)| f);
|
||||
let (model, sheet) = (flags("Model").unwrap(), flags("SHEET").unwrap());
|
||||
assert_ne!(model & 1024, 0, "Model, SHEET read with {read}: {layouts:?}");
|
||||
assert_eq!(sheet & 1024, 0, "SHEET read with {read}: {layouts:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,17 +25,12 @@ mod dwg_layout_owner;
|
||||
mod dwg_roundtrip_losses;
|
||||
mod dwt_template;
|
||||
mod dxf_versions;
|
||||
mod dynblock_array;
|
||||
mod dynblock_params;
|
||||
mod dynblock_read;
|
||||
mod dynblock_rotate_flip;
|
||||
mod dynblock_scale_polar;
|
||||
mod entity_props_roundtrip;
|
||||
mod exhausted_handseed;
|
||||
mod followups_626;
|
||||
mod groups_roundtrip;
|
||||
mod hatch_assoc_roundtrip;
|
||||
mod hatch_loop_flags;
|
||||
mod hatch_pattern_def;
|
||||
mod helix_roundtrip;
|
||||
mod layer_states_acad;
|
||||
@@ -95,7 +90,5 @@ mod user_lin_pat_roundtrip;
|
||||
mod view_tables_roundtrip;
|
||||
mod view_target;
|
||||
mod viewport_clip_roundtrip;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod visualstyle_dwg;
|
||||
mod xclip_roundtrip;
|
||||
mod xref_roundtrip;
|
||||
|
||||
@@ -19,7 +19,7 @@ fn regions(d: &Drawing) -> Vec<Region> {
|
||||
|
||||
fn square(x: f64, y: f64, s: f64, outer: bool) -> HatchLoop {
|
||||
let v = |a: f64, b: f64| PolyVertex::new(Vec2::new(a, b));
|
||||
HatchLoop { vertices: vec![v(x, y), v(x + s, y), v(x + s, y + s), v(x, y + s)], outer, boundary_flags: None, sources: Vec::new() }
|
||||
HatchLoop { vertices: vec![v(x, y), v(x + s, y), v(x + s, y + s), v(x, y + s)], outer, sources: Vec::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -29,7 +29,6 @@ fn region_with_islands_survives_save_and_reopen() {
|
||||
let hole = HatchLoop {
|
||||
vertices: vec![PolyVertex::with_bulge(Vec2::new(3.0, 5.0), 1.0), PolyVertex::with_bulge(Vec2::new(7.0, 5.0), 1.0)],
|
||||
outer: false,
|
||||
boundary_flags: None,
|
||||
sources: Vec::new(),
|
||||
};
|
||||
let r = Region { loops: vec![square(0.0, 0.0, 10.0, true), hole, square(4.5, 4.5, 1.0, true), square(20.0, 0.0, 2.0, true)] };
|
||||
|
||||
@@ -226,7 +226,7 @@ pub(crate) fn hatches() -> Vec<Case> {
|
||||
EntityKind::Hatch(Hatch {
|
||||
pattern: "SOLID".into(),
|
||||
solid: true,
|
||||
loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, boundary_flags: Some(3), sources: Vec::new() }],
|
||||
loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, sources: Vec::new() }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: false,
|
||||
|
||||
@@ -39,6 +39,8 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) {
|
||||
explodable,
|
||||
units,
|
||||
array,
|
||||
// Session state (when an xref was read), never in a file.
|
||||
xref_stamp: _,
|
||||
} = block.as_ref();
|
||||
equal(name, &back.name, &path, "name");
|
||||
equal(annotative, &back.annotative, &path, "annotative");
|
||||
@@ -373,53 +375,3 @@ fn angle_tolerance_does_not_hide_real_changes_or_nonfinite_values() {
|
||||
assert!(std::panic::catch_unwind(|| angle(0.7, actual, "self-test", "angle")).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// Authored two-point text saves the dimensions of its measured span. Expectations come from
|
||||
/// shaping and geometry, independently of the save fitting helper; all field assertions remain.
|
||||
pub(super) fn authored_text_dimensions(d: &Drawing) -> Drawing {
|
||||
fn fit(d: &Drawing, t: &mut Text) {
|
||||
use cadcraft_doc::HAlign;
|
||||
if !matches!(t.halign, HAlign::Aligned | HAlign::Fit) {
|
||||
return;
|
||||
}
|
||||
let Some(second) = t.align_pt else { return };
|
||||
let distance = t.insert.xy().dist(second.xy());
|
||||
if !distance.is_finite() || distance <= 1e-12 {
|
||||
return;
|
||||
}
|
||||
t.rotation = t.insert.xy().angle_to(second.xy());
|
||||
let style = d.text_style(&t.style).cloned().unwrap_or_default();
|
||||
let font = cadcraft_render::style_font(&style);
|
||||
let width = cadcraft_fonts::shape_line_dir(&font, &t.value, t.height, t.width_factor, t.oblique, Some(false)).width;
|
||||
if width.is_finite() && width > 1e-12 {
|
||||
if t.halign == HAlign::Aligned {
|
||||
t.height *= distance / width;
|
||||
} else {
|
||||
t.width_factor *= distance / width;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn store(d: &Drawing, entities: &mut EntityStore) {
|
||||
for h in entities.handles() {
|
||||
// Read-time measurements already have their own preservation contract.
|
||||
if d.foreign.text_fits.contains_key(&h) {
|
||||
continue;
|
||||
}
|
||||
entities.modify(h, |e| match &mut e.kind {
|
||||
EntityKind::Text(t) => fit(d, t),
|
||||
EntityKind::AttDef(a) => fit(d, &mut a.text),
|
||||
EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| fit(d, &mut a.text)),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut expected = d.clone();
|
||||
store(d, &mut expected.model);
|
||||
for layout in &mut expected.layouts {
|
||||
store(d, &mut layout.entities);
|
||||
}
|
||||
for block in expected.blocks.values_mut() {
|
||||
store(d, &mut std::sync::Arc::make_mut(block).entities);
|
||||
}
|
||||
expected
|
||||
}
|
||||
|
||||
@@ -57,8 +57,6 @@ fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, versio
|
||||
}
|
||||
|
||||
fn check_version_using(case: &str, original: &Drawing, expected: &Drawing, version: Version, verify: impl Fn(&Drawing, &Drawing, &str)) {
|
||||
let expected_dimensions = compare::authored_text_dimensions(expected);
|
||||
let expected = &expected_dimensions;
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let options = SaveOptions { version: Some(version), binary: false };
|
||||
let mut current = original.clone();
|
||||
|
||||
@@ -33,8 +33,6 @@ fn check_version(case: &str, original: &Drawing, expected: &Drawing, version: Ve
|
||||
}
|
||||
|
||||
fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, version: Version, extra: impl Fn(&Drawing, &Drawing, &str)) {
|
||||
let expected_dimensions = compare::authored_text_dimensions(expected);
|
||||
let expected = &expected_dimensions;
|
||||
for binary in [false, true] {
|
||||
let options = SaveOptions { version: Some(version), binary };
|
||||
let mut current = original.clone();
|
||||
|
||||
@@ -19,7 +19,7 @@ fn user_linetypes_and_patterns_survive_dxf() {
|
||||
let h = Hatch {
|
||||
pattern: steps.name.clone(),
|
||||
solid: false,
|
||||
loops: vec![HatchLoop { vertices: square, outer: true, boundary_flags: None, sources: Vec::new() }],
|
||||
loops: vec![HatchLoop { vertices: square, outer: true, sources: Vec::new() }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: false,
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
//! Original synthetic geometry, style values and xdata, licensed with the repository.
|
||||
//! The fixed fields follow Autodesk's 2010 DXF Reference, VISUALSTYLE, pp. 208-210:
|
||||
//! https://images.autodesk.com/adsk/files/acad_dxf1.pdf
|
||||
|
||||
use cadcraft_doc::EntityKind;
|
||||
use cadcraft_io::{SaveOptions, Version};
|
||||
|
||||
fn source(version: &str) -> String {
|
||||
let mut text = format!(
|
||||
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\n{version}\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nAPPID\n5\n10\n100\nAcDbSymbolTable\n70\n1\n\
|
||||
0\nAPPID\n5\n11\n330\n10\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n2\nACAD\n70\n0\n0\nENDTAB\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic0\n350\n21\n3\nSynthetic1\n350\n22\n"
|
||||
);
|
||||
for index in 0..2 {
|
||||
text.push_str(&format!(
|
||||
"0\nVISUALSTYLE\n5\n{:X}\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic{index}\n\
|
||||
70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\
|
||||
74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n\
|
||||
76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n\
|
||||
1001\nACAD\n1000\nAcRTDxfName\n1000\nVISUALSTYLE\n",
|
||||
0x21 + index
|
||||
));
|
||||
}
|
||||
text.push_str("0\nENDSEC\n0\nEOF\n");
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_visualstyles_are_reported_and_left_out_of_2007_dwg_only() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
for from in ["AC1021", "AC1024"] {
|
||||
let drawing = cadcraft_io::read_dxf(source(from).as_bytes()).unwrap();
|
||||
let styles = || drawing.foreign.objects.iter().filter(|object| object.kind == "VISUALSTYLE").count();
|
||||
assert_eq!(styles(), 2);
|
||||
for version in [Version::R2007, Version::R2013] {
|
||||
let options = SaveOptions { version: Some(version), binary: false };
|
||||
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
|
||||
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
|
||||
assert!(back.model.iter().any(|entity| matches!(entity.kind, EntityKind::Line(_))));
|
||||
let retained = back
|
||||
.foreign
|
||||
.objects
|
||||
.iter()
|
||||
.any(|object| object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 2 && tag.value.starts_with("Synthetic")));
|
||||
if version == Version::R2007 {
|
||||
assert_eq!(report.get("VISUALSTYLE"), Some(&styles()));
|
||||
assert!(!retained);
|
||||
} else {
|
||||
assert!(!report.contains_key("VISUALSTYLE"));
|
||||
assert!(retained);
|
||||
}
|
||||
let (dxf, report) = cadcraft_io::write_noted(&drawing, "styles.dxf", &options).unwrap();
|
||||
assert!(report.is_empty());
|
||||
let back = cadcraft_io::read_dxf(&dxf).unwrap();
|
||||
assert_eq!(back.foreign.objects.iter().filter(|object| object.kind == "VISUALSTYLE").count(), styles());
|
||||
}
|
||||
assert_eq!(styles(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orphaned_legacy_visualstyles_are_not_reported_as_compatibility_omissions() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut drawing = cadcraft_io::read_dxf(source("AC1021").as_bytes()).unwrap();
|
||||
let foreign = std::sync::Arc::make_mut(&mut drawing.foreign);
|
||||
let orphan = foreign.objects.iter_mut().find(|object| object.kind == "VISUALSTYLE").unwrap();
|
||||
orphan.tags.iter_mut().find(|tag| tag.code == 330).unwrap().value = "FF".into();
|
||||
let options = SaveOptions { version: Some(Version::R2007), binary: false };
|
||||
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
|
||||
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
|
||||
assert!(back.model.iter().any(|entity| matches!(entity.kind, EntityKind::Line(_))));
|
||||
assert_eq!(report.get("VISUALSTYLE"), Some(&1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newer_visualstyle_properties_are_kept_in_2007_dwg() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let document = acadrust::DxfReader::from_reader(std::io::Cursor::new(source("AC1027").into_bytes())).unwrap().read().unwrap();
|
||||
let modern = acadrust::DxfWriter::new(&document).write_to_vec().unwrap();
|
||||
let drawing = cadcraft_io::read_dxf(&modern).unwrap();
|
||||
assert!(drawing.foreign.objects.iter().any(|object| object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 176)));
|
||||
let options = SaveOptions { version: Some(Version::R2007), binary: false };
|
||||
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
|
||||
assert!(!report.contains_key("VISUALSTYLE"));
|
||||
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
|
||||
assert!(
|
||||
back.foreign
|
||||
.objects
|
||||
.iter()
|
||||
.any(|object| { object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 2 && tag.value.starts_with("Synthetic")) })
|
||||
);
|
||||
}
|
||||
+128
-22
@@ -3,8 +3,7 @@
|
||||
//! rotation, width factor and obliquing; fonts whose licence bits forbid embedding, the stroke
|
||||
//! font and the `text: "geometry"` option keep filled outlines.
|
||||
//!
|
||||
//! The fonts are tiny synthetic TrueType files built by the shared test helper in
|
||||
//! `crates/fonts/tests/support/sfnt.rs` (no font files in the repository).
|
||||
//! The fonts are tiny synthetic TrueType files built here (no font files in the repository).
|
||||
|
||||
use cadcraft_doc::{Common, Drawing, EntityKind, Space, Text, TextStyle, Viewport};
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
@@ -16,30 +15,137 @@ mod pdf_read;
|
||||
|
||||
use pdf_read::Doc;
|
||||
|
||||
// The synthetic TrueType file: the fonts layer's test-only helper, inlined rather than published
|
||||
// or depended on.
|
||||
#[path = "../../fonts/tests/support/sfnt.rs"]
|
||||
mod sfnt;
|
||||
|
||||
// ---------- a minimal TrueType font: .notdef, "A" (triangle), "B" (square) ----------
|
||||
|
||||
fn be16(v: &mut Vec<u8>, x: u16) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
fn be32(v: &mut Vec<u8>, x: u32) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
|
||||
/// A simple glyph: one closed contour of on-curve points.
|
||||
fn simple_glyph(pts: &[(i16, i16)]) -> Vec<u8> {
|
||||
let mut g = Vec::new();
|
||||
let xs: Vec<i16> = pts.iter().map(|p| p.0).collect();
|
||||
let ys: Vec<i16> = pts.iter().map(|p| p.1).collect();
|
||||
be16(&mut g, 1);
|
||||
for v in [*xs.iter().min().unwrap(), *ys.iter().min().unwrap(), *xs.iter().max().unwrap(), *ys.iter().max().unwrap()] {
|
||||
be16(&mut g, v as u16);
|
||||
}
|
||||
be16(&mut g, pts.len() as u16 - 1);
|
||||
be16(&mut g, 0);
|
||||
g.extend(std::iter::repeat_n(1u8, pts.len()));
|
||||
let (mut px, mut py) = (0i16, 0i16);
|
||||
for (x, _) in pts {
|
||||
be16(&mut g, (x - px) as u16);
|
||||
px = *x;
|
||||
}
|
||||
for (_, y) in pts {
|
||||
be16(&mut g, (y - py) as u16);
|
||||
py = *y;
|
||||
}
|
||||
while g.len() % 4 != 0 {
|
||||
g.push(0);
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
/// A TrueType font with glyphs .notdef (empty), A and B, and OS/2 `fsType`. `hmtx` holds
|
||||
/// `metrics` of the three metrics `hhea` declares: fewer is a font the writer cannot subset.
|
||||
/// `metrics` of the three metrics `hhea` declares.
|
||||
fn test_font(fs_type: u16, metrics: usize) -> Vec<u8> {
|
||||
sfnt::bytes(&sfnt::Sfnt {
|
||||
// "A" is a triangle and "B" a square: one contour each.
|
||||
glyphs: &[
|
||||
sfnt::notdef(),
|
||||
sfnt::glyph(&[vec![(50, 0), (550, 0), (300, 700)]]),
|
||||
sfnt::glyph(&[vec![(50, 0), (550, 0), (550, 700), (50, 700)]]),
|
||||
],
|
||||
cmap: &[(0x41, 0x42, 1 - 0x41)], // "A".."B" → glyphs 1..2
|
||||
advance: 600,
|
||||
lsb: 50,
|
||||
metrics,
|
||||
fs_type,
|
||||
ink_box: [0, 0, 600, 700],
|
||||
})
|
||||
let glyphs = [Vec::new(), simple_glyph(&[(50, 0), (550, 0), (300, 700)]), simple_glyph(&[(50, 0), (550, 0), (550, 700), (50, 700)])];
|
||||
let mut glyf = Vec::new();
|
||||
let mut loca = Vec::new();
|
||||
for g in &glyphs {
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
glyf.extend_from_slice(g);
|
||||
}
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
let mut head = Vec::new();
|
||||
be32(&mut head, 0x0001_0000);
|
||||
be32(&mut head, 0x0001_0000);
|
||||
be32(&mut head, 0);
|
||||
be32(&mut head, 0x5F0F_3CF5);
|
||||
be16(&mut head, 0);
|
||||
be16(&mut head, 1000);
|
||||
head.extend_from_slice(&[0; 16]);
|
||||
for v in [0i16, 0, 600, 700] {
|
||||
be16(&mut head, v as u16);
|
||||
}
|
||||
for v in [0u16, 8, 2, 1, 0] {
|
||||
be16(&mut head, v);
|
||||
}
|
||||
let mut hhea = Vec::new();
|
||||
be32(&mut hhea, 0x0001_0000);
|
||||
for v in [800i16, -200, 0, 600, 0, 0, 600, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut hhea, v as u16);
|
||||
}
|
||||
be16(&mut hhea, 3);
|
||||
let mut maxp = Vec::new();
|
||||
be32(&mut maxp, 0x0001_0000);
|
||||
for v in [3u16, 4, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut maxp, v);
|
||||
}
|
||||
let mut hmtx = Vec::new();
|
||||
for _ in 0..metrics {
|
||||
be16(&mut hmtx, 600);
|
||||
be16(&mut hmtx, 50);
|
||||
}
|
||||
// cmap: format 4, 'A'..'B' → 1..2.
|
||||
let mut sub = Vec::new();
|
||||
let segs: [(u16, u16, u16); 2] = [(0x41, 0x42, 1u16.wrapping_sub(0x41)), (0xFFFF, 0xFFFF, 1)];
|
||||
be16(&mut sub, 4);
|
||||
be16(&mut sub, (16 + segs.len() * 8) as u16);
|
||||
be16(&mut sub, 0);
|
||||
be16(&mut sub, (segs.len() * 2) as u16);
|
||||
for v in [4u16, 1, 0] {
|
||||
be16(&mut sub, v);
|
||||
}
|
||||
for s in segs {
|
||||
be16(&mut sub, s.1);
|
||||
}
|
||||
be16(&mut sub, 0);
|
||||
for s in segs {
|
||||
be16(&mut sub, s.0);
|
||||
}
|
||||
for s in segs {
|
||||
be16(&mut sub, s.2);
|
||||
}
|
||||
for _ in segs {
|
||||
be16(&mut sub, 0);
|
||||
}
|
||||
let mut cmap = Vec::new();
|
||||
for v in [0u16, 1, 3, 1] {
|
||||
be16(&mut cmap, v);
|
||||
}
|
||||
be32(&mut cmap, 12);
|
||||
cmap.extend_from_slice(&sub);
|
||||
let mut os2 = vec![0u8; 78];
|
||||
os2[8..10].copy_from_slice(&fs_type.to_be_bytes());
|
||||
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
|
||||
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
|
||||
tables.sort_by_key(|t| *t.0);
|
||||
let mut out = Vec::new();
|
||||
be32(&mut out, 0x0001_0000);
|
||||
for v in [tables.len() as u16, 128, 3, tables.len() as u16 * 16 - 128] {
|
||||
be16(&mut out, v);
|
||||
}
|
||||
let mut off = 12 + 16 * tables.len();
|
||||
for (t, d) in &tables {
|
||||
out.extend_from_slice(*t);
|
||||
be32(&mut out, 0);
|
||||
be32(&mut out, off as u32);
|
||||
be32(&mut out, d.len() as u32);
|
||||
off += d.len().div_ceil(4) * 4;
|
||||
}
|
||||
for (_, d) in &tables {
|
||||
out.extend_from_slice(d);
|
||||
while out.len() % 4 != 0 {
|
||||
out.push(0);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Register the test fonts once: an embeddable one, one with a restricted licence, and one
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user