Compare commits

..
Author SHA1 Message Date
FredApps 384d41d6ff fix(engine): use placed annotative text in selection 2026-12-03 16:12:10 +01:00
142 changed files with 622 additions and 8456 deletions
+2 -3
View File
@@ -32,8 +32,8 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
| `vendor/wgpu-hal/` | wgpu developers; Metal language probe by CADCraft contributors | [wgpu-hal 30.0.1](https://crates.io/crates/wgpu-hal/30.0.1) ([gfx-rs/wgpu 40f4a34e](https://github.com/gfx-rs/wgpu/tree/40f4a34ebaf56f9a046231f54125ad046239d3f3/wgpu-hal)), same patch as [storytold/craft-anything vendor/wgpu-hal](https://github.com/storytold/craft-anything/tree/6c7d1f07f9f33643714bd203e1e004f04481f28e/vendor/wgpu-hal) | MIT OR Apache-2.0 | Graphics dependency, patched in `src/metal/adapter.rs` only (#1631); see `vendor/wgpu-hal/CADCRAFT.md`. |
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.9](https://github.com/storytold/acadrust/blob/468b9d8e317755209020d5d3f2f1c8a76210c47f/LICENSE) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.9 third-party notices](https://github.com/storytold/acadrust/blob/468b9d8e317755209020d5d3f2f1c8a76210c47f/THIRD_PARTY_NOTICES.md) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.6](https://crates.io/crates/acadrust/0.6.6), [hakanaktt/acadrust](https://github.com/hakanaktt/acadrust), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.6 third-party notices](https://github.com/hakanaktt/acadrust/blob/v0.6.6/THIRD_PARTY_NOTICES.md), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. |
| `krilla 0.8.2 / icc/sGrey-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v4.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d`. |
@@ -89,7 +89,6 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star; terminology pass by @YannFR81 | Original French translations of CADCraft English strings; AI-assisted consistency pass (imperative prompts, cote/espace objet/réseau/présentation) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/zh.tsv` | @mayloglog | Original Simplified Chinese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/fi.tsv` | @Janiz-zzz with Claude Code (AI-assisted) | Original Finnish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted); terminology corrections: Andrea Brandi (@starise) with OpenAI Codex (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; targeted Chamfer terminology review by a native speaker |
| `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added |
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif; missing rows and the Find and Replace dialog: Saleh Hassan Alnemari (@salehnemari-max) with Claude Code (AI-assisted) | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the added rows reviewed line by line by the translator, a native speaker |
Generated
+137 -394
View File
File diff suppressed because it is too large Load Diff
+38 -43
View File
@@ -16,12 +16,12 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -31,24 +31,19 @@ cadcraft-io = { path = "crates/io" }
cadcraft-engine = { path = "crates/engine" }
cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# Agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and
# the CLI's live client (`agents`), shared by every Craft app.
craft-control = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# The agent link host (the window's control server for agents) and the Agents page of Options.
craft-automation = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", default-features = false }
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", default-features = false }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -82,12 +77,12 @@ encoding_rs = "0.8.35"
quick-xml = "0.42"
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", features = ["ui"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -98,7 +93,7 @@ egui-wgpu = "0.37"
# Monotonic time on native and web (performance.now on wasm).
web-time = "1.1"
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", features = ["ui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
rfd = "0.18"
arboard = { version = "3.6", default-features = false }
@@ -130,27 +125,27 @@ debug = 0
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
# (Cargo ignores dependency-local patches).
[patch.crates-io]
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# wgpu-hal that picks a Metal language version the system compiler accepts, not the OS's alone
# (#1631; upstream gfx-rs/wgpu#10687). See vendor/wgpu-hal/CADCRAFT.md for when to remove it.
wgpu-hal = { path = "vendor/wgpu-hal" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+12 -10
View File
@@ -10,10 +10,11 @@ docs/brand/LICENSE-brand.txt.
Third-party material
Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust
crate (DWG reading and writing) 0.6.9 is licensed under the Mozilla Public License 2.0
and is used as a separate library via craft-dwg. Its source is available at
https://github.com/storytold/acadrust/tree/468b9d8e317755209020d5d3f2f1c8a76210c47f. The licence text and
upstream third-party notices are retained in licenses/dwg/.
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) 0.6.6 is licensed under the
Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source
is available from crates.io and the repository above. The licence text and upstream third-party
notices are retained in licenses/dwg/, copied verbatim from craft-libs at
8fa4db64a9bb943520259ea95331a303ba788f21, the revision this repository pins.
acadrust's DWG reader and writer include code ported and adapted from ACadSharp
(https://github.com/DomCR/ACadSharp), Copyright (c) 2021 Albert Domenech, under the MIT License.
@@ -431,12 +432,13 @@ SOFTWARE.
## DWG Format References
The Open Design Alliance (ODA) DWG specification is the primary published reference for
the binary layouts documented by this project. Where the specification is incomplete or
ambiguous, implementation details are checked against native DWG files produced by CAD
applications. Source comments and regression tests identify the evidence used for each
layout and behavior. ACadSharp remains the attributed origin of the existing reader and
writer code described above.
DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG
specification and reverse engineering, including comparison with drawings produced by CAD
applications. LibreDWG is used as a secondary cross-check for selected field names and
layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's
`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not
translated routines. The repository history and source review found no LibreDWG routines
ported into the implementation. The source comments identify the specific cross-checks.
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
+1 -4
View File
@@ -124,7 +124,7 @@ numbers):
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული), Tamil (தமிழ், with an installed Tamil font), Dutch (Nederlands) and European Portuguese (Português (Portugal)) (catalogs in `storytold/craft-i18n`; fall back to English until embedded), Finnish (Suomi), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული), Tamil (தமிழ், with an installed Tamil font), Dutch (Nederlands) and European Portuguese (Português (Portugal)) (catalogs in `storytold/craft-i18n`; fall back to English until embedded), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) |
## Quick start
@@ -412,9 +412,6 @@ instead. `CADCRAFT_TITLEBAR=app` or `CADCRAFT_TITLEBAR=system` overrides the det
### FreeBSD
Prebuilt FreeBSD archives require FreeBSD 15.1 or later. They are built against
FreeBSD 15.1-STABLE; older FreeBSD releases are not supported by these binaries.
| Build | File |
|---|---|
| x86_64 | `cadcraft-<ver>-freebsd-x86_64.tar.gz` |
+8 -48
View File
@@ -11,7 +11,6 @@ use std::path::{Path, PathBuf};
use cadcraft_engine::geom::{Bounds2, Vec2};
use cadcraft_io::Format;
use cadcraft_mcp::args::{blank_env_is_unset, name_env_vars};
use cadcraft_mcp::live::WhenAppClosed;
use clap::builder::{OsStringValueParser, PathBufValueParser, TypedValueParser};
use clap::error::ErrorKind;
use clap::parser::ValueSource;
@@ -263,23 +262,12 @@ pub(crate) struct CommandsArgs {
pub(crate) compact: bool,
}
/// Run the MCP server on stdio: the open CADCraft window while ArtCraft Launcher › Settings › AI
/// agents lets agents use it, otherwise a headless drawing session
/// Run the MCP server on stdio: a headless drawing session, or a bridge to the running app
#[derive(Args)]
pub(crate) struct McpArgs {
/// Deprecated: plain `mcp` finds the open window by itself while the ArtCraft Launcher lets
/// agents use CADCraft. Bridges to the app's --control port (e.g. 127.0.0.1:7979); goes in a
/// later release
/// Bridge to the app's control channel (its --control port, e.g. 127.0.0.1:7979)
#[arg(long, value_name = "HOST:PORT", value_parser = connect_addr)]
pub(crate) connect: Option<String>,
/// Never the open window: a headless drawing session, also while the ArtCraft Launcher lets
/// agents use CADCraft
#[arg(long, conflicts_with = "connect")]
pub(crate) headless: bool,
/// While agents may use CADCraft but it is closed: `launch` (open it and wait), `headless`
/// (work without a window) or `error`. Default: Options › AI Agents › When CADCraft is closed
#[arg(long, value_name = "CHOICE", value_parser = when_closed, conflicts_with_all = ["connect", "headless"])]
pub(crate) when_closed: Option<WhenAppClosed>,
/// Reach the app at the first call instead of at startup, so the server can start before the
/// app is open
#[arg(long, requires = "connect")]
@@ -416,8 +404,6 @@ pub(crate) enum ValueError {
CmdJson(#[from] serde_json::Error),
#[error("expected a number of 0 or more, got `{0}`")]
Tolerance(String),
#[error("expected one of launch, headless, error, got `{0}`")]
WhenClosed(String),
}
/// Why `parse` refuses flags clap accepted: clap prints it as a usage error (exit 2).
@@ -537,12 +523,8 @@ fn out_is_input(cli: &Cli) -> Option<UsageError> {
/// The backend `cadcraft-cli mcp` serves from.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum McpTarget {
/// An in-process drawing session (`--headless`), optionally confined to the two folders.
/// An in-process drawing session (no `--connect`), optionally confined to the two folders.
Headless { read_root: Option<String>, write_root: Option<String> },
/// Plain `mcp`: the open window while the ArtCraft Launcher's switch lets agents use CADCraft,
/// otherwise a headless session with the two folders (`cadcraft_mcp::Live`); headless without
/// the suite's `AI-MCP` flag, as before.
Live { read_root: Option<String>, write_root: Option<String>, when_closed: Option<WhenAppClosed> },
/// The running app's control channel at `HOST:PORT`; `lazy`: reached at the first call;
/// `launch`: opened then if it isn't running.
Connect { addr: String, lazy: bool, launch: bool },
@@ -551,12 +533,10 @@ pub(crate) enum McpTarget {
impl McpArgs {
/// What these arguments ask the server to talk to.
pub(crate) fn target(&self) -> McpTarget {
let (read_root, write_root) = (self.automation_read_root.clone(), self.automation_write_root.clone());
match &self.connect {
// `--launch` connects at the first call too (the app opens then).
Some(addr) => McpTarget::Connect { addr: addr.clone(), lazy: self.lazy || self.launch, launch: self.launch },
None if self.headless => McpTarget::Headless { read_root, write_root },
None => McpTarget::Live { read_root, write_root, when_closed: self.when_closed },
None => McpTarget::Headless { read_root: self.automation_read_root.clone(), write_root: self.automation_write_root.clone() },
}
}
}
@@ -573,11 +553,6 @@ fn connect_addr(s: &str) -> Result<String, ValueError> {
if valid { Ok(s.to_string()) } else { Err(ValueError::Connect) }
}
/// `mcp --when-closed`: one of [`WhenAppClosed::NAMES`].
fn when_closed(s: &str) -> Result<WhenAppClosed, ValueError> {
WhenAppClosed::parse(s.trim()).ok_or_else(|| ValueError::WhenClosed(s.to_string()))
}
/// The values of `id` with their command-line indices.
fn indexed<'a, T: Clone + Send + Sync + 'static>(m: &'a ArgMatches, id: &str) -> impl Iterator<Item = (usize, &'a T)> {
let at = m.indices_of(id).into_iter().flatten();
@@ -690,21 +665,10 @@ mod tests {
}
}
/// Plain `mcp` looks for the open window (headless while the launcher doesn't let agents in);
/// `--headless` never does. Neither confines anything unless asked.
/// Without `--connect` the server runs headless, confining nothing unless asked.
#[test]
fn plain_mcp_looks_for_the_window_and_headless_never_does() {
assert_eq!(mcp(&[]).unwrap(), McpTarget::Live { read_root: None, write_root: None, when_closed: None });
assert_eq!(mcp(&["--headless"]).unwrap(), McpTarget::Headless { read_root: None, write_root: None });
assert_eq!(
mcp(&["--when-closed", "headless"]).unwrap(),
McpTarget::Live { read_root: None, write_root: None, when_closed: Some(WhenAppClosed::Headless) }
);
assert!(mcp(&["--when-closed", "later"]).unwrap_err().to_string().contains("launch, headless, error"));
// A closed-app choice means nothing without the window, and --connect names its own app.
for conflict in [&["--headless", "--when-closed", "error"][..], &["--headless", "--connect", "127.0.0.1:7979"]] {
assert_eq!(mcp(conflict).unwrap_err().kind(), clap::error::ErrorKind::ArgumentConflict, "{conflict:?}");
}
fn mcp_without_connect_is_headless() {
assert_eq!(mcp(&[]).unwrap(), McpTarget::Headless { read_root: None, write_root: None });
}
/// The automation roots confine a headless server; `--connect` is refused with the reason
@@ -712,13 +676,9 @@ mod tests {
#[test]
fn mcp_automation_roots_confine_a_headless_server_only() {
assert_eq!(
mcp(&["--headless", "--automation-read-root", "/work", "--automation-write-root=/work/out"]).unwrap(),
mcp(&["--automation-read-root", "/work", "--automation-write-root=/work/out"]).unwrap(),
McpTarget::Headless { read_root: Some("/work".into()), write_root: Some("/work/out".into()) }
);
assert_eq!(
mcp(&["--automation-read-root", "/work"]).unwrap(),
McpTarget::Live { read_root: Some("/work".into()), write_root: None, when_closed: None }
);
let e = mcp(&["--connect", "127.0.0.1:7979", "--automation-read-root", "/work"]).unwrap_err().to_string();
assert!(e.contains("headless MCP server") && e.contains("#1585"), "{e}");
let e = mcp(&["--automation-write-root=/work", "--connect", "127.0.0.1:7979"]).unwrap_err().to_string();
+13 -84
View File
@@ -1,96 +1,25 @@
use std::path::{Path, PathBuf};
use super::args::{McpArgs, McpTarget};
use super::error::{CliError, Result};
/// Serve MCP on stdin and stdout: plain `mcp` against the open window while the ArtCraft Launcher
/// lets agents use CADCraft, otherwise (and with `--headless`) a headless session held to any roots
/// given; `--connect` against an app's `--control` port.
/// Serve MCP on stdin and stdout against the running app or a headless session held to any roots given.
pub(crate) fn mcp(a: &McpArgs) -> Result {
let backend: Box<dyn cadcraft_mcp::Backend> = match a.target() {
McpTarget::Connect { addr, lazy, launch } => {
let remote = if lazy {
cadcraft_mcp::Remote::lazy(&addr, launch)
} else {
cadcraft_mcp::Remote::connect(&addr).map_err(|source| CliError::McpConnect { addr, source })?
};
// Once the bridge serves: a failed start says only why it failed.
eprintln!(
"cadcraft-cli: `mcp --connect` is deprecated and goes in a later release; plain `cadcraft-cli mcp` finds the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it"
);
Box::new(remote)
McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)),
McpTarget::Connect { addr, .. } => match cadcraft_mcp::Remote::connect(&addr) {
Ok(r) => Box::new(r),
Err(source) => return Err(CliError::McpConnect { addr, source }),
},
McpTarget::Headless { read_root, write_root } => {
let roots = cadcraft_engine::file_access::AutomationRoots::new(
read_root.as_deref().map(std::path::Path::new),
write_root.as_deref().map(std::path::Path::new),
)
.map_err(CliError::AutomationRoots)?;
Box::new(cadcraft_mcp::Headless::default().with_automation_roots(roots))
}
McpTarget::Live { read_root, write_root, when_closed } => {
match config_dir(a.settings.config_dir.as_deref()).filter(|_| cadcraft_mcp::live::mcp_flag()) {
Some(dir) => {
// Roots that can't be opened stop the server now, as they do headless.
headless(read_root.as_deref(), write_root.as_deref())?;
let mut cfg = cadcraft_mcp::LiveConfig::new(dir);
cfg.when_closed = when_closed;
cfg.read_root = read_root.map(PathBuf::from);
cfg.write_root = write_root.map(PathBuf::from);
cfg.launch = std::env::current_exe().ok().and_then(|cli| cadcraft_mcp::live::launcher(&cli));
Box::new(cadcraft_mcp::Live::new(cfg))
}
// Without the suite's flag (or a settings folder) agents work without a window, as before.
None => headless(read_root.as_deref(), write_root.as_deref())?,
}
}
McpTarget::Headless { read_root, write_root } => headless(read_root.as_deref(), write_root.as_deref())?,
};
let stdin = std::io::stdin();
let stdout = std::io::stdout();
cadcraft_mcp::Server::new(backend).serve(stdin.lock(), stdout.lock())?;
Ok(())
}
/// A headless session held to the roots given, if any.
fn headless(read_root: Option<&str>, write_root: Option<&str>) -> Result<Box<dyn cadcraft_mcp::Backend>> {
let roots =
cadcraft_engine::file_access::AutomationRoots::new(read_root.map(Path::new), write_root.map(Path::new)).map_err(CliError::AutomationRoots)?;
Ok(Box::new(cadcraft_mcp::Headless::default().with_automation_roots(roots)))
}
/// The app's settings folder, where it publishes the agent connection: `--config-dir` or
/// `CADCRAFT_CONFIG_DIR` (`given`; blank: none), else a portable copy's `CADCraftData` beside the
/// CLI, else the platform's, as the app resolves it.
fn config_dir(given: Option<&Path>) -> Option<PathBuf> {
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf));
config_dir_from(given, exe_dir.as_deref(), |k| std::env::var_os(k))
}
/// [`config_dir`] with the CLI in `exe_dir` and `var` looking the platform's variables up.
fn config_dir_from(given: Option<&Path>, exe_dir: Option<&Path>, var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
match given {
Some(dir) if dir.to_str().is_some_and(|d| d.trim().is_empty()) => None,
Some(dir) => Some(dir.to_path_buf()),
None => match exe_dir.filter(|d| d.join("portable.txt").is_file()) {
Some(exe) => Some(exe.join("CADCraftData")),
None => cadcraft_engine::settings_dir::platform(var),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::OsString;
/// The CLI looks for the connection where the app publishes it: `--config-dir` (or its
/// variable), a portable copy's folder beside it, or the platform's.
#[test]
fn the_settings_folder_is_the_apps() {
let exe = std::env::temp_dir().join(format!("cadcraft-cli-portable-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&exe);
std::fs::create_dir_all(&exe).unwrap();
let none = |_: &str| None::<OsString>;
let given = Path::new("/private/cc");
assert_eq!(config_dir_from(Some(given), Some(&exe), none), Some(given.to_path_buf()));
assert_eq!(config_dir_from(Some(Path::new(" ")), Some(&exe), none), None);
assert_eq!(config_dir_from(None, Some(&exe), none), cadcraft_engine::settings_dir::platform(none));
std::fs::write(exe.join("portable.txt"), b"").unwrap();
assert_eq!(config_dir_from(None, Some(&exe), none), Some(exe.join("CADCraftData")));
assert_eq!(config_dir_from(Some(given), Some(&exe), none), Some(given.to_path_buf()), "the folder given wins");
std::fs::remove_dir_all(exe).unwrap();
}
}
@@ -14,9 +14,6 @@ fn mcp(args: &[&str], input: &str) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli"))
.arg("mcp")
.args(args)
// No settings folder: plain `mcp` can't find a window and serves headless, whatever the
// ArtCraft Launcher's switch says on this computer.
.env("CADCRAFT_CONFIG_DIR", "")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -84,8 +81,6 @@ fn connect_with_address_routes_to_that_endpoint() {
assert!(instructions.contains(&format!("connected to CADCraft at {addr}")), "{instructions}");
let text = r.iter().find(|v| v["id"] == 2).and_then(|v| v["result"]["content"][0]["text"].as_str()).unwrap_or_default();
assert!(text.contains("loopback"), "{r:?}");
// Still served for one release, with the way forward on stderr.
assert!(String::from_utf8_lossy(&out.stderr).contains("`mcp --connect` is deprecated"));
}
#[test]
+1 -3
View File
@@ -151,9 +151,7 @@ fn subcommand_help_requests() {
"mcp --help",
&["mcp", "--help"],
0,
Line(
"Run the MCP server on stdio: the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it, otherwise a headless drawing session",
),
Line("Run the MCP server on stdio: a headless drawing session, or a bridge to the running app"),
Empty,
),
case(
+2 -2
View File
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
cadcraft-fonts = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+1 -3
View File
@@ -53,15 +53,13 @@ zbus = { version = "=5.19.0", default-features = false, features = ["async-io",
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-update = { workspace = true }
# The ArtCraft Launcher's switch and the agent link (main.rs `agents`).
craft-automation = { workspace = true, features = ["ui", "agents"] }
rfd = { workspace = true }
sys-locale = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.22", default-features = false }
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", features = ["ui"] }
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
# (system_animations.rs). Already in Cargo.lock through muda.
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
-27
View File
@@ -428,32 +428,6 @@ fn log_version() -> String {
format!("{} ({})", reported_version(), option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev"))
}
/// Agents in the open window: while the ArtCraft Launcher's switch (Settings › AI agents) names
/// CADCraft, the agent link serves the control channel for `cadcraft-cli mcp` and publishes
/// `agent-connection.json` in the settings folder (`cadcraft_ui_egui::agents`). `--control` manages
/// its own server for the whole run instead. A Nightly build is not the app the launcher's switch
/// names, so it takes no agents this way.
fn agents(control_port: Option<u16>, settings_dir: Option<std::path::PathBuf>, ctx: &egui::Context) -> cadcraft_ui_egui::agents::Agents {
use craft_automation::agents::{AgentLink, AgentSwitch, remove_stale_connection};
if is_nightly() {
return Default::default();
}
// A file a crashed launch left behind names a port nothing serves.
if let Some(dir) = &settings_dir {
remove_stale_connection(dir);
}
let wake = ctx.clone();
// The launcher's app list names CADCraft by its catalog id.
let switch = AgentSwitch::watch(profile_root::APP_ID, move || wake.request_repaint());
match control_port {
Some(port) => cadcraft_ui_egui::agents::Agents::managed_by_launch(port, switch, settings_dir),
None => {
let link = AgentLink::new(settings_dir.clone(), format!("CADCraft {}", cadcraft_engine::build_version()));
cadcraft_ui_egui::agents::Agents::new(link, switch, settings_dir)
}
}
}
/// Whether this start runs the isolated Nightly flavor.
fn is_nightly() -> bool {
launch_profile::current().is_nightly()
@@ -794,7 +768,6 @@ fn main() -> eframe::Result {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx);
}
app.agents = agents(control_port, vars.config_dir.clone(), &cc.egui_ctx);
if sample {
let _ = app.run("ui.sample", serde_json::json!({}));
}
-41
View File
@@ -233,39 +233,6 @@ pub fn anno_draw(e: &Entity, view: f64, all_visible: bool) -> AnnoDraw {
}
}
/// `e` at each of its scales other than the one it shows at in a view of scale `view` (see
/// [`anno_draw`]): at that scale's size and position, no longer annotative (so it draws as it
/// is). AutoCAD shows these faded while the object is selected (SELECTIONANNODISPLAY). Empty when
/// `e` isn't annotative, supports one scale or doesn't show in that view; scales of the same
/// ratio come once. At most `budget` are made, and `budget` goes down by each one: a selection
/// shares one budget, taken before any geometry is copied.
pub fn anno_others(e: &Entity, view: f64, all_visible: bool, budget: &mut usize) -> Vec<Entity> {
if *budget == 0 {
return Vec::new();
}
let AnnoDraw::Scaled { factor, .. } = anno_draw(e, view, all_visible) else {
return Vec::new();
};
let mut seen = vec![factor];
let mut out = Vec::new();
for s in e.common.anno_scales.iter().take(MAX_SCALES).filter(|s| s.is_valid()) {
if *budget == 0 {
break;
}
let f = s.factor();
if seen.iter().any(|g| same_factor(*g, f)) {
continue;
}
seen.push(f);
*budget -= 1;
let mut other = anno_placed(e, f, e.common.moved_at(&s.name));
other.common.anno_scales.clear();
other.common.anno_moves.clear();
out.push(other);
}
out
}
/// `e` as it draws at annotation scale `f` with its position moved `by` there: [`anno_scaled`],
/// then [`shift_position`].
pub fn anno_placed(e: &Entity, f: f64, by: Vec2) -> Entity {
@@ -379,14 +346,6 @@ impl Drawing {
_ => None,
}
}
/// `e` at its other scales outside a viewport (see [`anno_others`], which takes from
/// `budget`); none in a layout's paper space, which shows annotative objects at 1:1 only.
pub fn anno_others(&self, e: &Entity, budget: &mut usize) -> Vec<Entity> {
if !is_annotative(e) || (!self.model.contains(e.handle) && self.layouts.iter().any(|l| l.entities.contains(e.handle))) {
return Vec::new();
}
anno_others(e, self.current_anno_scale().factor(), self.anno_all_visible(), budget)
}
/// `e` as it draws outside a viewport: an annotative object at its scale and position there,
/// anything else (and a hidden annotative object) as stored.
pub fn anno_shown(&self, e: &Entity) -> EntityKind {
+12 -9
View File
@@ -367,16 +367,19 @@ impl Drawing {
}
let Some(cv) = serde_json::to_value(&cand).ok().and_then(|c| c.get(*field).cloned()) else { continue };
let same = match (base.get(*field), &cv) {
// An empty dimension linetype names ByBlock. DWG can spell that builtin explicitly.
// Text style and arrow block names compare without case.
(Some(serde_json::Value::String(a)), serde_json::Value::String(b))
if matches!(*field, "dimLinetype" | "extLinetype1" | "extLinetype2") =>
{
let a = if a.is_empty() { "ByBlock" } else { a };
let b = if b.is_empty() { "ByBlock" } else { b };
a.eq_ignore_ascii_case(b)
}
(Some(serde_json::Value::String(a)), serde_json::Value::String(b))
if matches!(*field, "textStyle" | "arrowBlock" | "arrowBlock1" | "arrowBlock2" | "leaderArrowBlock") =>
if matches!(
*field,
"textStyle"
| "arrowBlock"
| "arrowBlock1"
| "arrowBlock2"
| "leaderArrowBlock"
| "dimLinetype"
| "extLinetype1"
| "extLinetype2"
) =>
{
a.eq_ignore_ascii_case(b)
}
-18
View File
@@ -1160,21 +1160,3 @@ fn layout_lookups_by_name_cost_about_the_same_for_any_table_size() {
d.layouts = long_names("L").zip(1..).map(|(n, tab)| Layout::new(&n, tab)).collect();
lookups_by_name_are_quick("L", |n| d.layout(n).is_some());
}
#[test]
fn dimension_linetype_overrides_compare_effective_names() {
let mut d = Drawing::default();
for var in ["DIMLTYPE", "DIMLTEX1", "DIMLTEX2"] {
d.header.set_str(var, "byBLOCK");
}
assert!(d.dim_overrides().is_empty());
let style = d.dim_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case("Standard")).unwrap();
style.dim_linetype = "ByBlock".into();
style.ext_linetype1 = "DASHED".into();
style.ext_linetype2 = "ByLayer".into();
d.header.set_str("DIMLTYPE", "");
d.header.set_str("DIMLTEX1", "dashed");
d.header.set_str("DIMLTEX2", "ByBlock");
assert_eq!(d.dim_overrides(), serde_json::Map::from_iter([("extLinetype2".into(), serde_json::json!("ByBlock"))]));
}
-2
View File
@@ -19,8 +19,6 @@ cadcraft-constraints = { workspace = true }
cadcraft-fonts = { workspace = true }
cadcraft-render = { workspace = true }
craft-docpath = { workspace = true }
# The agent settings (Options › AI Agents) the app and `cadcraft-cli mcp` share.
craft-control = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
-104
View File
@@ -1,104 +0,0 @@
//! The agent settings of Options › AI Agents, shared by the app and `cadcraft-cli mcp`: the
//! control port agents connect on, the folders they may open from and save to, and what the CLI
//! does while CADCraft is closed. They are kept in [`FILE`] in the settings folder, beside the
//! connection file the app publishes for agents, so the CLI reads them without the app.
//!
//! Only the person changes them, in the Options dialog: the OPTIONS JSON form has no such keys,
//! so an agent can't widen its own folders through a command.
use std::io;
use std::path::Path;
use std::sync::Arc;
pub use craft_control::agents::{AgentSettings, WhenAppClosed};
use crate::file_access::AutomationRoots;
/// The settings file in the settings folder.
pub const FILE: &str = "agent-settings.json";
/// The largest settings file read; the settings are a few short fields.
const MAX_BYTES: usize = 64 * 1024;
/// The agent settings saved in the settings folder `dir`; the defaults when none are saved or the
/// file can't be read (the reason is logged), so neither the app nor the CLI fails over them.
pub fn load(dir: &Path) -> AgentSettings {
let path = dir.join(FILE);
match crate::capped_read::read_capped(&path, MAX_BYTES) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
log::warn!("agent settings {}: {e}; using the defaults", path.display());
AgentSettings::default()
}),
Err(e) if e.kind() == io::ErrorKind::NotFound => AgentSettings::default(),
Err(e) => {
log::warn!("agent settings {}: {e}; using the defaults", path.display());
AgentSettings::default()
}
}
}
/// Saves `settings` in the settings folder `dir` (made if missing), replacing the file whole.
pub fn save(dir: &Path, settings: &AgentSettings) -> io::Result<()> {
let json = serde_json::to_vec_pretty(settings).map_err(io::Error::other)?;
crate::atomic_write::write_atomic_making_folders(&dir.join(FILE), &json)
}
/// The roots agent requests run in, for the agent folders `read` and `write`. A folder that is
/// missing or can't be opened grants nothing in its direction, and with neither every file is
/// refused: leaving the roots out would confine nothing. The error names the folders that could
/// not be used.
pub fn roots(read: Option<&Path>, write: Option<&Path>) -> (Arc<AutomationRoots>, Option<String>) {
let mut problems = Vec::new();
let read = read.filter(|r| AutomationRoots::new(Some(r), None).map_err(|e| problems.push(e)).is_ok());
let write = write.filter(|w| AutomationRoots::new(None, Some(w)).map_err(|e| problems.push(e)).is_ok());
let roots = AutomationRoots::new(read, write).ok().flatten().unwrap_or_else(AutomationRoots::none);
(roots, (!problems.is_empty()).then(|| problems.join("; ")))
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::file_access::{check_read, check_write, confine};
fn temp(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("cadcraft-agent-settings-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// What the dialog saves is what the CLI reads; a damaged file reads as the defaults.
#[test]
fn saved_settings_read_back_and_a_damaged_file_is_the_defaults() {
let dir = temp("round-trip");
let mut settings = AgentSettings::default();
settings.read_root = "/agents/in".into();
settings.when_app_closed = WhenAppClosed::Headless;
save(&dir, &settings).unwrap();
assert_eq!(load(&dir), settings);
std::fs::write(dir.join(FILE), b"{not json").unwrap();
assert_eq!(load(&dir), AgentSettings::default());
std::fs::remove_dir_all(dir).unwrap();
}
/// Agent folders that can't be used refuse every file instead of confining nothing.
#[test]
fn folders_that_cannot_be_used_refuse_every_file() {
let dir = temp("roots");
let file = dir.join("plan.dxf");
let (roots, problem) = roots(Some(&dir.join("missing")), None);
assert!(problem.is_some());
confine(Some(&roots), || {
assert!(check_read(&file).is_err());
assert!(check_write(&file).is_err());
});
let (roots, problem) = super::roots(Some(&dir), Some(&dir.join("gone")));
assert!(problem.is_some(), "the missing write folder is named");
confine(Some(&roots), || {
assert!(check_read(&file).is_ok(), "the usable read folder still applies");
assert!(check_write(&file).is_err());
});
std::fs::remove_dir_all(dir).unwrap();
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ mod radial;
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
pub(super) use common::segment_at;
use common::{DimText, add_dim, assoc_enabled, circle_at, circle_of, dim};
use common::{DimText, add_dim, assoc_enabled, circle_of, dim, pick_at};
use edit::{DimSpaceM, OverrideM, dims_of, run_dimspace, run_dimtedit, run_disassociate, run_override, run_reassociate, run_tedit, run_update};
use linear::{ChainM, LinearM, MAX_CHAIN, OrdinateM, run_aligned, run_baseline, run_continue, run_linear, run_ordinate};
use mleader::{MLeaderM, run_leader, run_mleader};
-56
View File
@@ -120,62 +120,6 @@ pub(super) fn pick_at(s: &Session, p: Vec2) -> Option<Handle> {
s.pick_object(&s.space(), p, ap).ok().flatten()
}
/// Most objects of a block reference looked at for one pick (nested references included).
const MAX_NESTED_PICK: usize = 100_000;
/// The circle or arc picked at `p`, in drawing coordinates: a circle or arc of the drawing, or
/// one inside the block reference picked there (nested references too), as AutoCAD's DIMRADIUS,
/// DIMDIAMETER and DIMJOGGED take one (#1967). Inside a reference it is the object under the
/// cursor, so a pick on a block's line is not a circle; one the reference scales unevenly is
/// drawn as an ellipse and is not taken either.
pub(super) fn circle_at(s: &Session, p: Vec2) -> Option<(Vec2, f64)> {
let h = pick_at(s, p)?;
// A circle with no size (a zero radius read from a file) makes a degenerate dimension.
let usable = |(c, r): &(Vec2, f64)| c.is_finite() && r.is_finite() && *r > 0.0;
if let Some(c) = circle_of(s, h) {
return Some(c).filter(usable);
}
let d = s.doc().ok()?;
let EntityKind::Insert(ins) = &d.entity(h)?.kind else { return None };
let ap = crate::cmd::curves::pick_aperture(s);
let mut nearest: Option<(f64, Option<(Vec2, f64)>)> = None;
let mut budget = MAX_NESTED_PICK;
// Inside a layout viewport, what its frozen layers hold isn't drawn there.
let frozen = s.state().ok().and_then(|st| st.active_viewport().map(|(_, vp)| vp.frozen_layers)).unwrap_or_default();
let inside = crate::snap::Inside::drawn(&frozen);
crate::snap::block_leaves(d, ins, &cadcraft_geom::Mat3::IDENTITY, None, 0, &mut budget, inside, &mut |entity, m, _| {
let k = &entity.kind;
// Measured on what is drawn, as any pick measures (text inside its box, a SOLID inside
// its fill, a ray only ahead of its start), on the object placed by the reference. A curve
// the reference scales unevenly is drawn as an ellipse, which placing the object doesn't
// make, so it is measured on its exactly placed primitives instead.
let dist = match (k, m.similarity_scale()) {
(EntityKind::Circle(_) | EntityKind::Arc(_) | EntityKind::Ellipse(_), None) => {
k.prims().iter().map(|pr| crate::cmd::curves::prim_distance(&crate::snap::xform_prim(pr, m), p)).fold(f64::INFINITY, f64::min)
}
_ => {
let mut placed = k.clone();
placed.transform(m);
crate::select::entity_distance(d, &cadcraft_doc::Entity::new(Handle(0), placed), p, ap / 4.0)
}
};
if !dist.is_finite() || dist > ap {
return;
}
let circle = m.similarity_scale().and_then(|scale| match k {
EntityKind::Circle(c) => Some((m.apply(c.center.xy()), c.radius * scale)),
EntityKind::Arc(a) => Some((m.apply(a.center.xy()), a.radius * scale)),
_ => None,
});
// The nearest wins; at the same distance, a circle or arc over anything else.
let better = nearest.is_none_or(|(best, held)| dist < best || (dist <= best && held.is_none() && circle.is_some()));
if better {
nearest = Some((dist, circle));
}
});
nearest.and_then(|(_, c)| c).filter(usable)
}
/// The straight or curved piece of `h` picked at `p`: a line, an arc, or the polyline segment nearest `p`.
pub(in crate::cmd) fn segment_at(s: &Session, h: Handle, p: Vec2) -> Option<Segment> {
match &s.doc().ok()?.entity(h)?.kind {
+2 -2
View File
@@ -1,4 +1,4 @@
use super::common::{DimText, add_dim, circle_at, circle_of, dim, text_at};
use super::common::{DimText, add_dim, circle_of, dim, pick_at, text_at};
use super::{Accept, DimKind, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, bad, json, point_param, targets};
fn radial(s: &mut Session, p: &Value, diameter: bool) -> Result<Value> {
@@ -75,7 +75,7 @@ impl Interactive for RadialM {
}
match (self.target, i) {
(None, Input::Point(p)) => {
match circle_at(s, p) {
match pick_at(s, p).and_then(|h| circle_of(s, h)) {
Some(t) => self.target = Some(t),
None => s.echo("Object selected is not a circle or arc."),
}
+2 -2
View File
@@ -8,7 +8,7 @@ use serde_json::{Value, json};
use super::super::helpers::v3;
use super::super::machines::{SelOutcome, SelectPhase};
use super::super::{CommandSpec, bad, bool_or, point_param, point_req, size_param, str_param, targets};
use super::{DimText, add_dim, circle_at, circle_of, dim, dims_of};
use super::{DimText, add_dim, circle_of, dim, dims_of, pick_at};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
@@ -332,7 +332,7 @@ impl Interactive for JoggedM {
return Ok(Step::Continue);
}
match (self.circle, self.center, self.at, i) {
(None, _, _, Input::Point(p)) => match circle_at(s, p) {
(None, _, _, Input::Point(p)) => match pick_at(s, p).and_then(|h| circle_of(s, h)) {
Some(t) => self.circle = Some(t),
None => s.echo("Object selected is not a circle or arc."),
},
+18 -20
View File
@@ -604,26 +604,24 @@ pub fn seg_param(s: &Segment, p: Vec2) -> f64 {
/// Distance from `p` to an entity's geometry (prims; text and blocks by insertion point).
pub fn kind_distance(k: &EntityKind, p: Vec2) -> f64 {
k.prims().iter().map(|pr| prim_distance(pr, p)).fold(f64::INFINITY, f64::min)
}
/// Distance from `p` to one primitive.
pub fn prim_distance(pr: &Prim, p: Vec2) -> f64 {
match pr {
Prim::Seg(s) => s.closest(p).dist(p),
Prim::Circle(c) => c.closest(p).dist(p),
Prim::Ellipse(e) => e.closest(p).dist(p),
Prim::Spline(sp) => {
let pts = sp.tessellate(1e-3);
pts.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?).closest(p).dist(p))).fold(f64::INFINITY, f64::min)
}
Prim::Point(q) => q.dist(p),
Prim::Infinite { base, dir, .. } => Line::new(*base, *base + *dir).project(p).dist(p),
Prim::Fill(f) => {
let n = f.len();
(0..n).filter_map(|i| Some(Line::new(*f.get(i)?, *f.get((i + 1) % n)?).closest(p).dist(p))).fold(f64::INFINITY, f64::min)
}
}
k.prims()
.iter()
.map(|pr| match pr {
Prim::Seg(s) => s.closest(p).dist(p),
Prim::Circle(c) => c.closest(p).dist(p),
Prim::Ellipse(e) => e.closest(p).dist(p),
Prim::Spline(sp) => {
let pts = sp.tessellate(1e-3);
pts.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?).closest(p).dist(p))).fold(f64::INFINITY, f64::min)
}
Prim::Point(q) => q.dist(p),
Prim::Infinite { base, dir, .. } => Line::new(*base, *base + *dir).project(p).dist(p),
Prim::Fill(f) => {
let n = f.len();
(0..n).filter_map(|i| Some(Line::new(*f.get(i)?, *f.get((i + 1) % n)?).closest(p).dist(p))).fold(f64::INFINITY, f64::min)
}
})
.fold(f64::INFINITY, f64::min)
}
// ---------------- splines ----------------
+13 -96
View File
@@ -373,12 +373,12 @@ pub fn specs() -> Vec<CommandSpec> {
.noundo(),
CommandSpec::new("close", "Close", run_close).menu(&["File", "Close"]).key("Cmd+W").params("{index?}").noundo(),
CommandSpec::new("closeall", "Close All", run_closeall).menu(&["File", "Close All"]).enabled(always).noundo(),
CommandSpec::new("qsave", "Save", run_qsave_reporting).menu(&["File", "Save"]).key("Cmd+S").alias(&["save"]).params("{path?, overwrite?: bool}").noundo(),
CommandSpec::new("qsave", "Save", run_qsave_reporting).menu(&["File", "Save"]).key("Cmd+S").alias(&["save"]).params("{path?}").noundo(),
CommandSpec::new("saveas", "Save As...", run_saveas_reporting)
.menu(&["File", "Save As..."])
.key("Cmd+Shift+S")
.params(
"{path, version?: 2000|2004|2007|2010|2013|2018, binary?: bool, portableFonts?: bool (Windows fonts for Linux ones, in this file), overwrite?: bool}",
"{path, version?: 2000|2004|2007|2010|2013|2018, binary?: bool, portableFonts?: bool (Windows fonts for Linux ones, in this file)}",
)
.noundo(),
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
@@ -483,7 +483,6 @@ pub struct ReadFile {
binary_dxf: bool,
name: String,
path: Option<String>,
disk: Option<crate::disk_stamp::DiskStamp>,
}
/// Read and decode `path` (the slow half of `OPEN {path}`). Needs no session; runs anywhere.
@@ -514,8 +513,8 @@ pub fn read_file(path: &std::path::Path) -> std::result::Result<ReadFile, String
/// Add a [`read_file`] result to the session as the active drawing: the fast half of OPEN.
pub fn finish_open(s: &mut Session, f: ReadFile) -> Result<Value> {
let ReadFile { drawing, binary_dxf, name, path, disk } = f;
let i = add_read(s, drawing, binary_dxf, &name, path, disk);
let ReadFile { drawing, binary_dxf, name, path } = f;
let i = add_read(s, drawing, binary_dxf, &name, path);
super::blocks::xref::after_open(s, i);
super::image::after_open(s, i);
Ok(opened(s, i, true))
@@ -549,24 +548,15 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option<String>) -> Result<ReadFile
}
}
}
let disk = path.as_ref().map(|_| crate::disk_stamp::DiskStamp::of(bytes));
Ok(ReadFile { drawing, binary_dxf: craft_dxf::is_binary(bytes), name: name.to_string(), path, disk })
Ok(ReadFile { drawing, binary_dxf: craft_dxf::is_binary(bytes), name: name.to_string(), path })
}
fn add_read(
s: &mut Session,
drawing: Drawing,
binary_dxf: bool,
name: &str,
path: Option<String>,
disk: Option<crate::disk_stamp::DiskStamp>,
) -> usize {
fn add_read(s: &mut Session, drawing: Drawing, binary_dxf: bool, name: &str, path: Option<String>) -> usize {
let notes = drawing.read_notes.clone();
let i = s.open_drawing(drawing, &file_name(name), path);
if let Some(st) = s.docs.get_mut(i) {
// QSAVE keeps a binary DXF binary.
st.binary_dxf = binary_dxf;
st.disk = disk;
}
for note in notes {
s.echo(note);
@@ -575,8 +565,8 @@ fn add_read(
}
pub(crate) fn open_bytes(s: &mut Session, bytes: &[u8], name: &str, path: Option<String>) -> Result<usize> {
let ReadFile { drawing, binary_dxf, name, path, disk } = read_bytes(bytes, name, path)?;
Ok(add_read(s, drawing, binary_dxf, &name, path, disk))
let ReadFile { drawing, binary_dxf, name, path } = read_bytes(bytes, name, path)?;
Ok(add_read(s, drawing, binary_dxf, &name, path))
}
/// OPEN's reply: the drawing's index and what reading it left out.
@@ -679,90 +669,18 @@ fn run_closeall(s: &mut Session, _p: &Value) -> Result<Value> {
ok()
}
pub(crate) fn save_to(s: &mut Session, path: &str, overwrite: bool) -> Result<(usize, Vec<String>)> {
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<(usize, Vec<String>)> {
let opts = SaveAs { binary: s.state()?.binary_dxf && is_dxf(path), ..SaveAs::default() };
save_as(s, "save", path, &opts, overwrite)
}
/// `overwrite`: save over the drawing's own file although another program changed it.
fn overwrite_param(cmd: &str, p: &Value) -> Result<bool> {
match p.get("overwrite") {
None | Some(Value::Null) => Ok(false),
Some(Value::Bool(b)) => Ok(*b),
Some(_) => Err(bad(cmd, "`overwrite` must be true or false")),
}
}
/// Whether `a` and `b` name the same file: the same text, or the same file once resolved
/// (`./plan.dxf` and `plan.dxf`, a relative and an absolute path, a link).
#[cfg(not(target_arch = "wasm32"))]
fn same_file(a: &str, b: &str) -> bool {
a == b || matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b)
}
/// What saving the active drawing to `path` would replace, before anything is written: whether the
/// drawing's own file still holds what was opened or last saved here. [`OnDisk::Same`] when there is
/// nothing to compare: another file, a file that is gone, not a drawing file, or a target the
/// automation roots refuse (the save refuses it first, [`check_disk`]). The drawing's own path is
/// resolved only where it may be read. A user's save asks with this; [`check_disk`] refuses with it.
///
/// [`OnDisk::Same`]: crate::disk_stamp::OnDisk::Same
pub fn on_disk(s: &Session, path: &str) -> crate::disk_stamp::OnDisk {
use crate::disk_stamp::OnDisk;
#[cfg(not(target_arch = "wasm32"))]
{
let Ok(st) = s.state() else { return OnDisk::Same };
let Some(stamp) = st.disk else { return OnDisk::Same };
if !is_drawing_file(path) || crate::file_access::check_write(path).is_err() {
return OnDisk::Same;
}
let own = st.path.as_deref().filter(|own| *own == path || (crate::file_access::check_read(own).is_ok() && same_file(own, path)));
if own.is_none() {
return OnDisk::Same;
}
crate::disk_stamp::compare(std::path::Path::new(path), stamp, MAX_DRAWING_BYTES)
}
#[cfg(target_arch = "wasm32")]
{
let _ = (s, path);
OnDisk::Same
}
}
/// Refuse to save over the drawing's own file when it no longer holds what was opened or last
/// saved here (another program or person wrote it, and a save would silently replace their work),
/// or when it can't be read to tell ([`on_disk`]).
///
/// The file is compared only where the save may go: with automation roots in force
/// ([`crate::file_access`]), a target outside the write root is refused first, as the write
/// itself would be.
fn check_disk(s: &Session, cmd: &str, path: &str, overwrite: bool) -> Result<()> {
if overwrite || !is_drawing_file(path) || s.state()?.disk.is_none() {
return Ok(());
}
#[cfg(not(target_arch = "wasm32"))]
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
let keep = "Nothing was saved. Save under another name (saveas), or reopen the file to see what it holds; \
`overwrite: true` replaces it anyway.";
match on_disk(s, path) {
crate::disk_stamp::OnDisk::Same => Ok(()),
crate::disk_stamp::OnDisk::Changed => {
Err(bad(cmd, format!("{path} changed on disk after it was opened: another program or person saved it. {keep}")))
}
crate::disk_stamp::OnDisk::Unchecked(e) => {
Err(bad(cmd, format!("{path} may have changed on disk after it was opened: it could not be read to check ({e}). {keep}")))
}
}
save_as(s, "save", path, &opts)
}
/// Save to `path` with `opts`. A drawing file then keeps the version and binary choice: the
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again. Also an
/// image's notes ([`write_noted`]).
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs, overwrite: bool) -> Result<(usize, Vec<String>)> {
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usize, Vec<String>)> {
if s.doc()?.refedit.is_some() {
return Err(bad(cmd, "A block reference is being edited in place: finish with REFCLOSE (Save or Discard) before saving."));
}
check_disk(s, cmd, path, overwrite)?;
// A saved drawing carries the folder's plot style tables its layouts use.
if is_drawing_file(path) {
let st = s.state_mut()?;
@@ -1056,7 +974,6 @@ fn commit_save(s: &mut Session, path: &str, bytes: &[u8], store: impl FnOnce(&st
st.saved = st.drawing().clone();
st.path = Some(path.to_string());
st.title = file_name(path);
st.disk = Some(crate::disk_stamp::DiskStamp::of(bytes));
// A BEgin group still open when the drawing is saved ends there.
st.end_undo_group();
Ok(bytes.len())
@@ -1076,7 +993,7 @@ fn run_save(s: &mut Session, p: &Value) -> Result<Value> {
Some(p) => p.to_string(),
None => s.state()?.path.clone().ok_or_else(|| bad("qsave", "drawing has no file name yet; use saveas {path}"))?,
};
let (n, notes) = save_to(s, &path, overwrite_param("qsave", p)?)?;
let (n, notes) = save_to(s, &path)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
Ok(r)
@@ -1085,7 +1002,7 @@ fn run_save(s: &mut Session, p: &Value) -> Result<Value> {
fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("saveas", "`path` is required"))?.to_string();
let opts = save_options("saveas", p)?;
let (n, notes) = save_as(s, "saveas", &path, &opts, overwrite_param("saveas", p)?)?;
let (n, notes) = save_as(s, "saveas", &path, &opts)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
if is_drawing_file(&path) {
+1 -9
View File
@@ -1,6 +1,5 @@
//! Layouts, paper-space viewports, page setup and plotting: LAYOUT (new/delete/rename/copy/saveas),
//! MVIEW / VPORTS, viewport scale/lock/layer settings, PAGESETUP / -PAGESETUP, PLOT / -PLOT and
//! EXPORTPDF.
//! MVIEW / VPORTS, viewport scale/lock/layer settings, PAGESETUP, PLOT and EXPORTPDF.
//!
//! Plotting goes through the host's [`super::file::IoHooks::plot`] hook so the engine stays
//! I/O-agnostic.
@@ -15,7 +14,6 @@ use super::{CommandSpec, bad, bool_or, find_command, point_param, point_value, s
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
use viewports::MviewM;
mod plot_prompts;
mod plotstyle;
pub(crate) use plotstyle::keep_used_folder_copies;
mod prompts;
@@ -94,12 +92,6 @@ pub fn specs() -> Vec<CommandSpec> {
.key("Cmd+P")
.alias(&["print"])
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)"),
CommandSpec::new("-pagesetup", "Page Setup Manager...", run_pagesetup)
.params("as PAGESETUP (typed: asks the layout, then each page setup option in turn, and stores the answers)")
.interactive(|_| Ok(Box::new(plot_prompts::PlotM::page_setup()))),
CommandSpec::new("-plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
.params("as PLOT (typed: asks for a detailed configuration or not, the plot options, the output file, whether to save them to the page setup, then plots)")
.interactive(|_| Ok(Box::new(plot_prompts::PlotM::plot()))),
CommandSpec::new("exportpdf", "Export to PDF...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "exportpdf")?, "exportpdf"))
.menu(&["File", "Export to PDF..."])
.params("{path? (else returns base64 `data`), layout?, device? (its papers; the output stays PDF), paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)"),
File diff suppressed because it is too large Load Diff
+21 -65
View File
@@ -1,8 +1,7 @@
use cadcraft_doc::Drawing;
use cadcraft_geom::Bounds2;
use super::{
Arc, EngineError, Entity, EntityKind, Handle, Line, Mat3, PolyVertex, Polyline, Prim, Result, Segment, Session, TAU, Vec2, angle_in_sweep, arc,
Arc, EngineError, Entity, EntityKind, Handle, Line, PolyVertex, Polyline, Prim, Result, Segment, Session, TAU, Vec2, angle_in_sweep, arc,
ccw_sweep, intersect_ext, line, lwpoly, norm_angle,
};
@@ -35,17 +34,15 @@ pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, ove
let space = s.space();
let store = d.space(&space).ok_or(EngineError::NoDocument)?;
let mut out = Vec::new();
// One bound for the objects visited inside all the references together: Quick mode looks at
// every reference of the space on every preview, so a bound for each reference alone would
// leave the whole look unbounded. References past the bound give no edges inside them.
let mut budget = crate::snap::MAX_BLOCK_LEAVES;
let mut add = |kind: &EntityKind| {
push_edge(&mut out, d, kind, edges.implied, None);
// A block reference is an edge by what it draws: the objects inside it that are drawn,
// nested references expanded, each placed by the reference and giving the edges the same
// object gives outside a block. The reference's own attributes are not among them.
if let EntityKind::Insert(ins) = kind {
crate::snap::reference_leaves(d, ins, &mut budget, &mut |part, place| push_edge(&mut out, d, part, edges.implied, Some(place)));
if edges.implied
&& let Some(segs) = implied_edge(kind)
{
out.extend(segs);
return;
}
for p in kind.prims() {
out.extend(prim_to_segments(&p));
}
};
// An object is an edge when it is one of `edges.only` (all of them: `None`). A trim leaves
@@ -87,56 +84,15 @@ pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, ove
Ok(out)
}
/// Adds to `out` the segments `kind` gives as a cutting or boundary edge (`implied`: EDGEMODE 1,
/// [`implied_edge`]). `place`: the transform of the block reference that draws `kind`, for an
/// object inside one; a circle or an arc under a non-uniform scale is then the ellipse it is
/// drawn as. A proxy gives the graphics drawing `d` draws of it ([`drawn_prims`]).
fn push_edge(out: &mut Vec<Segment>, d: &Drawing, kind: &EntityKind, implied: bool, place: Option<&Mat3>) {
let prims = match implied.then(|| implied_edge(kind, place)).flatten() {
Some(prims) => prims,
None => drawn_prims(d, kind).iter().map(|p| placed(p, place)).collect(),
};
for p in &prims {
out.extend(prim_to_segments(p));
}
}
/// The primitives `kind` gives as an edge. A proxy (a record kept as read) gives those of the
/// graphics it draws in drawing `d`: a graphic that is hidden or on a layer that is off or frozen
/// is not drawn and is no edge, in a block reference and in the drawing itself.
fn drawn_prims(d: &Drawing, kind: &EntityKind) -> Vec<Prim> {
match kind {
EntityKind::Unknown(u) => crate::snap::drawn_graphics(d, u, &[]).flat_map(|g| g.kind.prims()).collect(),
k => k.prims(),
}
}
/// `p` where the block reference with transform `place` draws it (`None`: as it is).
fn placed(p: &Prim, place: Option<&Mat3>) -> Prim {
match place {
Some(m) => crate::snap::xform_prim(p, m),
None => p.clone(),
}
}
/// `k` as an implied edge (EDGEMODE 1), for lines, arcs and open polylines. `place`: the transform
/// of the block reference that draws `k`, for an object inside one. A line is placed first and
/// run on after, so it runs on as far in drawing units as outside a block whatever the scale of
/// the references above it; an arc is made whole and then placed.
fn implied_edge(k: &EntityKind, place: Option<&Mat3>) -> Option<Vec<Prim>> {
/// `k` as an implied edge (EDGEMODE 1), for lines, arcs and open polylines.
fn implied_edge(k: &EntityKind) -> Option<Vec<Segment>> {
const FAR: f64 = 1e8;
let whole = |a: &Arc| placed(&Prim::Seg(Segment::Arc { arc: Arc { start: 0.0, end: TAU - 1e-12, ..*a }, ccw: true }), place);
let whole = |a: &Arc| Segment::Arc { arc: Arc { start: 0.0, end: TAU - 1e-12, ..*a }, ccw: true };
// Run a segment on past its start and/or its end.
let run_on = |sg: Segment, back: bool, fwd: bool| match sg {
Segment::Line(l) => {
let (a, b, d) = match place {
// The direction is taken once the line is placed, and only a line with no length
// at all has none: a line very short in its block or drawn very short by a small
// scale still runs on along itself.
Some(m) => (m.apply(l.a), m.apply(l.b), crate::snap::placed_dir(l.b - l.a, m)),
None => (l.a, l.b, (l.b - l.a).normalized()),
};
Prim::Seg(Segment::Line(Line::new(if back { a - d * FAR } else { a }, if fwd { b + d * FAR } else { b })))
let d = (l.b - l.a).normalized();
Segment::Line(Line::new(if back { l.a - d * FAR } else { l.a }, if fwd { l.b + d * FAR } else { l.b }))
}
Segment::Arc { arc, .. } => whole(&arc),
};
@@ -144,14 +100,14 @@ fn implied_edge(k: &EntityKind, place: Option<&Mat3>) -> Option<Vec<Prim>> {
EntityKind::Line(l) => Some(vec![run_on(Segment::Line(Line::new(l.a.xy(), l.b.xy())), true, true)]),
EntityKind::Arc(a) => Some(vec![whole(&Arc::new(a.center.xy(), a.radius, a.start, a.end))]),
EntityKind::LwPolyline(p) if !p.closed => {
let segs = Polyline { vertices: p.vertices.clone(), closed: false }.segments();
let mut segs = Polyline { vertices: p.vertices.clone(), closed: false }.segments();
let last = segs.len().checked_sub(1)?;
Some(
segs.iter()
.enumerate()
.map(|(i, sg)| if i == 0 || i == last { run_on(*sg, i == 0, i == last) } else { placed(&Prim::Seg(*sg), place) })
.collect(),
)
for (i, sg) in segs.iter_mut().enumerate() {
if i == 0 || i == last {
*sg = run_on(*sg, i == 0, i == last);
}
}
Some(segs)
}
_ => None,
}
-2
View File
@@ -35,7 +35,6 @@ pub const PROFILE_VARS: &[&str] = &[
"QPMODE",
"SELECTIONEFFECT",
"SELECTIONPREVIEW",
"SELECTIONANNODISPLAY",
"PREVIEWEFFECT",
"PREVIEWFILTER",
"GRIPS",
@@ -169,7 +168,6 @@ pub fn reset(s: &mut Session) {
st.selectionpreview = d.selectionpreview;
st.previeweffect = d.previeweffect;
st.previewfilter = d.previewfilter;
st.selectionannodisplay = d.selectionannodisplay;
st.grips = d.grips;
st.gripobjlimit = d.gripobjlimit;
st.selectionarea = d.selectionarea;
+4 -12
View File
@@ -211,7 +211,7 @@ pub fn find_device(name: &str) -> Option<PlotterConfig> {
}
/// The paper of `dev` called `name`, also by a standard size's short name (`A3`, `Letter`…).
pub(crate) fn device_paper<'a>(dev: &'a PlotterConfig, name: &str) -> Option<&'a DevicePaper> {
fn device_paper<'a>(dev: &'a PlotterConfig, name: &str) -> Option<&'a DevicePaper> {
dev.paper(name).or_else(|| dev.paper(cadcraft_render::paper_size(name)?.name))
}
@@ -293,14 +293,6 @@ fn path_output(path: &str) -> Option<PlotOutput> {
PlotOutput::parse(&std::path::Path::new(path).extension()?.to_string_lossy())
}
/// Why `dev` cannot write the file `path`: the path's extension asks for another format than the
/// device writes. `None` for a path the device can write (its own format, or an extension that
/// names none).
pub(crate) fn path_refusal(dev: &PlotterConfig, path: &str) -> Option<String> {
let want = path_output(path)?;
(dev.output != want).then(|| format!("plotter `{}` writes {}, but the path asks for {}", dev.name, dev.output.as_str(), want.as_str()))
}
/// The options PLOT / EXPORTPDF hand the plotter with `device` and the device's papers
/// resolved: `device` (else the layout's page setup device) picks the output (`output`: pdf,
/// png or svg; EXPORTPDF always writes PDF) and `resolution`; a paper of the device becomes
@@ -338,10 +330,10 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
format!("can't tell the format of `{path}`: give a path ending in .png, .svg or .pdf, or set `output` to png, svg or pdf"),
));
}
if let (Some(_), Some(dev), true) = (by_path, &dev, given.is_some_and(|n| !n.is_empty()))
&& let Some(why) = str_param(p, "path").and_then(|path| path_refusal(dev, path))
if let (Some(want), Some(dev), true) = (by_path, &dev, given.is_some_and(|n| !n.is_empty()))
&& dev.output != want
{
return Err(bad(cmd, why));
return Err(bad(cmd, format!("plotter `{}` writes {}, but the path asks for {}", dev.name, dev.output.as_str(), want.as_str())));
}
// An `output` that says another format than the path's extension is refused too, as a device
// that does is: either way the file would not hold what its name says.
+1 -31
View File
@@ -103,12 +103,7 @@ pub fn specs() -> Vec<CommandSpec> {
.params("{name, value}")
.transparent()
.interactive(|_| Ok(Box::new(SetvarM::default()))),
CommandSpec::new("getvar", "Get Variable", run_getvar)
.params("{name}")
.enabled(always)
.noundo()
.transparent()
.interactive(|_| Ok(Box::new(GetvarM))),
CommandSpec::new("getvar", "Get Variable", run_getvar).params("{name}").enabled(always).noundo(),
CommandSpec::new("sysvars", "List System Variables", |s, _| Ok(crate::sysvars::list(s))).enabled(always).noundo(),
]
}
@@ -257,31 +252,6 @@ impl Interactive for SetvarM {
}
}
/// GETVAR at the command line: "Enter variable name", then the value is echoed, so a drawing's
/// settings (`GETVAR DIMSCALE`) can be read without changing them (#3273). Run without a name it
/// said only that `name` was required.
struct GetvarM;
impl Interactive for GetvarM {
fn name(&self) -> &'static str {
"GETVAR"
}
fn prompt(&self, _s: &Session) -> Prompt {
// Space ends the name, as for SETVAR.
Prompt::new("Enter variable name", Accept { number: true, ..Accept::TEXT })
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Input::Text(t) = i {
let n = t.trim().to_ascii_uppercase();
match crate::sysvars::get(s, &n) {
Some(v) => s.echo(format!("{n} = {}", show_value(&v))),
None => s.echo(format!("Unknown variable {n}. Type SETVAR ? to list variables.")),
}
}
Ok(Step::Done)
}
}
fn run_getvar(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("getvar", "`name` is required"))?;
let v = crate::sysvars::get(s, name).ok_or_else(|| bad("getvar", format!("unknown variable `{name}`")))?;
-56
View File
@@ -1,56 +0,0 @@
//! What a drawing file held when this session last read or wrote it.
//!
//! CADCraft keeps no file open while a drawing is edited: it reads the bytes and later replaces the
//! file atomically. Nothing then stops another program (another CAD program on a shared folder, a
//! sync client, another CADCraft) from saving the same file in between, and a plain save would
//! silently replace that work. A save over the drawing's own file therefore first checks that the
//! file still holds what was read or last written, and refuses otherwise (QSAVE/SAVEAS
//! `overwrite: true` replaces it anyway).
use std::hash::{DefaultHasher, Hasher};
/// The length and a 64-bit hash of a file's bytes. The hash only has to notice a change made by
/// someone else within this process's lifetime, so the standard library's hasher is enough.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DiskStamp {
len: u64,
hash: u64,
}
impl DiskStamp {
pub fn of(bytes: &[u8]) -> Self {
let mut h = DefaultHasher::new();
h.write(bytes);
DiskStamp { len: bytes.len() as u64, hash: h.finish() }
}
}
/// What a file holds compared with a [`DiskStamp`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OnDisk {
/// It holds what the stamp says, or it is gone (a file that is gone has nothing to lose).
Same,
/// It holds something else.
Changed,
/// It could not be read; the reason.
Unchecked(String),
}
/// What the file at `path` holds compared with `stamp`. Only a file of the stamp's length is read,
/// up to `max` or that length if this session wrote more.
#[cfg(not(target_arch = "wasm32"))]
pub fn compare(path: &std::path::Path, stamp: DiskStamp, max: usize) -> OnDisk {
match std::fs::metadata(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return OnDisk::Same,
Err(e) => return OnDisk::Unchecked(e.to_string()),
Ok(meta) if meta.len() != stamp.len => return OnDisk::Changed,
Ok(_) => {}
}
let cap = max.max(usize::try_from(stamp.len).unwrap_or(usize::MAX));
match crate::capped_read::read_capped(path, cap) {
Ok(bytes) if DiskStamp::of(&bytes) == stamp => OnDisk::Same,
Ok(_) => OnDisk::Changed,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => OnDisk::Same,
Err(e) => OnDisk::Unchecked(e.to_string()),
}
}
-4
View File
@@ -48,9 +48,6 @@ pub struct DocState {
/// The Block Editor (BEDIT), when it is open: `doc` is then the editor's drawing, and the
/// drawing itself waits in it ([`DocState::drawing`]).
pub block_edit: Option<blockedit::BlockEdit>,
/// What the drawing's file held when it was read or last saved here: a save over it checks
/// that nobody else wrote it in between ([`crate::disk_stamp`]).
pub disk: Option<crate::disk_stamp::DiskStamp>,
/// The user was told that the current UCS is tilted ([`Session::note_tilted_ucs`]).
pub ucs_tilted_noted: bool,
/// What the last erase removed, for OOPS.
@@ -90,7 +87,6 @@ impl DocState {
uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
binary_dxf: false,
block_edit: None,
disk: None,
ucs_tilted_noted: false,
erased: Default::default(),
fonts_noted: String::new(),
-6
View File
@@ -74,12 +74,6 @@ impl AutomationRoots {
Ok(Some(Arc::new(Self { read, write })))
}
/// Roots that grant nothing: every read and write is refused. For agents whose folders can't
/// be used, where leaving the roots out would confine nothing.
pub fn none() -> Arc<Self> {
Arc::new(Self { read: None, write: None })
}
/// The read root, absolute with its links followed.
pub fn read_root(&self) -> Option<&Path> {
self.read.as_deref()
@@ -9,8 +9,6 @@
pub const FILES: &[&str] = &[
"-hatch",
"-linetype",
"-pagesetup",
"-plot",
"-plottermanager",
"-wblock",
"-xref",
-10
View File
@@ -7,8 +7,6 @@
//! [`Session::input`], [`Session::cmdline`]) exactly like typing at AutoCAD's command line.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
#[cfg(not(target_arch = "wasm32"))]
pub mod agent_settings;
pub mod array_live;
pub mod assoc;
@@ -20,7 +18,6 @@ pub mod blockedit;
#[cfg(not(target_arch = "wasm32"))]
pub mod capped_read;
pub mod cmd;
pub mod disk_stamp;
pub mod doc_path;
pub mod drawlock;
pub mod file_access;
@@ -64,13 +61,6 @@ pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices, patte
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
/// The most selected objects [`Session::selection_anno_others`] shows at their other scales (as
/// grips, a big selection is drawn without them).
pub const MAX_ANNO_OTHERS: usize = 200;
/// The most faded representations [`Session::selection_anno_others`] makes for a whole selection
/// (each selected object can support many scales).
pub const MAX_ANNO_FADED: usize = 1000;
mod doc_state;
mod error;
mod last_used;
+1 -1
View File
@@ -286,7 +286,7 @@ fn convert_angles(kind: &str, tags: &mut [Tag], f: fn(f64) -> f64) {
fn tag_value(t: &Tag) -> Value {
match &t.value {
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) | craft_dxf::Value::Invalid(s) => Value::str(s),
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) => Value::str(s),
craft_dxf::Value::Real(r) => Value::Real(*r),
craft_dxf::Value::Int(i) => Value::Int(i32::try_from(*i).unwrap_or(if *i < 0 { i32::MIN } else { i32::MAX })),
craft_dxf::Value::Bool(b) => Value::Int(i32::from(*b)),
-35
View File
@@ -720,41 +720,6 @@ impl Session {
self.picking_objects() && self.settings.selectionpreview & bit != 0
}
/// The selected annotative objects at their other scales, drawn faded while they are selected
/// (SELECTIONANNODISPLAY): each at that scale's size and position, as
/// [`cadcraft_doc::anno_others`] gives them. In model space the current scale is CANNOSCALE;
/// inside an active viewport it is the viewport's scale. Empty with SELECTIONANNODISPLAY 0. At
/// most [`MAX_ANNO_OTHERS`] selected objects are looked at, and at most [`MAX_ANNO_FADED`]
/// representations made for all of them together.
pub fn selection_anno_others(&self) -> Vec<Entity> {
let Ok(st) = self.state() else { return Vec::new() };
if !self.settings.selectionannodisplay {
return Vec::new();
}
let d = &st.doc;
let vp_scale = st.anno_view();
let mut out = Vec::new();
let mut budget = crate::MAX_ANNO_FADED;
for h in st.selection.iter().take(crate::MAX_ANNO_OTHERS) {
if budget == 0 {
break;
}
match vp_scale {
Some(f) => {
if let Some(e) = d.model.get(*h) {
out.extend(cadcraft_doc::anno_others(e, f, d.anno_all_visible(), &mut budget));
}
}
None => {
if let Some(e) = d.entity(*h) {
out.extend(d.anno_others(e, &mut budget));
}
}
}
}
out
}
/// Whether selected objects show grips while `selected` objects are selected (GRIPS,
/// GRIPOBJLIMIT).
pub fn shows_grips(&self, selected: usize) -> bool {
-3
View File
@@ -110,8 +110,6 @@ pub struct Settings {
/// SELECTIONPREVIEW bits: the object under the cursor is highlighted (1) when no command is
/// active, (2) when a command asks for objects.
pub selectionpreview: u8,
/// SELECTIONANNODISPLAY: a selected annotative object also shows faded at its other scales.
pub selectionannodisplay: bool,
/// PREVIEWEFFECT: how that object is highlighted: 0 dashed, 1 thicker, 2 dashed and thicker.
pub previeweffect: u8,
/// PREVIEWFILTER bits: objects the cursor never highlights: 1 on locked layers, 2 xrefs,
@@ -209,7 +207,6 @@ impl Default for Settings {
highlight: true,
selectioneffect: 1,
selectionpreview: 3,
selectionannodisplay: true,
previeweffect: 2,
previewfilter: 3,
grips: 1,
+20 -82
View File
@@ -713,7 +713,7 @@ fn leaves_with_sources(
sink: &mut Sink<'_>,
src: &mut Sources,
) {
block_leaves(d, ins, &Mat3::IDENTITY, z, 0, budget, Inside::drawn(frozen), &mut |be, m, z| leaf_with_source(be, m, z, handle, sink, src));
block_leaves(d, ins, &Mat3::IDENTITY, z, 0, budget, frozen, &mut |be, m, z| leaf_with_source(be, m, z, handle, sink, src));
}
/// The snaps on `be`, an object drawn inside the drawing's object `handle` and placed by `m` and
@@ -1013,9 +1013,8 @@ fn distance_to_prim(p: &Prim, cursor: Vec2) -> f64 {
prim_segments(p).iter().map(|s| fix_circle(s).closest(cursor).dist(cursor)).fold(f64::INFINITY, f64::min)
}
/// Upper bound on the block-reference objects one snap query, or one look for TRIM and EXTEND
/// edges, looks at (hostile files).
pub(crate) const MAX_BLOCK_LEAVES: usize = 20_000;
/// Upper bound on the block-reference objects one snap query looks at (hostile files).
const MAX_BLOCK_LEAVES: usize = 20_000;
/// Collects snap candidates and the primitives near the cursor.
struct Sink<'a> {
@@ -1167,7 +1166,7 @@ impl Sink<'_> {
fn dimension(&mut self, d: &Drawing, dm: &cadcraft_doc::Dimension, budget: &mut usize, frozen: &[String]) {
match dm.block.as_ref().and_then(|n| d.block(n)) {
Some(blk) => {
block_leaves(d, &dimension_reference(blk, dm), &Mat3::IDENTITY, None, 0, budget, Inside::drawn(frozen), &mut |be, m, _| {
block_leaves(d, &dimension_reference(blk, dm), &Mat3::IDENTITY, None, 0, budget, frozen, &mut |be, m, _| {
self.object(&be.kind, Some(m))
});
}
@@ -1211,50 +1210,20 @@ fn dim_def_points(dm: &cadcraft_doc::Dimension) -> Vec<Vec2> {
pts.into_iter().map(|p| p.xy()).filter(|p| p.is_finite()).collect()
}
/// Which of the objects inside a block reference [`block_leaves`] visits.
#[derive(Clone, Copy)]
pub(crate) struct Inside<'a> {
/// Layers frozen in the viewport, whose objects are left out like those of a layer the
/// drawing has off or frozen.
frozen: &'a [String],
/// Whether a dimension and a record kept as read give the objects they draw (a snap finds
/// those) or come as they are, like the same object outside a block.
expand: bool,
}
impl<'a> Inside<'a> {
/// Everything the reference draws, down to the objects a dimension or a kept record draws.
pub(crate) fn drawn(frozen: &'a [String]) -> Self {
Inside { frozen, expand: true }
}
}
/// Calls `f` with each object inside the block reference `ins` that is drawn and the transform
/// placing it in the reference's space, nested references expanded ([`block_leaves`]). `budget`
/// is how many objects the caller's whole walk may still visit and goes down by those visited
/// here: one count, started at [`MAX_BLOCK_LEAVES`], bounds a walk over every reference of a
/// drawing as it bounds a snap query. A dimension and a record kept as read come as they are, so
/// what an object gives inside a reference is what the same object gives outside one. TRIM and
/// EXTEND take their edges inside a reference from here.
pub(crate) fn reference_leaves(d: &Drawing, ins: &Insert, budget: &mut usize, f: &mut dyn FnMut(&EntityKind, &Mat3)) {
block_leaves(d, ins, &Mat3::IDENTITY, None, 0, budget, Inside { frozen: &[], expand: false }, &mut |be, m, _| f(&be.kind, m));
}
/// Calls `f` with each object drawn by a block reference and the transform placing it, nested
/// references expanded (within [`MAX_BLOCK_DEPTH`] levels and `budget` objects); objects that
/// aren't drawn (hidden, on a layer that is off or frozen, attribute definitions) are left out.
/// The objects inside a block reference, each with its transform and, when every reference on
/// the way is in plan (`z`, from [`plan_z`]), how its Z maps to the drawing's. `inside` says
/// which of them come ([`Inside`]).
/// the way is in plan (`z`, from [`plan_z`]), how its Z maps to the drawing's.
#[allow(clippy::too_many_arguments)]
pub(crate) fn block_leaves(
fn block_leaves(
d: &Drawing,
ins: &Insert,
m: &Mat3,
z: Option<(f64, f64)>,
depth: usize,
budget: &mut usize,
inside: Inside<'_>,
frozen: &[String],
f: &mut dyn FnMut(&Entity, &Mat3, Option<(f64, f64)>),
) {
if depth >= MAX_BLOCK_DEPTH {
@@ -1280,33 +1249,22 @@ pub(crate) fn block_leaves(
return;
}
*budget -= 1;
if !drawn_inside(d, be, inside.frozen) {
if !drawn_inside(d, be, frozen) {
continue;
}
match &be.kind {
EntityKind::AttDef(_) => {}
EntityKind::Insert(inner) => {
let zz = z.and_then(|z| plan_z(&be.common, inner, z));
block_leaves(d, inner, &mm, zz, depth + 1, budget, inside, f);
block_leaves(d, inner, &mm, zz, depth + 1, budget, frozen, f);
}
// A dimension draws its block, as at the top level.
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().filter(|_| inside.expand).and_then(|n| d.block(n)) => {
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) => {
let r = dimension_reference(blk, dm);
let zz = z.and_then(|z| plan_z(&be.common, &r, z));
block_leaves(d, &r, &mm, zz, depth + 1, budget, inside, f);
}
EntityKind::Unknown(u) if inside.expand => graphics_leaves(d, u, &mm, z, depth + 1, budget, inside.frozen, f),
// A record kept as read that comes as it is spends one count for each graphic
// it holds as well, drawn or not: whoever takes it goes through them all to
// find the drawn ones, in every reference.
EntityKind::Unknown(u) => {
if u.graphics.len() > *budget {
*budget = 0;
return;
}
*budget -= u.graphics.len();
f(be, &mm, z);
block_leaves(d, &r, &mm, zz, depth + 1, budget, frozen, f);
}
EntityKind::Unknown(u) => graphics_leaves(d, u, &mm, z, depth + 1, budget, frozen, f),
_ => f(be, &mm, z),
}
}
@@ -1352,30 +1310,20 @@ fn graphics_leaves(
frozen: &[String],
f: &mut dyn FnMut(&Entity, &Mat3, Option<(f64, f64)>),
) {
for g in drawn_graphics(d, u, frozen) {
for g in &u.graphics {
if matches!(g.kind, EntityKind::Hatch(_)) || !drawn_inside(d, g, frozen) {
continue;
}
match &g.kind {
EntityKind::Insert(inner) => {
let zz = z.and_then(|z| plan_z(&g.common, inner, z));
block_leaves(d, inner, m, zz, depth, budget, Inside::drawn(frozen), f);
block_leaves(d, inner, m, zz, depth, budget, frozen, f);
}
_ => f(g, m, None),
}
}
}
/// The graphics of the record kept as read `u` that are drawn, as the renderer draws them: like
/// a block's contents, so not the hidden ones nor those on a layer that is off, frozen or among
/// `frozen` (the layers frozen in the viewport); those on layer 0 take the layer of the record.
/// The fill hatches are left out too, each filled shape's outline being drawn as well. A snap
/// and a TRIM or EXTEND edge both take a proxy's geometry from here.
pub(crate) fn drawn_graphics<'a>(
d: &'a Drawing,
u: &'a cadcraft_doc::Unknown,
frozen: &'a [String],
) -> impl Iterator<Item = &'a cadcraft_doc::Entity> {
u.graphics.iter().filter(move |g| !matches!(g.kind, EntityKind::Hatch(_)) && drawn_inside(d, g, frozen))
}
/// The reference that places a dimension's block as the renderer draws it: the block holds world
/// geometry, moved by the insertion point (DXF group 12, which an older AutoCAD sets for a moved
/// dimension; #2634).
@@ -1408,19 +1356,9 @@ fn prim_near(p: &Prim, probe: &Bounds2, aperture: f64) -> bool {
b.expand(aperture).intersects(probe)
}
/// The unit direction `v` has once `m` places it: zero only when the placed vector has no length
/// or is not finite. Its length is compared with zero, not with the drawing tolerance, so a
/// direction keeps pointing the same way however small or large the scale of `m` is.
pub(crate) fn placed_dir(v: Vec2, m: &Mat3) -> Vec2 {
let v = m.apply_vec(v);
let len = v.len();
if len > 0.0 && len.is_finite() { v / len } else { Vec2::ZERO }
}
/// `p` placed by the affine transform `m`, exactly: circles and arcs under a non-uniform scale
/// become ellipses and elliptical arcs. An xline or a ray keeps its direction at any scale
/// ([`placed_dir`]).
pub(crate) fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
/// become ellipses and elliptical arcs.
fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
let mirror = m.is_mirroring();
match p {
Prim::Seg(Segment::Line(l)) => Prim::Seg(Segment::Line(cadcraft_geom::Line::new(m.apply(l.a), m.apply(l.b)))),
@@ -1447,7 +1385,7 @@ pub(crate) fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
Prim::Spline(s)
}
Prim::Point(q) => Prim::Point(m.apply(*q)),
Prim::Infinite { base, dir, ray } => Prim::Infinite { base: m.apply(*base), dir: placed_dir(*dir, m), ray: *ray },
Prim::Infinite { base, dir, ray } => Prim::Infinite { base: m.apply(*base), dir: m.apply_vec(*dir).normalized(), ray: *ray },
Prim::Fill(f) => Prim::Fill(f.iter().map(|q| m.apply(*q)).collect()),
}
}
+2 -9
View File
@@ -55,7 +55,6 @@ const SESSION_VARS: &[&str] = &[
"HIGHLIGHT",
"SELECTIONEFFECT",
"SELECTIONPREVIEW",
"SELECTIONANNODISPLAY",
"PREVIEWEFFECT",
"PREVIEWFILTER",
"GRIPS",
@@ -186,7 +185,6 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"HIGHLIGHT" => json!(i32::from(st.highlight)),
"SELECTIONEFFECT" => json!(st.selectioneffect),
"SELECTIONPREVIEW" => json!(st.selectionpreview),
"SELECTIONANNODISPLAY" => json!(i32::from(st.selectionannodisplay)),
"PREVIEWEFFECT" => json!(st.previeweffect),
"PREVIEWFILTER" => json!(st.previewfilter),
"GRIPS" => json!(st.grips),
@@ -236,10 +234,7 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"TEXTEVAL" => json!(i32::from(st.texteval)),
// Dialogs are available (read-only; a batch session is still told 1, as AutoCAD does).
"POPUPS" => json!(1),
// The command a transparent one runs inside comes first, as AutoCAD gives it ("LINE'ZOOM").
// While a transparent command reads its input it isn't `running`, but the outer command
// is still suspended, and still active.
"CMDNAMES" => json!([&s.suspended, &s.running].into_iter().flatten().map(|r| r.id.to_ascii_uppercase()).collect::<Vec<_>>().join("'")),
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
"DWGNAME" => json!(s.state().map(|d| d.title.clone()).unwrap_or_default()),
"DBMOD" => json!(s.state().map(|d| i32::from(d.is_dirty())).unwrap_or(0)),
// The next handle the drawing gives out, in hex as `$HANDSEED` (the header keeps the
@@ -249,8 +244,7 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
// The drawing's folder with a trailing separator ("" while it has no file); DWGTITLED is 1 once it has one.
"DWGPREFIX" => json!(s.state().ok().and_then(|d| d.path.as_deref()).map(dwg_prefix).unwrap_or_default()),
"DWGTITLED" => json!(s.state().map(|d| i32::from(d.path.is_some())).unwrap_or(0)),
// 1: a command is active; 2: a transparent one, inside it.
"CMDACTIVE" => json!(i32::from(s.running.is_some() || s.suspended.is_some()) + 2 * i32::from(s.suspended.is_some())),
"CMDACTIVE" => json!(i32::from(s.running.is_some())),
"TILEMODE" => json!(i32::from(s.state().is_ok_and(|d| d.space.layout().is_none()))),
// The release number as AutoCAD reports it, so `(atof (getvar "ACADVER"))` is 24.3; the
// drawing's own `$ACADVER` (its file version) is left alone for the save version.
@@ -484,7 +478,6 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
"HIGHLIGHT" => st.highlight = as_bool(v).ok_or_else(bad)?,
"SELECTIONEFFECT" => st.selectioneffect = small(v, 1).ok_or_else(bad)?,
"SELECTIONPREVIEW" => st.selectionpreview = small(v, 3).ok_or_else(bad)?,
"SELECTIONANNODISPLAY" => st.selectionannodisplay = small(v, 1).ok_or_else(bad)? != 0,
"PREVIEWEFFECT" => st.previeweffect = small(v, 2).ok_or_else(bad)?,
"PREVIEWFILTER" => st.previewfilter = small(v, 63).ok_or_else(bad)?,
"GRIPS" => st.grips = small(v, 2).ok_or_else(bad)?,
-27
View File
@@ -965,33 +965,6 @@ fn setvar_at_command_line() {
assert!(s.running.is_none());
}
/// #3273: GETVAR at the command line asks for a name and echoes its value, without changing it;
/// it said only that `name` was required.
#[test]
fn getvar_at_command_line() {
let mut s = Session::new();
let dimscale = sysvars::get(&s, "DIMSCALE").unwrap();
// One line, as typed in the issue.
s.cmdline("GETVAR DIMSCALE").unwrap();
assert!(s.running.is_none());
assert!(s.log.last().is_some_and(|l| l.starts_with("DIMSCALE = ")), "{:?}", s.log.last());
assert_eq!(sysvars::get(&s, "DIMSCALE").unwrap(), dimscale, "reading changes nothing");
// Step by step, in any case.
s.cmdline("getvar").unwrap();
assert!(s.running.is_some());
s.cmdline("lunits").unwrap();
assert!(s.running.is_none());
assert!(s.log.last().is_some_and(|l| l.starts_with("LUNITS = ")), "{:?}", s.log.last());
// An unknown name says so, and Enter ends it.
s.cmdline("GETVAR NOSUCHVAR").unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Unknown variable NOSUCHVAR. Type SETVAR ? to list variables."));
s.cmdline("getvar").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none());
// The command an agent runs is unchanged.
assert_eq!(s.execute("getvar", &json!({"name": "dimscale"})).unwrap(), json!({"name": "DIMSCALE", "value": dimscale}));
}
#[test]
fn setvar_keeps_header_types() {
let mut s = Session::new();
@@ -10,7 +10,8 @@ use cadcraft_engine::cmd::file::MAX_ALIASES;
use cadcraft_engine::cmd::resolve_alias;
use serde_json::json;
use crate::temp_dir;
#[path = "support/temp_dir.rs"]
mod temp_dir;
use temp_dir::TempDir;
-659
View File
@@ -1,659 +0,0 @@
//! #3433: -PLOT and -PAGESETUP typed at the command line, in a script or from `(command …)` ask
//! for their options one at a time and run the `plot` and `pagesetup` commands with the answers,
//! so a script or a LISP routine can set a layout's paper and plot it without a dialog.
//!
//! In its own test binary, not `tests/it`, because it installs the real plotter: the io hooks
//! are process-wide and set once (`set_io` keeps the first value), so in `tests/it` they would
//! change what the other tests' saves and plots do, by test order.
use cadcraft_engine::cmd::file::{IoHooks, set_io};
use cadcraft_engine::cmd::plotters::{PlotterStore, set_plotter_store};
use cadcraft_engine::{Input, Session};
use serde_json::{Value, json};
#[path = "support/temp_dir.rs"]
mod temp_dir;
use temp_dir::TempDir;
/// ISO A4 in points, short side first.
const A4_PT: (f64, f64) = (595.28, 841.89);
/// ISO A3 in points, short side first.
const A3_PT: (f64, f64) = (841.89, 1190.55);
/// A session with the real plotter, the built-in devices only, and one line in model space.
fn session() -> Session {
set_plotter_store(PlotterStore::memory());
set_io(IoHooks {
read: |_, _| Err("no reader in this test".into()),
write: |_, _| Err("no writer in this test".into()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
let mut s = Session::new();
s.cmdline("line 0,0 100,50").unwrap();
s.cmdline("").unwrap();
s
}
/// A path in `dir` written with forward slashes, so it reads the same in a script line and in a
/// LISP string.
fn out(dir: &TempDir, name: &str) -> String {
dir.path_str(name).replace('\\', "/")
}
/// The page size of a plotted PDF in points, as (width, height).
fn media(path: &str) -> (f64, f64) {
let bytes = std::fs::read(path).unwrap_or_else(|e| panic!("{path}: {e}"));
assert!(bytes.starts_with(b"%PDF"), "{path} is a PDF");
let text = String::from_utf8_lossy(&bytes);
let at = text.find("/MediaBox").expect("the PDF names its page size");
let rest = &text[at..];
let (open, close) = (rest.find('[').expect("["), rest.find(']').expect("]"));
let n: Vec<f64> = rest[open + 1..close].split_whitespace().filter_map(|t| t.parse().ok()).collect();
assert_eq!(n.len(), 4, "a page box has four numbers: {n:?}");
(n[2] - n[0], n[3] - n[1])
}
/// Whether a page is the sheet `size` (short side first), turned to landscape or not.
fn is_sheet(page: (f64, f64), size: (f64, f64), landscape: bool) -> bool {
let want = if landscape { (size.1, size.0) } else { size };
(page.0 - want.0).abs() < 0.5 && (page.1 - want.1).abs() < 0.5
}
/// The stored page setup of a layout, as the `pagesetup` query reports it.
fn page(s: &mut Session, layout: &str) -> Value {
s.execute("pagesetup", &json!({ "layout": layout })).unwrap()["page"].clone()
}
/// The question on the command line now, as shown.
fn asked(s: &Session) -> String {
s.current_prompt().expect("a question is asked").display()
}
/// A script's long form on the Model tab plots a PDF on the paper and in the orientation its
/// answers name.
#[test]
fn the_long_form_on_model_plots_the_asked_paper_and_orientation() {
let mut s = session();
let dir = TempDir::new("dash-plot-model");
let pdf = out(&dir, "model.pdf");
s.script(&format!("-PLOT Y\nModel\nCADCraft PDF\nA3\nM L N E F C Y\n.\nY A\n{pdf}\nN Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert!(is_sheet(media(&pdf), A3_PT, true), "{:?}", media(&pdf));
// The other orientation and another paper, to show the answers decide and not a default.
let pdf = out(&dir, "model-portrait.pdf");
s.script(&format!("-PLOT Y\nModel\nCADCraft PDF\nA4\nM P N E F C Y\n.\nY A\n{pdf}\nN Y\n")).unwrap();
assert!(is_sheet(media(&pdf), A4_PT, false), "{:?}", media(&pdf));
}
/// The long form on a layout asks the layout's own questions (no shade plot; lineweight scaling,
/// paper space first and hiding instead) and plots that layout on the asked paper, without
/// touching its stored page setup when the answer to saving is No.
#[test]
fn the_long_form_on_a_layout_plots_the_asked_paper_and_keeps_the_page_setup() {
let mut s = session();
let dir = TempDir::new("dash-plot-layout");
let pdf = out(&dir, "layout.pdf");
let before = page(&mut s, "Layout1");
s.script(&format!("-PLOT Y\nLayout1\nCADCraft PDF\nA4\nM P N L 1=1 0,0 Y\n.\nY N N N\n{pdf}\nN Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert!(is_sheet(media(&pdf), A4_PT, false), "{:?}", media(&pdf));
assert_eq!(page(&mut s, "Layout1"), before, "saving answered No: the layout keeps its page setup");
}
/// The short form asks the layout, a page setup name, the device and the file, and plots the
/// layout with its stored page setup.
#[test]
fn the_short_form_plots_the_layout_as_its_page_setup_says() {
let mut s = session();
let dir = TempDir::new("dash-plot-short");
s.execute("pagesetup", &json!({ "layout": "Layout1", "paper": "A3", "landscape": true })).unwrap();
let pdf = out(&dir, "short.pdf");
s.cmdline("-PLOT").unwrap();
let mut seen = vec![asked(&s)];
for answer in ["N", "Layout1", "", "CADCraft PDF", &pdf, "", ""] {
s.cmdline(answer).unwrap();
seen.extend(s.current_prompt().map(|p| p.display()));
}
assert_eq!(seen.len(), 7, "seven questions: {seen:#?}");
let has = |i: usize, word: &str| seen[i].to_lowercase().contains(word);
assert!(
has(0, "detailed") && has(1, "layout") && has(2, "page setup") && has(3, "device") && has(4, "file") && has(5, "save") && has(6, "go ahead"),
"{seen:#?}"
);
assert!(s.current_prompt().is_none());
assert!(is_sheet(media(&pdf), A3_PT, true), "{:?}", media(&pdf));
}
/// An AutoLISP routine plots through `(command "_-PLOT" …)` and sets a layout's page setup
/// through `(command "_-PAGESETUP" …)`, with underscored keywords as routines write them.
#[test]
fn lisp_command_plots_and_sets_a_page_setup() {
let mut s = session();
let dir = TempDir::new("dash-plot-lisp");
let pdf = out(&dir, "lisp.pdf");
s.script(&format!(r#"(command "_-PLOT" "_Y" "Model" "CADCraft PDF" "A4" "_M" "_P" "_N" "_E" "_F" "_C" "_Y" "." "_Y" "_A" "{pdf}" "_N" "_Y")"#))
.unwrap();
assert!(s.current_prompt().is_none(), "the routine answered every question: {:?}", s.current_prompt());
assert!(is_sheet(media(&pdf), A4_PT, false), "{:?}", media(&pdf));
s.script(r#"(command "_-PAGESETUP" "Layout1" "CADCraft PDF" "A3" "_M" "_L" "_N" "_L" "_F" "0,0" "_Y" "monochrome.ctb" "_N" "_N" "_N" "_N")"#)
.unwrap();
assert!(s.current_prompt().is_none(), "the routine answered every question: {:?}", s.current_prompt());
let p = page(&mut s, "Layout1");
assert_eq!(p["device"], "CADCraft PDF");
assert!(p["paper"].as_str().unwrap().contains("A3"), "{p}");
assert_eq!(p["landscape"], true);
assert_eq!(p["paperMm"], true);
assert_eq!(p["scaleToFit"], true);
assert_eq!(p["plotStyleTable"], "monochrome.ctb");
assert_eq!(p["lineweights"], false);
}
/// -PAGESETUP from a script stores the answers on the layout, the `pagesetup` query reads them
/// back, the other layout is untouched, and the whole command is one undo step.
#[test]
fn pagesetup_script_changes_the_stored_page_setup() {
let mut s = session();
let before = page(&mut s, "Layout1");
let other = page(&mut s, "Layout2");
s.script("-PAGESETUP\nLayout1\nCADCraft PDF\nA3\nM P N L 1=2 0,0 Y\ngrayscale.ctb\nY N N N\n").unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
let p = page(&mut s, "Layout1");
assert_ne!(p, before);
assert_eq!(p["device"], "CADCraft PDF");
assert!(p["paper"].as_str().unwrap().contains("A3"), "{p}");
assert_eq!((&p["landscape"], &p["paperMm"], &p["scaleToFit"]), (&json!(false), &json!(true), &json!(false)));
assert!((p["scale"].as_f64().unwrap() - 0.5).abs() < 1e-9, "1=2 is half a paper unit per drawing unit: {p}");
assert_eq!(p["plotStyleTable"], "grayscale.ctb");
assert_eq!(page(&mut s, "Layout2"), other);
s.undo().unwrap();
assert_eq!(page(&mut s, "Layout1"), before, "one undo step takes the page setup back");
}
/// Enter at every question takes the default the question shows: on the Model tab the long form
/// asks its seventeen questions in order and plots as the `plot` command does with those
/// defaults; on a layout the defaults are its stored page setup.
#[test]
fn enter_takes_the_shown_default_at_each_question() {
let mut s = session();
let dir = TempDir::new("dash-plot-enter");
let pdf = out(&dir, "enter.pdf");
s.cmdline("-PLOT").unwrap();
s.cmdline("Y").unwrap();
let mut seen = vec![asked(&s)];
s.cmdline("").unwrap(); // the layout: the current tab
seen.push(asked(&s));
s.cmdline("CADCraft PDF").unwrap();
// Paper, units, orientation, upside down, area, scale, offset, plot styles, table,
// lineweights, shade plot: Enter at each.
for _ in 0..11 {
let p = s.current_prompt().expect("a question");
assert!(p.default.is_some(), "every question shows a default: {}", p.display());
seen.push(p.display());
s.cmdline("").unwrap();
}
let file = s.current_prompt().expect("the file question");
assert!(file.default.as_deref().is_some_and(|d| d.ends_with("-Model.pdf")), "{}", file.display());
seen.push(file.display());
s.cmdline(&pdf).unwrap();
seen.push(asked(&s));
s.cmdline("").unwrap(); // save: No
seen.push(asked(&s));
s.cmdline("").unwrap(); // proceed: Yes
assert!(s.current_prompt().is_none());
let order = [
"layout",
"device",
"paper size",
"paper units",
"orientation",
"upside down",
"plot area",
"plot scale",
"plot offset",
"plot styles",
"plot style table",
"lineweights",
"shade plot",
"file name",
"save",
"go ahead",
];
assert_eq!(seen.len(), order.len(), "{seen:#?}");
for (q, word) in seen.iter().zip(order) {
assert!(q.to_lowercase().contains(word), "`{q}` should ask for the {word}");
}
// The built-in device's default paper and orientation.
assert!(is_sheet(media(&pdf), A4_PT, true), "{:?}", media(&pdf));
// On a layout the defaults are its page setup: Enter everywhere plots it as stored.
s.execute("pagesetup", &json!({ "layout": "Layout2", "device": "CADCraft PDF", "paper": "A3", "landscape": false })).unwrap();
let stored = page(&mut s, "Layout2");
let pdf = out(&dir, "enter-layout.pdf");
s.cmdline("-PLOT").unwrap();
s.cmdline("Y").unwrap();
s.cmdline("Layout2").unwrap();
assert!(asked(&s).contains("<CADCraft PDF>"), "{}", asked(&s));
s.cmdline("").unwrap();
assert!(asked(&s).contains("A3"), "{}", asked(&s));
let mut layout_questions = Vec::new();
while !asked(&s).to_lowercase().contains("file name") {
layout_questions.push(asked(&s).to_lowercase());
s.cmdline("").unwrap();
}
assert!(layout_questions.iter().any(|q| q.contains("<layout>")), "the area defaults to the sheet: {layout_questions:#?}");
assert!(!layout_questions.iter().any(|q| q.contains("shade plot")), "no shade plot question on a layout: {layout_questions:#?}");
for word in ["scale the lineweights", "paper space first", "hide paper space"] {
assert!(layout_questions.iter().any(|q| q.contains(word)), "a layout is asked about {word}: {layout_questions:#?}");
}
s.cmdline(&pdf).unwrap();
s.cmdline("").unwrap();
s.cmdline("").unwrap();
assert!(is_sheet(media(&pdf), A3_PT, false), "{:?}", media(&pdf));
assert_eq!(page(&mut s, "Layout2"), stored);
}
/// A wrong answer is told and the same question is asked again; so is an answer the plotter
/// cannot honour, which is never accepted without effect.
#[test]
fn a_wrong_answer_asks_the_question_again() {
let mut s = session();
let dir = TempDir::new("dash-plot-wrong");
let pdf = out(&dir, "wrong.pdf");
s.cmdline("-PLOT").unwrap();
// Each pair: answers that must be refused at the question, then the answer that moves on.
let steps: [(&[&str], &str); 14] = [
(&["maybe"], "Y"),
(&["No such layout"], "Model"),
(&["No such device"], "CADCraft PDF"),
(&["No such paper"], "A4"),
(&["furlongs"], "M"),
(&["sideways"], "L"),
(&["Y"], "N"), // upside down
(&["everything"], "E"), // area
(&["abc", "0=1", "5"], "1=2"),
(&["left", "1;2"], "0,0"),
(&["perhaps"], "Y"), // plot styles
(&[], "."), // table
(&["perhaps"], "Y"), // lineweights
(&["H", "V", "R"], "A"), // shade plot
];
for (wrong, right) in steps {
let question = asked(&s);
for w in wrong {
let said = s.log.len();
s.cmdline(w).unwrap();
assert_eq!(asked(&s), question, "`{w}` is not an answer here");
assert!(s.log.len() > said, "`{w}` at `{question}` is told why it is refused");
}
s.cmdline(right).unwrap();
assert_ne!(asked(&s), question, "`{right}` answers `{question}`");
}
s.cmdline(&pdf).unwrap();
// Model space stores no page setup: saving is refused there, not silently dropped.
let question = asked(&s);
s.cmdline("Y").unwrap();
assert_eq!(asked(&s), question);
s.cmdline("N").unwrap();
s.cmdline("Y").unwrap();
assert!(s.current_prompt().is_none());
assert!(is_sheet(media(&pdf), A4_PT, true), "{:?}", media(&pdf));
}
/// Esc at any question ends the command with nothing plotted, nothing stored and no undo step.
#[test]
fn escape_cancels_and_changes_nothing() {
let mut s = session();
let dir = TempDir::new("dash-plot-esc");
let pdf = out(&dir, "never.pdf");
let before = page(&mut s, "Layout1");
let drawing = s.doc().unwrap().clone();
// -PAGESETUP, cancelled at its last question.
s.script("-PAGESETUP\nLayout1\nCADCraft PDF\nA3\nM P N L 1=2 0,0 Y\ngrayscale.ctb\nY N N\n").unwrap();
assert!(asked(&s).to_lowercase().contains("hide paper space"), "{}", asked(&s));
s.input(Input::Cancel).unwrap();
assert!(s.current_prompt().is_none());
assert_eq!(page(&mut s, "Layout1"), before);
// -PLOT with saving answered Yes, cancelled at "proceed".
s.script(&format!("-PLOT Y\nLayout1\nCADCraft PDF\nA3\nM P N L 1=2 0,0 Y\n.\nY N N N\n{pdf}\nY\n")).unwrap();
assert!(asked(&s).to_lowercase().contains("go ahead"), "{}", asked(&s));
s.input(Input::Cancel).unwrap();
assert!(s.current_prompt().is_none());
assert!(!std::path::Path::new(&pdf).exists(), "nothing was plotted");
assert_eq!(page(&mut s, "Layout1"), before);
assert_eq!(*s.doc().unwrap(), drawing, "the drawing is as it was");
s.undo().unwrap();
assert!(s.doc().unwrap().model.is_empty(), "undo takes back the line: neither command left an undo step");
}
/// The command ends without a plot where the observed behaviour ends it: no output device, a
/// plot style table that does not exist, and "proceed" answered No (which still saves the page
/// setup when saving was answered Yes).
#[test]
fn the_command_ends_without_a_plot_where_it_should() {
let mut s = session();
let dir = TempDir::new("dash-plot-ends");
// Enter at the device question on a tab without a device.
s.script("-PLOT Y\nModel\n\n").unwrap();
assert!(s.current_prompt().is_none(), "no device: the command ends: {:?}", s.current_prompt());
assert!(s.log.last().is_some_and(|l| l.contains("cannot plot")), "{:?}", s.log.last());
// An unknown plot style table, also when plot styles were answered No.
for styles in ["Y", "N"] {
s.script(&format!("-PLOT Y\nModel\nCADCraft PDF\nA4\nM P N E F C {styles}\nno-such-table.ctb\n")).unwrap();
assert!(s.current_prompt().is_none(), "an unknown table ends the command: {:?}", s.current_prompt());
assert!(s.log.last().is_some_and(|l| l.contains("no-such-table.ctb")), "{:?}", s.log.last());
}
// Proceed answered No: no file; the page setup is saved because saving was answered Yes.
let pdf = out(&dir, "declined.pdf");
let before = page(&mut s, "Layout1");
s.script(&format!("-PLOT Y\nLayout1\nCADCraft PDF\nA3\nM P N L F 0,0 Y\n.\nY N N N\n{pdf}\nY N\n")).unwrap();
assert!(s.current_prompt().is_none());
assert!(!std::path::Path::new(&pdf).exists(), "proceed answered No plots nothing");
let saved = page(&mut s, "Layout1");
assert_ne!(saved, before);
assert!(saved["paper"].as_str().unwrap().contains("A3") && saved["device"] == "CADCraft PDF", "{saved}");
// The next run on that layout offers the saved answers as its defaults.
s.script("-PLOT Y\nLayout1\n").unwrap();
assert!(asked(&s).contains("<CADCraft PDF>"), "{}", asked(&s));
s.cmdline("").unwrap();
assert!(asked(&s).contains("A3"), "{}", asked(&s));
s.input(Input::Cancel).unwrap();
}
/// The answers reach the `plot` command as the parameters they stand for: a typed plot writes
/// the same file as the JSON call with those parameters. The scale is given in the answered
/// paper units, the window by two corners, a named view as its rectangle.
#[test]
fn typed_answers_plot_as_the_same_json_parameters() {
let mut s = session();
let dir = TempDir::new("dash-plot-same");
let same = |s: &mut Session, name: &str, script: &str, params: Value| {
let typed = out(&dir, &format!("{name}-typed.pdf"));
let direct = out(&dir, &format!("{name}-json.pdf"));
s.script(&script.replace("{out}", &typed)).unwrap();
assert!(s.current_prompt().is_none(), "{name}: the command ended: {:?}", s.current_prompt());
let mut p = params;
p["path"] = json!(direct);
s.execute("plot", &p).unwrap();
assert_eq!(std::fs::read(&typed).unwrap(), std::fs::read(&direct).unwrap(), "{name}: the typed plot is the JSON plot");
};
// One inch on paper for two drawing units, on a sheet the plotter measures in millimetres.
same(
&mut s,
"inches",
"-PLOT Y\nModel\nCADCraft PDF\nANSI B\nI L N E 1=2 1,0.5 N\n.\nN A\n{out}\nN Y\n",
json!({ "layout": "Model", "device": "CADCraft PDF", "paper": "ANSI B", "landscape": true, "plotArea": "extents", "fit": false,
"scale": 12.7, "center": false, "offset": [25.4, 12.7], "plotStyleTable": "None", "lineweights": false }),
);
// A window by two corners, with a plot style table.
same(
&mut s,
"window",
"-PLOT Y\nModel\nCADCraft PDF\nA4\nM P N W 10,5 60,40 F C Y\nmonochrome.ctb\nY A\n{out}\nN Y\n",
json!({ "layout": "Model", "device": "CADCraft PDF", "paper": "A4", "landscape": false, "plotArea": "window",
"window": [[10, 5], [60, 40]], "fit": true, "center": true, "plotStyleTable": "monochrome.ctb", "lineweights": true }),
);
// A named model space view is its rectangle.
s.execute("view", &json!({ "option": "window", "name": "Detail", "p1": [10, 10], "p2": [50, 30] })).unwrap();
let v = s.doc().unwrap().views.iter().find(|v| v.name == "Detail").expect("the view was saved").clone();
let (lo, hi) = ((v.center.x - v.width / 2.0, v.center.y - v.height / 2.0), (v.center.x + v.width / 2.0, v.center.y + v.height / 2.0));
same(
&mut s,
"view",
"-PLOT Y\nModel\nCADCraft PDF\nA4\nM P N V\nDetail\nF C Y\n.\nY A\n{out}\nN Y\n",
json!({ "layout": "Model", "device": "CADCraft PDF", "paper": "A4", "landscape": false, "plotArea": "window",
"window": [[lo.0, lo.1], [hi.0, hi.1]], "fit": true, "center": true, "plotStyleTable": "None", "lineweights": true }),
);
}
/// A user device made from the built-in PDF device, whose paper `paper` has `margins` (mm).
fn device_with_margins(s: &mut Session, name: &str, paper: &str, margins: [f64; 4]) {
s.execute("plottermanager", &json!({ "action": "new", "name": name, "from": "CADCraft PDF", "output": "pdf" })).unwrap();
s.execute("plottermanager", &json!({ "action": "set", "name": name, "paper": { "name": paper, "margins": margins } })).unwrap();
}
/// The layout plotted as its stored page setup says, fitted to the printable area, so that the
/// stored margins show in the file.
fn plot_as_stored(s: &mut Session, layout: &str, path: &str) -> Vec<u8> {
s.execute("plot", &json!({ "layout": layout, "fit": true, "path": path })).unwrap();
std::fs::read(path).unwrap()
}
/// Enter at the paper question after a change of device keeps the paper's name but takes the new
/// device's margins for it, in the plot as in the saved page setup: the plot the user approved is
/// the plot the saved page setup gives.
#[test]
fn a_device_change_plots_with_the_margins_it_saves() {
let mut s = session();
let dir = TempDir::new("dash-plot-device-margins");
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "CADCraft PDF", "paper": "A3", "landscape": true })).unwrap();
let before = page(&mut s, "Layout1");
let paper = before["paper"].as_str().unwrap().to_string();
device_with_margins(&mut s, "Wide margins 3433", &paper, [30.0, 30.0, 30.0, 30.0]);
let typed = out(&dir, "typed.pdf");
s.script(&format!("-PLOT Y\nLayout1\nWide margins 3433\n\nM L N L F 0,0 Y\n.\nY N N N\n{typed}\nY Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
let saved = page(&mut s, "Layout1");
assert_eq!(saved["paper"], before["paper"], "Enter kept the paper");
assert_ne!(saved["marginsMm"], before["marginsMm"], "the saved page setup has the new device's margins");
let stored = plot_as_stored(&mut s, "Layout1", &out(&dir, "stored.pdf"));
assert!(std::fs::read(&typed).unwrap() == stored, "the typed plot is the plot its saved page setup gives");
}
/// Enter at the paper question on the layout's own device sends no paper, so the layout keeps
/// margins that are not the device's: the plot and the saved page setup both keep them.
#[test]
fn enter_at_the_paper_question_keeps_the_layouts_own_margins() {
let mut s = session();
let dir = TempDir::new("dash-plot-own-margins");
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "CADCraft PDF", "paper": "A3", "landscape": true, "margins": [12, 14, 16, 18] }))
.unwrap();
let before = page(&mut s, "Layout1");
let typed = out(&dir, "typed.pdf");
s.script(&format!("-PLOT Y\nLayout1\n\n\nM L N L F 0,0 Y\n.\nY N N N\n{typed}\nY Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert_eq!(page(&mut s, "Layout1")["marginsMm"], before["marginsMm"], "the layout keeps its own margins");
let stored = plot_as_stored(&mut s, "Layout1", &out(&dir, "stored.pdf"));
assert!(std::fs::read(&typed).unwrap() == stored, "the typed plot is the plot its saved page setup gives");
}
/// Turning the orientation of a layout that keeps its paper turns its margins with the sheet, in
/// the plot as in the saved page setup.
#[test]
fn a_turned_layout_plots_with_the_margins_it_saves() {
let mut s = session();
let dir = TempDir::new("dash-plot-turned");
s.execute("pagesetup", &json!({ "layout": "Layout2", "device": "CADCraft PDF", "paper": "A4", "landscape": false, "margins": [5, 10, 15, 20] }))
.unwrap();
let typed = out(&dir, "typed.pdf");
s.script(&format!("-PLOT Y\nLayout2\n\n\nM L N L F 0,0 Y\n.\nY N N N\n{typed}\nY Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert_eq!(page(&mut s, "Layout2")["landscape"], true);
let stored = plot_as_stored(&mut s, "Layout2", &out(&dir, "stored.pdf"));
assert!(std::fs::read(&typed).unwrap() == stored, "the typed plot is the plot its saved page setup gives");
}
/// A Model plot to an SVG device can only be centred (`plot` refuses an offset there): the offset
/// question says so, refuses an offset, and Enter plots. A PDF device keeps the offset 0,0.
#[test]
fn a_model_svg_plot_is_centred_at_the_offset_question() {
let mut s = session();
let dir = TempDir::new("dash-plot-svg");
let svg = out(&dir, "model.svg");
s.script("-PLOT Y\nModel\nCADCraft SVG\nA4\nM L N E F\n").unwrap();
let question = asked(&s);
assert!(question.to_lowercase().contains("offset") && question.contains("<Center>"), "{question}");
for offset in ["0,0", "5,5"] {
let said = s.log.len();
s.cmdline(offset).unwrap();
assert_eq!(asked(&s), question, "`{offset}` is not available for an SVG plot of model space");
assert!(s.log.len() > said, "`{offset}` is told why it is refused");
}
s.cmdline("").unwrap();
s.script(&format!("Y\n.\nY A\n{svg}\nN Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert!(std::fs::read(&svg).unwrap_or_else(|e| panic!("{svg}: {e}; {:?}", s.log.last())).starts_with(b"<svg"), "the SVG was plotted");
s.script("-PLOT Y\nModel\nCADCraft PDF\nA4\nM L N E F\n").unwrap();
assert!(asked(&s).contains("<0,0>"), "{}", asked(&s));
s.input(Input::Cancel).unwrap();
}
/// Enter at the paper units question stores the units the question showed: a metric drawing's
/// layout moved to an inch sheet shows Inches, and the scale typed there is saved in inches. A
/// layout that keeps its paper and its units is not given units of its own.
#[test]
fn enter_at_the_units_question_saves_the_units_it_shows() {
let mut s = session();
s.execute("setvar", &json!({ "name": "MEASUREMENT", "value": 1 })).unwrap();
s.script("-PAGESETUP\nLayout1\nCADCraft PDF\nANSI B\n").unwrap();
assert!(asked(&s).contains("<Inches>"), "{}", asked(&s));
s.cmdline("").unwrap();
s.script("L N L 1=2 0,0 Y\n.\nY N N N\n").unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
let p = page(&mut s, "Layout1");
assert!(p["paper"].as_str().unwrap().contains("ANSI B"), "{p}");
assert!((p["scale"].as_f64().unwrap() - 0.5).abs() < 1e-9, "{p}");
assert_eq!(p["paperMm"], false, "1=2 was answered in inches, so the saved scale is in inches: {p}");
let before = page(&mut s, "Layout2");
assert!(before.get("paperMm").is_none(), "a new layout follows the drawing's units: {before}");
s.script("-PAGESETUP\nLayout2\nCADCraft PDF\n\n").unwrap();
assert!(asked(&s).to_lowercase().contains("paper units"), "{}", asked(&s));
s.cmdline("").unwrap();
s.script("L N L F 0,0 Y\n.\nY N N N\n").unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
let after = page(&mut s, "Layout2");
assert_eq!(after["paper"], before["paper"]);
assert!(after.get("paperMm").is_none(), "the layout keeps following the drawing's units: {after}");
}
/// Set the plot area a layout's page setup stores, as a drawing file would have it.
fn store_plot_area(s: &mut Session, layout: &str, area: &str, window: [f64; 4]) {
let l = s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == layout).expect("the layout");
l.page.plot_area = area.into();
l.page.plot_window = window;
}
/// -PLOT on a layout shows and takes the area the plot really covers: the sheet, also when the
/// page setup read from a file stores another area that no plot of a layout honours, or the
/// stored plot window when there is a real one. -PAGESETUP still shows and keeps what is stored.
#[test]
fn a_layout_is_offered_the_plot_area_it_really_plots() {
let mut s = session();
let dir = TempDir::new("dash-plot-layout-area");
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "CADCraft PDF", "paper": "A4", "landscape": false })).unwrap();
let sheet = out(&dir, "sheet.pdf");
s.execute("plot", &json!({ "layout": "Layout1", "fit": false, "scale": 1, "path": sheet })).unwrap();
// A stored area that changes nothing in a plot (and a window with no size) is the sheet.
for (area, window) in [("extents", [0.0; 4]), ("display", [0.0; 4]), ("limits", [0.0; 4]), ("window", [0.0; 4])] {
store_plot_area(&mut s, "Layout1", area, window);
s.script("-PLOT Y\nLayout1\n\n\nM P N\n").unwrap();
let question = asked(&s);
assert!(question.to_lowercase().contains("plot area") && question.contains("<Layout>"), "stored {area}: {question}");
for other in ["E", "D", "W", "V"] {
let said = s.log.len();
s.cmdline(other).unwrap();
assert_eq!(asked(&s), question, "stored {area}: `{other}` is not what a layout plots");
assert!(s.log.len() > said, "`{other}` is told why it is refused");
}
let pdf = out(&dir, &format!("{area}.pdf"));
s.script(&format!("L 1=1 0,0 Y\n.\nY N N N\n{pdf}\nN Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "stored {area}: the command ended: {:?}", s.current_prompt());
assert!(std::fs::read(&pdf).unwrap() == std::fs::read(&sheet).unwrap(), "stored {area}: the sheet is what is plotted");
assert_eq!(page(&mut s, "Layout1")["plotArea"], area, "saving answered No: the stored area stays");
}
// A real stored window is what the plot covers: it is shown, and the sheet is refused.
store_plot_area(&mut s, "Layout1", "window", [0.0, 0.0, 100.0, 50.0]);
s.script("-PLOT Y\nLayout1\n\n\nM P N\n").unwrap();
let question = asked(&s);
assert!(question.contains("<Window>"), "{question}");
s.cmdline("L").unwrap();
assert_eq!(asked(&s), question, "the stored window is plotted, not the sheet");
s.input(Input::Cancel).unwrap();
// -PAGESETUP shows what the file stored and keeps it unless Layout is answered.
store_plot_area(&mut s, "Layout1", "extents", [0.0; 4]);
s.script("-PAGESETUP\nLayout1\n\n\nM P N\n").unwrap();
assert!(asked(&s).contains("<Extents>"), "{}", asked(&s));
s.cmdline("").unwrap();
s.script("1=1 0,0 Y\n.\nY N N N\n").unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert_eq!(page(&mut s, "Layout1")["plotArea"], "extents");
}
/// A file name whose type is not what the device writes is refused at the file question, which
/// is asked again; a name without a type still gets the device's.
#[test]
fn a_file_type_the_device_does_not_write_is_refused_at_the_file_question() {
let mut s = session();
let dir = TempDir::new("dash-plot-file-type");
s.script("-PLOT Y\nModel\nCADCraft PDF\nA4\nM L N E F C Y\n.\nY A\n").unwrap();
let question = asked(&s);
assert!(question.to_lowercase().contains("file name"), "{question}");
for wrong in ["sheet.svg", "sheet.PNG"] {
let said = s.log.len();
s.cmdline(&out(&dir, wrong)).unwrap();
assert_eq!(asked(&s), question, "`{wrong}` is not a file the PDF device writes");
assert!(s.log.len() > said, "`{wrong}` is told why it is refused");
}
s.cmdline(&out(&dir, "sheet")).unwrap();
assert!(asked(&s).to_lowercase().contains("save"), "{}", asked(&s));
s.script("N Y\n").unwrap();
assert!(s.current_prompt().is_none());
assert!(is_sheet(media(&out(&dir, "sheet.pdf")), A4_PT, true));
assert!(!std::path::Path::new(&out(&dir, "sheet.svg")).exists() && !std::path::Path::new(&out(&dir, "sheet.PNG")).exists());
// The short form asks the same question.
s.script("-PLOT N\nModel\n\nCADCraft PNG\n").unwrap();
let question = asked(&s);
s.cmdline(&out(&dir, "short.pdf")).unwrap();
assert_eq!(asked(&s), question, "the PNG device does not write a PDF");
s.input(Input::Cancel).unwrap();
}
/// Save answered Yes and the plot answered Yes: a plot that fails saves nothing, so the page
/// setup never holds answers whose plot the user did not get.
#[test]
fn a_failed_plot_saves_no_page_setup() {
let mut s = session();
let dir = TempDir::new("dash-plot-failed");
// A folder stands where the file should be written.
let taken = out(&dir, "taken.pdf");
std::fs::create_dir_all(&taken).unwrap();
let before = page(&mut s, "Layout1");
s.script(&format!("-PLOT Y\nLayout1\nCADCraft PDF\nA3\nM P N L F 0,0 Y\n.\nY N N N\n{taken}\nY Y\n")).unwrap();
assert!(s.current_prompt().is_none(), "the command ended: {:?}", s.current_prompt());
assert!(std::path::Path::new(&taken).is_dir(), "nothing was plotted over the folder");
assert_eq!(page(&mut s, "Layout1"), before, "the failed plot saved nothing");
assert!(!s.log.iter().any(|l| l.contains("saved")), "{:?}", s.log);
}
/// Drawing limits without an area cannot be plotted: Limits is refused at the plot area question
/// and not at the end of the command.
#[test]
fn limits_without_an_area_are_refused_at_the_area_question() {
let mut s = session();
s.execute("limits", &json!({ "min": [0, 0], "max": [0, 9] })).unwrap();
s.script("-PLOT Y\nModel\nCADCraft PDF\nA4\nM L N\n").unwrap();
let question = asked(&s);
assert!(question.to_lowercase().contains("plot area"), "{question}");
let said = s.log.len();
s.cmdline("L").unwrap();
assert_eq!(asked(&s), question, "limits without an area are not a plot area");
assert!(s.log.len() > said);
s.cmdline("E").unwrap();
assert_ne!(asked(&s), question);
s.input(Input::Cancel).unwrap();
}
-233
View File
@@ -1,233 +0,0 @@
//! DIMRADIUS, DIMDIAMETER and DIMJOGGED take a circle or arc inside a block reference, in nested
//! references too, as AutoCAD does (#1967). A pick on a block's line, or on a circle the reference
//! scales unevenly (drawn as an ellipse), is not a circle or arc.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{DimKind, Dimension, EntityKind};
use cadcraft_engine::geom::Vec2;
use serde_json::json;
/// A drawing with block "P": a circle of radius 5 and an arc of radius 3 from 0° to 90° at its
/// origin, and a line from (10, 0) to (20, 0).
fn session() -> Session {
let mut s = Session::new();
s.execute("circle", &json!({"center": [0, 0], "radius": 5})).unwrap();
s.execute("arc", &json!({"center": [0, 0], "radius": 3, "start": 0, "end": 90})).unwrap();
s.execute("line", &json!({"points": [[10, 0], [20, 0]]})).unwrap();
s.execute("selectall", &json!({})).unwrap();
s.execute("block", &json!({"name": "P", "base": [0, 0], "keep": "delete"})).unwrap();
s
}
fn dims(s: &Session) -> Vec<Dimension> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Dimension(d) = &e.kind { Some(d.clone()) } else { None }).collect()
}
/// `p` written for a typed point.
fn pt(p: Vec2) -> String {
format!("{},{}", p.x, p.y)
}
#[test]
fn radius_and_diameter_of_a_circle_or_arc_in_a_rotated_scaled_reference() {
let mut s = session();
s.execute("insert", &json!({"name": "P", "at": [40, 10], "rotation": 30, "scale": 2})).unwrap();
let c = Vec2::new(40.0, 10.0);
// The circle: radius 10 in the drawing, picked away from the arc and the line.
let on_circle = c + Vec2::from_angle(200f64.to_radians()) * 10.0;
s.script(&format!("dimradius {} {}\n", pt(on_circle), pt(c + Vec2::new(-15.0, -8.0)))).unwrap();
assert!(s.running.is_none());
let d = dims(&s);
assert_eq!(d.len(), 1, "a radius dimension of the nested circle");
assert!(matches!(d[0].kind, DimKind::Radius));
assert!(d[0].defpt.xy().dist(c) < 1e-9, "centred on the circle: {:?}", d[0].defpt);
assert!((d[0].p15.xy().dist(c) - 10.0).abs() < 1e-9, "radius {}", d[0].p15.xy().dist(c));
// The arc: the block's 0°–90° become 30°–120°, radius 6; its diameter is 12.
let on_arc = c + Vec2::from_angle(75f64.to_radians()) * 6.0;
s.script(&format!("dimdiameter {} {}\n", pt(on_arc), pt(c + Vec2::new(2.0, 20.0)))).unwrap();
let d = dims(&s);
assert_eq!(d.len(), 2, "a diameter dimension of the nested arc");
assert!(matches!(d[1].kind, DimKind::Diameter));
assert!((d[1].p15.xy().dist(d[1].defpt.xy()) - 12.0).abs() < 1e-9, "diameter {}", d[1].p15.xy().dist(d[1].defpt.xy()));
// DIMJOGGED takes it too: a jogged radius dimension of the nested circle.
s.script(&format!(
"dimjogged {} {} {} {}\n",
pt(on_circle),
pt(c + Vec2::new(-30.0, -20.0)),
pt(c + Vec2::new(-12.0, -9.0)),
pt(c + Vec2::new(-20.0, -12.0))
))
.unwrap();
let d = dims(&s);
assert_eq!(d.len(), 3, "a jogged dimension of the nested circle");
assert!(d[2].marks.jogged.is_some());
assert!((d[2].p15.xy().dist(c) - 10.0).abs() < 1e-9);
}
#[test]
fn a_circle_two_references_deep_is_taken() {
let mut s = session();
// Block Q holds P at (100, 0), half size; Q is inserted at (0, -50).
let p = s.execute("insert", &json!({"name": "P", "at": [100, 0], "scale": 0.5})).unwrap()["handle"].as_str().unwrap().to_string();
s.execute("block", &json!({"name": "Q", "base": [0, 0], "handles": [p], "keep": "delete"})).unwrap();
s.execute("insert", &json!({"name": "Q", "at": [0, -50]})).unwrap();
s.script("dimradius 100,-52.5 110,-60\n").unwrap();
let d = dims(&s);
assert_eq!(d.len(), 1);
assert!(d[0].defpt.xy().dist(Vec2::new(100.0, -50.0)) < 1e-9, "{:?}", d[0].defpt);
assert!((d[0].p15.xy().dist(Vec2::new(100.0, -50.0)) - 2.5).abs() < 1e-9);
}
/// A mirrored reference (scale -1 in X) still draws a circle: the dimension is centred on the
/// mirrored centre with the circle's radius, in drawing units. It is not associative: the
/// attachments name objects of the drawing, and the circle is inside the block.
#[test]
fn a_circle_in_a_mirrored_reference_is_taken_unassociated() {
let mut s = session();
s.execute("insert", &json!({"name": "P", "at": [-60, 0], "scale": [-1.5, 1.5]})).unwrap();
let c = Vec2::new(-60.0, 0.0);
// The circle has radius 7.5 here; picked on its left, away from the arc and the mirrored line.
s.script(&format!("dimradius {} {}\n", pt(c + Vec2::new(0.0, -7.5)), pt(c + Vec2::new(-5.0, -15.0)))).unwrap();
let d = dims(&s);
assert_eq!(d.len(), 1, "a radius dimension of the circle in the mirrored reference");
assert!(d[0].defpt.xy().dist(c) < 1e-9, "centred on the mirrored centre: {:?}", d[0].defpt);
assert!((d[0].p15.xy().dist(c) - 7.5).abs() < 1e-9, "radius {}", d[0].p15.xy().dist(c));
assert!(d[0].assoc.is_empty(), "{:?}", d[0].assoc);
}
#[test]
fn a_blocks_line_or_an_unevenly_scaled_circle_is_not_a_circle() {
let mut s = session();
// Twice as wide as tall: the circle is drawn as an ellipse.
s.execute("insert", &json!({"name": "P", "at": [0, 100], "scale": [2, 1]})).unwrap();
s.script("dimradius 10,100\n").unwrap();
assert!(s.log.iter().any(|l| l == "Object selected is not a circle or arc."), "{:?}", s.log);
s.cancel();
// The block's line, in an evenly scaled reference.
s.execute("insert", &json!({"name": "P", "at": [0, 200]})).unwrap();
s.script("dimdiameter 15,200\n").unwrap();
assert!(s.log.iter().filter(|l| *l == "Object selected is not a circle or arc.").count() == 2, "{:?}", s.log);
s.cancel();
assert!(dims(&s).is_empty(), "no dimension made");
}
/// A pick on a circle is not lost to an unevenly scaled circle nearby that comes first in the
/// block. That one is measured as the ellipse it is drawn as, not as a circle of its average
/// radius, which here passes through the very point picked.
#[test]
fn an_unevenly_scaled_circle_nearby_does_not_hide_a_circle() {
let mut s = session();
let avg = 50f64.sqrt(); // P's circle of radius 5 scaled 2 × 1: average radius 5·√2
let mut handle = |p: serde_json::Value| s.execute("insert", &p).unwrap()["handle"].as_str().unwrap().to_string();
let uneven = handle(json!({"name": "P", "at": [0, 0], "scale": [2, 1]}));
let even = handle(json!({"name": "P", "at": [avg + 5.0, 0]}));
s.execute("block", &json!({"name": "R", "base": [0, 0], "handles": [uneven, even], "keep": "delete"})).unwrap();
s.execute("insert", &json!({"name": "R", "at": [0, 300]})).unwrap();
s.script(&format!("dimradius {avg},300 {},310\n", avg + 5.0)).unwrap();
let d = dims(&s);
assert_eq!(d.len(), 1, "the even circle under the cursor is taken: {:?}", s.log.last());
let c = Vec2::new(avg + 5.0, 300.0);
assert!(d[0].defpt.xy().dist(c) < 1e-9, "{:?}", d[0].defpt);
assert!((d[0].p15.xy().dist(c) - 5.0).abs() < 1e-9);
}
/// A block of `make` (run in model space, then made into block "N"), inserted at the origin.
fn nested(make: impl FnOnce(&mut Session)) -> Session {
let mut s = Session::new();
make(&mut s);
s.execute("selectall", &json!({})).unwrap();
s.execute("block", &json!({"name": "N", "base": [0, 0], "keep": "delete"})).unwrap();
s.execute("insert", &json!({"name": "N", "at": [0, 0]})).unwrap();
s
}
/// A pick on what else a block draws is measured as any pick measures it: on a text's box or
/// inside a SOLID it is that object, not a circle passing a hair away; behind a ray's start it is
/// not the ray.
#[test]
fn text_solids_and_rays_in_a_block_are_measured_as_they_are_drawn() {
// Inside the box of a text, far from its insertion point.
let mut s = nested(|s| {
s.execute("text", &json!({"at": [0, 0], "text": "HELLO", "height": 2})).unwrap();
s.execute("circle", &json!({"center": [8.000001, 1], "radius": 5})).unwrap();
});
// The pick is refused: DIMRADIUS says so and still asks for an arc or circle, where taking the
// circle would have moved on to the dimension line's location.
let refused = |s: &Session| {
s.log.last().is_some_and(|l| l == "Object selected is not a circle or arc.") && s.prompt_text().contains("Select arc or circle")
};
s.script("dimradius 3,1\n").unwrap();
assert!(refused(&s), "the pick is on the text: {:?} / {}", s.log, s.prompt_text());
s.cancel();
assert!(dims(&s).is_empty(), "the pick is on the text");
// Inside a SOLID, far from its edges.
let mut s = nested(|s| {
s.execute("solid", &json!({"points": [[0, 0], [10, 0], [0, 10], [10, 10]]})).unwrap();
s.execute("circle", &json!({"center": [10.000001, 5], "radius": 5})).unwrap();
});
let kinds: Vec<&str> = s.doc().unwrap().block("N").unwrap().entities.iter().map(|e| e.kind.type_name()).collect();
assert!(kinds.contains(&"2D Solid"), "the block holds the SOLID: {kinds:?}");
s.script("dimradius 5,5\n").unwrap();
assert!(refused(&s), "the pick is on the SOLID: {:?} / {}", s.log, s.prompt_text());
s.cancel();
assert!(dims(&s).is_empty(), "the pick is on the SOLID");
// Behind the start of a ray: the circle passing there is the object picked.
let mut s = nested(|s| {
s.execute("ray", &json!({"base": [0, 0], "through": [1, 0]})).unwrap();
s.execute("circle", &json!({"center": [-5, 5.000001], "radius": 5})).unwrap();
});
s.script("dimradius -5,0 -12,-4\n").unwrap();
let d = dims(&s);
assert_eq!(d.len(), 1, "the circle behind the ray's start is taken: {:?}", s.log.last());
assert!((d[0].p15.xy().dist(d[0].defpt.xy()) - 5.0).abs() < 1e-9);
}
/// In a layout viewport, a circle on a layer frozen there is not drawn, so it can't be picked.
#[test]
fn a_circle_on_a_layer_frozen_in_the_viewport_is_not_taken() {
// Inside a layout viewport, the circle's layer frozen there or not.
let viewport = |freeze: bool| {
let mut s = nested(|s| {
s.execute("layer.new", &json!({"name": "HID", "current": true})).unwrap();
s.execute("circle", &json!({"center": [0, 0], "radius": 4})).unwrap();
s.execute("layer.current", &json!({"name": "0"})).unwrap();
s.execute("line", &json!({"points": [[-10, -10], [-9, -10]]})).unwrap();
});
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
let r = s.execute("mview", &json!({"p1": [20, 20], "p2": [220, 120]})).unwrap();
let vp = r["viewports"][0].as_str().unwrap().to_string();
s.execute("mspace", &json!({"handle": vp})).unwrap();
if freeze {
s.execute("vplayer", &json!({"handle": vp, "freeze": ["HID"]})).unwrap();
}
s.script("dimradius 4,0 6,3\n").unwrap();
s.cancel();
s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Dimension(_))).count()
};
assert_eq!(viewport(false), 1, "thawed, the circle is taken through the viewport");
assert_eq!(viewport(true), 0, "frozen in the viewport, it is not drawn there and not taken");
}
/// A circle with no size, as a file can hold, is refused rather than given a degenerate
/// dimension, whether it is picked directly or inside a block.
#[test]
fn a_zero_radius_circle_is_refused() {
let zero = || EntityKind::Circle(cadcraft_engine::doc::Circle { center: cadcraft_engine::geom::Vec3::new(50.0, 50.0, 0.0), radius: 0.0 });
let mut s = Session::new();
s.doc_mut().unwrap().add(&cadcraft_engine::doc::Space::Model, Default::default(), zero()).unwrap();
s.script("dimradius 50,50\n").unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Object selected is not a circle or arc."), "{:?}", s.log);
s.cancel();
let mut s = nested(|s| {
s.doc_mut().unwrap().add(&cadcraft_engine::doc::Space::Model, Default::default(), zero()).unwrap();
});
s.script("dimdiameter 50,50\n").unwrap();
assert_eq!(s.log.last().map(String::as_str), Some("Object selected is not a circle or arc."), "{:?}", s.log);
s.cancel();
assert!(dims(&s).is_empty());
}
+1 -1
View File
@@ -23,7 +23,7 @@ fn groups(d: &cadcraft_engine::doc::Drawing, e: &Entity) -> (String, Vec<(i32, V
.into_iter()
.map(|t| {
let v = match t.value {
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) | craft_dxf::Value::Invalid(s) => json!(s),
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) => json!(s),
craft_dxf::Value::Real(r) => json!(r),
craft_dxf::Value::Int(i) => json!(i),
craft_dxf::Value::Bool(b) => json!(i32::from(b)),
-31
View File
@@ -2,7 +2,6 @@
mod temp_dir;
mod acadver;
mod aliases;
mod angle_prompts;
mod angle_settings;
mod annotate_options;
@@ -15,7 +14,6 @@ mod array_key_point;
mod array_live;
mod assoc_array;
mod attdef_command;
mod attdef_justify_style;
mod attdisp_attsync;
mod attedit_prompts;
mod attrib_modes;
@@ -24,7 +22,6 @@ mod attrib_props;
mod attribute_tag_matching;
mod attribute_tools;
mod attribute_value_baseline;
mod base64_compat;
mod block_description;
mod block_keep;
mod block_redefine;
@@ -36,7 +33,6 @@ mod break_keeps_z;
mod break_trim_keep_handle;
mod break_trim_polyline_rules;
mod breakatpoint_command_line;
mod bsaveas_source;
mod burst;
mod change_command;
mod chprop_command;
@@ -54,23 +50,18 @@ mod dim_baseline_spacing;
mod dim_block_text_layer_pick;
mod dim_chain;
mod dim_commands;
mod dim_diameter_sign;
mod dim_explode_text;
mod dim_nested_circle;
mod dim_properties;
mod dim_radial_inside;
mod dim_radial_outside;
mod dim_style_menu;
mod dim_text_frame;
mod dim_vars;
mod dimassoc_mode;
mod dimassoc_saved;
mod dimstyle_cli;
mod dimtedit_prompts;
mod drafting_spacing;
mod draw_prompts;
mod draworder;
mod dview;
mod dyn_input;
mod dynamic_block_data;
mod dynamic_grips;
@@ -82,7 +73,6 @@ mod fillet_chamfer;
mod fix_holds_grips;
mod followups_626;
mod greek_keyboard;
mod greek_keyboard_aliases;
mod grip_dim_input;
mod grip_options;
mod grip_selection;
@@ -110,7 +100,6 @@ mod json_param_validation;
mod kept_dimension_snaps;
mod layer_cmdline;
mod layer_merge_delete;
mod layer_name_control_chars;
mod layer_state_cmdline;
mod layoff_repeat;
mod layout_prompts;
@@ -118,22 +107,18 @@ mod leader_command;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod leader_text_scale;
mod legacy_sysvars;
mod lin_pat_files;
mod lisp_answer_by_frames;
mod lisp_corpus;
mod lisp_findfile;
mod lisp_getangle_inputs;
mod lisp_textbox;
mod lisp_undo_in_routine;
mod loops;
mod malformed_handles;
mod matchprop;
mod measure_distance_snapping;
mod measureinit;
mod metric_linetypes;
mod minsert;
mod mirror_degenerate_line;
mod mirror_hatch_direction;
mod mleader_content;
mod mleader_remember;
mod mleader_text_edit;
@@ -151,8 +136,6 @@ mod non_finite_edits;
mod offset_closed_spline;
mod offset_ellipse_side;
mod offset_move;
mod offset_preselection;
mod ole_frame_transform;
mod oops_command;
mod options_profile;
mod osnap_opened_drawings;
@@ -175,7 +158,6 @@ mod properties_set_locked;
mod properties_set_text_dims;
mod props_bad_lineweight;
mod props_insert_scale_attribs;
mod purge_arrow_blocks;
mod purge_kept_dimension_blocks;
mod purge_mlinestyles;
mod purge_prompts;
@@ -192,18 +174,14 @@ mod refedit;
mod refedit_xref;
mod region;
mod rename_cmdline;
mod rename_keeps_extras;
mod revcloud_recognised;
mod rotate_reference;
mod rotation_grip_input;
#[cfg(not(target_arch = "wasm32"))]
mod save_changed_on_disk;
mod scale_offset_z;
mod scale_zero_factor;
mod select_keywords;
mod select_similar;
mod select_underscore_keywords;
mod selection_anno_display;
mod selection_cycling;
mod selection_modes;
mod setvar_cecolor;
@@ -226,9 +204,7 @@ mod spline_degree;
mod spline_options;
mod stretch;
mod stretch_select;
mod stretch_window_ortho;
mod table_formulas;
mod table_malformed_handle;
mod table_styles;
mod temp_tracking;
mod text_commands;
@@ -239,25 +215,18 @@ mod transparent;
mod trim_closed_polyline;
mod trim_cut_at_the_pick;
mod trim_cut_where_an_arc_span_starts;
mod trim_extend_block_edges;
mod trim_extend_json_pick;
mod trim_extend_options;
mod trim_highlight;
mod trim_keeps_z_and_width;
mod ucs;
mod ucs_drafting;
mod undo_count;
mod undo_layout_tab;
mod units_bearing;
mod usage;
mod view_twist;
mod viewport_clip;
mod viewport_frozen_block_parts;
mod viewport_frozen_selection;
mod viewport_ucs_copy;
mod vplayer_prompts;
mod vports;
mod wblock_pick;
mod window_rotated_text;
mod wipeout_grips;
mod xclip;
@@ -1,143 +0,0 @@
//! A save over the drawing's own file refuses when another program changed the file after it was
//! opened or last saved here (CADCraft keeps no file open, so nothing else would stop it), and
//! `overwrite: true` replaces it anyway. The hooks are the same `cadcraft_io` ones the other
//! modules of this harness install.
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io};
use serde_json::json;
fn hooks() {
set_io(IoHooks {
read: |b, n| cadcraft_io::read(b, n).map_err(|e| e.to_string()),
write: |d, n| cadcraft_io::write(d, n).map_err(|e| e.to_string()),
plot: None,
});
}
fn folder(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("cadcraft-disk-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn add_circle(s: &mut Session, x: f64) {
s.execute("circle", &json!({ "center": [x, 0], "radius": 1 })).unwrap();
}
#[test]
fn qsave_refuses_a_file_someone_else_saved_and_overwrite_replaces_it() {
hooks();
let dir = folder("qsave");
let file = dir.join("plan.dxf");
let path = file.to_string_lossy().to_string();
let mut s = Session::new();
add_circle(&mut s, 0.0);
s.execute("saveas", &json!({ "path": path })).unwrap();
// Untouched on disk: saves go through, each compared with what the one before wrote.
add_circle(&mut s, 5.0);
s.execute("qsave", &json!({})).unwrap();
add_circle(&mut s, 10.0);
s.execute("qsave", &json!({})).unwrap();
// Another program saves the same file, here with the same length.
let mut theirs = std::fs::read(&file).unwrap();
let last = theirs.len() - 1;
theirs[last] ^= 0x20;
std::fs::write(&file, &theirs).unwrap();
add_circle(&mut s, 15.0);
let e = s.execute("qsave", &json!({})).unwrap_err().to_string();
assert!(e.contains("changed on disk"), "{e}");
assert_eq!(std::fs::read(&file).unwrap(), theirs, "their work stays");
assert!(s.state().unwrap().is_dirty(), "the drawing still has its unsaved changes");
assert!(s.execute("saveas", &json!({ "path": path })).is_err(), "SAVEAS onto its own file checks too");
let spelled = dir.join(".").join("plan.dxf").to_string_lossy().to_string();
assert!(s.execute("saveas", &json!({ "path": spelled })).is_err(), "the same file under another spelling");
// A copy under another name is always possible, and leaves their file alone.
let copy = dir.join("plan-mine.dxf").to_string_lossy().to_string();
s.execute("saveas", &json!({ "path": copy })).unwrap();
assert_eq!(std::fs::read(&file).unwrap(), theirs);
s.execute("qsave", &json!({})).unwrap();
// Back onto the original with overwrite: replaced on purpose.
s.execute("saveas", &json!({ "path": path, "overwrite": true })).unwrap();
assert_ne!(std::fs::read(&file).unwrap(), theirs);
assert!(s.execute("qsave", &json!({ "overwrite": "yes" })).is_err(), "overwrite must be a bool");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_file_opened_and_changed_elsewhere_is_not_saved_over() {
hooks();
let dir = folder("open");
let file = dir.join("plan.dxf");
let path = file.to_string_lossy().to_string();
let mut first = Session::new();
add_circle(&mut first, 0.0);
first.execute("saveas", &json!({ "path": path })).unwrap();
// Two sessions open the same file; the first saves, then the second tries to.
let mut second = Session::new();
second.execute("open", &json!({ "path": path })).unwrap();
first.execute("open", &json!({ "path": path })).unwrap();
add_circle(&mut first, 5.0);
first.execute("qsave", &json!({})).unwrap();
let saved_by_first = std::fs::read(&file).unwrap();
add_circle(&mut second, 10.0);
let e = second.execute("qsave", &json!({})).unwrap_err().to_string();
assert!(e.contains("changed on disk"), "{e}");
assert_eq!(std::fs::read(&file).unwrap(), saved_by_first, "the first session's save stays");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_deleted_file_or_a_drawing_never_saved_has_nothing_to_check() {
hooks();
let dir = folder("gone");
let file = dir.join("plan.dxf");
let path = file.to_string_lossy().to_string();
let mut s = Session::new();
add_circle(&mut s, 0.0);
s.execute("saveas", &json!({ "path": path })).unwrap();
std::fs::remove_file(&file).unwrap();
add_circle(&mut s, 5.0);
s.execute("qsave", &json!({})).unwrap();
assert!(file.exists());
// A drawing that never came from this file has nothing to compare: SAVEAS over it behaves as before.
let mut fresh = Session::new();
add_circle(&mut fresh, 0.0);
fresh.execute("saveas", &json!({ "path": path })).unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// With automation roots in force, a save outside the write root is refused by the roots before
/// the file there is compared: the answer says nothing about a file the agent may not reach.
#[test]
fn outside_the_write_root_the_roots_refuse_before_the_file_is_compared() {
hooks();
let dir = folder("roots");
let inside = dir.join("in");
let outside = dir.join("out");
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let file = outside.join("plan.dxf");
let path = file.to_string_lossy().to_string();
let mut s = Session::new();
add_circle(&mut s, 0.0);
s.execute("saveas", &json!({ "path": path })).unwrap();
let mut theirs = std::fs::read(&file).unwrap();
let last = theirs.len() - 1;
theirs[last] ^= 0x20;
std::fs::write(&file, &theirs).unwrap();
add_circle(&mut s, 5.0);
let roots = cadcraft_engine::file_access::AutomationRoots::new(Some(&inside), Some(&inside)).unwrap();
let e = cadcraft_engine::file_access::confine(roots.as_ref(), || s.execute("qsave", &json!({}))).unwrap_err().to_string();
assert!(e.contains("automation path rejected") && !e.contains("changed on disk"), "{e}");
assert_eq!(std::fs::read(&file).unwrap(), theirs);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -1,141 +0,0 @@
//! A selected annotative object also shows at its other scales, faded (SELECTIONANNODISPLAY):
//! each at that scale's size and position. Grips stay on the current scale's representation.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{AnnoScale, Entity, EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use serde_json::{Value, json};
fn setvar(s: &mut Session, name: &str, value: Value) {
s.execute("setvar", &json!({ "name": name, "value": value })).unwrap();
}
fn getvar(s: &mut Session, name: &str) -> Value {
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
}
fn handle(r: &Value) -> Handle {
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).and_then(Handle::parse_hex).unwrap()
}
fn entity(s: &Session, h: Handle) -> Entity {
(**s.doc().unwrap().entity(h).unwrap()).clone()
}
fn near(a: Vec2, b: Vec2) -> bool {
a.dist(b) < 1e-9
}
/// An annotative multileader supporting 1:1 and 1:10, its landing moved (2, 1) at 1:10, with
/// 1:1 current again. Returns it as it shows at 1:10.
fn moved_at_one_to_ten() -> (Session, Handle, Entity) {
let mut s = Session::new();
s.execute("mleaderstyle", &json!({ "name": "Anno", "annotative": true })).unwrap();
let h = handle(&s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:10"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:10" })).unwrap();
let EntityKind::MLeader(m) = entity(&s, h).kind else { panic!() };
let landing = m.leaders.iter().map(Vec::len).sum::<usize>();
let to = m.landing.xy() + Vec2::new(2.0, 1.0);
s.execute("grip.move", &json!({ "handle": h.hex(), "index": landing, "to": [to.x, to.y] })).unwrap();
let d = s.doc().unwrap();
let e = d.entity(h).unwrap();
let at_ten = Entity { kind: d.anno_shown(e), ..(**e).clone() };
setvar(&mut s, "CANNOSCALE", json!("1:1"));
(s, h, at_ten)
}
#[test]
fn a_selected_multileader_shows_its_other_scale_where_it_was_moved() {
let (mut s, h, at_ten) = moved_at_one_to_ten();
assert_eq!(getvar(&mut s, "SELECTIONANNODISPLAY"), json!(1), "on by default");
assert!(s.selection_anno_others().is_empty(), "nothing selected");
s.set_selection(vec![h]);
let others = s.selection_anno_others();
assert_eq!(others.len(), 1, "one other scale");
let (EntityKind::MLeader(other), EntityKind::MLeader(ten)) = (&others[0].kind, &at_ten.kind) else { panic!() };
assert!(near(other.landing.xy(), ten.landing.xy()), "at 1:10's position");
assert_eq!(other, ten, "at 1:10's size too");
assert!(others[0].common.anno_scales.is_empty(), "drawn as it is");
// The grips stay on the 1:1 representation.
let EntityKind::MLeader(m) = entity(&s, h).kind else { panic!() };
let grips = s.grips_of(h).unwrap();
assert!(grips.iter().any(|g| near(*g, m.landing.xy())));
assert!(!grips.iter().any(|g| near(*g, ten.landing.xy())));
// At 1:10 the other one is 1:1's, where it was.
setvar(&mut s, "CANNOSCALE", json!("1:10"));
let others = s.selection_anno_others();
let [EntityKind::MLeader(one)] = others.iter().map(|e| &e.kind).collect::<Vec<_>>()[..] else { panic!() };
assert!(near(one.landing.xy(), m.landing.xy()));
}
#[test]
fn selectionannodisplay_0_shows_no_other_scale() {
let (mut s, h, _) = moved_at_one_to_ten();
s.set_selection(vec![h]);
s.execute("setvar", &json!({ "name": "SELECTIONANNODISPLAY", "value": 2 })).unwrap_err();
s.execute("setvar", &json!({ "name": "SELECTIONANNODISPLAY", "value": "x" })).unwrap_err();
assert_eq!(getvar(&mut s, "SELECTIONANNODISPLAY"), json!(1), "a refused value changes nothing");
setvar(&mut s, "SELECTIONANNODISPLAY", json!(0));
assert!(s.selection_anno_others().is_empty());
s.cmdline("SELECTIONANNODISPLAY 1").unwrap();
assert_eq!(s.selection_anno_others().len(), 1, "typed at the command line");
}
#[test]
fn a_single_scale_or_plain_object_shows_nothing_more() {
let mut s = Session::new();
s.execute("mleaderstyle", &json!({ "name": "Anno", "annotative": true })).unwrap();
let one = handle(&s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap());
let line = handle(&s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap());
s.set_selection(vec![one, line]);
assert_eq!(entity(&s, one).common.anno_scales.len(), 1);
assert!(s.selection_anno_others().is_empty());
}
#[test]
fn hostile_scales_give_bounded_representations() {
let (s, h, _) = moved_at_one_to_ten();
let mut e = entity(&s, h);
// Invalid ratios are skipped; the same ratio under many names comes once; the list is capped.
e.common.anno_scales.push(AnnoScale::new("nan", f64::NAN, 1.0));
e.common.anno_scales.push(AnnoScale::new("zero", 0.0, 1.0));
e.common.anno_scales.push(AnnoScale::new("inf", 1.0, f64::INFINITY));
e.common.anno_scales.push(AnnoScale::new("huge", 1e-308, 1e308));
for i in 0..5000 {
e.common.anno_scales.push(AnnoScale::new(&format!("dup{i}"), 1.0, 10.0));
}
let mut unlimited = usize::MAX;
for view in [1.0, 10.0, f64::NAN, -1.0, 0.0, f64::INFINITY] {
let others = cadcraft_engine::doc::anno_others(&e, view, true, &mut unlimited);
assert!(others.len() <= 2, "{view}: {}", others.len());
}
assert!(cadcraft_engine::doc::anno_others(&e, 3.0, false, &mut unlimited).is_empty(), "not shown in that view");
}
#[test]
fn a_selection_shares_one_budget_of_faded_representations() {
let (mut s, h, _) = moved_at_one_to_ten();
// An object supporting many distinct scales: each gives a representation.
let mut e = entity(&s, h);
for i in 2..300 {
e.common.anno_scales.push(AnnoScale::new(&format!("1:{i}"), 1.0, f64::from(i)));
}
let mut unlimited = usize::MAX;
let many = cadcraft_engine::doc::anno_others(&e, 1.0, true, &mut unlimited).len();
assert!(many > 200, "{many}");
// A small budget stops it, used up, and the next object gets none.
let mut budget = 5;
assert_eq!(cadcraft_engine::doc::anno_others(&e, 1.0, true, &mut budget).len(), 5);
assert_eq!(budget, 0);
assert!(cadcraft_engine::doc::anno_others(&e, 1.0, true, &mut budget).is_empty());
// Ten such objects selected: the selection's representations stay within the shared budget,
// fewer than the objects would make one by one.
let mut hs = Vec::new();
for _ in 0..10 {
hs.push(s.doc_mut().unwrap().add(&cadcraft_engine::doc::Space::Model, e.common.clone(), e.kind.clone()).unwrap());
}
s.set_selection(hs.clone());
let shown = s.selection_anno_others().len();
assert!(shown <= cadcraft_engine::MAX_ANNO_FADED && shown < many * hs.len(), "{shown}");
}
-24
View File
@@ -47,27 +47,3 @@ fn transparent_zoom_resumes_the_running_command() {
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("line"));
assert!(s.suspended.is_none());
}
/// #3273 review: GETVAR typed transparently inside LINE reads the command state LINE is in, and
/// LINE then carries on.
#[test]
fn transparent_getvar_sees_the_command_it_runs_inside() {
let mut s = Session::new();
s.cmdline("LINE 0,0").unwrap();
s.cmdline("'GETVAR CMDNAMES").unwrap();
// The value, then LINE resuming.
let tail = |s: &Session| s.log[s.log.len().saturating_sub(2)..].to_vec();
assert_eq!(tail(&s), ["CMDNAMES = LINE", "Resuming LINE command."]);
s.cmdline("'GETVAR CMDACTIVE").unwrap();
assert_eq!(tail(&s), ["CMDACTIVE = 3", "Resuming LINE command."], "a command, and a transparent one in it");
// A transparent command still prompting is named after the one it runs inside.
s.cmdline("'PAN").unwrap();
assert_eq!(cadcraft_engine::sysvars::get(&s, "CMDNAMES"), Some(serde_json::json!("LINE'PAN")));
s.cmdline("").unwrap();
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("line"), "{}", s.prompt_text());
s.cmdline("10,0").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert_eq!(lines(&s), 1);
assert_eq!(cadcraft_engine::sysvars::get(&s, "CMDACTIVE"), Some(serde_json::json!(0)));
}
@@ -1,594 +0,0 @@
//! #3569: TRIM and EXTEND take what a block reference draws as cutting and boundary edges: the
//! objects inside it, placed by the reference (insertion point, scale, rotation), nested
//! references too, and only the objects that are drawn.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Block, Entity, EntityKind, Handle, Line};
use cadcraft_engine::geom::{Vec2, Vec3};
use serde_json::{Value, json};
/// The object a command made: its `handle`, or the first of its `handles`.
fn made(v: &Value) -> Handle {
let hex = v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap_or_else(|| panic!("{v}"));
Handle::parse_hex(hex).unwrap()
}
/// Draws a line from `a` to `b`.
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
made(&s.execute("line", &json!({ "points": [a, b] })).unwrap())
}
/// Makes block `name` (base point at the origin) of the objects `parts`, which leave the drawing.
fn block(s: &mut Session, name: &str, parts: &[Handle]) {
let handles: Vec<String> = parts.iter().map(|h| h.hex()).collect();
s.execute("block", &json!({ "name": name, "base": [0, 0], "handles": handles, "keep": "delete" })).unwrap();
}
/// Inserts block `name` at `at`, scaled by `scale` along its axes and turned by `rotation` degrees.
fn reference(s: &mut Session, name: &str, at: [f64; 2], scale: [f64; 2], rotation: f64) -> Handle {
made(&s.execute("insert", &json!({ "name": name, "at": at, "scale": scale, "rotation": rotation })).unwrap())
}
/// Puts `h` on layer `name`.
fn on_layer(s: &mut Session, h: Handle, name: &str) {
s.execute("properties.set", &json!({ "handles": [h.hex()], "layer": name })).unwrap();
}
/// The ends of line `h`.
fn ends(s: &Session, h: Handle) -> (Vec2, Vec2) {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Line(l) => (l.a.xy(), l.b.xy()),
k => panic!("{h:?} is not a line: {k:?}"),
}
}
/// Asserts that line `h` runs from `a` to `b`.
fn assert_ends(s: &Session, h: Handle, a: [f64; 2], b: [f64; 2]) {
let (p, q) = ends(s, h);
assert!(p.near(Vec2::new(a[0], a[1]), 1e-9) && q.near(Vec2::new(b[0], b[1]), 1e-9), "{p:?} to {q:?}, expected {a:?} to {b:?}");
}
/// A drawing with block "B" holding the vertical line x = 50, referenced once at (20, 5), which
/// draws it at x = 70 across the X axis. Returns the reference.
fn one_reference() -> (Session, Handle) {
let mut s = Session::new();
let part = line(&mut s, [50.0, -10.0], [50.0, 10.0]);
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [20.0, 5.0], [1.0, 1.0], 0.0);
(s, r)
}
/// TRIM with a block reference as its only cutting edge cuts at the line the reference draws.
#[test]
fn trim_cuts_at_a_line_a_reference_draws() {
let (mut s, r) = one_reference();
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [90, 0], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [0.0, 0.0], [70.0, 0.0]);
}
/// With no edges named every object is an edge, and a block reference is one of them.
#[test]
fn trim_with_every_object_an_edge_counts_references() {
let (mut s, _) = one_reference();
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [90, 0] })).unwrap();
assert_ends(&s, l, [0.0, 0.0], [70.0, 0.0]);
}
/// EXTEND reaches the line a block reference draws, with the reference named as the boundary
/// and with every object a boundary.
#[test]
fn extend_reaches_a_line_a_reference_draws() {
for edges in [true, false] {
let (mut s, r) = one_reference();
let l = line(&mut s, [0.0, 0.0], [30.0, 0.0]);
let mut p = json!({ "handle": l.hex(), "pick": [29, 0] });
if edges {
p["edges"] = json!([r.hex()]);
}
s.execute("extend", &p).unwrap();
assert_ends(&s, l, [0.0, 0.0], [70.0, 0.0]);
}
}
/// A line two references deep is an edge where both references put it: their offsets and
/// scales compose.
#[test]
fn a_nested_reference_is_placed_by_every_reference_above_it() {
let mut s = Session::new();
let part = line(&mut s, [50.0, -10.0], [50.0, 10.0]);
block(&mut s, "INNER", &[part]);
let inner = reference(&mut s, "INNER", [10.0, 0.0], [1.0, 1.0], 0.0);
block(&mut s, "OUTER", &[inner]);
// The line is at x = 50 in INNER, 60 in OUTER and, OUTER being twice as large along X, 125 here.
let r = reference(&mut s, "OUTER", [5.0, 0.0], [2.0, 1.0], 0.0);
let l = line(&mut s, [0.0, 0.0], [200.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [190, 0], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [0.0, 0.0], [125.0, 0.0]);
}
/// Rotation, uneven scale and mirroring together still put the edge where the reference draws
/// it, and a line the edge does not reach is not cut.
#[test]
fn a_turned_stretched_and_mirrored_reference_cuts_where_it_draws() {
let mut s = Session::new();
// x = 10 for y in -10..2. Scaled by (3, -2): x = 30 for y in -4..20. Turned a quarter turn:
// y = 30 for x in -20..4. Moved to (40, 0): y = 30 for x in 20..44.
let part = line(&mut s, [10.0, -10.0], [10.0, 2.0]);
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [40.0, 0.0], [3.0, -2.0], 90.0);
// x = 25 is crossed only by the mirrored line: unmirrored it would span x in 36..60.
let l = line(&mut s, [25.0, 0.0], [25.0, 100.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [25, 90], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [25.0, 0.0], [25.0, 30.0]);
// An object the line does not reach is not cut by its extension.
let past = line(&mut s, [50.0, 0.0], [50.0, 100.0]);
assert!(s.execute("trim", &json!({ "handle": past.hex(), "pick": [50, 90], "edges": [r.hex()] })).is_err());
assert_ends(&s, past, [50.0, 0.0], [50.0, 100.0]);
}
/// A turned reference, and a turned one with different X and Y scales, cut where they draw the
/// line, for TRIM and for EXTEND, also one level deeper.
#[test]
fn a_turned_and_unevenly_scaled_reference_cuts_where_it_draws() {
// The line x = 10 of the block, scaled along X and turned 30 degrees about the insertion
// point, crosses the horizontal through that point at 10 * scale / cos 30.
let cos30 = 30.0_f64.to_radians().cos();
for (scale, nested) in [([1.0, 1.0], false), ([1.5, 2.0], false), ([1.5, 2.0], true)] {
let mut s = Session::new();
let part = line(&mut s, [10.0, -10.0], [10.0, 10.0]);
block(&mut s, "B", &[part]);
if nested {
let inner = reference(&mut s, "B", [0.0, 0.0], [1.0, 1.0], 0.0);
block(&mut s, "OUTER", &[inner]);
}
let r = reference(&mut s, if nested { "OUTER" } else { "B" }, [0.0, 3.0], scale, 30.0);
let l = line(&mut s, [0.0, 3.0], [40.0, 3.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [39, 3], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [0.0, 3.0], [10.0 * scale[0] / cos30, 3.0]);
let short = line(&mut s, [0.0, 3.0], [5.0, 3.0]);
s.execute("extend", &json!({ "handle": short.hex(), "pick": [4, 3], "edges": [r.hex()] })).unwrap();
assert_ends(&s, short, [0.0, 3.0], [10.0 * scale[0] / cos30, 3.0]);
}
}
/// A reference with X scale -1 cuts on the mirrored side of its insertion point.
#[test]
fn a_mirrored_reference_cuts_on_its_mirrored_side() {
let mut s = Session::new();
let part = line(&mut s, [10.0, -10.0], [10.0, 10.0]);
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [0.0, 3.0], [-1.0, 1.0], 0.0);
// The only edge is at x = -10: nothing cuts the line at x = 10.
let l = line(&mut s, [-40.0, 3.0], [40.0, 3.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [39, 3], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [-40.0, 3.0], [-10.0, 3.0]);
}
/// A circle in a reference with different X and Y scales cuts as the ellipse it is drawn as.
#[test]
fn a_circle_in_an_unevenly_scaled_reference_cuts_as_the_ellipse_it_draws() {
let mut s = Session::new();
let part = made(&s.execute("circle", &json!({ "center": [10, 0], "radius": 5 })).unwrap());
block(&mut s, "B", &[part]);
// Twice as wide along X: the circle is drawn as an ellipse about (10, 3) from x = 0 to 20.
let r = reference(&mut s, "B", [-10.0, 3.0], [2.0, 1.0], 0.0);
let l = line(&mut s, [-20.0, 3.0], [40.0, 3.0]);
let v = s.execute("trim", &json!({ "handle": l.hex(), "pick": [10, 3], "edges": [r.hex()] })).unwrap();
let pieces: Vec<Handle> = v["handles"].as_array().unwrap().iter().map(|h| Handle::parse_hex(h.as_str().unwrap()).unwrap()).collect();
let mut cuts: Vec<f64> = pieces.iter().map(|h| ends(&s, *h)).map(|(a, b)| if a.x.abs() < b.x.abs() { a.x } else { b.x }).collect();
cuts.sort_by(f64::total_cmp);
let [left, right] = cuts.as_slice() else { panic!("{cuts:?}") };
assert!(left.abs() < 0.01 && (right - 20.0).abs() < 0.01, "{cuts:?}");
}
/// A polyline with a width inside a reference is an edge at its centre line, not at its sides.
#[test]
fn a_wide_polyline_in_a_reference_cuts_at_its_centre_line() {
let mut s = Session::new();
let part = made(&s.execute("pline", &json!({ "vertices": [[10, -10], [10, 10]], "width": 2 })).unwrap());
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [20.0, 5.0], [1.0, 1.0], 0.0);
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [90, 0], "edges": [r.hex()] })).unwrap();
assert_ends(&s, l, [0.0, 0.0], [30.0, 0.0]);
}
/// A line in a reference that stops short of the object is no edge by default; with edges that
/// run on (EDGEMODE 1) it is one.
#[test]
fn a_part_that_stops_short_is_an_edge_only_when_edges_run_on() {
let mut s = Session::new();
// Drawn from y = 4 up: its extension, not the line, crosses the X axis at x = 10.
let part = line(&mut s, [10.0, 4.0], [10.0, 12.0]);
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [0.0, 0.0], [1.0, 1.0], 0.0);
let l = line(&mut s, [0.0, 0.0], [40.0, 0.0]);
let short = line(&mut s, [0.0, -2.0], [5.0, -2.0]);
for edges in [json!([r.hex()]), Value::Null] {
assert!(s.execute("trim", &json!({ "handle": l.hex(), "pick": [39, 0], "edges": edges })).is_err());
assert!(s.execute("extend", &json!({ "handle": short.hex(), "pick": [4, -2], "edges": edges })).is_err());
}
assert_ends(&s, l, [0.0, 0.0], [40.0, 0.0]);
assert_ends(&s, short, [0.0, -2.0], [5.0, -2.0]);
// With edges that run on, it is one, as the same line outside a block is.
s.execute("trim", &json!({ "handle": l.hex(), "pick": [39, 0], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends(&s, l, [0.0, 0.0], [10.0, 0.0]);
s.execute("extend", &json!({ "handle": short.hex(), "pick": [4, -2], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends(&s, short, [0.0, -2.0], [10.0, -2.0]);
}
/// A dimension inside a reference gives no edge, as a dimension outside a block gives none.
#[test]
fn a_dimension_in_a_reference_is_no_more_an_edge_than_outside_one() {
let mut s = Session::new();
let dim = made(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [50, 0], "at": [25, 20] })).unwrap());
// The dimension draws through a block of its own, here one line along y = 20.
let d = s.doc_mut().unwrap();
let mut drawn = Block::new("*D1");
drawn.entities.push(Entity::new(d.new_handle(), EntityKind::Line(Line { a: Vec3::new(0.0, 20.0, 0.0), b: Vec3::new(50.0, 20.0, 0.0) })));
d.blocks.insert("*D1".into(), std::sync::Arc::new(drawn));
d.modify_entity(dim, |e| {
if let EntityKind::Dimension(dm) = &mut e.kind {
dm.block = Some("*D1".into());
}
})
.unwrap();
// Outside a block the dimension cuts nothing, and so it cuts nothing inside a reference.
let l = line(&mut s, [25.0, -10.0], [25.0, 100.0]);
assert!(s.execute("trim", &json!({ "handle": l.hex(), "pick": [25, 90], "edges": [dim.hex()] })).is_err());
block(&mut s, "B", &[dim]);
let r = reference(&mut s, "B", [0.0, 0.0], [1.0, 1.0], 0.0);
assert!(s.execute("trim", &json!({ "handle": l.hex(), "pick": [25, 90], "edges": [r.hex()] })).is_err());
assert_ends(&s, l, [25.0, -10.0], [25.0, 100.0]);
}
/// Parts on a frozen layer, on a layer that is off, and hidden parts are not edges; the drawn
/// part beside them is.
#[test]
fn parts_that_are_not_drawn_are_not_edges() {
let mut s = Session::new();
let frozen = line(&mut s, [30.0, -10.0], [30.0, 10.0]);
on_layer(&mut s, frozen, "FROZEN");
let off = line(&mut s, [40.0, -10.0], [40.0, 10.0]);
on_layer(&mut s, off, "OFF");
let hidden = line(&mut s, [50.0, -10.0], [50.0, 10.0]);
s.doc_mut().unwrap().modify_entity(hidden, |e| e.common.visible = false).unwrap();
let drawn = line(&mut s, [60.0, -10.0], [60.0, 10.0]);
block(&mut s, "B", &[frozen, off, hidden, drawn]);
let d = s.doc_mut().unwrap();
d.layer_mut("FROZEN").unwrap().frozen = true;
d.layer_mut("OFF").unwrap().on = false;
let r = reference(&mut s, "B", [0.0, 0.0], [1.0, 1.0], 0.0);
// Picked at its start, the line loses the stretch up to the first edge: the only drawn part.
for edges in [true, false] {
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
let mut p = json!({ "handle": l.hex(), "pick": [1, 0] });
if edges {
p["edges"] = json!([r.hex()]);
}
s.execute("trim", &p).unwrap();
assert_ends(&s, l, [60.0, 0.0], [100.0, 0.0]);
s.execute("erase", &json!({ "handles": [l.hex()] })).unwrap();
}
}
/// A part on layer 0 follows its reference's layer: the reference on a frozen layer is no edge.
#[test]
fn a_reference_on_a_frozen_layer_is_no_edge() {
let mut s = Session::new();
// The part is on layer 0, so it is drawn on each reference's layer.
let part = line(&mut s, [0.0, -10.0], [0.0, 10.0]);
block(&mut s, "B", &[part]);
let frozen = reference(&mut s, "B", [30.0, 0.0], [1.0, 1.0], 0.0);
on_layer(&mut s, frozen, "FROZEN");
s.doc_mut().unwrap().layer_mut("FROZEN").unwrap().frozen = true;
reference(&mut s, "B", [60.0, 0.0], [1.0, 1.0], 0.0);
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [1, 0] })).unwrap();
assert_ends(&s, l, [60.0, 0.0], [100.0, 0.0]);
}
/// The highlight under the cursor in the running command shows the cut at the reference's line.
#[test]
fn the_rollover_highlight_shows_the_cut_at_a_reference() {
let (mut s, _) = one_reference();
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.zoom_extents().unwrap();
s.start("trim").unwrap();
// Quick mode: every object is an edge. The piece past the reference's line is what goes.
let part = s.highlight(l, Vec2::new(90.0, 0.0)).expect("a part of the line is highlighted");
let outline: Vec<Vec2> = part.iter().flat_map(|e| cadcraft_engine::select::hit_polylines(s.doc().unwrap(), e, 1e-4)).flatten().collect();
let by_x = |a: &Vec2, b: &Vec2| a.x.total_cmp(&b.x);
let (near, far) = (outline.iter().copied().min_by(by_x).unwrap(), outline.iter().copied().max_by(by_x).unwrap());
assert!(near.near(Vec2::new(70.0, 0.0), 1e-6) && far.near(Vec2::new(100.0, 0.0), 1e-6), "{near:?} to {far:?}");
}
/// Asserts that line `h` runs from `a` to `b`, within `tol`: for cuts far from the edge that makes
/// them, where the last digits of the crossing are not exact.
fn assert_ends_within(s: &Session, h: Handle, a: [f64; 2], b: [f64; 2], tol: f64) {
let (p, q) = ends(s, h);
assert!(p.near(Vec2::new(a[0], a[1]), tol) && q.near(Vec2::new(b[0], b[1]), tol), "{p:?} to {q:?}, expected {a:?} to {b:?}");
}
/// With edges that run on, a line in a reference a thousand times smaller than its block still
/// runs on as far as the same line outside a block: it cuts, and is a boundary for, an object
/// half a million units away. Also through two references that make it that small together.
#[test]
fn a_run_on_edge_in_a_small_reference_reaches_as_far_as_outside_a_block() {
for nested in [false, true] {
let mut s = Session::new();
let part = line(&mut s, [10.0, 4.0], [10.0, 12.0]);
block(&mut s, "B", &[part]);
// Drawn at x = 0.01 either way, from y = 0.004 to 0.012.
let r = if nested {
let inner = reference(&mut s, "B", [0.0, 0.0], [0.01, 0.01], 0.0);
block(&mut s, "OUTER", &[inner]);
reference(&mut s, "OUTER", [0.0, 0.0], [0.1, 0.1], 0.0)
} else {
reference(&mut s, "B", [0.0, 0.0], [0.001, 0.001], 0.0)
};
let l = line(&mut s, [-1.0, -5e5], [1.0, -5e5]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [0.9, -5e5], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, l, [-1.0, -5e5], [0.01, -5e5], 1e-6);
let short = line(&mut s, [-1.0, -6e5], [-0.5, -6e5]);
s.execute("extend", &json!({ "handle": short.hex(), "pick": [-0.6, -6e5], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, short, [-1.0, -6e5], [0.01, -6e5], 1e-6);
}
}
/// The run-on of a line in a small reference follows the line as the reference draws it: turned,
/// mirrored and scaled differently along X and Y, where its direction is not the block's.
#[test]
fn a_run_on_edge_in_a_small_uneven_reference_runs_along_the_drawn_line() {
// x = 10 for y in 4..12. Scaled by (0.001, -0.002) and turned a quarter turn: y = 0.01 for
// x in 0.008..0.024.
let mut s = Session::new();
let part = line(&mut s, [10.0, 4.0], [10.0, 12.0]);
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [0.0, 0.0], [0.001, -0.002], 90.0);
let l = line(&mut s, [5e5, -1.0], [5e5, 1.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [5e5, 0.9], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, l, [5e5, -1.0], [5e5, 0.01], 1e-6);
// A slanted line, twice as tall as wide once drawn: it passes y = 1e6 at x = 5e5.
let mut s = Session::new();
let part = line(&mut s, [0.0, 0.0], [10.0, 10.0]);
block(&mut s, "S", &[part]);
let r = reference(&mut s, "S", [0.0, 0.0], [0.001, 0.002], 0.0);
let l = line(&mut s, [5e5 - 1.0, 1e6], [5e5 + 1.0, 1e6]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [5e5 + 0.9, 1e6], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, l, [5e5 - 1.0, 1e6], [5e5, 1e6], 1e-3);
}
/// The end segments of an open polyline in a small reference run on as far as outside a block.
#[test]
fn a_run_on_polyline_end_in_a_small_reference_reaches_as_far_as_outside_a_block() {
let mut s = Session::new();
let part = made(&s.execute("pline", &json!({ "vertices": [[10, 4], [10, 12], [20, 12]] })).unwrap());
block(&mut s, "B", &[part]);
let r = reference(&mut s, "B", [0.0, 0.0], [0.001, 0.001], 0.0);
// The first segment runs on down x = 0.01, the last one along y = 0.012.
let below = line(&mut s, [-1.0, -5e5], [1.0, -5e5]);
s.execute("trim", &json!({ "handle": below.hex(), "pick": [0.9, -5e5], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, below, [-1.0, -5e5], [0.01, -5e5], 1e-6);
let beside = line(&mut s, [5e5, -1.0], [5e5, 1.0]);
s.execute("trim", &json!({ "handle": beside.hex(), "pick": [5e5, 0.9], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, beside, [5e5, -1.0], [5e5, 0.012], 1e-6);
}
/// In a reference a million times larger than its block a line runs on no farther than the same
/// line outside a block does: an object neither reaches is cut by neither.
#[test]
fn a_run_on_edge_in_a_large_reference_reaches_no_farther_than_outside_a_block() {
let mut s = Session::new();
let part = line(&mut s, [10.0, 4.0], [10.0, 12.0]);
block(&mut s, "B", &[part]);
// Drawn at x = 1e7 from y = 4e6 to 1.2e7, as the line beside it outside a block.
let r = reference(&mut s, "B", [0.0, 0.0], [1e6, 1e6], 0.0);
let plain = line(&mut s, [1e7, 4e6], [1e7, 1.2e7]);
let l = line(&mut s, [1e7 - 1e3, -1e10], [1e7 + 1e3, -1e10]);
for edge in [plain, r] {
assert!(s.execute("trim", &json!({ "handle": l.hex(), "pick": [1e7 + 900.0, -1e10], "edges": [edge.hex()], "edgeMode": "extend" })).is_err());
}
// Both reach an object within their run-on.
let near = line(&mut s, [1e7 - 1e3, -1e7], [1e7 + 1e3, -1e7]);
s.execute("trim", &json!({ "handle": near.hex(), "pick": [1e7 + 900.0, -1e7], "edges": [r.hex()], "edgeMode": "extend" })).unwrap();
assert_ends_within(&s, near, [1e7 - 1e3, -1e7], [1e7, -1e7], 1e-3);
}
/// A drawing whose block "TINY" holds `part` alone, referenced at the origin with `scale` on both
/// axes. Returns the reference. The part goes into the block as it is, however small.
fn one_part_reference(part: EntityKind, scale: f64) -> (Session, Handle) {
use cadcraft_engine::doc::{Common, Insert, Space};
let mut s = Session::new();
let d = s.doc_mut().unwrap();
let mut blk = Block::new("TINY");
blk.entities.push(Entity::new(d.new_handle(), part));
d.blocks.insert("TINY".into(), std::sync::Arc::new(blk));
let insert = Insert { block: "TINY".into(), scale: Vec3::new(scale, scale, 1.0), ..Insert::default() };
let r = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
(s, r)
}
/// A construction line and a ray in a reference keep their direction however small or large the
/// reference draws them: along the X axis they cut a line that crosses it, as the same object
/// outside a block does.
#[test]
fn an_endless_line_in_a_very_small_or_large_reference_still_cuts() {
use cadcraft_engine::doc::RayLine;
let along_x = RayLine { base: Vec3::ZERO, dir: Vec3::new(1.0, 0.0, 0.0) };
for scale in [1e-10, 1e-6, 1.0, 1e6, 1e10] {
for part in [EntityKind::XLine(along_x.clone()), EntityKind::Ray(along_x.clone())] {
let (mut s, r) = one_part_reference(part, scale);
let l = line(&mut s, [1.0, -5.0], [1.0, 5.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [1, 4], "edges": [r.hex()] })).unwrap_or_else(|e| panic!("scale {scale}: {e}"));
assert_ends(&s, l, [1.0, -5.0], [1.0, 0.0]);
}
}
}
/// With edges that run on, a line too short to have a direction by the drawing tolerance in its
/// block runs on once a large reference draws it long: from (0, 0) to (1, 0) it reaches a line
/// at x = 2. A line drawn that short by a small reference runs on too.
#[test]
fn a_run_on_edge_runs_along_the_placed_line_however_short_it_is_in_its_block() {
for (len, scale) in [(1e-10, 1e10), (1e-12, 1e12), (1.0, 1e-10), (1.0, 1.0)] {
let part = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(len, 0.0, 0.0) });
let (mut s, r) = one_part_reference(part, scale);
let l = line(&mut s, [2.0, -5.0], [2.0, 5.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [2, 4], "edges": [r.hex()], "edgeMode": "extend" }))
.unwrap_or_else(|e| panic!("length {len}, scale {scale}: {e}"));
assert_ends(&s, l, [2.0, -5.0], [2.0, 0.0]);
}
}
/// A drawing with a proxy whose graphics are four vertical lines across the X axis: at x = 30 on
/// a layer that is off, at x = 40 on a frozen layer, at x = 50 hidden, and at x = 60 on layer 0,
/// the only one drawn. `in_block`: the proxy is the one part of a block referenced at the origin,
/// else it is in the drawing itself. Returns the reference or the proxy.
fn proxy_with_one_drawn_graphic(in_block: bool) -> (Session, Handle) {
use cadcraft_engine::doc::{Common, Insert, Space, Unknown};
let mut s = Session::new();
let d = s.doc_mut().unwrap();
for (name, on, frozen) in [("OFF", false, false), ("FROZEN", true, true)] {
d.ensure_layer(name);
let l = d.layer_mut(name).unwrap();
(l.on, l.frozen) = (on, frozen);
}
let graphic = |x: f64, layer: &str, visible: bool| {
let mut g = Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(x, -10.0, 0.0), b: Vec3::new(x, 10.0, 0.0) }));
g.common.layer = layer.into();
g.common.visible = visible;
g
};
let graphics = vec![graphic(30.0, "OFF", true), graphic(40.0, "FROZEN", true), graphic(50.0, "0", false), graphic(60.0, "0", true)];
let proxy = EntityKind::Unknown(Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics });
let h = if in_block {
let mut blk = Block::new("PROXIES");
blk.entities.push(Entity::new(d.new_handle(), proxy));
d.blocks.insert("PROXIES".into(), std::sync::Arc::new(blk));
d.add(&Space::Model, Common::default(), EntityKind::Insert(Insert { block: "PROXIES".into(), ..Insert::default() })).unwrap()
} else {
d.add(&Space::Model, Common::default(), proxy).unwrap()
};
(s, h)
}
/// A proxy is an edge by the graphics it draws: those on a layer that is off or frozen and the
/// hidden ones cut nothing and stop nothing, in a block reference and in the drawing itself, with
/// the edge named and with every object an edge.
#[test]
fn proxy_graphics_that_are_not_drawn_are_not_edges() {
let mut wrong = Vec::new();
for (in_block, named) in [(true, true), (true, false), (false, true), (false, false)] {
let (mut s, edge) = proxy_with_one_drawn_graphic(in_block);
let edges = if named { json!([edge.hex()]) } else { Value::Null };
// Picked at its start, the line loses the stretch up to the first edge: the drawn graphic.
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [1, 0], "edges": edges })).unwrap();
let (a, b) = ends(&s, l);
if !(a.near(Vec2::new(60.0, 0.0), 1e-9) && b.near(Vec2::new(100.0, 0.0), 1e-9)) {
wrong.push(format!("trim, in a block {in_block}, named {named}: {a:?} to {b:?}"));
}
s.execute("erase", &json!({ "handles": [l.hex()] })).unwrap();
// The first boundary a line running towards them reaches is the drawn graphic too.
let short = line(&mut s, [0.0, -2.0], [5.0, -2.0]);
s.execute("extend", &json!({ "handle": short.hex(), "pick": [4, -2], "edges": edges })).unwrap();
let (a, b) = ends(&s, short);
if !(a.near(Vec2::new(0.0, -2.0), 1e-9) && b.near(Vec2::new(60.0, -2.0), 1e-9)) {
wrong.push(format!("extend, in a block {in_block}, named {named}: {a:?} to {b:?}"));
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// One look for edges stays inside one bound on the objects it visits in block references,
/// however many references the drawing has: with far more references than the bound allows, the
/// edge in the first reference still cuts and the edge in the last one is no edge. (Each
/// reference had the whole bound to itself, so the walk over all of them had none.)
#[test]
fn the_look_for_edges_in_references_is_bounded_over_all_of_them() {
use cadcraft_engine::doc::{Common, Insert, Space};
let (mut s, _) = one_reference();
let d = s.doc_mut().unwrap();
let at = |x: f64, y: f64| EntityKind::Insert(Insert { block: "B".into(), insert: Vec3::new(x, y, 0.0), ..Insert::default() });
// The references between the two draw their line far above the X axis, where it cuts nothing.
for _ in 0..30_000 {
d.add(&Space::Model, Common::default(), at(0.0, 1000.0)).unwrap();
}
// The last reference draws the block's line at x = 40, nearer the pick than the first one's.
d.add(&Space::Model, Common::default(), at(-10.0, 0.0)).unwrap();
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [10, 0] })).unwrap();
assert_ends(&s, l, [70.0, 0.0], [100.0, 0.0]);
}
/// A drawing with six references to block "PROXY", whose one object is a proxy that draws the
/// vertical line x = 50 across the X axis and 5,000 short lines far above it. The first reference
/// draws the vertical line at x = 70 and the last one at x = 40; the four between draw theirs far
/// above the X axis. The graphics of the six are more than one look for edges may visit.
/// `drawn`: whether the short lines are drawn, or hidden (the vertical line always is drawn).
fn references_to_a_proxy_with_many_graphics(drawn: bool) -> Session {
use cadcraft_engine::doc::{Common, Insert, Space, Unknown};
let mut s = Session::new();
let d = s.doc_mut().unwrap();
let graphic =
|a: [f64; 2], b: [f64; 2]| Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) }));
let mut graphics = vec![graphic([50.0, -10.0], [50.0, 10.0])];
graphics.extend((0..5_000).map(|i| {
let mut g = graphic([f64::from(i), 1000.0], [f64::from(i), 1001.0]);
g.common.visible = drawn;
g
}));
let mut blk = Block::new("PROXY");
blk.entities.push(Entity::new(d.new_handle(), EntityKind::Unknown(Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics })));
d.blocks.insert("PROXY".into(), std::sync::Arc::new(blk));
for at in [[20.0, 0.0], [0.0, 2000.0], [0.0, 2000.0], [0.0, 2000.0], [0.0, 2000.0], [-10.0, 0.0]] {
let insert = Insert { block: "PROXY".into(), insert: Vec3::new(at[0], at[1], 0.0), ..Insert::default() };
d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
}
s
}
/// The graphics of a proxy count toward the same bound: a proxy inside a block comes as one
/// object, but the look goes through every graphic it holds, in every reference, to take the
/// drawn ones. With a few references to a block whose proxy holds thousands of graphics, the edge
/// in the first reference is still an edge and the edge in the last one, reached after the bound
/// is spent, is none: for TRIM, for EXTEND and for the highlight under the cursor, which looks
/// for edges on every move, and whether those graphics are drawn or hidden.
#[test]
fn the_graphics_of_a_proxy_in_references_count_toward_the_bound() {
let mut wrong = Vec::new();
for drawn in [true, false] {
// TRIM: the pick is left of both lines; the cut is at the first reference's, the farther one.
let mut s = references_to_a_proxy_with_many_graphics(drawn);
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.execute("trim", &json!({ "handle": l.hex(), "pick": [10, 0] })).unwrap();
let (a, b) = ends(&s, l);
if !(a.near(Vec2::new(70.0, 0.0), 1e-9) && b.near(Vec2::new(100.0, 0.0), 1e-9)) {
wrong.push(format!("trim, drawn {drawn}: {a:?} to {b:?}"));
}
// EXTEND: the line grows to the right, past x = 40, to the first reference's line.
let mut s = references_to_a_proxy_with_many_graphics(drawn);
let l = line(&mut s, [0.0, 0.0], [30.0, 0.0]);
s.execute("extend", &json!({ "handle": l.hex(), "pick": [29, 0] })).unwrap();
let (a, b) = ends(&s, l);
if !(a.near(Vec2::new(0.0, 0.0), 1e-9) && b.near(Vec2::new(70.0, 0.0), 1e-9)) {
wrong.push(format!("extend, drawn {drawn}: {a:?} to {b:?}"));
}
// The highlight in the running TRIM: the piece a click at x = 10 removes ends at x = 70.
let mut s = references_to_a_proxy_with_many_graphics(drawn);
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
s.zoom_extents().unwrap();
s.start("trim").unwrap();
let part = s.highlight(l, Vec2::new(10.0, 0.0)).expect("a part of the line is highlighted");
let outline: Vec<Vec2> = part.iter().flat_map(|e| cadcraft_engine::select::hit_polylines(s.doc().unwrap(), e, 1e-4)).flatten().collect();
let by_x = |a: &Vec2, b: &Vec2| a.x.total_cmp(&b.x);
let (near, far) = (outline.iter().copied().min_by(by_x).unwrap(), outline.iter().copied().max_by(by_x).unwrap());
if !(near.near(Vec2::new(0.0, 0.0), 1e-6) && far.near(Vec2::new(70.0, 0.0), 1e-6)) {
wrong.push(format!("highlight, drawn {drawn}: {near:?} to {far:?}"));
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
@@ -6,7 +6,8 @@ use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Hatch};
use serde_json::json;
use crate::temp_dir;
#[path = "support/temp_dir.rs"]
mod temp_dir;
use temp_dir::TempDir;
@@ -23,7 +23,7 @@ fn session() -> Session {
let layer = "0 TABLE\n2 LAYER\n5 2\n330 0\n100 AcDbSymbolTable\n70 1\n\
0 LAYER\n5 10\n330 2\n100 AcDbSymbolTableRecord\n100 AcDbLayerTableRecord\n2 Walls\n70 0\n62 3\n6 Continuous\n\
1001 ACME_TAGS\n1000 W-01\n1070 7\n0 ENDTAB\n";
let src = include_str!("../../../io/tests/data/dynblock_door.txt").replace("\r\n", "\n").replacen(
let src = include_str!("../../io/tests/data/dynblock_door.txt").replace("\r\n", "\n").replacen(
"0 TABLE\n2 BLOCK_RECORD\n",
&format!("{layer}0 TABLE\n2 BLOCK_RECORD\n"),
1,
+14 -15
View File
@@ -7,24 +7,23 @@ use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io, set_write_as};
use serde_json::json;
/// A 2018 DXF with plain and mental ray settings. Both store base class version 2.
/// A 2018 DXF with one mental ray render settings object, stored as `90 2` (class version 1 in the
/// 2013+ form).
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nRENDERSETTINGS\n2\nAcDbRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n\
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n3\nPlain\n350\n22\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\
0\nMENTALRAYRENDERSETTINGS\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n\
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nRENDERSETTINGS\n5\n22\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nPlain\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n0\nENDSEC\n0\nEOF\n";
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nENDSEC\n0\nEOF\n";
/// The `AcDbRenderSettings` class version in a written DXF.
fn class_versions(path: &std::path::Path) -> [Option<i64>; 2] {
fn class_version(path: &std::path::Path) -> Option<i64> {
let text = std::fs::read_to_string(path).unwrap();
let l: Vec<&str> = text.lines().map(str::trim).collect();
["RENDERSETTINGS", "MENTALRAYRENDERSETTINGS"].map(|kind| {
let at = l.windows(2).position(|w| w == ["0", kind])?;
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
})
let at = l.windows(2).position(|w| w == ["0", "MENTALRAYRENDERSETTINGS"])?;
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
}
#[test]
@@ -44,13 +43,13 @@ fn saveas_down_and_back_up_keeps_the_render_settings_class_version() {
let save = |s: &mut Session, name: &str, version: &str| {
let path = dir.join(name);
s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": version })).unwrap();
class_versions(&path)
class_version(&path)
};
assert_eq!(save(&mut s, "2018.dxf", "2018"), [Some(2), Some(2)], "same version: as read");
assert_eq!(save(&mut s, "2000.dxf", "2000"), [Some(1), Some(2)], "only plain settings have a lower 2000 form");
assert_eq!(save(&mut s, "2018.dxf", "2018"), Some(2), "same version: as read");
assert_eq!(save(&mut s, "2000.dxf", "2000"), Some(1), "the 2000 form is one lower");
s.execute("qsave", &json!({})).unwrap();
assert_eq!(class_versions(&dir.join("2000.dxf")), [Some(1), Some(2)], "QSAVE keeps both 2000 forms");
assert_eq!(save(&mut s, "back.dxf", "2018"), [Some(2), Some(2)], "back to 2018: the 2018 file's value, not one higher");
assert_eq!(class_version(&dir.join("2000.dxf")), Some(1), "QSAVE keeps the 2000 form");
assert_eq!(save(&mut s, "back.dxf", "2018"), Some(2), "back to 2018: the 2018 file's value, not one higher");
let _ = std::fs::remove_dir_all(&dir);
}
+7 -10
View File
@@ -1,8 +1,5 @@
//! Saving over a drawing keeps the previous file as `<name>.bak` (ISAVEBAK, #540), and the
//! save itself replaces the file atomically: no temporary files are left behind.
//!
//! Some tests damage the file behind the session's back on purpose; the save after that passes
//! `overwrite: true`, since a save refuses a file changed on disk (`save_changed_on_disk.rs`).
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, backup_path, looks_complete, looks_like_drawing, save_keeps_current, set_io};
@@ -101,7 +98,7 @@ fn a_damaged_file_never_replaces_a_good_backup_and_isavebak_0_keeps_none() {
// Another program truncates the drawing; the next save keeps the good backup.
std::fs::write(&path, b"").unwrap();
add_circle(&mut s, 10.0);
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
s.execute("qsave", &json!({})).unwrap();
assert_eq!((circles(&path), circles(&backup_path(&path))), (3, 1));
// Cut off with a drawing's start kept (half a DXF, a DWG's version tag alone): the backup
@@ -109,11 +106,11 @@ fn a_damaged_file_never_replaces_a_good_backup_and_isavebak_0_keeps_none() {
let whole = std::fs::read(&path).unwrap();
std::fs::write(&path, &whole[..whole.len() / 2]).unwrap();
add_circle(&mut s, 11.0);
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
s.execute("qsave", &json!({})).unwrap();
assert_eq!(circles(&backup_path(&path)), 1, "half a DXF");
std::fs::write(&path, b"AC1032").unwrap();
add_circle(&mut s, 12.0);
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
s.execute("qsave", &json!({})).unwrap();
assert_eq!(circles(&backup_path(&path)), 1, "a DWG's tag alone");
// ISAVEBAK 0: the backup is left as it was.
@@ -237,7 +234,7 @@ fn a_dwg_cut_off_anywhere_keeps_the_good_backup() {
// Another program leaves it cut off at 90%: the next save keeps the good backup.
std::fs::write(&path, &whole[..whole.len() * 9 / 10]).unwrap();
add_circle(&mut s, 10.0);
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
s.execute("qsave", &json!({})).unwrap();
assert_eq!(circles(&backup_path(&path)), 1, "{version}: the cut-off file didn't replace it");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -258,7 +255,7 @@ fn a_file_that_looks_damaged_is_kept_when_there_is_no_backup_yet() {
let odd = b"AC1032 but not as this header expects it".to_vec();
std::fs::write(&path, &odd).unwrap();
add_circle(&mut s, 5.0);
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
s.execute("qsave", &json!({})).unwrap();
assert_eq!(std::fs::read(backup_path(&path)).unwrap(), odd);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -284,14 +281,14 @@ fn the_backup_a_save_promises_is_the_one_it_writes() {
std::fs::write(&path, &dwg2007).unwrap();
assert!(save_keeps_current(&path));
add_circle(&mut s, 10.0);
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
s.execute("qsave", &json!({})).unwrap();
assert_eq!(std::fs::read(backup_path(&path)).unwrap(), dwg2007, "the promise was kept");
std::fs::write(backup_path(&path), &old).unwrap();
std::fs::write(&path, b"AC1032").unwrap();
assert!(!save_keeps_current(&path));
add_circle(&mut s, 15.0);
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
s.execute("qsave", &json!({})).unwrap();
assert_eq!(std::fs::read(backup_path(&path)).unwrap(), old, "cut off: nothing was promised");
cadcraft_engine::autosave::set_isavebak(false);
+4 -2
View File
@@ -35,6 +35,8 @@ craft-pdf = { workspace = true, features = ["read"] }
# Inspect DWG output only where craft-dwg builds its native bridge. An unconditional
# dev-dependency also builds acadrust during --all-targets, breaking FreeBSD aarch64 (#2526).
# Use the same fork revision as craft-dwg so these fixtures exercise its DWG representation.
# The storytold/acadrust fork at tag `storytold/v0.6.6` (upstream v0.6.6), the source craft-dwg moves
# to in storytold/craft-libs#4762; until craft-libs is repinned, craft-dwg still takes the identical
# crates.io 0.6.6.
[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies]
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "468b9d8e317755209020d5d3f2f1c8a76210c47f" }
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "5d5c482b3fcb3dc77e8281474461760f32959436" }
+106
View File
@@ -0,0 +1,106 @@
//! The angles of a hatch's elliptic boundary edges in the DXF a DWG is read through.
//!
//! A DWG holds an elliptic edge's start and end angles in radians, and so does the DXF the DWG
//! decoder writes (groups 50 and 51 of an edge of type 3). DXF itself keeps them in degrees, which
//! is how [`crate::dxf_read`] reads them: a circle stored as an elliptic edge with the end angle
//! 6.2832 became an arc of 6.28 degrees, and the hatch covered the hole it should have left open.
//! Only the DWG path needs this; a DXF file is read as written.
use std::f64::consts::PI;
/// `dxf` with the start and end angles (groups 50 and 51) of every elliptic hatch edge (edge type
/// 3, group 72) turned from radians to degrees. The text is handled as bytes: a drawing from
/// before 2007 is written in its code page, which is not UTF-8, and every other byte is kept as it
/// was. Binary DXF, and text with no such edge, come back as they were.
pub(crate) fn elliptic_edge_degrees(dxf: Vec<u8>) -> Vec<u8> {
if dxf.starts_with(b"AutoCAD Binary DXF") || !dxf.windows(5).any(|w| w == b"HATCH") {
return dxf;
}
let mut out = Vec::with_capacity(dxf.len());
let mut lines = dxf.split_inclusive(|b| *b == b'\n');
let mut in_hatch = false;
// After an elliptic edge's type, until the next edge or loop: the angles still to convert.
let mut ellipse = false;
let mut changed = false;
while let Some(code_line) = lines.next() {
let Some(value_line) = lines.next() else {
out.extend_from_slice(code_line);
break;
};
let code = code_line.trim_ascii();
let value = value_line.trim_ascii();
match code {
b"0" => {
in_hatch = value == b"HATCH";
ellipse = false;
}
b"72" if in_hatch => ellipse = value == b"3",
b"92" | b"97" if in_hatch => ellipse = false,
b"50" | b"51" if in_hatch && ellipse => {
if let Some(radians) = std::str::from_utf8(value).ok().and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) {
let ending = &value_line[value_line.trim_ascii_end().len()..];
out.extend_from_slice(code_line);
out.extend_from_slice(format!("{}", radians * 180.0 / PI).as_bytes());
out.extend_from_slice(ending);
changed = true;
continue;
}
}
_ => {}
}
out.extend_from_slice(code_line);
out.extend_from_slice(value_line);
}
if changed { out } else { dxf }
}
#[cfg(test)]
mod tests {
use super::*;
fn pairs(text: &str) -> Vec<(String, String)> {
let lines: Vec<&str> = text.lines().collect();
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
}
const HATCH: &str = "0\r\nHATCH\r\n91\r\n1\r\n92\r\n1\r\n93\r\n2\r\n72\r\n3\r\n10\r\n5.0\r\n20\r\n6.0\r\n11\r\n-55.5\r\n21\r\n0.0\r\n40\r\n1.0\r\n50\r\n0.0\r\n51\r\n6.283185307179586\r\n73\r\n1\r\n72\r\n1\r\n10\r\n1.0\r\n20\r\n2.0\r\n11\r\n3.0\r\n21\r\n4.0\r\n50\r\n7.0\r\n0\r\nLINE\r\n50\r\n9.0\r\n";
#[test]
fn an_elliptic_edge_gets_its_angles_in_degrees_and_nothing_else_changes() {
let out = String::from_utf8(elliptic_edge_degrees(HATCH.as_bytes().to_vec())).unwrap();
let p = pairs(&out.replace("\r\n", "\n"));
let value = |code: &str, n: usize| p.iter().filter(|(c, _)| c == code).nth(n).map(|(_, v)| v.parse::<f64>().unwrap());
assert!((value("51", 0).unwrap() - 360.0).abs() < 1e-9);
assert_eq!(value("50", 0), Some(0.0));
// A line edge's 50 and another entity's are left alone, as is the line ending.
assert_eq!(value("50", 1), Some(7.0));
assert_eq!(value("50", 2), Some(9.0));
assert!(out.contains("\r\n") && !out.replace("\r\n", "").contains('\r'));
}
/// A drawing from before 2007 is written in its code page: an accented letter is one byte that
/// is not valid UTF-8, and it must not stop the angles being converted or change.
#[test]
fn a_code_page_drawing_still_has_its_angles_converted() {
let mut dxf = b"0\r\nTEXT\r\n1\r\ncaf".to_vec();
dxf.push(0xE9);
dxf.extend_from_slice(b"\r\n");
dxf.extend_from_slice(HATCH.as_bytes());
let out = elliptic_edge_degrees(dxf.clone());
assert!(std::str::from_utf8(&dxf).is_err(), "the input is not UTF-8");
assert!(out.windows(4).any(|w| w == b"caf\xE9"), "the accented byte is kept");
let text: String = out.iter().map(|b| char::from(*b)).collect();
assert!(text.contains("51\r\n360"), "the end angle is 360 degrees: {text}");
}
#[test]
fn text_without_a_hatch_ellipse_comes_back_untouched() {
let dxf = b"0\nLINE\n50\n1.5\n".to_vec();
assert_eq!(elliptic_edge_degrees(dxf.clone()), dxf);
let binary = b"AutoCAD Binary DXF\r\n\x1a\x00HATCH".to_vec();
assert_eq!(elliptic_edge_degrees(binary.clone()), binary);
// A hatch with no elliptic edge is left as it is.
let plain = "0\nHATCH\n72\n1\n50\n2.0\n".as_bytes().to_vec();
assert_eq!(elliptic_edge_degrees(plain.clone()), plain);
}
}
+24 -12
View File
@@ -1861,25 +1861,37 @@ fn unknown_handles(d: &Drawing) -> HashSet<String> {
all_entities(d).filter(|e| matches!(e.kind, EntityKind::Unknown(_))).map(|e| e.handle.hex()).collect()
}
/// Plain RENDERSETTINGS stores its base class version one higher in 2013+ files.
/// Mental ray and rapid RT settings store their base version verbatim in every file version.
/// Use the source of the retained objects, since SAVEAS can change the drawing's header.
/// Render settings (`RENDERSETTINGS`, `MENTALRAYRENDERSETTINGS`, `RAPIDRTRENDERSETTINGS`) store
/// their `AcDbRenderSettings` class version (the first group 90 after that marker) in the form of
/// the file's version: a 2013+ file stores it one higher, and a 2013 file stores a rapid RT one
/// one lower, as acadrust reads and writes them (`write_render_settings_dxf` in acadrust 0.6.6's
/// `io/dxf/writer/section_writer.rs`, and its DWG class-object reader and writer; the test
/// `render_settings_class_version_matches_what_acadrust_writes` fails if the two drift apart). A
/// kept object carries the form of the file it was read from ([`Foreign::version`], not the
/// drawing's `$ACADVER`, which SAVEAS changes); written into a file read as another version, it
/// takes that version's form. The DWG bridge's R2000 text is read as the version the kept objects
/// came from (craft-dwg's `encode_kept_noted`), so there they stay as read (#907, #2471).
///
/// Only that first group 90 is converted, on purpose: the group 90 that starts a kind's own
/// subclass (`AcDbMentalRayRenderSettings`, `AcDbRapidRTRenderSettings`) is that kind's version,
/// stored the same in every file version, and is left as read.
pub(crate) fn render_settings_versions(tags: &mut [Tag], source: Option<Version>, declared: Version) {
let Some(source) = source else { return };
let delta = i64::from(declared >= Version::R2013) - i64::from(source >= Version::R2013);
if delta == 0 {
return;
}
let (mut plain, mut in_base) = (false, false);
let Some(source) = source.filter(|s| *s != declared) else { return };
let shift = |rapid: bool, v: Version| if rapid { -i64::from(v == Version::R2013) } else { i64::from(v >= Version::R2013) };
let (mut kind, mut in_base) = (String::new(), false);
for t in tags.iter_mut() {
match t.code {
0 => {
plain = t.str().trim().eq_ignore_ascii_case("RENDERSETTINGS");
kind = up(&t.str());
in_base = false;
}
100 if plain => in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings"),
100 if matches!(kind.as_str(), "RENDERSETTINGS" | "MENTALRAYRENDERSETTINGS" | "RAPIDRTRENDERSETTINGS") => {
in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings");
}
90 if in_base => {
*t = Tag::i(90, t.i64().saturating_add(delta));
let rapid = kind == "RAPIDRTRENDERSETTINGS";
let logical = t.i64().saturating_sub(shift(rapid, source));
*t = Tag::i(90, logical.saturating_add(shift(rapid, declared)));
in_base = false;
}
_ => {}
+8 -25
View File
@@ -48,7 +48,6 @@ struct BlockProps {
/// Handle maps and references gathered while reading.
#[derive(Default)]
struct Rx {
from_dwg: bool,
/// STYLE record handle (upper case) → text style name.
styles: HashMap<String, String>,
/// BLOCK_RECORD handle (upper case) → block name.
@@ -178,12 +177,7 @@ fn draw_kept_dimensions_from_their_blocks(d: &mut Drawing) {
/// Read a DXF file into a drawing.
pub fn read(bytes: &[u8]) -> Result<Drawing> {
read_with_origin(bytes, false)
}
/// The DWG bridge emits explicit viewport defaults that are absent from its source.
pub(super) fn read_with_origin(bytes: &[u8], from_dwg: bool) -> Result<Drawing> {
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS, None, from_dwg)
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS, None)
}
/// A block definition read from BLOCKS: name, base point, description, entities (owner, paper
@@ -197,13 +191,7 @@ type LayoutDef = (String, u32, String, PageSetup, Option<(Vec2, Vec2)>, Option<i
/// Import DXF sections while sharing one materialized-table-cell budget and one hatch curve-point
/// budget across blocks and entity sections. `entities_refused_past` is for tests (see `Rx`).
fn read_budgeted(
bytes: &[u8],
mut table_cells_left: usize,
curve_points: usize,
entities_refused_past: Option<usize>,
from_dwg: bool,
) -> Result<Drawing> {
fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize, entities_refused_past: Option<usize>) -> Result<Drawing> {
let tags = craft_dxf::parse(bytes).map_err(|e| IoError::Format(e.to_string()))?;
let secs = section_slices(&tags);
if secs.is_empty() {
@@ -213,13 +201,8 @@ fn read_budgeted(
d.layouts.clear();
// A file without $INSUNITS declares no units (#1209); only new drawings take the template's.
d.header.set_i64("INSUNITS", 0);
let mut rx = Rx {
pstyles: plot_style_names(&secs),
curves: hatch::CurvePoints { left: curve_points, cut: 0 },
entities_refused_past,
from_dwg,
..Rx::default()
};
let mut rx =
Rx { pstyles: plot_style_names(&secs), curves: hatch::CurvePoints { left: curve_points, cut: 0 }, entities_refused_past, ..Rx::default() };
let mut blocks: Vec<BlockDef> = Vec::new();
let mut layout_objs: Vec<LayoutDef> = Vec::new();
let mut entities = Vec::new();
@@ -443,7 +426,7 @@ mod table_budget_tests {
let dxf = format!(
"0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\nTEST\n10\n0\n20\n0\n{table}0\nENDBLK\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nEOF\n"
);
let d = read_budgeted(dxf.as_bytes(), 2, hatch::MAX_READ_CURVE_POINTS, None, false).unwrap();
let d = read_budgeted(dxf.as_bytes(), 2, hatch::MAX_READ_CURVE_POINTS, None).unwrap();
let block = d.block("TEST").unwrap();
let count = |e: &Entity| match &e.kind {
EntityKind::Table(t) => t.cells.iter().map(Vec::len).sum::<usize>(),
@@ -487,10 +470,10 @@ mod hatch_budget_tests {
#[test]
fn hatch_curves_stop_at_the_read_budget_and_say_so() {
let dxf = format!("0\nSECTION\n2\nENTITIES\n{}{}0\nENDSEC\n0\nEOF\n", spline_hatch(10), spline_hatch(10));
let full = read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, None, false).unwrap();
let full = read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, None).unwrap();
assert!(full.read_notes.is_empty(), "{:?}", full.read_notes);
assert!(hatch_points(&full) > 20_000, "{}", hatch_points(&full));
let d = read_budgeted(dxf.as_bytes(), 4_000_000, 1000, None, false).unwrap();
let d = read_budgeted(dxf.as_bytes(), 4_000_000, 1000, None).unwrap();
// The budget is checked before each edge: the last one sampled may pass it by its own
// points (at most about 4,000); every edge after it is its four control points.
assert!(hatch_points(&d) <= 1000 + 4001 + 20 * 4, "{}", hatch_points(&d));
@@ -621,7 +604,7 @@ mod entity_list_tests {
let block = |name: &str| format!("0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\n{name}\n10\n0\n20\n0\n{lines}0\nENDBLK\n0\nENDSEC\n0\nEOF\n");
let files = [format!("0\nSECTION\n2\nENTITIES\n{lines}0\nENDSEC\n0\nEOF\n"), block("*Model_Space"), block("*Paper_Space"), block("B")];
for dxf in &files {
let open = |refused_past| read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, refused_past, false);
let open = |refused_past| read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, refused_past);
let d = open(Some(3)).unwrap();
let in_layouts: usize = d.layouts.iter().map(|l| l.entities.len()).sum();
assert_eq!(d.model.len() + in_layouts + d.block("B").map_or(0, |b| b.entities.len()), 3, "{dxf}");
+1 -1
View File
@@ -143,7 +143,7 @@ pub(super) fn parse_entities(
if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) {
rx.paper_views_dropped.push((owner.clone(), paper, rx.block.clone()));
}
let mut kindent = entity_with_table_budget(kind, tags, table_cells_left, &mut rx.curves, rx.from_dwg);
let mut kindent = entity_with_table_budget(kind, tags, table_cells_left, &mut rx.curves);
if let Some((c, _)) = kindent.as_mut()
&& let Some(n) = entity_plot_style(tags, rx)
{
+4 -15
View File
@@ -117,7 +117,7 @@ fn viewport_ucs(tags: &[Tag]) -> Option<ViewportUcs> {
/// A VIEWPORT's groups CADCraft doesn't model, as read ([`VIEWPORT_NOT_EXTRA`]), plus those of
/// CADCraft's xdata copy that the record lacks (a DWG drops some).
fn viewport_extra(tags: &[Tag], from_dwg: bool) -> Vec<RawTag> {
fn viewport_extra(tags: &[Tag]) -> Vec<RawTag> {
// Only groups that can stand inside the AcDbViewport subclass: no record start (0), handle (5,
// 105), subclass (100), group brace (102) or xdata (1000 on), which written back would break
// the record or give it a second handle.
@@ -137,17 +137,7 @@ fn viewport_extra(tags: &[Tag], from_dwg: bool) -> Vec<RawTag> {
out.push(RawTag { code, value });
}
}
// The DWG bridge writes an empty style sheet and UCS-at-origin 0 even for a viewport
// without its own UCS. Keep nonempty styles and nondefault UCS-icon settings.
let no_ucs = viewport_ucs(tags).is_none();
let keep: Vec<bool> = out
.iter()
.map(|t| {
!at_default(&out, t.code, &t.value)
&& !(from_dwg && t.code == 1 && t.value.is_empty())
&& !(from_dwg && no_ucs && t.code == 74 && t.value.trim().parse::<i32>().ok() == Some(0))
})
.collect();
let keep: Vec<bool> = out.iter().map(|t| !at_default(&out, t.code, &t.value)).collect();
let mut keep = keep.into_iter();
out.retain(|_| keep.next().unwrap_or(true));
out
@@ -155,7 +145,7 @@ fn viewport_extra(tags: &[Tag], from_dwg: bool) -> Vec<RawTag> {
/// Parse one entity record. POLYLINE/INSERT followers are handled by the caller.
pub(super) fn entity(kind: &str, tags: &[Tag]) -> Option<(Common, EntityKind)> {
entity_with_table_budget(kind, tags, &mut 4_000_000, &mut CurvePoints::default(), false)
entity_with_table_budget(kind, tags, &mut 4_000_000, &mut CurvePoints::default())
}
/// Parse one entity while charging materialized table cells to the caller's shared import budget.
@@ -296,7 +286,6 @@ pub(super) fn entity_with_table_budget(
tags: &[Tag],
table_cells_left: &mut usize,
curves: &mut CurvePoints,
from_dwg: bool,
) -> Option<(Common, EntityKind)> {
// The paper-space viewport our writer adds (dxf_write::paper_view) stays implicit.
if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) {
@@ -504,7 +493,7 @@ pub(super) fn entity_with_table_budget(
twist,
ucs: viewport_ucs(tags),
ucs_per_viewport: t.i(71) == Some(1),
extra: viewport_extra(tags, from_dwg),
extra: viewport_extra(tags),
}
}),
"WIPEOUT" => {
+2 -12
View File
@@ -215,22 +215,12 @@ fn circular_edge(tags: &[Tag], index: &mut usize, vertices: &mut Vec<PolyVertex>
/// as the edge has groups.
const COARSE_ELLIPSE_POINTS: u32 = 8;
/// HATCH groups 50/51 are circular ray angles; an ellipse uses eccentric parameters.
/// Keep the same revolution so full turns and negative angles retain their sweep.
fn ellipse_parameter(angle: f64, ratio: f64) -> f64 {
if ratio == 1.0 || !(ratio > 0.0 && ratio.is_finite() && angle.is_finite()) {
return angle;
}
let param = angle.sin().atan2(ratio * angle.cos());
param + ((angle - param) / std::f64::consts::TAU).round() * std::f64::consts::TAU
}
fn elliptic_edge(tags: &[Tag], index: &mut usize, vertices: &mut Vec<PolyVertex>, budget: &mut EdgeBudget) {
let center = Vec2::new(edge_value(tags, *index), edge_value(tags, *index + 1));
let major = Vec2::new(edge_value(tags, *index + 2), edge_value(tags, *index + 3));
let ratio = edge_value(tags, *index + 4);
let start_angle = ellipse_parameter(edge_value(tags, *index + 5).to_radians(), ratio);
let end_angle = ellipse_parameter(edge_value(tags, *index + 6).to_radians(), ratio);
let start_angle = edge_value(tags, *index + 5).to_radians();
let end_angle = edge_value(tags, *index + 6).to_radians();
let ccw = tags.get(*index + 7).filter(|tag| tag.code == 73).map(Tag::i64).unwrap_or(1) != 0;
*index += 8;
let (start, end) = if ccw { (start_angle, end_angle) } else { (-end_angle, -start_angle) };
+1 -4
View File
@@ -96,14 +96,11 @@ pub(crate) fn read_table_style(name: &str, tags: &[Tag]) -> TableStyle {
i = next;
}
let data_h = blocks.first().and_then(|b| first(140, b)).filter(|h| *h > 0.0);
// A group 280 before the description (3) is the class version. Title suppression
// uses another 280 after it. Older writers sometimes omit the description.
let properties = head.iter().position(|t| t.code == 3).map_or(head, |i| &head[i + 1..]);
let mut st = TableStyle {
name: name.to_string(),
text_height: data_h.unwrap_or(def.text_height),
margin: first(40, head).filter(|m| *m >= 0.0).unwrap_or(def.margin),
title: properties.iter().find(|t| t.code == 280).map(Tag::i64).unwrap_or(0) == 0,
title: head.iter().find(|t| t.code == 280).map(Tag::i64).unwrap_or(0) == 0,
header: head.iter().find(|t| t.code == 281).map(Tag::i64).unwrap_or(0) == 0,
cell_styles: Vec::new(),
};
+7 -3
View File
@@ -2,6 +2,8 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
/// A DWG hatch's elliptic boundary edge angles, in degrees in the DXF the DWG is read through (#3332).
mod dwg_hatch;
/// What a DXF file holds that CADCraft doesn't model, kept and written back (#528).
mod dxf_raw;
@@ -101,7 +103,9 @@ pub fn read(bytes: &[u8], name: impl AsRef<Path>) -> Result<Drawing> {
pub(crate) fn read_source(bytes: &[u8], name: &Path) -> Result<(Drawing, Option<Vec<u8>>)> {
if craft_dwg::is_dwg(bytes) {
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(dwg_error)?;
let mut d = dxf_read::read_with_origin(&dxf, true).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?;
// The decoder writes an elliptic hatch edge's angles in radians; DXF keeps degrees.
let dxf = dwg_hatch::elliptic_edge_degrees(dxf);
let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?;
d.read_notes = notes.into_iter().map(|note| cadcraft_dwg_message(&note)).collect();
return Ok((d, Some(dxf)));
}
@@ -132,8 +136,8 @@ pub fn write_with(d: &Drawing, name: impl AsRef<Path>, opts: &SaveOptions) -> Re
// Before 2007 the text is in the code page the header declares.
let code_page = dxf_write::code_page(d, version);
Ok(match (opts.binary, version.utf8()) {
(true, true) => craft_dxf::write_binary(&tags, true).map_err(|e| IoError::Format(e.to_string()))?,
(true, false) => craft_dxf::write_binary_in(&tags, &code_page).map_err(|e| IoError::Format(e.to_string()))?,
(true, true) => craft_dxf::write_binary(&tags, true),
(true, false) => craft_dxf::write_binary_in(&tags, &code_page),
(false, true) => craft_dxf::write_ascii_as(&tags, true).into_bytes(),
(false, false) => craft_dxf::write_ascii_in(&tags, &code_page),
})
+3 -14
View File
@@ -1,6 +1,6 @@
//! A hatch boundary stored in a DWG as an elliptic edge keeps its sweep: a circle (0 to 2π) stays a
//! circle, so the hatch leaves the hole open. The DWG decoder used to write the edge's angles in radians
//! while DXF reads degrees, so the circle came out as an arc of 6.28 degrees.
//! circle, so the hatch leaves the hole open. The DWG decoder writes the edge's angles in radians
//! and DXF reads degrees, so the circle used to come out as an arc of 6.28 degrees.
// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DXF still works.
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
@@ -16,10 +16,6 @@ fn line(a: (f64, f64), b: (f64, f64)) -> BoundaryEdge {
/// A DWG with a pattern hatch over a 100 x 100 square with a round hole of radius 10 stored as an
/// elliptic edge from `start` to `end` radians.
fn dwg_with_hole(start: f64, end: f64) -> Vec<u8> {
dwg_with_elliptic_hole(start, end, 1.0)
}
fn dwg_with_elliptic_hole(start: f64, end: f64, ratio: f64) -> Vec<u8> {
let mut hatch = Hatch::new();
hatch.is_solid = false;
let mut outer = BoundaryPath::new();
@@ -31,7 +27,7 @@ fn dwg_with_elliptic_hole(start: f64, end: f64, ratio: f64) -> Vec<u8> {
hole.edges = vec![BoundaryEdge::EllipticArc(EllipticArcEdge {
center: Vector2::new(50.0, 50.0),
major_axis_endpoint: Vector2::new(-10.0, 0.0),
minor_axis_ratio: ratio,
minor_axis_ratio: 1.0,
start_angle: start,
end_angle: end,
counter_clockwise: true,
@@ -70,10 +66,3 @@ fn a_quarter_arc_stored_as_an_elliptic_edge_keeps_its_quarter() {
// From the point at 0 degrees (60, 50) to the one at 90 degrees (50, 60), closed by a chord: x spans 10.
assert!(max - min > 9.9 && max - min < 10.5, "the arc spans {} in x", max - min);
}
#[test]
fn a_non_circular_elliptic_arc_keeps_its_dwg_endpoints() {
let (min, max) = hole_extent(&dwg_with_elliptic_hole(std::f64::consts::FRAC_PI_4, std::f64::consts::FRAC_PI_2, 0.5));
let expected_min = 50.0 - 10.0 / 2.0_f64.sqrt();
assert!((min - expected_min).abs() < 0.02 && (max - 50.0).abs() < 0.02, "arc x range {min}..{max}");
}
-19
View File
@@ -83,25 +83,6 @@ fn vertices(edges: &[Edge]) -> Vec<PolyVertex> {
loops.into_iter().next().map(|l| l.vertices).unwrap_or_default()
}
/// HATCH ellipse endpoints are circular ray angles, not the ellipse's eccentric parameters.
#[test]
fn a_non_circular_ellipse_edge_uses_ray_angles_in_both_directions() {
let expected = 10.0 / 5.0_f64.sqrt(); // x = y at 45 degrees on x²/100 + y²/25 = 1
let bounds = |l: &HatchLoop| l.vertices.iter().fold((f64::NEG_INFINITY, f64::INFINITY), |(max_x, min_y), v| (max_x.max(v.p.x), min_y.min(v.p.y)));
for (start, end, ccw) in [(45.0, 90.0, true), (270.0, 315.0, false), (405.0, 450.0, true)] {
let edge = Edge::Ellipse([0.0, 0.0], [10.0, 0.0], 0.5, start, end, ccw);
let drawing = cadcraft_io::read(dxf(&[vec![edge]]).as_bytes(), "ellipse.dxf").unwrap();
let loops = loops_of(&drawing);
let (max_x, min_y) = bounds(&loops[0]);
assert!((max_x - expected).abs() < 1e-8 && (min_y - expected).abs() < 1e-8, "{start} {end} {ccw}: {max_x} {min_y}");
// CADCraft writes the sampled contour as a polyline; the geometry survives a DXF save.
let saved = cadcraft_io::write_dxf(&drawing);
let reopened = cadcraft_io::read(saved.as_bytes(), "ellipse.dxf").unwrap();
let (x2, y2) = bounds(&loops_of(&reopened)[0]);
assert!((x2 - max_x).abs() < 1e-6 && (y2 - min_y).abs() < 1e-6);
}
}
/// The same vertices, up to the rounding of points and bulges computed from other stored values.
fn assert_same(got: &[PolyVertex], expected: &[PolyVertex]) {
let same = got.len() == expected.len() && got.iter().zip(expected).all(|(a, b)| a.p.near(b.p, 1e-9) && (a.bulge - b.bulge).abs() < 1e-12);
+6 -11
View File
@@ -5,25 +5,20 @@
use cadcraft_doc::EntityKind;
/// A saved-layout OLE frame header followed by opaque stand-in object bytes, long enough to
/// take several 310 groups. The payload is not claimed to be a valid compound file.
/// Stand-in OLE data as a DWG carries it: a two-byte marker, the frame's four corners (upper
/// left, upper right, lower right, lower left; x, y, z doubles), then the object's bytes, here
/// opaque text long enough to take several 310 groups.
fn payload() -> Vec<u8> {
let mut data = 0x5580u16.to_le_bytes().to_vec();
let mut data = vec![0x80, 0x00];
for [x, y] in [[10.0f64, 40.0], [70.0, 40.0], [70.0, 5.0], [10.0, 5.0]] {
for v in [x, y, 0.0] {
data.extend_from_slice(&v.to_le_bytes());
}
}
let mut extension = [0u8; 26];
extension[16..20].copy_from_slice(&1u32.to_le_bytes()); // embedded object
data.extend_from_slice(&extension);
let mut object = vec![];
for i in 0..12u8 {
object.extend_from_slice(b"synthetic embedded object ");
object.push(i);
data.extend_from_slice(b"synthetic embedded object ");
data.push(i);
}
data.extend_from_slice(&(object.len() as u32).to_le_bytes());
data.extend_from_slice(&object);
data
}
+1 -5
View File
@@ -12,16 +12,12 @@ const LR: (f64, f64) = (35.27, -22.39);
/// The OLE data: the envelope with the frame's corners.
fn blob() -> Vec<u8> {
let mut b = 0x5580u16.to_le_bytes().to_vec();
let mut b = vec![1u8, 0];
for (x, y) in [UL, (LR.0, UL.1), LR, (UL.0, LR.1)] {
for v in [x, y, 0.0] {
b.extend_from_slice(&v.to_le_bytes());
}
}
let mut extension = [0u8; 26];
extension[16..20].copy_from_slice(&1u32.to_le_bytes()); // embedded object
b.extend_from_slice(&extension);
b.extend_from_slice(&0u32.to_le_bytes()); // no compound-file bytes
b
}
+15 -9
View File
@@ -1,5 +1,10 @@
//! Plain render settings use a version-specific base class version. Mental ray and rapid RT
//! settings keep their stored value across both DXF and DWG versions (#907, #2471).
//! Render settings store their `AcDbRenderSettings` class version in the form of the file's
//! version: a 2013+ file stores it one higher (a 2013 file stores a rapid RT one one lower), as
//! acadrust reads and writes them. A kept object carries the form of the file it came from; written
//! into a file declaring another version, it takes that version's form. The DWG bridge is an R2000
//! DXF for a 2018 DWG: without this, a 2018 drawing's MENTALRAYRENDERSETTINGS went in with the 2018
//! form, the DWG writer raised it once more, and BricsCAD refused the DWG ("Object improperly
//! read", #907).
use cadcraft_io::{SaveOptions, Version};
@@ -45,7 +50,7 @@ fn written(d: &cadcraft_doc::Drawing, version: Version) -> String {
#[test]
fn render_settings_class_version_takes_the_declared_versions_form() {
let kind = "RENDERSETTINGS";
let kind = "MENTALRAYRENDERSETTINGS";
// From a 2018 file (stored 2 = class version 1 in the 2013+ form).
let d = cadcraft_io::read_dxf(dxf("AC1032", kind, 2).as_bytes()).unwrap();
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2), "same version: as read");
@@ -56,19 +61,19 @@ fn render_settings_class_version_takes_the_declared_versions_form() {
let d = cadcraft_io::read_dxf(dxf("AC1015", kind, 1).as_bytes()).unwrap();
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
// Rapid RT keeps the stored base class version across file versions.
// Rapid RT settings: the 2013 file alone stores one lower.
let kind = "RAPIDRTRENDERSETTINGS";
let d = cadcraft_io::read_dxf(dxf("AC1027", kind, 1).as_bytes()).unwrap();
assert_eq!(class_version(&written(&d, Version::R2013), kind), Some(1));
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(1));
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(2));
}
/// A file that declares no `$ACADVER` gives no source form: its kept objects are written as read,
/// not as if the new drawing's 2018 were their form.
#[test]
fn render_settings_without_a_declared_version_are_written_as_read() {
let kind = "RENDERSETTINGS";
let kind = "MENTALRAYRENDERSETTINGS";
let text = dxf("AC1032", kind, 1).replace("9\n$ACADVER\n1\nAC1032\n", "");
assert!(!text.contains("$ACADVER"));
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
@@ -105,7 +110,8 @@ fn render_settings_class_version_matches_what_acadrust_writes() {
(DxfVersion::AC1027, Version::R2013),
(DxfVersion::AC1032, Version::R2018),
];
for (kind, stored) in [("RENDERSETTINGS", 2), ("MENTALRAYRENDERSETTINGS", 2), ("RAPIDRTRENDERSETTINGS", 2)] {
// As a 2018 file stores them: mental ray one higher than its class version, rapid RT as is.
for (kind, stored) in [("MENTALRAYRENDERSETTINGS", 2), ("RAPIDRTRENDERSETTINGS", 2)] {
let source = std::io::Cursor::new(dxf("AC1032", kind, stored).into_bytes());
let mut doc = acadrust::DxfReader::from_reader(source).unwrap().read().unwrap();
let by_acadrust: Vec<(Version, String)> = versions
@@ -116,7 +122,7 @@ fn render_settings_class_version_matches_what_acadrust_writes() {
})
.collect();
let forms: Vec<Option<i64>> = by_acadrust.iter().map(|(_, text)| class_version(text, kind)).collect();
let expected = if kind == "RENDERSETTINGS" { [1, 1, 2, 2] } else { [2, 2, 2, 2] };
let expected = if kind == "RAPIDRTRENDERSETTINGS" { [2, 2, 1, 2] } else { [1, 1, 2, 2] };
assert_eq!(forms, expected.map(Some), "{kind}: acadrust's own forms for 2000, 2010, 2013, 2018");
for (read_from, text) in &by_acadrust {
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
+12 -26
View File
@@ -1,5 +1,5 @@
//! Shared preservation assertions for ordered entities, authored blocks and referenced tables.
//! Every field of the explicitly supported entities is checked; converted angles and interpolated spline controls allow
//! Every field of the explicitly supported entities is checked; converted angles alone allow
//! floating-point roundoff, never wrapping or geometric approximation. Blocks are visited once
//! as stored definitions, not recursively expanded, so cyclic references remain bounded.
//! Header defaults, generated objects and other drawing collections are outside this slice.
@@ -12,7 +12,8 @@ fn equal<T: PartialEq + Debug>(expected: &T, actual: &T, context: &str, field: &
assert_eq!(actual, expected, "{context}.{field}");
}
fn roundoff(expected: f64, actual: f64, context: &str, field: &str) {
fn angle(expected: f64, actual: f64, context: &str, field: &str) {
// Two floating-point unit conversions, not a geometric approximation or angle wrapping.
let tolerance = 8.0 * f64::EPSILON * expected.abs().max(1.0);
assert!(
expected.is_finite() && actual.is_finite() && (actual - expected).abs() <= tolerance,
@@ -143,7 +144,7 @@ fn linetype(expected: Option<&cadcraft_doc::Linetype>, actual: Option<&cadcraft_
equal(shape, &b.shape, &path, "shape");
equal(style, &b.style, &path, "style");
equal(scale, &b.scale, &path, "scale");
roundoff(*rotation, b.rotation, &path, "rotation");
angle(*rotation, b.rotation, &path, "rotation");
equal(offset, &b.offset, &path, "offset");
equal(absolute, &b.absolute, &path, "absolute");
}
@@ -166,23 +167,8 @@ fn entity(expected: &Entity, actual: &Entity, context: &str) {
(EntityKind::Arc(Arc { center, radius, start, end }), EntityKind::Arc(b)) => {
equal(center, &b.center, context, "arc.center");
equal(radius, &b.radius, context, "arc.radius");
roundoff(*start, b.start, context, "arc.start");
roundoff(*end, b.end, context, "arc.end");
}
(EntityKind::Spline(a), EntityKind::Spline(b)) if !a.fit.is_empty() => {
// DWG stores the fit points. The decoder interpolates the cubic controls for DXF.
let cadcraft_geom::Spline { degree, knots, control, weights, fit, closed, fit_opts } = a;
equal(degree, &b.degree, context, "spline.degree");
equal(knots, &b.knots, context, "spline.knots");
equal(weights, &b.weights, context, "spline.weights");
equal(fit, &b.fit, context, "spline.fit");
equal(closed, &b.closed, context, "spline.closed");
equal(fit_opts, &b.fit_opts, context, "spline.fit_opts");
equal(&control.len(), &b.control.len(), context, "spline.control.len");
for (p, q) in control.iter().zip(&b.control) {
roundoff(p.x, q.x, context, "spline.control.x");
roundoff(p.y, q.y, context, "spline.control.y");
}
angle(*start, b.start, context, "arc.start");
angle(*end, b.end, context, "arc.end");
}
(EntityKind::MText(a), EntityKind::MText(b)) => mtext(a, b, context),
(EntityKind::AttDef(a), EntityKind::AttDef(b)) => attrib(a, b, context),
@@ -254,9 +240,9 @@ fn text(expected: &Text, actual: &Text, context: &str) {
equal(align_pt, &actual.align_pt, context, "align_pt");
equal(height, &actual.height, context, "height");
equal(value, &actual.value, context, "value");
roundoff(*rotation, actual.rotation, context, "rotation");
angle(*rotation, actual.rotation, context, "rotation");
equal(width_factor, &actual.width_factor, context, "width_factor");
roundoff(*oblique, actual.oblique, context, "oblique");
angle(*oblique, actual.oblique, context, "oblique");
equal(style, &actual.style, context, "style");
equal(halign, &actual.halign, context, "halign");
equal(valign, &actual.valign, context, "valign");
@@ -270,7 +256,7 @@ fn mtext(expected: &MText, actual: &MText, context: &str) {
equal(height, &actual.height, context, "mtext.height");
equal(width, &actual.width, context, "mtext.width");
equal(attach, &actual.attach, context, "mtext.attach");
roundoff(*rotation, actual.rotation, context, "mtext.rotation");
angle(*rotation, actual.rotation, context, "mtext.rotation");
equal(style, &actual.style, context, "mtext.style");
equal(contents, &actual.contents, context, "mtext.contents");
equal(line_spacing, &actual.line_spacing, context, "mtext.line_spacing");
@@ -302,7 +288,7 @@ fn insert(expected: &Insert, actual: &Insert, context: &str) {
equal(block, &actual.block, context, "insert.block");
equal(insert, &actual.insert, context, "insert.insert");
equal(scale, &actual.scale, context, "insert.scale");
roundoff(*rotation, actual.rotation, context, "insert.rotation");
angle(*rotation, actual.rotation, context, "insert.rotation");
equal(cols, &actual.cols, context, "insert.cols");
equal(rows, &actual.rows, context, "insert.rows");
equal(col_spacing, &actual.col_spacing, context, "insert.col_spacing");
@@ -403,9 +389,9 @@ fn comparison_rejects_block_and_attribute_dependency_losses() {
#[test]
fn angle_tolerance_does_not_hide_real_changes_or_nonfinite_values() {
roundoff(0.7, 0.7_f64.to_degrees().to_radians(), "self-test", "angle");
angle(0.7, 0.7_f64.to_degrees().to_radians(), "self-test", "angle");
for actual in [0.700001, f64::NAN, f64::INFINITY] {
assert!(std::panic::catch_unwind(|| roundoff(0.7, actual, "self-test", "angle")).is_err());
assert!(std::panic::catch_unwind(|| angle(0.7, actual, "self-test", "angle")).is_err());
}
}
+1 -21
View File
@@ -375,27 +375,7 @@ fn layer_states() {
}
#[test]
fn layouts_and_paperspace() {
let case = collections::layouts();
for version in Version::ALL {
let mut expected = case.drawing.clone();
if version >= Version::R2007 {
// DWG stores effective viewport lighting from R2007 onward. Preserve it for DXF export.
for layout in expected.layouts.iter_mut() {
let handles: Vec<_> = layout.entities.iter().map(|e| e.handle).collect();
for handle in handles {
layout.entities.modify(handle, |e| {
if let cadcraft_doc::EntityKind::Viewport(v) = &mut e.kind {
v.extra = [(292, "1"), (282, "1"), (141, "0.0"), (142, "0.0")]
.into_iter()
.map(|(code, value)| cadcraft_doc::RawTag { code, value: value.into() })
.collect();
}
});
}
}
}
super::check_version_with(&case.name, &case.drawing, &expected, version, collections::assert_layouts);
}
collection(collections::layouts(), collections::assert_layouts);
}
fn with_dimension_styles(cases: Vec<Case>) {
+3 -78
View File
@@ -395,69 +395,9 @@ fn hostile_viewport_ucs_groups_do_not_panic() {
assert_eq!((u.x_axis, u.y_axis), (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)));
}
#[test]
fn a_viewport_keeps_its_nondefault_style_sheet_and_ucs_icon_origin() {
let (d, h) = base();
let text = cadcraft_io::write_dxf(&d);
let groups = [(1, "monochrome.ctb".into()), (74, "1".into())];
let back = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
let (_, viewport) = the_viewport(&back);
assert!(viewport.extra.iter().any(|t| t.code == 1 && t.value == "monochrome.ctb"));
assert!(viewport.extra.iter().any(|t| t.code == 74 && t.value == "1"));
}
/// An explicit 282=1 selects two lights. A DXF consumer can interpret an omitted 282
/// as one light; keep the authored groups even when they match DWG-generated values.
#[test]
fn explicit_dxf_lighting_survives_save_and_reopen() {
let (d, h) = base();
let text = cadcraft_io::write_dxf(&d);
for (enabled, brightness, ambient) in [("1", "0.0", false), ("0", "0.0", false), ("1", "0.25", false), ("1", "0.0", true)] {
let mut groups = vec![(292, enabled.into()), (282, "1".into()), (141, brightness.into()), (142, "0.0".into())];
if ambient {
groups.push((63, "250".into()));
}
let drawing = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
let saved = cadcraft_io::write_dxf(&drawing);
let native = viewport_record(&saved, h);
for (code, value) in &groups {
assert_eq!(group(&native, &code.to_string()).and_then(num), num(value), "native DXF viewport group {code}");
}
let back = cadcraft_io::read_dxf(saved.as_bytes()).unwrap();
let (_, viewport) = the_viewport(&back);
for (code, value) in &groups {
assert!(viewport.extra.iter().any(|t| t.code == *code && num(&t.value) == num(value)), "{code}: {:?}", viewport.extra);
}
}
}
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
#[test]
fn dwg_preserves_explicit_viewport_lighting() {
cadcraft_io::dwg_worker::allow_in_process();
let (d, h) = base();
let text = cadcraft_io::write_dxf(&d);
for (enabled, brightness) in [("1", "0.0"), ("0", "0.0"), ("1", "0.25")] {
let groups = [(292, enabled.into()), (282, "1".into()), (141, brightness.into()), (142, "0.0".into())];
let drawing = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
let bytes = cadcraft_io::write_with(
&drawing,
"lighting.dwg",
&cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2010), binary: false },
)
.unwrap();
let back = cadcraft_io::read(&bytes, "lighting.dwg").unwrap();
let (_, viewport) = the_viewport(&back);
for (code, value) in &groups {
let want = num(value).unwrap();
assert!(viewport.extra.iter().any(|t| t.code == *code && num(&t.value) == Some(want)), "{code}: {:?}", viewport.extra);
}
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_default_dwg_viewport_exports_its_effective_lighting() {
fn a_default_viewport_reads_back_without_ucs_or_extras() {
cadcraft_io::dwg_worker::allow_in_process();
for version in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] {
let (d, _) = base();
@@ -466,17 +406,7 @@ fn a_default_dwg_viewport_exports_its_effective_lighting() {
let (_, viewport) = the_viewport(&back);
assert!(viewport.ucs.is_none(), "{version}: {:?}", viewport.ucs);
assert!(!viewport.ucs_per_viewport, "{version}");
let native = viewport_record(&cadcraft_io::write_dxf(&back), the_viewport(&back).0);
let lighting = [(292, "1"), (282, "1"), (141, "0.0"), (142, "0.0")];
if version >= cadcraft_io::Version::R2007 {
assert_eq!(viewport.extra.len(), lighting.len());
for (code, value) in lighting {
assert_eq!(group(&native, &code.to_string()).and_then(num), num(value), "exported DWG lighting {code}");
}
} else {
assert!(viewport.extra.is_empty(), "{version}: {:?}", viewport.extra);
assert!(group(&native, "282").is_none());
}
assert!(viewport.extra.is_empty(), "{version}: {:?}", viewport.extra);
}
}
@@ -497,11 +427,6 @@ fn a_viewport_with_non_default_snap_keeps_it() {
for code in [14, 24] {
assert_eq!(viewport.extra.iter().find(|t| t.code == code).and_then(|t| num(&t.value)), Some(2.0), "{version}");
}
let extras = viewport.extra.iter().map(|t| t.code).collect::<Vec<_>>();
let mut expected = vec![14, 24];
if version >= cadcraft_io::Version::R2007 {
expected.extend([292, 282, 141, 142]);
}
assert_eq!(extras, expected, "{version}");
assert_eq!(viewport.extra.len(), 2, "only the non-default snap spacing remains: {version}: {:?}", viewport.extra);
}
}
+2 -11
View File
@@ -65,16 +65,7 @@ fn check(bytes: &[u8], name: &str) -> cadcraft_doc::Drawing {
assert_eq!(proxy.payload.bit_count, 9);
assert_eq!(proxy.payload.data(), [0xA5, 0x80]);
assert_eq!(proxy.graphics.data(), [0x12, 0x34, 0x56]);
// The DXF refers to the CLASSES section by ordinal, while the decoder renumbers
// that same proxy against its document class table.
let entities = sections.iter().find(|s| s.name == "ENTITIES").unwrap();
let records = craft_dxf::records(&entities.tags);
let (_, record) = records.iter().find(|(kind, _)| kind == "ACAD_PROXY_ENTITY").unwrap();
let file_id = record.iter().skip_while(|t| t.code != 100 || t.str() != "AcDbProxyEntity").find(|t| t.code == 91).unwrap().i64();
let class = classes.get(usize::try_from(file_id - 500).unwrap()).unwrap();
let decoded_class = decoded.classes.iter().find(|c| i32::from(c.class_number) == proxy.class_id).unwrap();
assert_eq!(decoded_class.dxf_name, "SPDSNOTEPOSITION");
assert_eq!(decoded_class.cpp_class_name, "mcsDbObjectNotePosition");
let class = classes.get(usize::try_from(proxy.class_id - 500).unwrap()).unwrap();
assert!(class.1.iter().any(|t| t.code == 1 && t.str() == "SPDSNOTEPOSITION"));
assert!(class.1.iter().any(|t| t.code == 2 && t.str() == "mcsDbObjectNotePosition"));
drawing
@@ -130,7 +121,7 @@ fn duplicate_names_keep_distinct_classes_for_entities_and_dictionary_objects() {
cadcraft_io::dwg_worker::allow_in_process();
let source = duplicate_class_dxf();
for binary in [false, true] {
let input = if binary { craft_dxf::write_binary(&craft_dxf::parse(&source).unwrap(), true).unwrap() } else { source.clone() };
let input = if binary { craft_dxf::write_binary(&craft_dxf::parse(&source).unwrap(), true) } else { source.clone() };
let mut drawing = cadcraft_io::read(&input, "source.dxf").unwrap();
for _ in 0..3 {
for name in ["copy.dxf", "copy.dwg"] {
-4
View File
@@ -11,10 +11,6 @@ workspace = true
[dependencies]
craft-mcp = { workspace = true }
craft-jsonrpc = { workspace = true }
# The live client: tool calls go to the open window while the ArtCraft Launcher's switch allows it.
craft-control = { workspace = true, features = ["agents"] }
# The challenge handshake of the window's agent server (`craft_automation::security`; no egui without `ui`).
craft-automation = { workspace = true }
cadcraft-engine = { workspace = true }
cadcraft-render = { workspace = true }
cadcraft-io = { workspace = true }
+4 -107
View File
@@ -2,7 +2,6 @@
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{Ipv4Addr, SocketAddr, TcpStream, ToSocketAddrs};
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
@@ -19,9 +18,6 @@ pub trait Backend {
fn has_ui(&self) -> bool;
/// Describe the backend connection for client-facing status.
fn describe(&self) -> String;
/// The `agent_folders` tool's answer: the folders this session may open from and save to, and
/// whether files outside them are refused ([`crate::live::folders_reply`]).
fn agent_folders(&mut self) -> Result<Value, String>;
}
/// A running CADCraft app reached through its loopback control port.
@@ -39,10 +35,6 @@ pub struct Remote {
authed: bool,
/// Longest reply line accepted (`MAX_REPLY_LINE`; smaller in tests).
max_reply: usize,
/// The open window's agent server ([`Remote::signed_in`]): each connection signs in once with
/// the challenge handshake and this token, which never crosses the wire. `None`: the `--control`
/// server, which takes the token from its token file on every request.
handshake: Option<String>,
}
/// The port component of a `HOST:PORT` address, for locating the token file.
@@ -50,15 +42,6 @@ fn port_of(addr: &str) -> Option<u16> {
addr.rsplit(':').next().and_then(|p| p.parse::<u16>().ok())
}
/// How long a reply may take; the app answers a request within its own 60 s deadline.
const REPLY_WAIT: Duration = Duration::from_secs(90);
/// How long each sign-in reply of the agent server may take.
const SIGN_IN_WAIT: Duration = Duration::from_secs(10);
/// Longest sign-in reply read (two nonces and a proof).
const SIGN_IN_REPLY: usize = 64 * 1024;
/// How long a launched app has to open its control port.
const LAUNCH_WAIT: Duration = Duration::from_secs(30);
@@ -84,17 +67,7 @@ fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) ->
impl Remote {
/// Connect to a running control server; its session token is read lazily when the first request is sent.
pub fn connect(addr: &str) -> std::io::Result<Self> {
let mut r = Self::lazy(addr, false);
r.reconnect()?;
Ok(r)
}
/// The open window's agent server at `addr` (`127.0.0.1:<port>` from the connection file the
/// app publishes while the ArtCraft Launcher's switch lets agents in), signed in with the
/// challenge handshake and `token` from the token file it names: the app proves it holds the
/// token before anything derived from it is sent, so a program that took the port of an app
/// that quit learns nothing.
pub fn signed_in(addr: &str, token: String) -> std::io::Result<Self> {
let mut r = Self { handshake: Some(token), ..Self::lazy(addr, false) };
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None, authed: false, max_reply: MAX_REPLY_LINE };
r.reconnect()?;
Ok(r)
}
@@ -102,7 +75,7 @@ impl Remote {
/// the server before the app is open. With `launch`, a call that finds nothing at `addr`
/// opens the app with that control port first (macOS) and waits for it.
pub fn lazy(addr: &str, launch: bool) -> Self {
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE, handshake: None }
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE }
}
/// The per-session token for this port, read (and cached) from the owner-only token file. A
@@ -113,10 +86,6 @@ impl Remote {
/// peer: a name that also resolves elsewhere (`localhost` → `::1`, where another local account
/// may listen on the same port) must not be handed the desktop's credential (CWE-522).
fn token(&mut self) -> Option<&str> {
// The agent server took the handshake: no request carries the token.
if self.handshake.is_some() {
return None;
}
let port = port_of(&self.addr)?;
let peer = self.conn.as_ref().and_then(|(_, s)| s.peer_addr().ok());
if peer != Some(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) {
@@ -162,12 +131,9 @@ impl Remote {
match TcpStream::connect_timeout(&sa, Duration::from_millis(800)) {
Ok(s) => {
s.set_nodelay(true).ok();
s.set_read_timeout(Some(REPLY_WAIT)).ok();
s.set_read_timeout(Some(Duration::from_secs(90))).ok();
let read = s.try_clone()?;
self.conn = Some((BufReader::new(read), s));
if let Some(token) = self.handshake.clone() {
return self.sign_in(&token).inspect_err(|_| self.conn = None);
}
return Ok(());
}
Err(e) => last = e,
@@ -175,52 +141,6 @@ impl Remote {
}
Err(last)
}
/// The challenge handshake of the agent server (`craft_automation::security`) on the new
/// connection: send a nonce, check the app's proof that it holds the token, then send this
/// side's proof.
fn sign_in(&mut self, token: &str) -> std::io::Result<()> {
use craft_automation::security::{AUTH_METHOD, CHALLENGE_METHOD, ProofRole, generate_nonce, handshake_proof, proof_matches};
let addr = self.addr.clone();
let refused =
|why: &str| std::io::Error::new(std::io::ErrorKind::PermissionDenied, format!("CADCraft at {addr} refused the agent connection: {why}"));
let client_nonce = generate_nonce().map_err(|e| std::io::Error::other(e.to_string()))?;
let challenge = self.sign_in_frame(CHALLENGE_METHOD, json!({"clientNonce": client_nonce}))?;
if challenge.get("ok") != Some(&Value::Bool(true)) {
return Err(refused(challenge.get("error").and_then(Value::as_str).unwrap_or("no challenge")));
}
let field = |key: &str| challenge.pointer(&format!("/result/{key}")).and_then(Value::as_str).unwrap_or_default().to_string();
let (server_nonce, server_proof) = (field("serverNonce"), field("serverProof"));
if !proof_matches(token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) {
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
format!("the program on {addr} did not prove it is the CADCraft that published the agent connection; start CADCraft again"),
));
}
let proof = handshake_proof(token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| std::io::Error::other(e.to_string()))?;
let signed = self.sign_in_frame(AUTH_METHOD, json!({"proof": proof}))?;
if signed.get("ok") != Some(&Value::Bool(true)) {
return Err(refused(signed.get("error").and_then(Value::as_str).unwrap_or("authentication failed")));
}
self.authed = true;
Ok(())
}
/// One sign-in frame (id 0; requests count from 1) and its reply, within [`SIGN_IN_WAIT`].
fn sign_in_frame(&mut self, method: &str, params: Value) -> std::io::Result<Value> {
let addr = self.addr.clone();
let Some((reader, writer)) = self.conn.as_mut() else { return Err(std::io::Error::other("not connected")) };
writer.set_read_timeout(Some(SIGN_IN_WAIT)).ok();
writeln!(writer, "{}", json!({"id": 0, "method": method, "params": params}))?;
writer.flush()?;
let mut reply = String::new();
let n = read_reply_line(reader, &mut reply, SIGN_IN_REPLY)?;
writer.set_read_timeout(Some(REPLY_WAIT)).ok();
if n == 0 {
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, format!("{addr} closed the connection during the sign-in")));
}
serde_json::from_str(&reply).map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidData, format!("{addr} did not answer the sign-in; is that CADCraft's agent connection?"))
})
}
/// On failure the flag says whether the request may already have reached the server.
fn roundtrip(&mut self, line: &str) -> Result<String, (std::io::Error, bool)> {
if self.conn.is_none() {
@@ -310,11 +230,6 @@ impl Remote {
}
self.set_token(req);
let line = req.to_string();
// The agent server refuses a longer line and closes the connection; nothing was sent.
if self.handshake.is_some() && line.len() > craft_automation::security::MAX_REQUEST_BYTES {
let why = format!("the request is longer than the {} bytes the agent connection takes", craft_automation::security::MAX_REQUEST_BYTES);
return Err((std::io::Error::new(std::io::ErrorKind::InvalidInput, why), false));
}
if !self.authed && line.len() > crate::control_token::MAX_UNAUTHENTICATED_LINE {
let mut ping = json!({"id": req.get("id").cloned().unwrap_or(Value::Null), "method": "ping"});
self.set_token(&mut ping);
@@ -418,18 +333,7 @@ impl Backend for Remote {
}
/// What this backend talks to, for messages.
fn describe(&self) -> String {
if self.handshake.is_some() {
format!("the open CADCraft window at {}", self.addr)
} else {
format!("connected to CADCraft at {}", self.addr)
}
}
/// The window's agent server holds requests to Options › AI Agents' folders; `--control` to none.
fn agent_folders(&mut self) -> Result<Value, String> {
if self.handshake.is_some() {
return Err("the window holds agents to the folders of Options › AI Agents; `cadcraft-cli mcp` answers `agent_folders` for it".into());
}
Ok(crate::live::folders_reply(&craft_control::agents::AgentFolders::default(), false))
format!("connected to CADCraft at {}", self.addr)
}
}
@@ -621,13 +525,6 @@ impl Backend for Headless {
fn describe(&self) -> String {
"headless CADCraft session".into()
}
/// The automation roots it runs in, if any.
fn agent_folders(&mut self) -> Result<Value, String> {
let mut folders = craft_control::agents::AgentFolders::default();
folders.read = self.roots.as_ref().and_then(|r| r.read_root().map(Path::to_path_buf));
folders.write = self.roots.as_ref().and_then(|r| r.write_root().map(Path::to_path_buf));
Ok(crate::live::folders_reply(&folders, self.roots.is_some()))
}
}
#[cfg(test)]
-2
View File
@@ -11,12 +11,10 @@
pub mod args;
mod backend;
pub mod control_token;
pub mod live;
mod server;
mod tools;
pub use backend::{Backend, Headless, Remote};
pub use live::{Live, LiveConfig};
pub use server::{PROTOCOL_VERSION, Server};
#[cfg(test)]
-344
View File
@@ -1,344 +0,0 @@
//! Plain `cadcraft-cli mcp` with the suite's `AI-MCP` flag: tools go to the open CADCraft window
//! while the ArtCraft Launcher's switch lets agents use it, found through the connection file the
//! app publishes in its settings folder, and otherwise to a session without a window, as `mcp`
//! always did (`--headless` forces that). The file is read again on every tool call, so the app may
//! start, quit or move to another port while the MCP client stays connected; the client's
//! configuration holds no port and no token.
//!
//! While agents may use the app but it is closed, Options › AI Agents › When CADCraft is closed (or
//! `--when-closed`) decides: start the app and wait for it, work without a window, or an error that
//! says what to do. A session that went headless stays headless for the rest of the MCP session, so
//! the drawing doesn't move under the agent.
//!
//! The lookup is the framework's, shared by every Craft app ([`craft_control::agents::Live`]); this
//! module supplies CADCraft's parts: where its settings are, its window client
//! ([`Remote::signed_in`]) and its headless session ([`Headless`]).
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use cadcraft_engine::agent_settings;
use cadcraft_engine::file_access::AutomationRoots;
use craft_control::agents::{self, AgentFolders, Consent, HeadlessFolders, Route, Window};
use serde_json::{Value, json};
pub use craft_control::agents::{LAUNCH_TIMEOUT, LaunchFn, WhenAppClosed, mcp_flag};
use crate::backend::{Backend, Headless, Remote};
/// The id the ArtCraft Launcher's app list names CADCraft by (its catalog id).
pub const LAUNCHER_APP_ID: &str = "cadcraft";
/// The app's name in the lookup's messages and in its default agent folder,
/// `Documents/ArtCraft/Agents/CADCraft`.
pub const APP_NAME: &str = "CADCraft";
/// The desktop app's file name beside the CLI (without `.exe`).
const APP_EXE: &str = "cadcraft";
/// Whether agents may use the open window now: with the suite's `AI-MCP` flag, the ArtCraft
/// Launcher's switch. CADCraft had no agent consent of its own before the switch (`--control` is a
/// launch option, not a consent), so without the flag agents get no window this way.
pub fn agents_allowed_now() -> bool {
agents::agents_allowed(agents::mcp_flag(), agents::launcher_allows(LAUNCHER_APP_ID), false)
}
/// The default agent folder, `Documents/ArtCraft/Agents/CADCraft`.
pub fn default_folder() -> Option<PathBuf> {
agents::default_folder(APP_NAME)
}
/// The folders the open window holds agent requests to: Options › AI Agents' folders, the default
/// agent folder for an empty one (made when used). The app uses the same.
pub fn window_folders(settings: &agent_settings::AgentSettings, default: Option<&Path>) -> AgentFolders {
settings.folders_with(default)
}
/// The `agent_folders` tool's answer: the folders, and whether files outside them are refused.
pub fn folders_reply(folders: &AgentFolders, confined: bool) -> Value {
let mut answer = agents::folders_answer(folders);
answer["confined"] = json!(confined);
if !confined {
answer["note"] = json!("This session is not held to folders: keep to the files the person gave you.");
}
answer
}
/// What [`Live`] needs from the CLI.
pub struct LiveConfig {
/// The app's settings folder: its connection file, token file and agent settings.
pub config_dir: PathBuf,
/// Overrides the app's closed-app choice (`--when-closed`).
pub when_closed: Option<WhenAppClosed>,
/// The CLI's `--automation-read-root` and `--automation-write-root`.
pub read_root: Option<PathBuf>,
pub write_root: Option<PathBuf>,
/// Starts the app; `None` when this install can't (no app beside the CLI).
pub launch: Option<LaunchFn>,
pub launch_timeout: Duration,
/// Whether the person lets agents use the open app ([`agents_allowed_now`]); tests replace it.
pub allowed: fn() -> bool,
/// The default agent folder for an empty folder setting ([`default_folder`]); tests replace it.
pub default_folder: Option<PathBuf>,
}
impl LiveConfig {
/// The lookup for the app with its settings in `config_dir`.
pub fn new(config_dir: PathBuf) -> Self {
LiveConfig {
config_dir,
when_closed: None,
read_root: None,
write_root: None,
launch: None,
launch_timeout: LAUNCH_TIMEOUT,
allowed: agents_allowed_now,
default_folder: default_folder(),
}
}
}
/// A session without a window and the folders it is held to.
struct HeadlessSession {
backend: Headless,
folders: AgentFolders,
confined: bool,
}
type Shared = agents::Live<Arc<Mutex<Remote>>, Arc<Mutex<HeadlessSession>>>;
/// The backend of plain `cadcraft-cli mcp` with the `AI-MCP` flag: each call goes where
/// [`craft_control::agents::Live::resolve`] says.
pub struct Live {
shared: Shared,
config_dir: PathBuf,
default_folder: Option<PathBuf>,
allowed: fn() -> bool,
}
impl Live {
/// The lookup with `cfg`; nothing is looked up until the first call.
pub fn new(cfg: LiveConfig) -> Self {
let LiveConfig { config_dir, when_closed, read_root, write_root, launch, launch_timeout, allowed, default_folder } = cfg;
let consent = move |dir: &Path| Consent::new(allowed(), agent_settings::load(dir));
let connect = |w: &Window| Remote::signed_in(&w.addr(), w.token.clone()).map(|r| Arc::new(Mutex::new(r))).map_err(|e| e.to_string());
let headless = move |folders: &HeadlessFolders| headless_session(folders, allowed()).map(|h| Arc::new(Mutex::new(h)));
let mut shared = agents::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, headless);
shared.when_closed = when_closed;
shared.read_roots = read_root.into_iter().collect();
shared.write_root = write_root;
shared.launch = launch;
shared.launch_timeout = launch_timeout;
shared.default_folder = default_folder.clone();
Live { shared: agents::Live::new(shared), config_dir, default_folder, allowed }
}
}
/// The headless session for `folders`. Without folders it is held to none, as `mcp` always was,
/// unless agents are `allowed`: then the folders are the app's agent folders, and having none
/// (the default folder couldn't be made) refuses every file rather than none.
fn headless_session(folders: &HeadlessFolders, allowed: bool) -> Result<HeadlessSession, String> {
// The CLI takes one read root, and the agent settings name one read folder.
let read = folders.read.first().map(PathBuf::as_path);
let write = folders.write.as_deref();
let roots = match AutomationRoots::new(read, write)? {
Some(roots) => Some(roots),
None if allowed => Some(AutomationRoots::none()),
None => None,
};
let mut shown = AgentFolders::default();
shown.read = read.map(Path::to_path_buf);
shown.write = write.map(Path::to_path_buf);
Ok(HeadlessSession { confined: roots.is_some(), backend: Headless::default().with_automation_roots(roots), folders: shown })
}
impl Backend for Live {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
match self.shared.resolve()? {
Route::Window(window) => window.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
Route::Headless(session) => session.lock().unwrap_or_else(PoisonError::into_inner).backend.call(method, params),
}
}
/// A window may answer while agents are allowed and the session hasn't gone headless.
fn has_ui(&self) -> bool {
match self.shared.current() {
Some(Route::Window(_)) => true,
Some(Route::Headless(_)) => false,
None => (self.allowed)(),
}
}
fn describe(&self) -> String {
match self.shared.current() {
Some(Route::Window(window)) => window.lock().unwrap_or_else(PoisonError::into_inner).describe(),
Some(Route::Headless(session)) => session.lock().unwrap_or_else(PoisonError::into_inner).backend.describe(),
None => "the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it, otherwise a headless session".into(),
}
}
fn agent_folders(&mut self) -> Result<Value, String> {
match self.shared.resolve()? {
Route::Window(_) => {
let settings = agent_settings::load(&self.config_dir);
Ok(folders_reply(&window_folders(&settings, self.default_folder.as_deref()), true))
}
Route::Headless(session) => {
let session = session.lock().unwrap_or_else(PoisonError::into_inner);
Ok(folders_reply(&session.folders, session.confined))
}
}
}
}
/// How to start the desktop app that ships with the CLI at `cli` (detached, with no standard
/// streams: the CLI's carry the MCP protocol, and the app must outlive the MCP client).
pub fn launcher(cli: &Path) -> Option<LaunchFn> {
agents::launcher(cli, APP_EXE)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use craft_automation::security::{AuthStep, ServerHandshake};
use craft_control::agents::{Connection, TOKEN_FILE, write_connection};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const OTHER: &str = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210";
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("cadcraft-live-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// A stand-in for the window's agent server (`craft_automation::server`): the challenge
/// handshake with `token`, then every request answered `{"window": true}`. Returns the port and
/// every line it read.
fn agent_server(token: &'static str) -> (u16, Arc<Mutex<Vec<Value>>>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let seen = Arc::new(Mutex::new(Vec::new()));
let log = Arc::clone(&seen);
std::thread::spawn(move || {
for conn in listener.incoming() {
let Ok(conn) = conn else { continue };
let log = Arc::clone(&log);
std::thread::spawn(move || {
let mut out = conn.try_clone().unwrap();
let mut handshake = ServerHandshake::new();
let mut signed_in = false;
for line in BufReader::new(conn).lines() {
let Ok(line) = line else { return };
let req: Value = serde_json::from_str(&line).unwrap();
log.lock().unwrap().push(req.clone());
let reply = if signed_in {
json!({"id": req["id"], "ok": true, "result": {"window": true}})
} else {
let (reply, step) = handshake.reply(&line, token);
signed_in = step == AuthStep::Authenticated;
if step == AuthStep::Rejected {
let _ = writeln!(out, "{reply}");
return;
}
reply
};
if writeln!(out, "{reply}").is_err() {
return;
}
}
});
}
});
(port, seen)
}
/// Publish a window on `port` in `dir` with `token` in its token file, as the app's link does.
fn publish(dir: &Path, port: u16, token: &str) {
let token_file = dir.join(TOKEN_FILE);
std::fs::write(&token_file, token).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&token_file, std::fs::Permissions::from_mode(0o600)).unwrap();
}
write_connection(dir, &Connection::new(port, token_file, "CADCraft test")).unwrap();
}
fn live(dir: &Path, allowed: fn() -> bool, when_closed: Option<WhenAppClosed>) -> Live {
let mut cfg = LiveConfig::new(dir.to_path_buf());
cfg.allowed = allowed;
cfg.when_closed = when_closed;
cfg.default_folder = Some(dir.join("Agents"));
Live::new(cfg)
}
/// With the window published, calls go to it after the challenge handshake, and nothing sent
/// carries the token.
#[test]
fn live_calls_go_to_the_open_window_while_the_switch_allows() {
let dir = temp("window");
let (port, seen) = agent_server(TOKEN);
publish(&dir, port, TOKEN);
let mut live = live(&dir, || true, None);
assert_eq!(live.call("ping", json!({})), Ok(json!({"window": true})));
assert_eq!(live.call("drawing.inspect", json!({})), Ok(json!({"window": true})));
assert!(live.has_ui());
let seen = seen.lock().unwrap();
assert!(seen.iter().any(|req| req["method"] == "drawing.inspect"), "{seen:?}");
assert!(!serde_json::to_string(&*seen).unwrap().contains(TOKEN), "the token crossed the wire: {seen:?}");
drop(seen);
let _ = std::fs::remove_dir_all(dir);
}
/// While the launcher's switch doesn't let agents in and no window is published, calls work
/// without a window, as plain `mcp` always did, held to no folders the command didn't give.
#[test]
fn live_without_the_switch_works_without_a_window() {
let dir = temp("no-switch");
let mut live = live(&dir, || false, None);
assert_eq!(live.call("ping", json!({})), Ok(json!("pong")));
assert!(!live.has_ui());
assert_eq!(live.agent_folders().unwrap()["confined"], json!(false));
let _ = std::fs::remove_dir_all(dir);
}
/// A connection file a crashed app left behind (nothing listens on its port) is not a window:
/// the closed-app choice decides, and a headless session is held to the agent folders.
#[test]
fn live_with_the_app_closed_follows_the_closed_app_choice() {
let dir = temp("closed");
let gone = TcpListener::bind("127.0.0.1:0").unwrap();
let port = gone.local_addr().unwrap().port();
drop(gone);
publish(&dir, port, TOKEN);
let err = live(&dir, || true, Some(WhenAppClosed::Error)).call("ping", json!({})).unwrap_err();
assert!(err.contains("isn't running"), "{err}");
let mut headless = live(&dir, || true, Some(WhenAppClosed::Headless));
assert_eq!(headless.call("ping", json!({})), Ok(json!("pong")));
let folders = headless.agent_folders().unwrap();
assert_eq!(folders["confined"], json!(true));
assert_eq!(folders["write_folder"], json!(dir.join("Agents").to_string_lossy()));
let outside = dir.parent().unwrap().join("outside.png");
let err = headless.call("ui.render", json!({"path": outside.to_string_lossy()})).unwrap_err();
assert!(err.contains("outside the write root"), "a file outside the agent folder is refused: {err}");
let inside = dir.join("Agents").join("plan.png");
assert!(headless.call("ui.render", json!({"path": inside.to_string_lossy()})).is_ok(), "one inside it is written");
let _ = std::fs::remove_dir_all(dir);
}
/// A program on the published port that doesn't hold the token gets nothing from the client:
/// it can't prove itself, so no request is sent.
#[test]
fn a_window_without_the_token_is_refused() {
let dir = temp("bad-token");
let (port, seen) = agent_server(OTHER);
publish(&dir, port, TOKEN);
let err = live(&dir, || true, Some(WhenAppClosed::Error)).call("drawing.inspect", json!({})).unwrap_err();
assert!(err.contains("did not prove"), "{err}");
assert!(seen.lock().unwrap().iter().all(|req| req["method"] != "drawing.inspect"));
let _ = std::fs::remove_dir_all(dir);
}
}
-2
View File
@@ -38,7 +38,6 @@ pub fn tool_definitions(has_ui: bool) -> Value {
json!({"name": "open", "description": "Open a DXF or DWG file.", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}),
json!({"name": "save", "description": "Save the drawing (DXF or DWG by extension). A .svg, .png or .pdf path exports instead: the drawing keeps its name and unsaved changes.", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}}),
json!({"name": "cancel", "description": "Press Escape: cancel the running command (or clear the selection).", "inputSchema": {"type": "object", "properties": {}}}),
craft_control::agents::folders_tool(),
];
if has_ui {
tools.push(json!({"name": "screenshot", "description": "Screenshot the CADCraft window (PNG).", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}}));
@@ -138,7 +137,6 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Result<Value,
"open" => b.call("app.open", a),
"save" => b.call("app.save", a),
"cancel" => b.call("cmdline.key", json!({"key": "escape"})),
craft_control::agents::FOLDERS_TOOL => b.agent_folders(),
"screenshot" => b.call("ui.screenshot", a),
"ui_inspect" => b.call("ui.inspect", json!({})),
"ui_click" => b.call("ui.pointer", a),
-3
View File
@@ -37,9 +37,6 @@ web-time = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-update = { workspace = true }
# Agents in the open window: the agent link host and the Agents page of Options.
craft-automation = { workspace = true, features = ["ui", "agents"] }
craft-control = { workspace = true, features = ["agents"] }
[dev-dependencies]
# `Updater::ready_for_tests`.

Some files were not shown because too many files have changed in this diff Show More