mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-06 04:37:16 -06:00
Compare commits
90
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
787864e056 | ||
|
|
c7543246df | ||
|
|
2b392c34de | ||
|
|
0fcbe92a45 | ||
|
|
7adf543923 | ||
|
|
e07c3f0c11 | ||
|
|
6eb4096e38 | ||
|
|
8c98078687 | ||
|
|
9a1c0919e4 | ||
|
|
3fb4b51f0f | ||
|
|
3825b49f9e | ||
|
|
e3feeacabb | ||
|
|
56b496d9e8 | ||
|
|
c6a6a3ab96 | ||
|
|
26bd9f171d | ||
|
|
c556983869 | ||
|
|
2d08ea7b74 | ||
|
|
976d2357ff | ||
|
|
4dc420ab90 | ||
|
|
9d85a971f4 | ||
|
|
40d4098375 | ||
|
|
a24fb6f930 | ||
|
|
586f3d38b5 | ||
|
|
d327547208 | ||
|
|
246aaf35de | ||
|
|
c15cec8a98 | ||
|
|
5586822f8a | ||
|
|
f48ae711e1 | ||
|
|
f78ca4e722 | ||
|
|
52ab5d2549 | ||
|
|
3b95d0510c | ||
|
|
07bec9df31 | ||
|
|
e785adb63d | ||
|
|
c870f83900 | ||
|
|
0be750a98a | ||
|
|
55703a9ff7 | ||
|
|
20ad85efc4 | ||
|
|
d9f7de77e0 | ||
|
|
db4f07655b | ||
|
|
5c2a897abc | ||
|
|
b760962907 | ||
|
|
489df47647 | ||
|
|
23354c91f5 | ||
|
|
901e5fb6fd | ||
|
|
16b3732b63 | ||
|
|
272dc5cecf | ||
|
|
c6974ad9dd | ||
|
|
bf0936ff65 | ||
|
|
489d873a50 | ||
|
|
f70e167f7f | ||
|
|
6f0dfa7b18 | ||
|
|
41928f5611 | ||
|
|
f9c31fe169 | ||
|
|
9f7d3fa401 | ||
|
|
9ecbd92d56 | ||
|
|
526238ef8f | ||
|
|
d371a7e372 | ||
|
|
79b2c24e2d | ||
|
|
443a6d6d74 | ||
|
|
a356c4977a | ||
|
|
2cad9407dc | ||
|
|
7007b3eed8 | ||
|
|
c17363df01 | ||
|
|
0231ab7d2e | ||
|
|
733c4ee649 | ||
|
|
cdb6ce8542 | ||
|
|
d77d1b9e22 | ||
|
|
511ef31b59 | ||
|
|
c9149c1f67 | ||
|
|
959162f991 | ||
|
|
fd1d588044 | ||
|
|
b3e8d8fb7a | ||
|
|
250c9ddb83 | ||
|
|
641c54d575 | ||
|
|
ea0c22bcf5 | ||
|
|
079e1f102f | ||
|
|
37f54e0087 | ||
|
|
a11576dc92 | ||
|
|
1193084a9c | ||
|
|
a3871bd612 | ||
|
|
da13daf1a8 | ||
|
|
b34a7cc912 | ||
|
|
d3ae923cf8 | ||
|
|
5603be4f8b | ||
|
|
067df21392 | ||
|
|
6f09cc7189 | ||
|
|
7a78095756 | ||
|
|
d22cfde29d | ||
|
|
000b28315a | ||
|
|
c6c2413c39 |
+3
-2
@@ -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.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. |
|
||||
| `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. |
|
||||
| `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,6 +89,7 @@ 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
+395
-137
File diff suppressed because it is too large
Load Diff
+43
-38
@@ -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 = "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" }
|
||||
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" }
|
||||
cadcraft-color = { path = "crates/color" }
|
||||
cadcraft-doc = { path = "crates/doc" }
|
||||
cadcraft-constraints = { path = "crates/constraints" }
|
||||
@@ -31,19 +31,24 @@ 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 = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
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" }
|
||||
# SVG/SVGZ import and export geometry (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
|
||||
# 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 = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
|
||||
# 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 = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", default-features = false }
|
||||
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", default-features = false }
|
||||
# Delimited text (CSV/TSV) parsing (shared Craft library).
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4.6.11"
|
||||
clap_mangen = { version = "0.3.3", features = ["env"] }
|
||||
@@ -77,12 +82,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 = "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"] }
|
||||
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"] }
|
||||
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 }
|
||||
@@ -93,7 +98,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 = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", features = ["ui"] }
|
||||
rfd = "0.18"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
@@ -125,27 +130,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 = "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" }
|
||||
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" }
|
||||
|
||||
# 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 = "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" }
|
||||
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" }
|
||||
|
||||
@@ -10,11 +10,10 @@ 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, 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.
|
||||
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/.
|
||||
|
||||
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.
|
||||
@@ -432,13 +431,12 @@ SOFTWARE.
|
||||
|
||||
## DWG Format References
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
|
||||
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
|
||||
|
||||
@@ -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), 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), Finnish (Suomi), 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,6 +412,9 @@ 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` |
|
||||
|
||||
@@ -11,6 +11,7 @@ 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;
|
||||
@@ -262,12 +263,23 @@ pub(crate) struct CommandsArgs {
|
||||
pub(crate) compact: bool,
|
||||
}
|
||||
|
||||
/// Run the MCP server on stdio: a headless drawing session, or a bridge to the running app
|
||||
/// 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
|
||||
#[derive(Args)]
|
||||
pub(crate) struct McpArgs {
|
||||
/// Bridge to the app's control channel (its --control port, e.g. 127.0.0.1:7979)
|
||||
/// 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
|
||||
#[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")]
|
||||
@@ -404,6 +416,8 @@ 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).
|
||||
@@ -523,8 +537,12 @@ fn out_is_input(cli: &Cli) -> Option<UsageError> {
|
||||
/// The backend `cadcraft-cli mcp` serves from.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum McpTarget {
|
||||
/// An in-process drawing session (no `--connect`), optionally confined to the two folders.
|
||||
/// An in-process drawing session (`--headless`), 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 },
|
||||
@@ -533,10 +551,12 @@ 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 => McpTarget::Headless { read_root: self.automation_read_root.clone(), write_root: self.automation_write_root.clone() },
|
||||
None if self.headless => McpTarget::Headless { read_root, write_root },
|
||||
None => McpTarget::Live { read_root, write_root, when_closed: self.when_closed },
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -553,6 +573,11 @@ 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();
|
||||
@@ -665,10 +690,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Without `--connect` the server runs headless, confining nothing unless asked.
|
||||
/// Plain `mcp` looks for the open window (headless while the launcher doesn't let agents in);
|
||||
/// `--headless` never does. Neither confines anything unless asked.
|
||||
#[test]
|
||||
fn mcp_without_connect_is_headless() {
|
||||
assert_eq!(mcp(&[]).unwrap(), McpTarget::Headless { read_root: None, write_root: None });
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The automation roots confine a headless server; `--connect` is refused with the reason
|
||||
@@ -676,9 +712,13 @@ mod tests {
|
||||
#[test]
|
||||
fn mcp_automation_roots_confine_a_headless_server_only() {
|
||||
assert_eq!(
|
||||
mcp(&["--automation-read-root", "/work", "--automation-write-root=/work/out"]).unwrap(),
|
||||
mcp(&["--headless", "--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();
|
||||
|
||||
@@ -1,25 +1,96 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::args::{McpArgs, McpTarget};
|
||||
use super::error::{CliError, Result};
|
||||
|
||||
/// Serve MCP on stdin and stdout against the running app or a headless session held to any roots given.
|
||||
/// 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.
|
||||
pub(crate) fn mcp(a: &McpArgs) -> Result {
|
||||
let backend: Box<dyn cadcraft_mcp::Backend> = match a.target() {
|
||||
McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)),
|
||||
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::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::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,6 +14,9 @@ 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())
|
||||
@@ -81,6 +84,8 @@ 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]
|
||||
|
||||
@@ -151,7 +151,9 @@ fn subcommand_help_requests() {
|
||||
"mcp --help",
|
||||
&["mcp", "--help"],
|
||||
0,
|
||||
Line("Run the MCP server on stdio: a headless drawing session, or a bridge to the running app"),
|
||||
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",
|
||||
),
|
||||
Empty,
|
||||
),
|
||||
case(
|
||||
|
||||
@@ -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 = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
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" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -53,13 +53,15 @@ 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 = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", 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"] }
|
||||
|
||||
@@ -428,6 +428,32 @@ 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()
|
||||
@@ -768,6 +794,7 @@ 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!({}));
|
||||
}
|
||||
|
||||
@@ -233,6 +233,39 @@ 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 {
|
||||
@@ -346,6 +379,14 @@ 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 {
|
||||
|
||||
+9
-12
@@ -367,19 +367,16 @@ 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) {
|
||||
// Text style and arrow block names compare without case.
|
||||
// An empty dimension linetype names ByBlock. DWG can spell that builtin explicitly.
|
||||
(Some(serde_json::Value::String(a)), serde_json::Value::String(b))
|
||||
if matches!(
|
||||
*field,
|
||||
"textStyle"
|
||||
| "arrowBlock"
|
||||
| "arrowBlock1"
|
||||
| "arrowBlock2"
|
||||
| "leaderArrowBlock"
|
||||
| "dimLinetype"
|
||||
| "extLinetype1"
|
||||
| "extLinetype2"
|
||||
) =>
|
||||
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") =>
|
||||
{
|
||||
a.eq_ignore_ascii_case(b)
|
||||
}
|
||||
|
||||
@@ -1160,3 +1160,21 @@ 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"))]));
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
cadcraft-geom = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
cadcraft-color = { workspace = true }
|
||||
cadcraft-doc = { workspace = true }
|
||||
craft-mime = { workspace = true }
|
||||
@@ -19,6 +20,8 @@ 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 }
|
||||
@@ -29,6 +32,10 @@ rstar = { version = "0.14", default-features = false }
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
# The computer's time zone for vl-file-systime; the web build has no file times, so no clock there.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
chrono = { workspace = true, features = ["clock"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# Real DXF files for the external reference tests (io is a lower layer).
|
||||
cadcraft-io = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
//! 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();
|
||||
}
|
||||
}
|
||||
@@ -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_of, dim, pick_at};
|
||||
use common::{DimText, add_dim, assoc_enabled, circle_at, circle_of, dim};
|
||||
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};
|
||||
|
||||
@@ -120,6 +120,62 @@ 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 {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::common::{DimText, add_dim, circle_of, dim, pick_at, text_at};
|
||||
use super::common::{DimText, add_dim, circle_at, circle_of, dim, 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 pick_at(s, p).and_then(|h| circle_of(s, h)) {
|
||||
match circle_at(s, p) {
|
||||
Some(t) => self.target = Some(t),
|
||||
None => s.echo("Object selected is not a circle or arc."),
|
||||
}
|
||||
|
||||
@@ -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_of, dim, dims_of, pick_at};
|
||||
use super::{DimText, add_dim, circle_at, circle_of, dim, dims_of};
|
||||
|
||||
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 pick_at(s, p).and_then(|h| circle_of(s, h)) {
|
||||
(None, _, _, Input::Point(p)) => match circle_at(s, p) {
|
||||
Some(t) => self.circle = Some(t),
|
||||
None => s.echo("Object selected is not a circle or arc."),
|
||||
},
|
||||
|
||||
@@ -604,24 +604,26 @@ 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| 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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- splines ----------------
|
||||
|
||||
@@ -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?}").noundo(),
|
||||
CommandSpec::new("qsave", "Save", run_qsave_reporting).menu(&["File", "Save"]).key("Cmd+S").alias(&["save"]).params("{path?, overwrite?: bool}").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)}",
|
||||
"{path, version?: 2000|2004|2007|2010|2013|2018, binary?: bool, portableFonts?: bool (Windows fonts for Linux ones, in this file), overwrite?: bool}",
|
||||
)
|
||||
.noundo(),
|
||||
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
|
||||
@@ -483,6 +483,7 @@ 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.
|
||||
@@ -513,8 +514,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 } = f;
|
||||
let i = add_read(s, drawing, binary_dxf, &name, path);
|
||||
let ReadFile { drawing, binary_dxf, name, path, disk } = f;
|
||||
let i = add_read(s, drawing, binary_dxf, &name, path, disk);
|
||||
super::blocks::xref::after_open(s, i);
|
||||
super::image::after_open(s, i);
|
||||
Ok(opened(s, i, true))
|
||||
@@ -548,15 +549,24 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option<String>) -> Result<ReadFile
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(ReadFile { drawing, binary_dxf: craft_dxf::is_binary(bytes), name: name.to_string(), path })
|
||||
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 })
|
||||
}
|
||||
|
||||
fn add_read(s: &mut Session, drawing: Drawing, binary_dxf: bool, name: &str, path: Option<String>) -> usize {
|
||||
fn add_read(
|
||||
s: &mut Session,
|
||||
drawing: Drawing,
|
||||
binary_dxf: bool,
|
||||
name: &str,
|
||||
path: Option<String>,
|
||||
disk: Option<crate::disk_stamp::DiskStamp>,
|
||||
) -> 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);
|
||||
@@ -565,8 +575,8 @@ fn add_read(s: &mut Session, drawing: Drawing, binary_dxf: bool, name: &str, pat
|
||||
}
|
||||
|
||||
pub(crate) fn open_bytes(s: &mut Session, bytes: &[u8], name: &str, path: Option<String>) -> Result<usize> {
|
||||
let ReadFile { drawing, binary_dxf, name, path } = read_bytes(bytes, name, path)?;
|
||||
Ok(add_read(s, drawing, binary_dxf, &name, path))
|
||||
let ReadFile { drawing, binary_dxf, name, path, disk } = read_bytes(bytes, name, path)?;
|
||||
Ok(add_read(s, drawing, binary_dxf, &name, path, disk))
|
||||
}
|
||||
|
||||
/// OPEN's reply: the drawing's index and what reading it left out.
|
||||
@@ -669,18 +679,90 @@ fn run_closeall(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<(usize, Vec<String>)> {
|
||||
pub(crate) fn save_to(s: &mut Session, path: &str, overwrite: bool) -> Result<(usize, Vec<String>)> {
|
||||
let opts = SaveAs { binary: s.state()?.binary_dxf && is_dxf(path), ..SaveAs::default() };
|
||||
save_as(s, "save", path, &opts)
|
||||
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 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) -> Result<(usize, Vec<String>)> {
|
||||
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs, overwrite: bool) -> 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()?;
|
||||
@@ -974,6 +1056,7 @@ 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())
|
||||
@@ -993,7 +1076,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)?;
|
||||
let (n, notes) = save_to(s, &path, overwrite_param("qsave", p)?)?;
|
||||
let mut r = saved(&path, n);
|
||||
report_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
@@ -1002,7 +1085,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)?;
|
||||
let (n, notes) = save_as(s, "saveas", &path, &opts, overwrite_param("saveas", p)?)?;
|
||||
let mut r = saved(&path, n);
|
||||
report_notes(s, &mut r, notes);
|
||||
if is_drawing_file(&path) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Layouts, paper-space viewports, page setup and plotting: LAYOUT (new/delete/rename/copy/saveas),
|
||||
//! MVIEW / VPORTS, viewport scale/lock/layer settings, PAGESETUP, PLOT and EXPORTPDF.
|
||||
//! MVIEW / VPORTS, viewport scale/lock/layer settings, PAGESETUP / -PAGESETUP, PLOT / -PLOT and
|
||||
//! EXPORTPDF.
|
||||
//!
|
||||
//! Plotting goes through the host's [`super::file::IoHooks::plot`] hook so the engine stays
|
||||
//! I/O-agnostic.
|
||||
@@ -14,6 +15,7 @@ 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;
|
||||
@@ -92,6 +94,12 @@ 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
@@ -1,7 +1,8 @@
|
||||
use cadcraft_doc::Drawing;
|
||||
use cadcraft_geom::Bounds2;
|
||||
|
||||
use super::{
|
||||
Arc, EngineError, Entity, EntityKind, Handle, Line, PolyVertex, Polyline, Prim, Result, Segment, Session, TAU, Vec2, angle_in_sweep, arc,
|
||||
Arc, EngineError, Entity, EntityKind, Handle, Line, Mat3, PolyVertex, Polyline, Prim, Result, Segment, Session, TAU, Vec2, angle_in_sweep, arc,
|
||||
ccw_sweep, intersect_ext, line, lwpoly, norm_angle,
|
||||
};
|
||||
|
||||
@@ -34,15 +35,17 @@ 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| {
|
||||
if edges.implied
|
||||
&& let Some(segs) = implied_edge(kind)
|
||||
{
|
||||
out.extend(segs);
|
||||
return;
|
||||
}
|
||||
for p in kind.prims() {
|
||||
out.extend(prim_to_segments(&p));
|
||||
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)));
|
||||
}
|
||||
};
|
||||
// An object is an edge when it is one of `edges.only` (all of them: `None`). A trim leaves
|
||||
@@ -84,15 +87,56 @@ pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, ove
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `k` as an implied edge (EDGEMODE 1), for lines, arcs and open polylines.
|
||||
fn implied_edge(k: &EntityKind) -> Option<Vec<Segment>> {
|
||||
/// 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>> {
|
||||
const FAR: f64 = 1e8;
|
||||
let whole = |a: &Arc| Segment::Arc { arc: Arc { start: 0.0, end: TAU - 1e-12, ..*a }, ccw: true };
|
||||
let whole = |a: &Arc| placed(&Prim::Seg(Segment::Arc { arc: Arc { start: 0.0, end: TAU - 1e-12, ..*a }, ccw: true }), place);
|
||||
// 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 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 }))
|
||||
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 })))
|
||||
}
|
||||
Segment::Arc { arc, .. } => whole(&arc),
|
||||
};
|
||||
@@ -100,14 +144,14 @@ fn implied_edge(k: &EntityKind) -> Option<Vec<Segment>> {
|
||||
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 mut segs = Polyline { vertices: p.vertices.clone(), closed: false }.segments();
|
||||
let segs = Polyline { vertices: p.vertices.clone(), closed: false }.segments();
|
||||
let last = segs.len().checked_sub(1)?;
|
||||
for (i, sg) in segs.iter_mut().enumerate() {
|
||||
if i == 0 || i == last {
|
||||
*sg = run_on(*sg, i == 0, i == last);
|
||||
}
|
||||
}
|
||||
Some(segs)
|
||||
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(),
|
||||
)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
|
||||
@@ -137,9 +137,9 @@ pub(super) fn lengthen_spline(sp: &Spline, pick: Option<Vec2>, mode: LenMode) ->
|
||||
} else if target >= len - 1e-12 {
|
||||
sp.clone()
|
||||
} else if at_end {
|
||||
sp.sub_between(lo, sp.param_at_length(lo, target)).ok_or_else(fail)?
|
||||
sp.sub_between(lo, sp.param_at_length(lo, target).ok_or_else(fail)?).ok_or_else(fail)?
|
||||
} else {
|
||||
sp.sub_between(sp.param_at_length(hi, -target), hi).ok_or_else(fail)?
|
||||
sp.sub_between(sp.param_at_length(hi, -target).ok_or_else(fail)?, hi).ok_or_else(fail)?
|
||||
};
|
||||
Ok(EntityKind::Spline(out))
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ pub const PROFILE_VARS: &[&str] = &[
|
||||
"QPMODE",
|
||||
"SELECTIONEFFECT",
|
||||
"SELECTIONPREVIEW",
|
||||
"SELECTIONANNODISPLAY",
|
||||
"PREVIEWEFFECT",
|
||||
"PREVIEWFILTER",
|
||||
"GRIPS",
|
||||
@@ -168,6 +169,7 @@ 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;
|
||||
|
||||
@@ -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`…).
|
||||
fn device_paper<'a>(dev: &'a PlotterConfig, name: &str) -> Option<&'a DevicePaper> {
|
||||
pub(crate) 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,6 +293,14 @@ 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
|
||||
@@ -330,10 +338,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(want), Some(dev), true) = (by_path, &dev, given.is_some_and(|n| !n.is_empty()))
|
||||
&& dev.output != want
|
||||
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))
|
||||
{
|
||||
return Err(bad(cmd, format!("plotter `{}` writes {}, but the path asks for {}", dev.name, dev.output.as_str(), want.as_str())));
|
||||
return Err(bad(cmd, why));
|
||||
}
|
||||
// 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.
|
||||
|
||||
@@ -103,7 +103,12 @@ 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(),
|
||||
CommandSpec::new("getvar", "Get Variable", run_getvar)
|
||||
.params("{name}")
|
||||
.enabled(always)
|
||||
.noundo()
|
||||
.transparent()
|
||||
.interactive(|_| Ok(Box::new(GetvarM))),
|
||||
CommandSpec::new("sysvars", "List System Variables", |s, _| Ok(crate::sysvars::list(s))).enabled(always).noundo(),
|
||||
]
|
||||
}
|
||||
@@ -252,6 +257,31 @@ 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}`")))?;
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
//! 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()),
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,9 @@ 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.
|
||||
@@ -87,6 +90,7 @@ 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(),
|
||||
|
||||
@@ -74,6 +74,12 @@ 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,6 +9,8 @@
|
||||
pub const FILES: &[&str] = &[
|
||||
"-hatch",
|
||||
"-linetype",
|
||||
"-pagesetup",
|
||||
"-plot",
|
||||
"-plottermanager",
|
||||
"-wblock",
|
||||
"-xref",
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
//! [`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;
|
||||
@@ -18,6 +20,7 @@ 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;
|
||||
@@ -61,6 +64,13 @@ 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;
|
||||
|
||||
@@ -9,12 +9,14 @@
|
||||
pub type BlockSlots = HashMap<Handle, (Arc<cadcraft_doc::Entity>, Option<Handle>)>;
|
||||
|
||||
pub mod builtins;
|
||||
mod curve;
|
||||
mod drawing;
|
||||
pub mod eval;
|
||||
pub mod input;
|
||||
mod objects;
|
||||
pub mod read;
|
||||
mod startup;
|
||||
mod system;
|
||||
pub mod value;
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -584,6 +586,7 @@ impl Session {
|
||||
input::Answer::Value(v) => return (req, Some(v)),
|
||||
input::Answer::Again(msg) => self.echo(msg),
|
||||
input::Answer::Second(p) => req = input::with_first(&req, p),
|
||||
input::Answer::Ask(next) => req = *next,
|
||||
}
|
||||
}
|
||||
(req, None)
|
||||
@@ -771,6 +774,12 @@ impl Session {
|
||||
r.waiting = Some(Need::Get(input::with_first(&req, p)));
|
||||
}
|
||||
}
|
||||
// The prompt goes on as another request (`getfiled`: replace the file, or a name again).
|
||||
input::Answer::Ask(next) => {
|
||||
if let Some(r) = self.lisp.run.as_mut() {
|
||||
r.waiting = Some(Need::Get(*next));
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -933,6 +942,10 @@ fn file_key(name: &str) -> String {
|
||||
base.strip_suffix(".lsp").map(str::to_string).unwrap_or(base)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod curve_props;
|
||||
#[cfg(test)]
|
||||
mod curve_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::sync::Arc;
|
||||
|
||||
use super::eval::{Ctx, Flow, Special};
|
||||
use super::value::{Builtin, BuiltinKind, Sym, Value, charge_bytes, check_string_len, eq, equal, real_text, to_text};
|
||||
use super::{Env, LispError, drawing, input, objects, read};
|
||||
use super::{Env, LispError, curve, drawing, input, objects, read, system};
|
||||
|
||||
macro_rules! cxrs {
|
||||
($($name:ident $path:literal),*) => {
|
||||
@@ -51,7 +51,7 @@ mod wcmatch;
|
||||
|
||||
use args::R;
|
||||
pub use args::args_err;
|
||||
pub use files::{LispFile, read_text_file};
|
||||
pub use files::{LispFile, file_exists, read_text_file};
|
||||
use files::{close, findfile, open, read_line, write_line};
|
||||
pub use functions::catch_all_error;
|
||||
use functions::{
|
||||
@@ -68,7 +68,7 @@ use numbers::{
|
||||
numberp, one_minus, one_plus, rem, sin, sqrt, sub, zerop,
|
||||
};
|
||||
use output::{alert, prin1, princ, print, prompt, terpri};
|
||||
pub use output::{is_null_symbol, null_symbol, real};
|
||||
pub use output::{emit, is_null_symbol, null_symbol, real};
|
||||
use strings::{
|
||||
ascii, atof, atoi, chr, itoa, read_fn, strcase, strcat, strlen, substr, vl_filename_base, vl_filename_directory, vl_filename_extension,
|
||||
vl_list_to_string, vl_prin1_to_string, vl_princ_to_string, vl_string_left_trim, vl_string_right_trim, vl_string_search, vl_string_subst,
|
||||
@@ -273,6 +273,50 @@ static BUILTINS: &[Builtin] = &[
|
||||
ctx!("DISTOF", drawing::distof),
|
||||
ctx!("ANGTOF", drawing::angtof),
|
||||
ctx!("TRANS", drawing::trans),
|
||||
ctx!("GETFILED", input::getfiled),
|
||||
ctx!("OSNAP", system::osnap),
|
||||
ctx!("ATOMS-FAMILY", system::atoms_family),
|
||||
ctx!("READ-CHAR", system::read_char),
|
||||
ctx!("WRITE-CHAR", system::write_char),
|
||||
pure!("VL-FILE-COPY", system::vl_file_copy),
|
||||
pure!("VL-FILE-DELETE", system::vl_file_delete),
|
||||
pure!("VL-FILE-RENAME", system::vl_file_rename),
|
||||
pure!("VL-FILE-SIZE", system::vl_file_size),
|
||||
pure!("VL-FILE-SYSTIME", system::vl_file_systime),
|
||||
pure!("VL-FILE-DIRECTORY-P", system::vl_file_directory_p),
|
||||
pure!("VL-DIRECTORY-FILES", system::vl_directory_files),
|
||||
pure!("VL-MKDIR", system::vl_mkdir),
|
||||
pure!("GETENV", system::getenv),
|
||||
pure!("SETENV", system::setenv),
|
||||
pure!("GETCNAME", system::getcname),
|
||||
pure!("SNVALID", system::snvalid),
|
||||
pure!("BOOLE", system::boole),
|
||||
pure!("VL-STRING-POSITION", system::vl_string_position),
|
||||
pure!("VL-STRING-ELT", system::vl_string_elt),
|
||||
pure!("VL-STRING-MISMATCH", system::vl_string_mismatch),
|
||||
pure!("ACAD-PUSH-DBMOD", system::t),
|
||||
pure!("ACAD-POP-DBMOD", system::t),
|
||||
pure!("TEXTSCR", system::nil),
|
||||
pure!("GRAPHSCR", system::nil),
|
||||
pure!("TEXTPAGE", system::nil),
|
||||
ctx!("VLAX-CURVE-GETSTARTPARAM", curve::get_start_param),
|
||||
ctx!("VLAX-CURVE-GETENDPARAM", curve::get_end_param),
|
||||
ctx!("VLAX-CURVE-GETSTARTPOINT", curve::get_start_point),
|
||||
ctx!("VLAX-CURVE-GETENDPOINT", curve::get_end_point),
|
||||
ctx!("VLAX-CURVE-GETDISTATPARAM", curve::get_dist_at_param),
|
||||
ctx!("VLAX-CURVE-GETPARAMATDIST", curve::get_param_at_dist),
|
||||
ctx!("VLAX-CURVE-GETPOINTATPARAM", curve::get_point_at_param),
|
||||
ctx!("VLAX-CURVE-GETPOINTATDIST", curve::get_point_at_dist),
|
||||
ctx!("VLAX-CURVE-GETPARAMATPOINT", curve::get_param_at_point),
|
||||
ctx!("VLAX-CURVE-GETDISTATPOINT", curve::get_dist_at_point),
|
||||
ctx!("VLAX-CURVE-GETCLOSESTPOINTTO", curve::get_closest_point_to),
|
||||
ctx!("VLAX-CURVE-GETCLOSESTPOINTTOPROJECTION", curve::get_closest_point_to_projection),
|
||||
ctx!("VLAX-CURVE-GETFIRSTDERIV", curve::get_first_deriv),
|
||||
ctx!("VLAX-CURVE-GETSECONDDERIV", curve::get_second_deriv),
|
||||
ctx!("VLAX-CURVE-GETAREA", curve::get_area),
|
||||
ctx!("VLAX-CURVE-ISCLOSED", curve::is_closed),
|
||||
ctx!("VLAX-CURVE-ISPERIODIC", curve::is_periodic),
|
||||
ctx!("VLAX-CURVE-ISPLANAR", curve::is_planar),
|
||||
];
|
||||
|
||||
/// Bind the builtins and constants in a new environment.
|
||||
|
||||
@@ -10,9 +10,34 @@ pub struct LispFile {
|
||||
pub writing: bool,
|
||||
pub append: bool,
|
||||
pub lines: std::collections::VecDeque<String>,
|
||||
/// How far (bytes) `read-char` has read into the first of `lines`.
|
||||
pub pos: usize,
|
||||
/// The last of `lines` had no terminator in the file, so `read-char` gives no 10 after it.
|
||||
pub unterminated: bool,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// The lines of a file's text, ended by LF or CRLF (a lone CR is data), and whether the last of
|
||||
/// them had a terminator. `count` is the number of lines (as `str::lines` counts them), so the
|
||||
/// queue is allocated exactly once.
|
||||
fn split_lines(t: &str, count: usize) -> (std::collections::VecDeque<String>, bool) {
|
||||
// Exact capacity: collecting would grow by doubling and hold unbilled slack.
|
||||
let mut lines = std::collections::VecDeque::with_capacity(count);
|
||||
lines.extend(t.split_inclusive('\n').map(|l| match l.strip_suffix('\n') {
|
||||
Some(l) => l.strip_suffix('\r').unwrap_or(l).to_string(),
|
||||
None => l.to_string(),
|
||||
}));
|
||||
(lines, !t.is_empty() && !t.ends_with('\n'))
|
||||
}
|
||||
|
||||
impl LispFile {
|
||||
/// Whether the line at the front is the last and has no terminator in the file, so it is
|
||||
/// followed by the end of the file rather than by a line end.
|
||||
pub fn at_unterminated_last(&self) -> bool {
|
||||
self.unterminated && self.lines.len() == 1
|
||||
}
|
||||
}
|
||||
|
||||
/// LISP `open`: a file handle, or nil when the file can't be opened or the automation roots refuse it.
|
||||
pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 3)?;
|
||||
@@ -22,9 +47,11 @@ pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError>
|
||||
"r" => (false, false),
|
||||
"w" => (true, false),
|
||||
"a" => (true, true),
|
||||
_ => return Err(LispError::new(format!("bad argument value: file mode {mode}"))),
|
||||
_ => {
|
||||
return Err(LispError::new(format!("bad argument value: file mode {mode}")));
|
||||
}
|
||||
};
|
||||
let mut f = LispFile { path: path.clone(), writing, append, lines: Default::default(), text: String::new() };
|
||||
let mut f = LispFile { path: path.clone(), writing, append, lines: Default::default(), pos: 0, unterminated: false, text: String::new() };
|
||||
if !writing {
|
||||
match read_text_file(&path) {
|
||||
Some(t) => {
|
||||
@@ -33,9 +60,7 @@ pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError>
|
||||
// allocation size, before collecting so many short lines cannot evade the budget.
|
||||
let count = t.lines().count();
|
||||
charge_bytes(t.len().saturating_add(count.saturating_mul(64)))?;
|
||||
// Exact capacity: collecting would grow by doubling and hold unbilled slack.
|
||||
f.lines = std::collections::VecDeque::with_capacity(count);
|
||||
f.lines.extend(t.lines().map(str::to_string));
|
||||
(f.lines, f.unterminated) = split_lines(&t, count);
|
||||
}
|
||||
None => return Ok(Flow::Value(Value::Nil)),
|
||||
}
|
||||
@@ -50,8 +75,12 @@ pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError>
|
||||
|
||||
pub(super) fn close(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
let Value::File(id) = a[0] else { return Err(LispError::bad_arg("streamp", &a[0])) };
|
||||
let Some(f) = ctx.env.files.remove(&id) else { return Err(LispError::bad_arg("streamp", &a[0])) };
|
||||
let Value::File(id) = a[0] else {
|
||||
return Err(LispError::bad_arg("streamp", &a[0]));
|
||||
};
|
||||
let Some(f) = ctx.env.files.remove(&id) else {
|
||||
return Err(LispError::bad_arg("streamp", &a[0]));
|
||||
};
|
||||
if f.writing {
|
||||
write_text_file(&f.path, &f.text, f.append);
|
||||
}
|
||||
@@ -60,8 +89,20 @@ pub(super) fn close(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError>
|
||||
|
||||
pub(super) fn read_line(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 0, 1)?;
|
||||
let Some(Value::File(id)) = a.first() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let line = ctx.env.files.get_mut(id).filter(|f| !f.writing).and_then(|f| f.lines.pop_front());
|
||||
let Some(Value::File(id)) = a.first() else {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
};
|
||||
// The rest of the line: what `read-char` hasn't read of it yet. Nothing left of an
|
||||
// unterminated last line is the end of the file.
|
||||
let line = ctx.env.files.get_mut(id).filter(|f| !f.writing).and_then(|f| {
|
||||
let last_unterminated = f.at_unterminated_last();
|
||||
let l = f.lines.pop_front()?;
|
||||
let rest = l.get(std::mem::take(&mut f.pos)..).unwrap_or("").to_string();
|
||||
if last_unterminated && rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(rest)
|
||||
});
|
||||
Ok(Flow::Value(line.map(|l| Value::str(&l)).unwrap_or_default()))
|
||||
}
|
||||
|
||||
@@ -135,13 +176,13 @@ fn write_text_file(_path: &str, _text: &str, _append: bool) {}
|
||||
/// A file or a folder: routines test whether a module is installed with `(findfile "module/.")`.
|
||||
/// Outside the automation roots the answer is no.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn file_exists(path: &str) -> bool {
|
||||
pub fn file_exists(path: &str) -> bool {
|
||||
let p = std::path::Path::new(path);
|
||||
crate::file_access::check_read(p).is_ok() && (p.is_file() || p.is_dir())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn file_exists(_path: &str) -> bool {
|
||||
pub fn file_exists(_path: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::{Arc, Ctx, Flow, LispError, Sym, Value, charge_bytes, real_text, to_t
|
||||
// ---------------- output ----------------
|
||||
|
||||
/// Text printed to a file (an open file argument) or the command line.
|
||||
pub(super) fn emit(ctx: &mut Ctx<'_>, text: &str, file: Option<&Value>) -> Result<(), LispError> {
|
||||
pub fn emit(ctx: &mut Ctx<'_>, text: &str, file: Option<&Value>) -> Result<(), LispError> {
|
||||
charge_bytes(text.len())?;
|
||||
match file {
|
||||
None | Some(Value::Nil) => {
|
||||
|
||||
@@ -0,0 +1,746 @@
|
||||
//! `vlax-curve-*`: lengths, points, parameters, derivatives and areas along a curve entity.
|
||||
//!
|
||||
//! Each kind keeps AutoLISP's parameter: a line's is the distance from its start, an arc's or a
|
||||
//! circle's the angle, a polyline's the vertex index (a fraction of the way along the segment
|
||||
//! after it), an ellipse's its own parameter, a spline's its knot parameter. Everything is
|
||||
//! exact: ellipses and splines are evaluated on the curve itself, and their lengths and areas
|
||||
//! integrated along it (the same arc lengths LENGTHEN uses); a fine flattening only finds where
|
||||
//! to start looking for a closest point.
|
||||
|
||||
use cadcraft_doc::{Entity, EntityKind};
|
||||
use cadcraft_geom::{Arc as GArc, Ellipse as GEllipse, Spline as GSpline, Vec2, bulge_to_arc};
|
||||
|
||||
use super::LispError;
|
||||
use super::builtins::args_err;
|
||||
use super::eval::{Ctx, Flow};
|
||||
use super::value::Value;
|
||||
|
||||
type P3 = [f64; 3];
|
||||
|
||||
/// One stretch of the curve: a line or an arc, over parameters `p0..p1`, starting `d0` along.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Piece {
|
||||
p0: f64,
|
||||
p1: f64,
|
||||
d0: f64,
|
||||
seg: Seg,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Seg {
|
||||
Line(P3, P3),
|
||||
/// From angle `a0`, turning `turn` radians (negative: clockwise), at height `z`.
|
||||
Arc {
|
||||
c: Vec2,
|
||||
r: f64,
|
||||
a0: f64,
|
||||
turn: f64,
|
||||
z: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl Seg {
|
||||
fn len(&self) -> f64 {
|
||||
match self {
|
||||
Seg::Line(a, b) => dist3(a, b),
|
||||
Seg::Arc { r, turn, .. } => r * turn.abs(),
|
||||
}
|
||||
}
|
||||
fn at(&self, t: f64) -> P3 {
|
||||
match self {
|
||||
Seg::Line(a, b) => lerp3(a, b, t),
|
||||
Seg::Arc { c, r, a0, turn, z } => {
|
||||
let q = Vec2::polar(*c, *r, a0 + turn * t);
|
||||
[q.x, q.y, *z]
|
||||
}
|
||||
}
|
||||
}
|
||||
/// d/dt and d²/dt² at `t` (t from 0 to 1 along the piece).
|
||||
fn derivs(&self, t: f64) -> (P3, P3) {
|
||||
match self {
|
||||
Seg::Line(a, b) => ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [0.0; 3]),
|
||||
Seg::Arc { r, a0, turn, .. } => {
|
||||
let th = a0 + turn * t;
|
||||
let (s, c) = th.sin_cos();
|
||||
([-r * turn * s, r * turn * c, 0.0], [-r * turn * turn * c, -r * turn * turn * s, 0.0])
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The nearest point's `t` (0..1).
|
||||
fn closest(&self, p: &P3) -> f64 {
|
||||
match self {
|
||||
Seg::Line(a, b) => {
|
||||
let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
|
||||
let l2 = dot3(&d, &d);
|
||||
if l2 <= 1e-30 { 0.0 } else { (dot3(&[p[0] - a[0], p[1] - a[1], p[2] - a[2]], &d) / l2).clamp(0.0, 1.0) }
|
||||
}
|
||||
Seg::Arc { c, a0, turn, .. } => {
|
||||
if turn.abs() <= 1e-15 {
|
||||
return 0.0;
|
||||
}
|
||||
let q = Vec2::new(p[0], p[1]);
|
||||
if q.dist(*c) <= 1e-15 {
|
||||
return 0.0;
|
||||
}
|
||||
// Angle from the start in the direction of travel, 0..2π.
|
||||
let rel = (q.angle_to_from(*c) - a0) * turn.signum();
|
||||
let rel = rel.rem_euclid(std::f64::consts::TAU);
|
||||
let span = turn.abs();
|
||||
if rel <= span {
|
||||
return rel / span;
|
||||
}
|
||||
// Outside the arc: the nearer end.
|
||||
let (s, e) = (self.at(0.0), self.at(1.0));
|
||||
if dist3(&s, p) <= dist3(&e, p) { 0.0 } else { 1.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The nearest point on the line or the whole circle the piece lies on.
|
||||
fn closest_extended(&self, p: &P3) -> P3 {
|
||||
match self {
|
||||
Seg::Line(a, b) => {
|
||||
let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
|
||||
let l2 = dot3(&d, &d);
|
||||
let t = if l2 <= 1e-30 { 0.0 } else { dot3(&[p[0] - a[0], p[1] - a[1], p[2] - a[2]], &d) / l2 };
|
||||
lerp3(a, b, t)
|
||||
}
|
||||
Seg::Arc { c, r, z, .. } => {
|
||||
let q = Vec2::new(p[0], p[1]) - *c;
|
||||
let u = if q.len() <= 1e-15 { Vec2::new(1.0, 0.0) } else { q.normalized() };
|
||||
[c.x + u.x * r, c.y + u.y * r, *z]
|
||||
}
|
||||
}
|
||||
}
|
||||
/// ∫ (x dy − y dx) / 2 along the piece: its share of the enclosed area.
|
||||
fn area_term(&self) -> f64 {
|
||||
match self {
|
||||
Seg::Line(a, b) => (a[0] * b[1] - b[0] * a[1]) / 2.0,
|
||||
Seg::Arc { c, r, turn, .. } => {
|
||||
let (s, e) = (self.at(0.0), self.at(1.0));
|
||||
(c.x * (e[1] - s[1]) - c.y * (e[0] - s[0]) + r * r * turn) / 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait AngleFrom {
|
||||
fn angle_to_from(self, c: Vec2) -> f64;
|
||||
}
|
||||
impl AngleFrom for Vec2 {
|
||||
fn angle_to_from(self, c: Vec2) -> f64 {
|
||||
(self.y - c.y).atan2(self.x - c.x)
|
||||
}
|
||||
}
|
||||
|
||||
fn dot3(a: &P3, b: &P3) -> f64 {
|
||||
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
||||
}
|
||||
fn dist3(a: &P3, b: &P3) -> f64 {
|
||||
((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
|
||||
}
|
||||
fn lerp3(a: &P3, b: &P3, t: f64) -> P3 {
|
||||
[a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]
|
||||
}
|
||||
fn scale3(a: &P3, k: f64) -> P3 {
|
||||
[a[0] * k, a[1] * k, a[2] * k]
|
||||
}
|
||||
|
||||
/// What evaluates the curve exactly at a parameter, where the pieces are only a flattening.
|
||||
#[derive(Clone, Debug)]
|
||||
enum Exact {
|
||||
None,
|
||||
Ellipse(GEllipse, f64),
|
||||
Spline(GSpline),
|
||||
}
|
||||
|
||||
/// A curve entity, ready to measure.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Curve {
|
||||
pieces: Vec<Piece>,
|
||||
exact: Exact,
|
||||
start: f64,
|
||||
end: f64,
|
||||
/// The whole length: the pieces' for lines, arcs and polylines, the exact curve's otherwise.
|
||||
len: f64,
|
||||
closed: bool,
|
||||
periodic: bool,
|
||||
planar: bool,
|
||||
}
|
||||
|
||||
/// Most points a flattened ellipse or spline is searched along.
|
||||
const MAX_SAMPLES: usize = 16_384;
|
||||
|
||||
impl Curve {
|
||||
/// The curve an entity is, or `None` for one that isn't (text, blocks, hatches…).
|
||||
pub fn of(e: &Entity) -> Option<Curve> {
|
||||
let tau = std::f64::consts::TAU;
|
||||
let c = match &e.kind {
|
||||
EntityKind::Line(l) => {
|
||||
let (a, b) = ([l.a.x, l.a.y, l.a.z], [l.b.x, l.b.y, l.b.z]);
|
||||
let len = dist3(&a, &b);
|
||||
Curve::from_pieces(vec![(0.0, len, Seg::Line(a, b))], Exact::None, false, false, true)
|
||||
}
|
||||
EntityKind::Arc(a) => {
|
||||
let sweep = GArc::new(a.center.xy(), a.radius, a.start, a.end).sweep();
|
||||
let seg = Seg::Arc { c: a.center.xy(), r: a.radius, a0: a.start, turn: sweep, z: a.center.z };
|
||||
Curve::from_pieces(vec![(a.start, a.start + sweep, seg)], Exact::None, false, false, true)
|
||||
}
|
||||
EntityKind::Circle(c) => {
|
||||
let seg = Seg::Arc { c: c.center.xy(), r: c.radius, a0: 0.0, turn: tau, z: c.center.z };
|
||||
Curve::from_pieces(vec![(0.0, tau, seg)], Exact::None, true, true, true)
|
||||
}
|
||||
EntityKind::LwPolyline(p) => {
|
||||
let z = p.elevation;
|
||||
// One piece per vertex, zero-length ones included: parameters count every vertex.
|
||||
let n = if p.closed { p.vertices.len() } else { p.vertices.len().saturating_sub(1) };
|
||||
let mut pieces = Vec::new();
|
||||
for i in 0..n {
|
||||
let Some(a) = p.vertices.get(i) else { break };
|
||||
let Some(b) = p.vertices.get((i + 1) % p.vertices.len().max(1)) else { break };
|
||||
let seg = match bulge_to_arc(a.p, b.p, a.bulge) {
|
||||
Some((arc, ccw)) => {
|
||||
let turn = if ccw { arc.sweep() } else { -arc.sweep() };
|
||||
let a0 = if ccw { arc.start } else { arc.start + arc.sweep() };
|
||||
Seg::Arc { c: arc.center, r: arc.radius, a0, turn, z }
|
||||
}
|
||||
None => Seg::Line([a.p.x, a.p.y, z], [b.p.x, b.p.y, z]),
|
||||
};
|
||||
pieces.push((i as f64, (i + 1) as f64, seg));
|
||||
}
|
||||
if pieces.is_empty() {
|
||||
let v = p.vertices.first()?;
|
||||
pieces.push((0.0, 0.0, Seg::Line([v.p.x, v.p.y, z], [v.p.x, v.p.y, z])));
|
||||
}
|
||||
Curve::from_pieces(pieces, Exact::None, p.closed, false, true)
|
||||
}
|
||||
EntityKind::Polyline3d(p) => {
|
||||
let pts: Vec<P3> = p.points.iter().map(|q| [q.x, q.y, q.z]).collect();
|
||||
let n = if p.closed { pts.len() } else { pts.len().saturating_sub(1) };
|
||||
let mut pieces = Vec::new();
|
||||
for i in 0..n {
|
||||
let (Some(a), Some(b)) = (pts.get(i), pts.get((i + 1) % pts.len().max(1))) else { break };
|
||||
pieces.push((i as f64, (i + 1) as f64, Seg::Line(*a, *b)));
|
||||
}
|
||||
if pieces.is_empty() {
|
||||
let a = *pts.first()?;
|
||||
pieces.push((0.0, 0.0, Seg::Line(a, a)));
|
||||
}
|
||||
let planar = coplanar(&pts);
|
||||
Curve::from_pieces(pieces, Exact::None, p.closed, false, planar)
|
||||
}
|
||||
EntityKind::Ellipse(el) => {
|
||||
let ge = GEllipse { center: el.center.xy(), major: el.major.xy(), ratio: el.ratio, start: el.start, end: el.end };
|
||||
let full = ge.is_full();
|
||||
let (t0, sweep) = if full { (0.0, tau) } else { (el.start, ge.sweep()) };
|
||||
let n = ((sweep / tau * 4096.0).ceil() as usize).clamp(64, MAX_SAMPLES);
|
||||
let z = el.center.z;
|
||||
let pts: Vec<(f64, P3)> = (0..=n)
|
||||
.map(|i| {
|
||||
let t = t0 + sweep * i as f64 / n as f64;
|
||||
let q = ge.at_param(t);
|
||||
(t, [q.x, q.y, z])
|
||||
})
|
||||
.collect();
|
||||
Curve::from_pieces(flattened(&pts), Exact::Ellipse(ge, z), full, full, true)
|
||||
.map(|c| Curve { len: ge.arc_length_from(t0, sweep), ..c })
|
||||
}
|
||||
EntityKind::Spline(sp) => {
|
||||
if !sp.is_valid() {
|
||||
return None;
|
||||
}
|
||||
let (lo, hi) = sp.domain();
|
||||
if !(lo.is_finite() && hi.is_finite() && hi >= lo) {
|
||||
return None;
|
||||
}
|
||||
let n = (sp.control.len().saturating_mul(256)).clamp(1024, MAX_SAMPLES);
|
||||
let pts: Vec<(f64, P3)> = (0..=n)
|
||||
.map(|i| {
|
||||
let t = lo + (hi - lo) * i as f64 / n as f64;
|
||||
let q = sp.eval(t);
|
||||
(t, [q.x, q.y, 0.0])
|
||||
})
|
||||
.collect();
|
||||
Curve::from_pieces(flattened(&pts), Exact::Spline(sp.clone()), sp.closed, sp.closed && sp.is_periodic(), true)
|
||||
.and_then(|c| Some(Curve { len: sp.checked_length()?, ..c }))
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
c.filter(|c| c.len.is_finite() && c.pieces.iter().all(|p| p.p0.is_finite() && p.p1.is_finite() && p.seg.len().is_finite()))
|
||||
}
|
||||
|
||||
fn from_pieces(raw: Vec<(f64, f64, Seg)>, exact: Exact, closed: bool, periodic: bool, planar: bool) -> Option<Curve> {
|
||||
let start = raw.first()?.0;
|
||||
let end = raw.last()?.1;
|
||||
let mut d = 0.0;
|
||||
let pieces = raw
|
||||
.into_iter()
|
||||
.map(|(p0, p1, seg)| {
|
||||
let piece = Piece { p0, p1, d0: d, seg };
|
||||
d += piece.seg.len();
|
||||
piece
|
||||
})
|
||||
.collect();
|
||||
Some(Curve { pieces, exact, start, end, len: d, closed, periodic, planar })
|
||||
}
|
||||
|
||||
pub fn start_param(&self) -> f64 {
|
||||
self.start
|
||||
}
|
||||
pub fn end_param(&self) -> f64 {
|
||||
self.end
|
||||
}
|
||||
pub fn length(&self) -> f64 {
|
||||
self.len
|
||||
}
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.closed
|
||||
}
|
||||
pub fn is_periodic(&self) -> bool {
|
||||
self.periodic
|
||||
}
|
||||
pub fn is_planar(&self) -> bool {
|
||||
self.planar
|
||||
}
|
||||
|
||||
fn tol(&self) -> f64 {
|
||||
1e-9 * (1.0 + self.length())
|
||||
}
|
||||
|
||||
/// The piece holding parameter `t` and how far along it (0..1); `None` off the curve.
|
||||
fn at_param(&self, t: f64) -> Option<(&Piece, f64)> {
|
||||
let eps = 1e-9 * (1.0 + (self.end - self.start).abs());
|
||||
if !t.is_finite() || t < self.start - eps || t > self.end + eps {
|
||||
return None;
|
||||
}
|
||||
let t = t.clamp(self.start, self.end);
|
||||
let p = self.pieces.iter().find(|p| t <= p.p1 + 1e-12).or(self.pieces.last())?;
|
||||
let span = p.p1 - p.p0;
|
||||
Some((p, if span.abs() <= 1e-15 { 0.0 } else { ((t - p.p0) / span).clamp(0.0, 1.0) }))
|
||||
}
|
||||
|
||||
/// `d` kept within the curve's length; `None` past either end.
|
||||
fn in_length(&self, d: f64) -> Option<f64> {
|
||||
let eps = self.tol();
|
||||
(d.is_finite() && d >= -eps && d <= self.len + eps).then(|| d.clamp(0.0, self.len))
|
||||
}
|
||||
|
||||
/// The piece `d` along the pieces and how far along it (0..1); `None` past either end.
|
||||
fn at_dist(&self, d: f64) -> Option<(&Piece, f64)> {
|
||||
let d = self.in_length(d)?;
|
||||
let p = self.pieces.iter().find(|p| d <= p.d0 + p.seg.len() + 1e-12).or(self.pieces.last())?;
|
||||
let l = p.seg.len();
|
||||
Some((p, if l <= 1e-15 { 0.0 } else { ((d - p.d0) / l).clamp(0.0, 1.0) }))
|
||||
}
|
||||
|
||||
fn param_of(p: &Piece, f: f64) -> f64 {
|
||||
p.p0 + (p.p1 - p.p0) * f
|
||||
}
|
||||
|
||||
pub fn point_at_param(&self, t: f64) -> Option<P3> {
|
||||
let (p, f) = self.at_param(t)?;
|
||||
Some(match &self.exact {
|
||||
Exact::None => p.seg.at(f),
|
||||
Exact::Ellipse(e, z) => {
|
||||
let q = e.at_param(t);
|
||||
[q.x, q.y, *z]
|
||||
}
|
||||
Exact::Spline(sp) => {
|
||||
let q = sp.eval(t);
|
||||
[q.x, q.y, 0.0]
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn dist_at_param(&self, t: f64) -> Option<f64> {
|
||||
let (p, f) = self.at_param(t)?;
|
||||
let t = t.clamp(self.start, self.end);
|
||||
Some(match &self.exact {
|
||||
Exact::None => p.d0 + p.seg.len() * f,
|
||||
Exact::Ellipse(e, _) => e.arc_length_from(self.start, t - self.start),
|
||||
Exact::Spline(sp) => sp.length_between(self.start, t),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn param_at_dist(&self, d: f64) -> Option<f64> {
|
||||
if let Exact::None = self.exact {
|
||||
let (p, f) = self.at_dist(d)?;
|
||||
return Some(Curve::param_of(p, f));
|
||||
}
|
||||
let d = self.in_length(d)?;
|
||||
if d >= self.len {
|
||||
return Some(self.end);
|
||||
}
|
||||
if let Some(t) = self.newton_param_at(d) {
|
||||
return Some(t);
|
||||
}
|
||||
Some(match &self.exact {
|
||||
Exact::Ellipse(e, _) => e.param_at_length(self.start, d).unwrap_or(self.end).clamp(self.start, self.end),
|
||||
Exact::Spline(sp) => sp.param_at_length(self.start, d)?,
|
||||
Exact::None => self.start,
|
||||
})
|
||||
}
|
||||
|
||||
/// Exact arc length from parameter `a` to `b` (negative when `b` comes first).
|
||||
fn exact_len_between(&self, a: f64, b: f64) -> f64 {
|
||||
let (lo, hi, sign) = if a <= b { (a, b, 1.0) } else { (b, a, -1.0) };
|
||||
sign * match &self.exact {
|
||||
Exact::Ellipse(e, _) => e.arc_length_from(lo, hi - lo),
|
||||
Exact::Spline(sp) => sp.length_between(lo, hi),
|
||||
Exact::None => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The speed |dC/dt| of an ellipse or a spline.
|
||||
fn exact_speed(&self, t: f64) -> f64 {
|
||||
match &self.exact {
|
||||
Exact::Ellipse(e, _) => e.derivative(t).len(),
|
||||
Exact::Spline(sp) => sp.derivative(t).len(),
|
||||
Exact::None => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameter `d` along an ellipse or a spline: the flattening's guess, then Newton steps
|
||||
/// on the exact arc length (whose derivative is the speed), measured from the guessed piece's
|
||||
/// start so that each step integrates only a short stretch. `None` when it doesn't settle
|
||||
/// (a cusp, where the speed vanishes), for the slower bisection to answer.
|
||||
fn newton_param_at(&self, d: f64) -> Option<f64> {
|
||||
let chord = self.pieces.last().map_or(0.0, |p| p.d0 + p.seg.len());
|
||||
let g = if self.len > 0.0 { (d * chord / self.len).clamp(0.0, chord) } else { 0.0 };
|
||||
let p = self.pieces.iter().find(|p| g <= p.d0 + p.seg.len() + 1e-12).or(self.pieces.last())?;
|
||||
let l = p.seg.len();
|
||||
let mut t = Curve::param_of(p, if l <= 1e-15 { 0.0 } else { ((g - p.d0) / l).clamp(0.0, 1.0) });
|
||||
let (base_t, base) = (p.p0, self.exact_len_between(self.start, p.p0));
|
||||
let tol = 1e-12 * (1.0 + self.len);
|
||||
for _ in 0..16 {
|
||||
let err = base + self.exact_len_between(base_t, t) - d;
|
||||
if !err.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if err.abs() <= tol {
|
||||
return Some(t);
|
||||
}
|
||||
let speed = self.exact_speed(t);
|
||||
if !(speed.is_finite() && speed > 1e-12 * (1.0 + self.len)) {
|
||||
return None;
|
||||
}
|
||||
let next = (t - err / speed).clamp(self.start, self.end);
|
||||
if next == t {
|
||||
// Held at an end short of `d`: leave it to the bisection.
|
||||
return None;
|
||||
}
|
||||
t = next;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn point_at_dist(&self, d: f64) -> Option<P3> {
|
||||
let t = self.param_at_dist(d)?;
|
||||
self.point_at_param(t)
|
||||
}
|
||||
|
||||
/// First and second derivatives with respect to the parameter.
|
||||
pub fn derivs(&self, t: f64) -> Option<(P3, P3)> {
|
||||
let (p, f) = self.at_param(t)?;
|
||||
Some(match &self.exact {
|
||||
Exact::None => {
|
||||
let span = p.p1 - p.p0;
|
||||
if span.abs() <= 1e-15 {
|
||||
return Some(([0.0; 3], [0.0; 3]));
|
||||
}
|
||||
let (d1, d2) = p.seg.derivs(f);
|
||||
(scale3(&d1, 1.0 / span), scale3(&d2, 1.0 / (span * span)))
|
||||
}
|
||||
Exact::Ellipse(e, _) => {
|
||||
let (a, b) = (e.major, e.minor());
|
||||
let (s, c) = t.sin_cos();
|
||||
([-a.x * s + b.x * c, -a.y * s + b.y * c, 0.0], [-a.x * c - b.x * s, -a.y * c - b.y * s, 0.0])
|
||||
}
|
||||
Exact::Spline(sp) => {
|
||||
// The exact first derivative; the second by central differences on it, one-sided
|
||||
// at the ends.
|
||||
let t = t.clamp(self.start, self.end);
|
||||
let d1 = sp.derivative(t);
|
||||
let h = 1e-5 * (self.end - self.start).abs().max(1e-9);
|
||||
let (lo, hi) = ((t - h).max(self.start), (t + h).min(self.end));
|
||||
let w = hi - lo;
|
||||
if w <= 0.0 {
|
||||
return Some(([d1.x, d1.y, 0.0], [0.0; 3]));
|
||||
}
|
||||
let d2 = (sp.derivative(hi) - sp.derivative(lo)) * (1.0 / w);
|
||||
([d1.x, d1.y, 0.0], [d2.x, d2.y, 0.0])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The parameter of the point nearest `q`, and that point.
|
||||
pub fn closest(&self, q: &P3) -> Option<(f64, P3)> {
|
||||
let mut best: Option<(f64, f64)> = None;
|
||||
for p in &self.pieces {
|
||||
let f = p.seg.closest(q);
|
||||
let d = dist3(&p.seg.at(f), q);
|
||||
if best.is_none_or(|(bd, _)| d < bd) {
|
||||
best = Some((d, Curve::param_of(p, f)));
|
||||
}
|
||||
}
|
||||
let (_, mut t) = best?;
|
||||
// Refine on the exact curve (the pieces are a flattening there).
|
||||
match &self.exact {
|
||||
Exact::None => {}
|
||||
Exact::Ellipse(..) | Exact::Spline(_) => t = newton(self, q, t),
|
||||
}
|
||||
Some((t, self.point_at_param(t)?))
|
||||
}
|
||||
|
||||
/// With `extend`, an open curve's ends are carried on along their line or circle.
|
||||
pub fn closest_point(&self, q: &P3, extend: bool) -> Option<P3> {
|
||||
let (_, mut best) = self.closest(q)?;
|
||||
if extend && !self.closed {
|
||||
let ends = [self.pieces.first(), self.pieces.last()];
|
||||
for p in ends.into_iter().flatten() {
|
||||
let e = match (&self.exact, &p.seg) {
|
||||
(Exact::None, seg) => seg.closest_extended(q),
|
||||
// An open ellipse goes on round the whole ellipse.
|
||||
(Exact::Ellipse(e, z), _) => {
|
||||
let full = GEllipse { start: 0.0, end: std::f64::consts::TAU, ..*e };
|
||||
let v = full.closest(Vec2::new(q[0], q[1]));
|
||||
[v.x, v.y, *z]
|
||||
}
|
||||
(Exact::Spline(_), _) => continue,
|
||||
};
|
||||
if dist3(&e, q) < dist3(&best, q) {
|
||||
best = e;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(best)
|
||||
}
|
||||
|
||||
/// The parameter of a point on the curve; `None` for a point off it.
|
||||
pub fn param_at_point(&self, q: &P3) -> Option<f64> {
|
||||
let (t, p) = self.closest(q)?;
|
||||
(dist3(&p, q) <= 1e-6 * (1.0 + self.length())).then_some(t)
|
||||
}
|
||||
|
||||
/// The area the curve encloses (an open one closed by the chord between its ends).
|
||||
pub fn area(&self) -> f64 {
|
||||
let mut a: f64 = match &self.exact {
|
||||
Exact::Ellipse(e, _) => {
|
||||
let (t0, t1) = (self.start, self.end);
|
||||
let (p0, p1) = (e.at_param(t0), e.at_param(t1));
|
||||
let (c, ma, mi) = (e.center, e.major, e.minor());
|
||||
(c.x * (p1.y - p0.y) - c.y * (p1.x - p0.x) + (ma.x * mi.y - ma.y * mi.x) * (t1 - t0)) / 2.0
|
||||
}
|
||||
// Integrated on the exact curve, seen from its start point, so the closing chord adds
|
||||
// nothing.
|
||||
Exact::Spline(sp) => return sp.area_term_between(self.start, self.end, sp.eval(self.start)).abs(),
|
||||
Exact::None => self.pieces.iter().map(|p| p.seg.area_term()).sum(),
|
||||
};
|
||||
if !self.closed
|
||||
&& let (Some(s), Some(e)) = (self.point_at_param(self.start), self.point_at_param(self.end))
|
||||
{
|
||||
a += (e[0] * s[1] - s[0] * e[1]) / 2.0;
|
||||
}
|
||||
a.abs()
|
||||
}
|
||||
}
|
||||
|
||||
/// Lines between consecutive (parameter, point) samples.
|
||||
fn flattened(pts: &[(f64, P3)]) -> Vec<(f64, f64, Seg)> {
|
||||
pts.windows(2).filter_map(|w| Some((w.first()?.0, w.get(1)?.0, Seg::Line(w.first()?.1, w.get(1)?.1)))).collect()
|
||||
}
|
||||
|
||||
/// A few Newton steps on (C(t) − q)·C'(t) = 0, kept within the curve's parameters.
|
||||
fn newton(c: &Curve, q: &P3, mut t: f64) -> f64 {
|
||||
// A periodic curve (a full ellipse, a periodic spline) goes on round past its ends, so a step
|
||||
// wraps over the seam; any other curve stops at its ends.
|
||||
let period = c.end - c.start;
|
||||
let wraps = c.periodic && period > 0.0 && period.is_finite();
|
||||
for _ in 0..8 {
|
||||
let (Some(p), Some((d1, d2))) = (c.point_at_param(t), c.derivs(t)) else { break };
|
||||
let r = [p[0] - q[0], p[1] - q[1], p[2] - q[2]];
|
||||
let f = dot3(&r, &d1);
|
||||
let df = dot3(&d1, &d1) + dot3(&r, &d2);
|
||||
if df.abs() <= 1e-30 || !f.is_finite() || !df.is_finite() {
|
||||
break;
|
||||
}
|
||||
let raw = t - f / df;
|
||||
let next = if wraps { c.start + (raw - c.start).rem_euclid(period) } else { raw.clamp(c.start, c.end) };
|
||||
if (raw - t).abs() <= 1e-14 * (1.0 + t.abs()) || next == t {
|
||||
t = next;
|
||||
break;
|
||||
}
|
||||
// Keep a step only when it brings the point nearer.
|
||||
match c.point_at_param(next) {
|
||||
Some(pn) if dist3(&pn, q) <= dist3(&p, q) => t = next,
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// Whether 3D points lie in one plane.
|
||||
fn coplanar(pts: &[P3]) -> bool {
|
||||
let Some(o) = pts.first() else { return true };
|
||||
let sub = |a: &P3| [a[0] - o[0], a[1] - o[1], a[2] - o[2]];
|
||||
let cross = |a: &P3, b: &P3| [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
|
||||
let scale = pts.iter().map(|p| dist3(p, o)).fold(0.0, f64::max).max(1e-12);
|
||||
let mut normal: Option<P3> = None;
|
||||
for (i, a) in pts.iter().enumerate().skip(1) {
|
||||
for b in pts.iter().skip(i + 1) {
|
||||
let n = cross(&sub(a), &sub(b));
|
||||
if dot3(&n, &n).sqrt() > 1e-9 * scale * scale {
|
||||
normal = Some(n);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if normal.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(n) = normal else { return true };
|
||||
let nl = dot3(&n, &n).sqrt();
|
||||
pts.iter().all(|p| (dot3(&sub(p), &n) / nl).abs() <= 1e-9 * scale)
|
||||
}
|
||||
|
||||
// ---------------- the builtins ----------------
|
||||
|
||||
fn arity(a: &[Value], min: usize, max: usize) -> Result<(), LispError> {
|
||||
if a.len() < min {
|
||||
return Err(args_err(true));
|
||||
}
|
||||
if a.len() > max {
|
||||
return Err(args_err(false));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The curve an argument names (an entity name).
|
||||
fn curve_arg(ctx: &mut Ctx<'_>, v: &Value) -> Result<Curve, LispError> {
|
||||
let Value::Ename(h) = v else { return Err(LispError::bad_arg("lentityp", v)) };
|
||||
let d = ctx.s.doc().map_err(|e| LispError::new(e.to_string()))?;
|
||||
let e = d.entity(*h).ok_or_else(|| LispError::bad_arg("lentityp", v))?;
|
||||
Curve::of(e).ok_or_else(|| LispError::bad_arg("curvep", v))
|
||||
}
|
||||
|
||||
fn num(v: &Value) -> Result<f64, LispError> {
|
||||
v.as_number().ok_or_else(|| LispError::bad_arg("numberp", v))
|
||||
}
|
||||
|
||||
fn point(v: &Value) -> Result<P3, LispError> {
|
||||
v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", v))
|
||||
}
|
||||
|
||||
fn val_point(p: Option<P3>) -> Value {
|
||||
p.map(|p| Value::point(&p)).unwrap_or_default()
|
||||
}
|
||||
fn val_real(r: Option<f64>) -> Value {
|
||||
r.map(Value::Real).unwrap_or_default()
|
||||
}
|
||||
fn done(v: Value) -> Result<Flow, LispError> {
|
||||
Ok(Flow::Value(v))
|
||||
}
|
||||
|
||||
pub fn get_start_param(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
done(Value::Real(curve_arg(ctx, &a[0])?.start_param()))
|
||||
}
|
||||
pub fn get_end_param(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
done(Value::Real(curve_arg(ctx, &a[0])?.end_param()))
|
||||
}
|
||||
pub fn get_start_point(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
done(val_point(c.point_at_param(c.start_param())))
|
||||
}
|
||||
pub fn get_end_point(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
done(val_point(c.point_at_param(c.end_param())))
|
||||
}
|
||||
pub fn get_dist_at_param(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
done(val_real(c.dist_at_param(num(&a[1])?)))
|
||||
}
|
||||
pub fn get_param_at_dist(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
done(val_real(c.param_at_dist(num(&a[1])?)))
|
||||
}
|
||||
pub fn get_point_at_param(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
done(val_point(c.point_at_param(num(&a[1])?)))
|
||||
}
|
||||
pub fn get_point_at_dist(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
done(val_point(c.point_at_dist(num(&a[1])?)))
|
||||
}
|
||||
pub fn get_param_at_point(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
done(val_real(c.param_at_point(&point(&a[1])?)))
|
||||
}
|
||||
pub fn get_dist_at_point(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
let t = c.param_at_point(&point(&a[1])?);
|
||||
done(val_real(t.and_then(|t| c.dist_at_param(t))))
|
||||
}
|
||||
pub fn get_closest_point_to(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 3)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
let extend = a.get(2).is_some_and(|v| !v.is_nil());
|
||||
done(val_point(c.closest_point(&point(&a[1])?, extend)))
|
||||
}
|
||||
/// `(vlax-curve-getClosestPointToProjection curve point normal [extend])`: the curves here lie
|
||||
/// in planes square to Z, so for a Z normal this is the closest point to the point dropped onto
|
||||
/// that plane.
|
||||
pub fn get_closest_point_to_projection(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 3, 4)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
let q = point(&a[1])?;
|
||||
let n = point(&a[2])?;
|
||||
let nl = dot3(&n, &n).sqrt();
|
||||
if nl <= 1e-12 {
|
||||
return Err(LispError::bad_arg("vector", &a[2]));
|
||||
}
|
||||
let extend = a.get(3).is_some_and(|v| !v.is_nil());
|
||||
// Slide the point along the normal into the curve's plane (z of its start).
|
||||
let z0 = c.point_at_param(c.start_param()).map_or(0.0, |p| p[2]);
|
||||
let q = if n[2].abs() > 1e-12 * nl {
|
||||
let k = (z0 - q[2]) / n[2];
|
||||
[q[0] + n[0] * k, q[1] + n[1] * k, z0]
|
||||
} else {
|
||||
q
|
||||
};
|
||||
done(val_point(c.closest_point(&q, extend)))
|
||||
}
|
||||
pub fn get_first_deriv(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
done(val_point(c.derivs(num(&a[1])?).map(|d| d.0)))
|
||||
}
|
||||
pub fn get_second_deriv(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
let c = curve_arg(ctx, &a[0])?;
|
||||
done(val_point(c.derivs(num(&a[1])?).map(|d| d.1)))
|
||||
}
|
||||
pub fn get_area(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
done(Value::Real(curve_arg(ctx, &a[0])?.area()))
|
||||
}
|
||||
pub fn is_closed(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
done(Value::bool(curve_arg(ctx, &a[0])?.is_closed()))
|
||||
}
|
||||
pub fn is_periodic(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
done(Value::bool(curve_arg(ctx, &a[0])?.is_periodic()))
|
||||
}
|
||||
pub fn is_planar(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
done(Value::bool(curve_arg(ctx, &a[0])?.is_planar()))
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
//! Property tests for `vlax-curve-*`: hundreds of random curves of every kind, each function
|
||||
//! checked against the others and against independent oracles (CADCraft's own curve lengths and
|
||||
//! MEASURE points, AREA, dense sampling and numeric integration).
|
||||
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use cadcraft_doc::{Arc, Circle, Ellipse, Entity, EntityKind, Line, LwPolyline, Polyline3d};
|
||||
use cadcraft_geom::{PolyVertex, Polyline, Spline, Vec2, Vec3};
|
||||
|
||||
use super::curve::Curve;
|
||||
use crate::Session;
|
||||
use crate::cmd::curves::Chain;
|
||||
|
||||
type P3 = [f64; 3];
|
||||
|
||||
/// A small deterministic generator (xorshift64*), so a failure reproduces.
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
/// Uniform in `lo..hi`.
|
||||
fn f(&mut self, lo: f64, hi: f64) -> f64 {
|
||||
lo + (hi - lo) * (self.next() >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
fn n(&mut self, lo: usize, hi: usize) -> usize {
|
||||
lo + (self.next() % (hi - lo + 1) as u64) as usize
|
||||
}
|
||||
fn chance(&mut self, p: f64) -> bool {
|
||||
self.f(0.0, 1.0) < p
|
||||
}
|
||||
fn v2(&mut self, r: f64) -> Vec2 {
|
||||
Vec2::new(self.f(-r, r), self.f(-r, r))
|
||||
}
|
||||
fn v3(&mut self, r: f64) -> Vec3 {
|
||||
Vec3::new(self.f(-r, r), self.f(-r, r), self.f(-r, r))
|
||||
}
|
||||
}
|
||||
|
||||
fn dist(a: &P3, b: &P3) -> f64 {
|
||||
((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
|
||||
}
|
||||
|
||||
/// A random curve entity of kind `k` (0 line … 6 3D polyline).
|
||||
fn random_kind(r: &mut Rng, k: usize) -> EntityKind {
|
||||
let tau = std::f64::consts::TAU;
|
||||
match k {
|
||||
0 => EntityKind::Line(Line { a: r.v3(100.0), b: r.v3(100.0) }),
|
||||
1 => {
|
||||
let c = r.v2(100.0);
|
||||
// Angles on either side of 0 and beyond 2π: the arc may cross the 0° direction.
|
||||
EntityKind::Arc(Arc { center: c.to3(r.f(-5.0, 5.0)), radius: r.f(0.05, 80.0), start: r.f(-7.0, 7.0), end: r.f(-7.0, 7.0) })
|
||||
}
|
||||
2 => EntityKind::Circle(Circle { center: r.v2(100.0).to3(r.f(-5.0, 5.0)), radius: r.f(0.05, 80.0) }),
|
||||
3 => {
|
||||
let n = r.n(2, 12);
|
||||
let mut vertices = Vec::new();
|
||||
let mut p = r.v2(50.0);
|
||||
for _ in 0..n {
|
||||
// Some repeated vertices (zero-length segments), bulges both ways and none.
|
||||
if !r.chance(0.1) {
|
||||
p += r.v2(30.0);
|
||||
}
|
||||
let bulge = if r.chance(0.4) { 0.0 } else { r.f(-2.5, 2.5) };
|
||||
vertices.push(PolyVertex::with_bulge(p, bulge));
|
||||
}
|
||||
EntityKind::LwPolyline(LwPolyline { vertices, closed: r.chance(0.5), const_width: 0.0, elevation: r.f(-5.0, 5.0), plinegen: false })
|
||||
}
|
||||
4 => {
|
||||
let major = Vec2::from_angle(r.f(0.0, tau)) * r.f(0.5, 50.0);
|
||||
let full = r.chance(0.3);
|
||||
let (start, end) = if full { (0.0, tau) } else { (r.f(-1.0, 7.0), r.f(-1.0, 7.0)) };
|
||||
EntityKind::Ellipse(Ellipse { center: r.v2(100.0).to3(r.f(-5.0, 5.0)), major: major.to3(0.0), ratio: r.f(0.05, 1.0), start, end })
|
||||
}
|
||||
5 => {
|
||||
let n = r.n(3, 8);
|
||||
let mut fit = Vec::new();
|
||||
let mut p = r.v2(50.0);
|
||||
for _ in 0..n {
|
||||
p = p + r.v2(20.0) + Vec2::new(5.0, 0.0);
|
||||
fit.push(p);
|
||||
}
|
||||
EntityKind::Spline(if r.chance(0.3) { Spline::from_fit_points_closed(&fit) } else { Spline::from_fit_points(&fit) })
|
||||
}
|
||||
_ => {
|
||||
let n = r.n(2, 8);
|
||||
EntityKind::Polyline3d(Polyline3d { points: (0..n).map(|_| r.v3(50.0)).collect(), closed: r.chance(0.4) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn entity_of(s: &mut Session, kind: EntityKind) -> Entity {
|
||||
let h = s.add_entity(kind).unwrap();
|
||||
(**s.doc().unwrap().entity(h).unwrap()).clone()
|
||||
}
|
||||
|
||||
/// `n + 1` points on the curve, evenly spaced by parameter (straight from the exact evaluation,
|
||||
/// not through the distance functions under test).
|
||||
fn samples(c: &Curve, n: usize) -> Vec<P3> {
|
||||
let (t0, t1) = (c.start_param(), c.end_param());
|
||||
(0..=n).filter_map(|i| c.point_at_param(t0 + (t1 - t0) * i as f64 / n as f64)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_function_agrees_with_the_others_on_random_curves() {
|
||||
let mut r = Rng(0x5EED_CAD0_1335);
|
||||
let mut s = Session::new();
|
||||
let mut checked = 0;
|
||||
for round in 0..70 {
|
||||
for k in 0..7 {
|
||||
let kind = random_kind(&mut r, k);
|
||||
let e = entity_of(&mut s, kind.clone());
|
||||
let Some(c) = Curve::of(&e) else { panic!("round {round} kind {k}: not a curve: {kind:?}") };
|
||||
let ctx = format!("round {round} kind {k}: {kind:?}");
|
||||
let len = c.length();
|
||||
let scale = 1.0 + len;
|
||||
let tol = 1e-9 * scale;
|
||||
assert!(len.is_finite() && len >= 0.0, "{ctx}");
|
||||
let (t0, t1) = (c.start_param(), c.end_param());
|
||||
assert!(t1 >= t0, "{ctx}");
|
||||
// Ends: distance 0 and the whole length.
|
||||
assert!(c.dist_at_param(t0).unwrap().abs() <= tol, "{ctx}");
|
||||
assert!((c.dist_at_param(t1).unwrap() - len).abs() <= tol, "{ctx}");
|
||||
let mut last_d = -1.0;
|
||||
for i in 0..=24 {
|
||||
let t = t0 + (t1 - t0) * i as f64 / 24.0;
|
||||
let p = c.point_at_param(t).unwrap();
|
||||
let d = c.dist_at_param(t).unwrap();
|
||||
// Distance never goes back as the parameter grows.
|
||||
assert!(d >= last_d - tol, "{ctx}: t {t}");
|
||||
last_d = d;
|
||||
// Distance → parameter → point comes back to the same point.
|
||||
let t2 = c.param_at_dist(d).unwrap();
|
||||
assert!(dist(&c.point_at_param(t2).unwrap(), &p) <= 1e3 * tol, "{ctx}: t {t} t2 {t2}");
|
||||
assert!(dist(&c.point_at_dist(d).unwrap(), &p) <= 1e3 * tol, "{ctx}: d {d}");
|
||||
// A point on the curve is its own closest point, and has a parameter.
|
||||
let (_, q) = c.closest(&p).unwrap();
|
||||
assert!(dist(&q, &p) <= 1e3 * tol, "{ctx}: closest of on-curve point {p:?} gave {q:?}");
|
||||
let tp = c.param_at_point(&p).unwrap_or_else(|| panic!("{ctx}: no parameter at its own point {p:?}"));
|
||||
assert!(dist(&c.point_at_param(tp).unwrap(), &p) <= 1e3 * tol, "{ctx}");
|
||||
checked += 1;
|
||||
}
|
||||
// Past either end: nil.
|
||||
assert!(c.point_at_param(t1 + 1e-3 * (1.0 + (t1 - t0))).is_none(), "{ctx}");
|
||||
assert!(c.point_at_dist(len + 1e-3 * scale).is_none(), "{ctx}");
|
||||
assert!(c.point_at_dist(-1e-3 * scale).is_none(), "{ctx}");
|
||||
}
|
||||
}
|
||||
assert!(checked > 10_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lengths_and_measure_points_match_cadcraft_s_own_curves() {
|
||||
// `Chain` is what MEASURE, DIVIDE, LENGTHEN and BREAK walk along.
|
||||
let mut r = Rng(0xC4A1_0001);
|
||||
let mut s = Session::new();
|
||||
for round in 0..150 {
|
||||
for k in [0, 1, 2, 3] {
|
||||
let kind = random_kind(&mut r, k);
|
||||
let e = entity_of(&mut s, kind.clone());
|
||||
let c = Curve::of(&e).unwrap_or_else(|| panic!("not a curve: {kind:?}"));
|
||||
// CADCraft's chain leaves out a polyline with no length at all.
|
||||
let Some(chain) = Chain::of(&kind) else {
|
||||
assert!(c.length() <= 1e-9, "{kind:?}");
|
||||
continue;
|
||||
};
|
||||
let ctx = format!("round {round}: {kind:?}");
|
||||
// A line's z is its own; the chain is flat. Compare in plan for the others.
|
||||
if k == 0 {
|
||||
continue;
|
||||
}
|
||||
let len = chain.len();
|
||||
assert!((c.length() - len).abs() <= 1e-9 * (1.0 + len), "{ctx}: {} vs {len}", c.length());
|
||||
for i in 0..=16 {
|
||||
let d = len * i as f64 / 16.0;
|
||||
let (want, _) = chain.at_length(d).unwrap();
|
||||
let got = c.point_at_dist(d).unwrap();
|
||||
assert!(Vec2::new(got[0], got[1]).dist(want) <= 1e-7 * (1.0 + len), "{ctx}: at {d}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipse_and_spline_lengths_match_numeric_integration() {
|
||||
let mut r = Rng(0xE111_9505);
|
||||
let mut s = Session::new();
|
||||
for round in 0..40 {
|
||||
for k in [4, 5] {
|
||||
let kind = random_kind(&mut r, k);
|
||||
let e = entity_of(&mut s, kind.clone());
|
||||
let c = Curve::of(&e).unwrap();
|
||||
let (t0, t1) = (c.start_param(), c.end_param());
|
||||
// Simpson's rule on |C'(t)|, 4000 steps between each pair of knots (a spline is smooth
|
||||
// only within a span) and 20 000 over an ellipse, the speed from points on the exact
|
||||
// curve a millionth of the parameter range apart (a wider step's chord falls short).
|
||||
let dt = 1e-6 * (t1 - t0);
|
||||
let speed = |t: f64| {
|
||||
let (lo, hi) = ((t - dt).max(t0), (t + dt).min(t1));
|
||||
dist(&c.point_at_param(lo).unwrap(), &c.point_at_param(hi).unwrap()) / (hi - lo)
|
||||
};
|
||||
let mut cuts = vec![t0];
|
||||
if let EntityKind::Spline(sp) = &kind {
|
||||
cuts.extend(sp.knots.iter().copied().filter(|k| *k > t0 && *k < t1));
|
||||
}
|
||||
cuts.push(t1);
|
||||
cuts.dedup();
|
||||
let n = if cuts.len() > 2 { 4000 } else { 20_000 };
|
||||
let mut want = 0.0;
|
||||
for w in cuts.windows(2) {
|
||||
let (a, b) = (w[0], w[1]);
|
||||
let h = (b - a) / n as f64;
|
||||
let mut sum = speed(a) + speed(b);
|
||||
for i in 1..n {
|
||||
sum += speed(a + h * i as f64) * if i % 2 == 1 { 4.0 } else { 2.0 };
|
||||
}
|
||||
want += sum * h / 3.0;
|
||||
}
|
||||
let got = c.length();
|
||||
assert!((got - want).abs() <= 1e-8 * (1.0 + want), "round {round}: {kind:?}: {got} vs {want}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipse_and_spline_lengths_are_lengthen_s_own() {
|
||||
// LENGTHEN measures with the geometry crate's arc lengths: a routine and the command agree.
|
||||
let mut r = Rng(0x1E57_0335);
|
||||
let mut s = Session::new();
|
||||
for round in 0..60 {
|
||||
for k in [4, 5] {
|
||||
let kind = random_kind(&mut r, k);
|
||||
let e = entity_of(&mut s, kind.clone());
|
||||
let c = Curve::of(&e).unwrap();
|
||||
let (t0, t1) = (c.start_param(), c.end_param());
|
||||
let ctx = format!("round {round}: {kind:?}");
|
||||
let (len, at) = match &kind {
|
||||
EntityKind::Spline(sp) => (sp.length(), sp.length_between(t0, (t0 + t1) / 2.0)),
|
||||
EntityKind::Ellipse(el) => {
|
||||
let g = cadcraft_geom::Ellipse { center: el.center.xy(), major: el.major.xy(), ratio: el.ratio, start: el.start, end: el.end };
|
||||
let full = if g.is_full() { g.arc_length_from(0.0, std::f64::consts::TAU) } else { g.length() };
|
||||
(full, g.arc_length_from(t0, (t1 - t0) / 2.0))
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
assert!((c.length() - len).abs() <= 1e-12 * (1.0 + len), "{ctx}: {} vs {len}", c.length());
|
||||
assert!((c.dist_at_param((t0 + t1) / 2.0).unwrap() - at).abs() <= 1e-12 * (1.0 + len), "{ctx}");
|
||||
// Distance → parameter → distance comes back to the same distance.
|
||||
for i in 0..=20 {
|
||||
let d = len * i as f64 / 20.0;
|
||||
let t = c.param_at_dist(d).unwrap();
|
||||
assert!((c.dist_at_param(t).unwrap() - d).abs() <= 1e-9 * (1.0 + len), "{ctx}: at {d}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closest_points_are_never_beaten_by_a_sampled_point() {
|
||||
let mut r = Rng(0xC105_E570);
|
||||
let mut s = Session::new();
|
||||
for round in 0..40 {
|
||||
for k in 0..7 {
|
||||
let kind = random_kind(&mut r, k);
|
||||
let e = entity_of(&mut s, kind.clone());
|
||||
let c = Curve::of(&e).unwrap();
|
||||
let pts = samples(&c, 4000);
|
||||
for _ in 0..8 {
|
||||
let q3 = r.v3(150.0);
|
||||
// Plan curves are compared in their own plane.
|
||||
let q = if k == 6 || k == 0 { [q3.x, q3.y, q3.z] } else { [q3.x, q3.y, pts.first().map_or(0.0, |p| p[2])] };
|
||||
let (_, best) = c.closest(&q).unwrap();
|
||||
let got = dist(&best, &q);
|
||||
let sampled = pts.iter().map(|p| dist(p, &q)).fold(f64::INFINITY, f64::min);
|
||||
assert!(got <= sampled + 1e-7 * (1.0 + c.length()), "round {round} kind {k}: {got} > {sampled} for {q:?}: {kind:?}");
|
||||
// Extending never gives a farther point.
|
||||
let ext = c.closest_point(&q, true).unwrap();
|
||||
assert!(dist(&ext, &q) <= got + 1e-9, "round {round} kind {k}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derivatives_match_finite_differences() {
|
||||
let mut r = Rng(0xDE21_7A7E);
|
||||
let mut s = Session::new();
|
||||
for round in 0..60 {
|
||||
for k in [0, 1, 2, 3, 4, 5, 6] {
|
||||
let kind = random_kind(&mut r, k);
|
||||
let e = entity_of(&mut s, kind.clone());
|
||||
let c = Curve::of(&e).unwrap();
|
||||
let (t0, t1) = (c.start_param(), c.end_param());
|
||||
if t1 - t0 <= 1e-9 {
|
||||
continue;
|
||||
}
|
||||
for i in 0..10 {
|
||||
// Inside a polyline segment (derivatives jump at its vertices).
|
||||
let t = if matches!(k, 3 | 6) { (t0 + i as f64).min(t1 - 1.0) + 0.5 } else { t0 + (t1 - t0) * (0.05 + 0.9 * i as f64 / 9.0) };
|
||||
if t >= t1 {
|
||||
continue;
|
||||
}
|
||||
let h = 1e-6 * (t1 - t0).max(1.0);
|
||||
let (a, b) = (c.point_at_param(t - h).unwrap(), c.point_at_param(t + h).unwrap());
|
||||
let fd = [(b[0] - a[0]) / (2.0 * h), (b[1] - a[1]) / (2.0 * h), (b[2] - a[2]) / (2.0 * h)];
|
||||
let (d1, d2) = c.derivs(t).unwrap();
|
||||
let mag = dist(&fd, &[0.0; 3]).max(1.0);
|
||||
assert!(dist(&d1, &fd) <= 1e-4 * mag, "round {round} kind {k} t {t}: {d1:?} vs {fd:?}: {kind:?}");
|
||||
if k != 5 {
|
||||
let (da, db) = (c.derivs(t - h).unwrap().0, c.derivs(t + h).unwrap().0);
|
||||
let fd2 = [(db[0] - da[0]) / (2.0 * h), (db[1] - da[1]) / (2.0 * h), (db[2] - da[2]) / (2.0 * h)];
|
||||
let mag2 = dist(&fd2, &[0.0; 3]).max(1.0);
|
||||
assert!(dist(&d2, &fd2) <= 1e-3 * mag2, "round {round} kind {k} t {t}: {d2:?} vs {fd2:?}");
|
||||
}
|
||||
}
|
||||
// A line's parameter is its length: unit speed. An arc's or a circle's is the angle: speed r.
|
||||
match &kind {
|
||||
EntityKind::Line(_) if c.length() > 1e-9 => assert!((dist(&c.derivs(t0).unwrap().0, &[0.0; 3]) - 1.0).abs() <= 1e-9),
|
||||
EntityKind::Arc(a) => assert!((dist(&c.derivs(t0).unwrap().0, &[0.0; 3]) - a.radius).abs() <= 1e-9 * a.radius),
|
||||
EntityKind::Circle(ci) => assert!((dist(&c.derivs(t0).unwrap().0, &[0.0; 3]) - ci.radius).abs() <= 1e-9 * ci.radius),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The area of a closed polygon through dense samples of the curve.
|
||||
fn sampled_area(c: &Curve, n: usize) -> f64 {
|
||||
let pts: Vec<Vec2> = samples(c, n).into_iter().map(|p| Vec2::new(p[0], p[1])).collect();
|
||||
cadcraft_geom::shoelace(&pts).abs()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn areas_match_the_area_command_and_dense_sampling() {
|
||||
let mut r = Rng(0xA2EA_0042);
|
||||
let mut s = Session::new();
|
||||
for round in 0..80 {
|
||||
for k in [1, 2, 3, 4, 5] {
|
||||
let kind = random_kind(&mut r, k);
|
||||
let e = entity_of(&mut s, kind.clone());
|
||||
let c = Curve::of(&e).unwrap();
|
||||
let got = c.area();
|
||||
// Dense sampling, closed by the chord as an open curve is.
|
||||
let want = sampled_area(&c, 40_000);
|
||||
let size = c.length().powi(2).max(1.0);
|
||||
// A polygon through 40 000 points is itself ~1e-9 of the size short on a bend.
|
||||
assert!((got - want).abs() <= 1e-8 * size, "round {round} kind {k}: {got} vs {want}: {kind:?}");
|
||||
// AREA's Object option, for what it accepts.
|
||||
match &kind {
|
||||
EntityKind::Circle(_) | EntityKind::LwPolyline(LwPolyline { closed: true, .. }) => {
|
||||
let a = s.execute("area", &serde_json::json!({"handle": e.handle.hex()})).unwrap();
|
||||
let area = a["area"].as_f64().unwrap();
|
||||
assert!((got - area).abs() <= 1e-9 * size, "round {round}: {got} vs AREA {area}: {kind:?}");
|
||||
}
|
||||
EntityKind::Ellipse(el) if (el.end - el.start - std::f64::consts::TAU).abs() < 1e-12 => {
|
||||
let a = s.execute("area", &serde_json::json!({"handle": e.handle.hex()})).unwrap();
|
||||
assert!((got - a["area"].as_f64().unwrap()).abs() <= 1e-9 * size, "round {round}: {kind:?}");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let EntityKind::LwPolyline(pl) = &kind
|
||||
&& pl.closed
|
||||
{
|
||||
let g = Polyline { vertices: pl.vertices.clone(), closed: true };
|
||||
assert!((got - g.area().abs()).abs() <= 1e-9 * size, "round {round}");
|
||||
assert!((c.length() - g.len()).abs() <= 1e-9 * (1.0 + g.len()), "round {round}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ends_are_the_entity_s_own_points() {
|
||||
let mut r = Rng(0xE2D5_0001);
|
||||
let mut s = Session::new();
|
||||
for _ in 0..100 {
|
||||
for k in [0, 1, 3, 6] {
|
||||
let kind = random_kind(&mut r, k);
|
||||
let e = entity_of(&mut s, kind.clone());
|
||||
let c = Curve::of(&e).unwrap();
|
||||
let (a, b) = (c.point_at_param(c.start_param()).unwrap(), c.point_at_param(c.end_param()).unwrap());
|
||||
let (wa, wb): (P3, P3) = match &kind {
|
||||
EntityKind::Line(l) => ([l.a.x, l.a.y, l.a.z], [l.b.x, l.b.y, l.b.z]),
|
||||
EntityKind::Arc(ar) => {
|
||||
let (s0, s1) = (Vec2::polar(ar.center.xy(), ar.radius, ar.start), Vec2::polar(ar.center.xy(), ar.radius, ar.end));
|
||||
([s0.x, s0.y, ar.center.z], [s1.x, s1.y, ar.center.z])
|
||||
}
|
||||
EntityKind::LwPolyline(pl) => {
|
||||
let f = pl.vertices.first().unwrap().p;
|
||||
let l = if pl.closed { f } else { pl.vertices.last().unwrap().p };
|
||||
([f.x, f.y, pl.elevation], [l.x, l.y, pl.elevation])
|
||||
}
|
||||
EntityKind::Polyline3d(pl) => {
|
||||
let f = pl.points.first().unwrap();
|
||||
let l = if pl.closed { f } else { pl.points.last().unwrap() };
|
||||
([f.x, f.y, f.z], [l.x, l.y, l.z])
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
assert!(dist(&a, &wa) <= 1e-9 * (1.0 + c.length()), "{kind:?}: start {a:?} vs {wa:?}");
|
||||
assert!(dist(&b, &wb) <= 1e-9 * (1.0 + c.length()), "{kind:?}: end {b:?} vs {wb:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_geometry_never_panics() {
|
||||
let mut s = Session::new();
|
||||
let big = 1e300;
|
||||
let kinds = vec![
|
||||
EntityKind::Line(Line { a: Vec3::new(big, -big, big), b: Vec3::new(-big, big, -big) }),
|
||||
EntityKind::Line(Line { a: Vec3::new(1.0, 1.0, 1.0), b: Vec3::new(1.0, 1.0, 1.0) }),
|
||||
EntityKind::Arc(Arc { center: Vec3::new(0.0, 0.0, 0.0), radius: big, start: 0.0, end: 1.0 }),
|
||||
EntityKind::Arc(Arc { center: Vec3::new(0.0, 0.0, 0.0), radius: 0.0, start: 0.0, end: 1.0 }),
|
||||
EntityKind::Arc(Arc { center: Vec3::new(0.0, 0.0, 0.0), radius: 1.0, start: 1.0, end: 1.0 }),
|
||||
EntityKind::Circle(Circle { center: Vec3::new(big, big, 0.0), radius: big }),
|
||||
EntityKind::Ellipse(Ellipse { center: Vec3::new(0.0, 0.0, 0.0), major: Vec3::new(0.0, 0.0, 0.0), ratio: 0.0, start: 0.0, end: 1.0 }),
|
||||
EntityKind::Ellipse(Ellipse { center: Vec3::new(0.0, 0.0, 0.0), major: Vec3::new(big, 0.0, 0.0), ratio: 1.0, start: 0.0, end: 7.0 }),
|
||||
EntityKind::LwPolyline(LwPolyline {
|
||||
vertices: vec![
|
||||
PolyVertex::with_bulge(Vec2::new(0.0, 0.0), 1e12),
|
||||
PolyVertex::with_bulge(Vec2::new(1e-300, 0.0), -1e12),
|
||||
PolyVertex::new(Vec2::new(5.0, 5.0)),
|
||||
],
|
||||
closed: true,
|
||||
const_width: 0.0,
|
||||
elevation: 0.0,
|
||||
plinegen: false,
|
||||
}),
|
||||
EntityKind::LwPolyline(LwPolyline { vertices: Vec::new(), closed: true, const_width: 0.0, elevation: 0.0, plinegen: false }),
|
||||
EntityKind::Polyline3d(Polyline3d { points: vec![Vec3::new(0.0, 0.0, 0.0)], closed: true }),
|
||||
EntityKind::Polyline3d(Polyline3d { points: Vec::new(), closed: false }),
|
||||
EntityKind::Spline(Spline::from_fit_points(&[Vec2::new(0.0, 0.0), Vec2::new(0.0, 0.0), Vec2::new(0.0, 0.0)])),
|
||||
EntityKind::Spline(Spline::from_control(vec![Vec2::new(big, 0.0), Vec2::new(-big, big), Vec2::new(0.0, -big)], 2)),
|
||||
EntityKind::Spline(Spline::from_control(vec![Vec2::new(0.0, 0.0)], 3)),
|
||||
];
|
||||
for kind in kinds {
|
||||
let Ok(h) = s.add_entity(kind.clone()) else { continue };
|
||||
let e = (**s.doc().unwrap().entity(h).unwrap()).clone();
|
||||
let Some(c) = Curve::of(&e) else { continue };
|
||||
for t in [f64::NAN, f64::INFINITY, -f64::INFINITY, 0.0, 0.5, 1.0, 1e300, -1e300] {
|
||||
let _ = (c.point_at_param(t), c.dist_at_param(t), c.param_at_dist(t), c.point_at_dist(t), c.derivs(t));
|
||||
}
|
||||
for q in [[0.0, 0.0, 0.0], [f64::NAN, 0.0, 0.0], [big, -big, big], [f64::INFINITY, 1.0, 1.0]] {
|
||||
let _ = (c.closest(&q), c.closest_point(&q, true), c.param_at_point(&q));
|
||||
}
|
||||
let _ = (c.area(), c.length(), c.is_closed(), c.is_planar());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,635 @@
|
||||
//! `vlax-curve-*`, file and folder functions, environment variables, `getfiled`, `osnap` and the
|
||||
//! small helpers.
|
||||
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use cadcraft_doc::{Arc, Circle, Ellipse, EntityKind, Line, LwPolyline, Point, Polyline3d};
|
||||
use cadcraft_geom::{PolyVertex, Spline, Vec2, Vec3};
|
||||
|
||||
use super::value::to_text;
|
||||
use crate::Session;
|
||||
use crate::cmd::file::{EntityCodec, set_entity_codec};
|
||||
|
||||
fn session() -> Session {
|
||||
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
|
||||
Session::new()
|
||||
}
|
||||
|
||||
fn eval(s: &mut Session, code: &str) -> Result<String, String> {
|
||||
match s.lisp_eval(code, false, true, Vec::new()) {
|
||||
Ok(Some(Ok(v))) => Ok(to_text(&v, true)),
|
||||
Ok(Some(Err(e))) => Err(e),
|
||||
Ok(None) => Err("did not finish".into()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ok(s: &mut Session, code: &str) -> String {
|
||||
match eval(s, code) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{code}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds an entity and binds its name to `var`.
|
||||
fn add(s: &mut Session, var: &str, kind: EntityKind) {
|
||||
let h = s.add_entity(kind).unwrap();
|
||||
ok(s, &format!("(setq {var} (handent \"{}\"))", h.hex()));
|
||||
}
|
||||
|
||||
fn v3(x: f64, y: f64, z: f64) -> Vec3 {
|
||||
Vec3::new(x, y, z)
|
||||
}
|
||||
|
||||
/// `code` is T (the checks use `equal` with a fuzz).
|
||||
fn is_t(s: &mut Session, code: &str) {
|
||||
assert_eq!(ok(s, code), "T", "{code}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_is_measured_by_distance() {
|
||||
let mut s = session();
|
||||
add(&mut s, "e", EntityKind::Line(Line { a: v3(0.0, 0.0, 0.0), b: v3(3.0, 4.0, 0.0) }));
|
||||
is_t(&mut s, "(equal (vlax-curve-getStartParam e) 0.0 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getEndParam e) 5.0 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getDistAtParam e 2.5) 2.5 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getPointAtDist e 2.5) '(1.5 2.0 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getStartPoint e) '(0.0 0.0 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getEndPoint e) '(3.0 4.0 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getClosestPointTo e '(3 0)) '(1.08 1.44 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getFirstDeriv e 1.0) '(0.6 0.8 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getSecondDeriv e 1.0) '(0.0 0.0 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getParamAtPoint e '(1.5 2.0)) 2.5 1e-9)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getDistAtPoint e '(1.5 2.0 0.0)) 2.5 1e-9)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getArea e) 0.0 1e-12)");
|
||||
// Off the line, past its ends: nil.
|
||||
assert_eq!(ok(&mut s, "(vlax-curve-getParamAtPoint e '(5 5))"), "nil");
|
||||
assert_eq!(ok(&mut s, "(vlax-curve-getPointAtDist e 6)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(vlax-curve-getPointAtParam e -1)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(vlax-curve-isClosed e)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(vlax-curve-isPlanar e)"), "T");
|
||||
// Extended, the line goes on past its end.
|
||||
is_t(&mut s, "(equal (vlax-curve-getClosestPointTo e '(6 8) T) '(6.0 8.0 0.0) 1e-9)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getClosestPointTo e '(6 8)) '(3.0 4.0 0.0) 1e-9)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arc_is_measured_by_angle() {
|
||||
let mut s = session();
|
||||
let half_pi = std::f64::consts::FRAC_PI_2;
|
||||
add(&mut s, "e", EntityKind::Arc(Arc { center: v3(0.0, 0.0, 0.0), radius: 1.0, start: 0.0, end: half_pi }));
|
||||
is_t(&mut s, "(equal (vlax-curve-getEndParam e) (/ pi 2) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getDistAtParam e (vlax-curve-getEndParam e)) (/ pi 2) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getPointAtDist e (/ pi 4)) (list (sqrt 0.5) (sqrt 0.5) 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getParamAtPoint e '(0 1)) (/ pi 2) 1e-9)");
|
||||
assert_eq!(ok(&mut s, "(vlax-curve-getParamAtPoint e '(2 2))"), "nil");
|
||||
// The chord closes it: a quarter disc less the triangle.
|
||||
is_t(&mut s, "(equal (vlax-curve-getArea e) (- (/ pi 4) 0.5) 1e-12)");
|
||||
// Below the arc: its nearer end, or the circle it lies on when extended.
|
||||
is_t(&mut s, "(equal (vlax-curve-getClosestPointTo e '(0 -2)) '(1.0 0.0 0.0) 1e-9)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getClosestPointTo e '(0 -2) T) '(0.0 -1.0 0.0) 1e-9)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getFirstDeriv e 0.0) '(0.0 1.0 0.0) 1e-12)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_is_closed_and_periodic() {
|
||||
let mut s = session();
|
||||
add(&mut s, "e", EntityKind::Circle(Circle { center: v3(0.0, 0.0, 0.0), radius: 2.0 }));
|
||||
is_t(&mut s, "(equal (vlax-curve-getEndParam e) (* 2 pi) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getArea e) (* 4 pi) 1e-9)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getPointAtParam e (/ pi 2)) '(0.0 2.0 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getFirstDeriv e 0.0) '(0.0 2.0 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getSecondDeriv e 0.0) '(-2.0 0.0 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getDistAtParam e pi) (* 2 pi) 1e-12)");
|
||||
assert_eq!(ok(&mut s, "(list (vlax-curve-isClosed e) (vlax-curve-isPeriodic e))"), "(T T)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getClosestPointTo e '(5 0)) '(2.0 0.0 0.0) 1e-12)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_is_measured_by_vertex() {
|
||||
let mut s = session();
|
||||
// A line, then a counter-clockwise half circle from (10,0) to (10,10) round (15,5).
|
||||
let vertices =
|
||||
vec![PolyVertex::new(Vec2::new(0.0, 0.0)), PolyVertex::with_bulge(Vec2::new(10.0, 0.0), 1.0), PolyVertex::new(Vec2::new(10.0, 10.0))];
|
||||
let pl = LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 2.0, plinegen: false };
|
||||
add(&mut s, "e", EntityKind::LwPolyline(pl.clone()));
|
||||
is_t(&mut s, "(equal (vlax-curve-getEndParam e) 2.0 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getDistAtParam e 2.0) (+ 10 (* 5 pi)) 1e-9)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getDistAtParam e 1.5) (+ 10 (* 2.5 pi)) 1e-9)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getPointAtParam e 1.5) '(15.0 5.0 2.0) 1e-9)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getParamAtDist e 5) 0.5 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getEndPoint e) '(10.0 10.0 2.0) 1e-9)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getParamAtPoint e '(15 5 2)) 1.5 1e-9)");
|
||||
// The triangle the chord closes, and the half disc outside it.
|
||||
is_t(&mut s, "(equal (vlax-curve-getArea e) (+ 50 (* 12.5 pi)) 1e-9)");
|
||||
assert_eq!(ok(&mut s, "(vlax-curve-isClosed e)"), "nil");
|
||||
// Closed: one more segment, back to the start.
|
||||
add(&mut s, "c", EntityKind::LwPolyline(LwPolyline { closed: true, ..pl }));
|
||||
is_t(&mut s, "(equal (vlax-curve-getEndParam c) 3.0 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getDistAtParam c 3.0) (+ 10 (* 5 pi) (sqrt 200)) 1e-9)");
|
||||
assert_eq!(ok(&mut s, "(vlax-curve-isClosed c)"), "T");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ellipse_keeps_its_own_parameter() {
|
||||
let mut s = session();
|
||||
let tau = std::f64::consts::TAU;
|
||||
add(&mut s, "e", EntityKind::Ellipse(Ellipse { center: v3(0.0, 0.0, 0.0), major: v3(4.0, 0.0, 0.0), ratio: 0.5, start: 0.0, end: tau }));
|
||||
is_t(&mut s, "(equal (vlax-curve-getEndParam e) (* 2 pi) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getPointAtParam e (/ pi 2)) '(0.0 2.0 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getArea e) (* 8 pi) 1e-9)");
|
||||
// Ramanujan's perimeter is within 1e-5 of the true one at this ratio.
|
||||
is_t(&mut s, "(equal (vlax-curve-getDistAtParam e (* 2 pi)) (* pi (- 18 (sqrt 140))) 1e-4)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getParamAtPoint e '(0 -2)) (* 1.5 pi) 1e-6)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getFirstDeriv e 0.0) '(0.0 2.0 0.0) 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getClosestPointTo e '(10 0)) '(4.0 0.0 0.0) 1e-9)");
|
||||
assert_eq!(ok(&mut s, "(list (vlax-curve-isClosed e) (vlax-curve-isPeriodic e))"), "(T T)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_ellipse_queried_near_its_centre_finds_the_minor_end() {
|
||||
let mut s = session();
|
||||
let tau = std::f64::consts::TAU;
|
||||
add(&mut s, "e", EntityKind::Ellipse(Ellipse { center: v3(0.0, 0.0, 0.0), major: v3(10.0, 0.0, 0.0), ratio: 0.1, start: 0.0, end: tau }));
|
||||
// The centre and a point just off it: the nearest point is a minor-axis end (1 away), not a major-axis end (10 away).
|
||||
is_t(&mut s, "(< (distance (vlax-curve-getClosestPointTo e '(0 0)) '(0 0)) 1.0001)");
|
||||
is_t(&mut s, "(< (distance (vlax-curve-getClosestPointTo e '(0.001 0.2)) '(0.001 0.2)) (+ 0.8 1e-3))");
|
||||
}
|
||||
|
||||
/// Near the +major end of a full ellipse the nearest point can lie across the 0/TAU seam from
|
||||
/// where the search starts, so the refinement wraps rather than stopping at a parameter end.
|
||||
#[test]
|
||||
fn a_full_ellipse_is_searched_across_its_seam() {
|
||||
let mut s = session();
|
||||
let tau = std::f64::consts::TAU;
|
||||
add(&mut s, "e", EntityKind::Ellipse(Ellipse { center: v3(0.0, 0.0, 0.0), major: v3(10.0, 0.0, 0.0), ratio: 0.1, start: 0.0, end: tau }));
|
||||
// Just inside the +major end and a little below the axis: the nearest t is about TAU - 0.00056.
|
||||
is_t(
|
||||
&mut s,
|
||||
"(setq q '(9.99 -0.0005) p (vlax-curve-getClosestPointTo e q) u (vlax-curve-getParamAtPoint e p)) (and (> u (- (* 2 pi) 0.001)) (< u (* 2 pi)))",
|
||||
);
|
||||
is_t(
|
||||
&mut s,
|
||||
"(and (< (cadr p) 0.0) (< (distance p q) (distance '(10.0 0.0) q)) (equal (vlax-curve-getParamAtPoint e (vlax-curve-getClosestPointTo e q)) u 1e-9))",
|
||||
);
|
||||
is_t(&mut s, "(equal (vlax-curve-getParamAtPoint e (vlax-curve-getClosestPointTo e '(9.99 0.0005))) 0.000556 1e-4)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spline_round_trips_parameters_points_and_distances() {
|
||||
let mut s = session();
|
||||
let sp = Spline::from_fit_points(&[Vec2::new(0.0, 0.0), Vec2::new(3.0, 2.0), Vec2::new(6.0, -1.0), Vec2::new(9.0, 1.0)]);
|
||||
add(&mut s, "e", EntityKind::Spline(sp));
|
||||
is_t(&mut s, "(equal (vlax-curve-getStartPoint e) '(0.0 0.0 0.0) 1e-9)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getEndPoint e) '(9.0 1.0 0.0) 1e-9)");
|
||||
// Halfway along: the parameter there gives back the point, and the point the parameter.
|
||||
ok(
|
||||
&mut s,
|
||||
"(setq len (vlax-curve-getDistAtParam e (vlax-curve-getEndParam e)) pm (vlax-curve-getParamAtDist e (/ len 2)) p (vlax-curve-getPointAtParam e pm))",
|
||||
);
|
||||
is_t(&mut s, "(> len 9.0)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getParamAtPoint e p) pm 1e-6)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getDistAtPoint e p) (/ len 2) 1e-4)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getPointAtDist e (/ len 2)) p 1e-6)");
|
||||
// A point off the curve is pulled onto it.
|
||||
is_t(&mut s, "(equal (vlax-curve-getClosestPointTo e (mapcar '+ p '(0 0.001 0))) p 1e-3)");
|
||||
// The first derivative points the way the curve goes.
|
||||
is_t(&mut s, "(> (car (vlax-curve-getFirstDeriv e pm)) 0)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vlax_curve_rejects_a_spline_whose_length_overflows() {
|
||||
let mut s = session();
|
||||
let huge = Spline {
|
||||
degree: 1,
|
||||
knots: vec![0.0, 0.0, 1.0, 2.0, 2.0],
|
||||
control: vec![Vec2::new(0.0, 0.0), Vec2::new(1e308, 0.0), Vec2::new(0.0, 0.0)],
|
||||
..Spline::default()
|
||||
};
|
||||
add(&mut s, "e", EntityKind::Spline(huge));
|
||||
// Not 0.0: a length past f64's range is not measurable.
|
||||
for code in [
|
||||
"(vlax-curve-getDistAtParam e 1.0)",
|
||||
"(vlax-curve-getDistAtParam e 2.0)",
|
||||
"(vlax-curve-getParamAtDist e 1e300)",
|
||||
"(vlax-curve-getPointAtDist e 1e300)",
|
||||
] {
|
||||
let r = eval(&mut s, code);
|
||||
assert!(matches!(r.as_deref(), Ok("nil") | Err(_)), "{code}: {r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_3d_polyline_measures_in_space() {
|
||||
let mut s = session();
|
||||
let flat = Polyline3d { points: vec![v3(0.0, 0.0, 0.0), v3(3.0, 4.0, 0.0), v3(3.0, 4.0, 12.0)], closed: false };
|
||||
add(&mut s, "e", EntityKind::Polyline3d(flat));
|
||||
is_t(&mut s, "(equal (vlax-curve-getDistAtParam e 2) 17.0 1e-12)");
|
||||
is_t(&mut s, "(equal (vlax-curve-getPointAtDist e 11) '(3.0 4.0 6.0) 1e-12)");
|
||||
assert_eq!(ok(&mut s, "(vlax-curve-isPlanar e)"), "T");
|
||||
let twisted = Polyline3d { points: vec![v3(0.0, 0.0, 0.0), v3(1.0, 0.0, 0.0), v3(1.0, 1.0, 0.0), v3(1.0, 1.0, 1.0)], closed: false };
|
||||
add(&mut s, "tw", EntityKind::Polyline3d(twisted));
|
||||
assert_eq!(ok(&mut s, "(vlax-curve-isPlanar tw)"), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_not_a_curve_is_an_error() {
|
||||
let mut s = session();
|
||||
add(&mut s, "pt", EntityKind::Point(Point { p: v3(1.0, 1.0, 0.0), angle: 0.0 }));
|
||||
assert_eq!(eval(&mut s, "(vlax-curve-getEndParam pt)").map_err(|e| e.starts_with("bad argument type: curvep")), Err(true));
|
||||
assert_eq!(eval(&mut s, "(vlax-curve-getEndParam 1)"), Err("bad argument type: lentityp: 1".into()));
|
||||
assert_eq!(eval(&mut s, "(vlax-curve-getEndParam)"), Err("too few arguments".into()));
|
||||
}
|
||||
|
||||
/// `read-char` reads on from where it left off in a line (multi-byte characters whole, 10 at
|
||||
/// each line end), and `read-line` gives the rest of a line `read-char` has started.
|
||||
#[test]
|
||||
fn read_char_and_read_line_share_their_place_in_the_file() {
|
||||
let mut s = session();
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-readchar-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("r.txt");
|
||||
std::fs::write(&path, "h\u{e9}llo\nab\n").unwrap();
|
||||
let p = path.to_string_lossy().replace('\\', "/");
|
||||
let code = format!(
|
||||
"(setq f (open \"{p}\" \"r\")) (list (read-char f) (read-char f) (read-line f) (read-char f) (read-char f) (read-char f) (read-char f) (progn (close f) 1))"
|
||||
);
|
||||
// h, é (233, one character of two bytes), the rest "llo", then a, b, the line end, the end.
|
||||
assert_eq!(ok(&mut s, &code), "(104 233 \"llo\" 97 98 10 nil 1)");
|
||||
// A long line read a character at a time comes out whole, in order.
|
||||
std::fs::write(&path, format!("{}\n", "xy".repeat(2000))).unwrap();
|
||||
let code = format!("(setq f (open \"{p}\" \"r\") n 0 c (read-char f)) (while (and c (/= c 10)) (setq n (1+ n) c (read-char f))) (close f) n");
|
||||
assert_eq!(ok(&mut s, &code), "4000");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The end of a file as `read-char` and `read-line` see it: a last line with no terminator
|
||||
/// reads back without an invented 10 and ends the file once its characters are used up (also
|
||||
/// for `read-line` after a `read-char`); only LF and CRLF end a line (a lone CR is data).
|
||||
#[test]
|
||||
fn read_char_reproduces_the_final_terminator_state() {
|
||||
let mut s = session();
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-eof-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("r.txt");
|
||||
let p = path.to_string_lossy().replace('\\', "/");
|
||||
let code = format!("(setq f (open \"{p}\" \"r\")) (list (read-char f) (read-char f) (read-char f) (progn (close f) 1))");
|
||||
std::fs::write(&path, "a").unwrap();
|
||||
assert_eq!(ok(&mut s, &code), "(97 nil nil 1)");
|
||||
std::fs::write(&path, "a\n").unwrap();
|
||||
assert_eq!(ok(&mut s, &code), "(97 10 nil 1)");
|
||||
std::fs::write(&path, "a\r\n").unwrap();
|
||||
assert_eq!(ok(&mut s, &code), "(97 10 nil 1)");
|
||||
std::fs::write(&path, "a\nb").unwrap();
|
||||
assert_eq!(ok(&mut s, &code), "(97 10 98 1)");
|
||||
// A lone CR is data (only LF and CRLF end a line), also at the end of the file: "a\r" is an
|
||||
// unterminated line of two characters.
|
||||
std::fs::write(&path, "a\r").unwrap();
|
||||
assert_eq!(ok(&mut s, &code), "(97 13 nil 1)");
|
||||
let lens = format!("(setq f (open \"{p}\" \"r\")) (list (strlen (read-line f)) (read-line f) (progn (close f) 1))");
|
||||
assert_eq!(ok(&mut s, &lens), "(2 nil 1)");
|
||||
std::fs::write(&path, "a\rb\r\nc").unwrap();
|
||||
let all = format!("(setq f (open \"{p}\" \"r\")) (list (strlen (read-line f)) (read-line f) (read-line f) (progn (close f) 1))");
|
||||
assert_eq!(ok(&mut s, &all), "(3 \"c\" nil 1)");
|
||||
let chars = format!(
|
||||
"(setq f (open \"{p}\" \"r\")) (list (read-char f) (read-char f) (read-char f) (read-char f) (read-char f) (read-char f) (progn (close f) 1))"
|
||||
);
|
||||
assert_eq!(ok(&mut s, &chars), "(97 13 98 10 99 nil 1)");
|
||||
// read-line after read-char: the rest of the line, and nothing once an unterminated last line is used up.
|
||||
let mixed = format!("(setq f (open \"{p}\" \"r\")) (list (read-char f) (read-line f) (read-line f) (progn (close f) 1))");
|
||||
std::fs::write(&path, "a").unwrap();
|
||||
assert_eq!(ok(&mut s, &mixed), "(97 nil nil 1)");
|
||||
std::fs::write(&path, "a\n").unwrap();
|
||||
assert_eq!(ok(&mut s, &mixed), "(97 \"\" nil 1)");
|
||||
std::fs::write(&path, "ab").unwrap();
|
||||
assert_eq!(ok(&mut s, &mixed), "(97 \"b\" nil 1)");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_and_folders() {
|
||||
let mut s = session();
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-files-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let d = dir.to_string_lossy().replace('\\', "/");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-mkdir \"{d}\")")), "T");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-mkdir \"{d}\")")), "nil", "it exists");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-directory-p \"{d}\")")), "T");
|
||||
ok(&mut s, &format!("(setq f (open \"{d}/a.txt\" \"w\")) (write-line \"hello\" f) (close f)"));
|
||||
let a = format!("{d}/a.txt");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-size \"{a}\")")), "6");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-size \"{d}\")")), "0", "a folder");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-copy \"{a}\" \"{d}/b.txt\")")), "6");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-copy \"{a}\" \"{d}/b.txt\")")), "nil", "never over an existing file");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-copy \"{a}\" \"{d}/b.txt\" T)")), "6");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-size \"{d}/b.txt\")")), "12");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-rename \"{d}/b.txt\" \"{d}/c.lsp\")")), "T");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-rename \"{d}/b.txt\" \"{d}/d.lsp\")")), "nil", "gone");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-directory-files \"{d}\" \"*.lsp\" 1)")), "(\"c.lsp\")");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-directory-files \"{d}\" nil 1)")), "(\"a.txt\" \"c.lsp\")");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-directory-files \"{d}\" nil -1)")), "(\".\" \"..\")");
|
||||
// Seven elements on Windows, eight (with milliseconds) elsewhere.
|
||||
assert_eq!(ok(&mut s, &format!("(length (vl-file-systime \"{a}\"))")), if cfg!(windows) { "7" } else { "8" });
|
||||
is_t(&mut s, &format!("(>= (car (vl-file-systime \"{a}\")) 2024)"));
|
||||
// read-char gives one character at a time.
|
||||
assert_eq!(ok(&mut s, &format!("(setq f (open \"{a}\" \"r\")) (list (read-char f) (read-char f) (progn (close f) 1))")), "(104 101 1)");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-delete \"{d}/c.lsp\")")), "T");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-delete \"{d}/c.lsp\")")), "nil");
|
||||
assert_eq!(ok(&mut s, "(vl-file-size \"no/such/file/anywhere.txt\")"), "nil");
|
||||
assert_eq!(ok(&mut s, "(vl-directory-files \"no/such/folder/anywhere\")"), "nil");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environment_variables() {
|
||||
let mut s = session();
|
||||
assert_eq!(ok(&mut s, "(setenv \"CadCraftLispTestVar\" \"42\")"), "\"42\"");
|
||||
assert_eq!(ok(&mut s, "(getenv \"CADCRAFTLISPTESTVAR\")"), "\"42\"", "names ignore case");
|
||||
assert_eq!(ok(&mut s, "(getenv \"CADCRAFT_LISP_NEVER_SET_ANYWHERE\")"), "nil");
|
||||
assert!(eval(&mut s, "(setenv \"\" \"x\")").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn getfiled_asks_at_the_command_line() {
|
||||
let mut s = session();
|
||||
// A new file: any name, the extension added.
|
||||
s.cmdline("(setq f (getfiled \"Save drawing as\" \"\" \"dxf\" 1))").unwrap();
|
||||
assert!(s.lisp_running());
|
||||
assert_eq!(s.prompt_text(), "Save drawing as: ");
|
||||
s.cmdline("plans/site").unwrap();
|
||||
assert!(!s.lisp_running());
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), "\"plans/site.dxf\"");
|
||||
// Enter takes the default.
|
||||
s.cmdline("(setq f (getfiled \"Export\" \"out\" \"csv\" 1))").unwrap();
|
||||
assert_eq!(s.prompt_text(), "Export <out>: ");
|
||||
s.input(crate::Input::Enter).unwrap();
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), "\"out.csv\"");
|
||||
// An existing file must exist: ask again; Enter with no default gives nil.
|
||||
s.cmdline("(setq f (getfiled \"Open\" \"\" \"lsp\" 0))").unwrap();
|
||||
s.cmdline("no-such-routine-anywhere").unwrap();
|
||||
assert!(s.lisp_running(), "asks again");
|
||||
s.input(crate::Input::Enter).unwrap();
|
||||
assert!(!s.lisp_running());
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), "nil");
|
||||
// Enter on a default that isn't there, in open mode, asks again as a typed name does; a file
|
||||
// that is there is taken.
|
||||
s.cmdline("(setq f (getfiled \"Open\" \"no-such-default-anywhere\" \"lsp\" 0))").unwrap();
|
||||
s.input(crate::Input::Enter).unwrap();
|
||||
assert!(s.lisp_running(), "a default that isn't there asks again");
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-getfiled-enter-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let real = dir.join("here.lsp");
|
||||
std::fs::write(&real, "(princ)").unwrap();
|
||||
let real = real.to_string_lossy().replace('\\', "/");
|
||||
s.cmdline(&real).unwrap();
|
||||
assert!(!s.lisp_running());
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), format!("\"{real}\""));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// New-file mode asks before a file that is there is replaced, unless flag 32 says not to; No
|
||||
/// (the default) asks for a name again.
|
||||
#[test]
|
||||
fn getfiled_asks_before_replacing_a_file() {
|
||||
let mut s = session();
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-getfiled-replace-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let real = dir.join("plan.dxf");
|
||||
std::fs::write(&real, "0\nEOF\n").unwrap();
|
||||
let real = real.to_string_lossy().replace('\\', "/");
|
||||
let ask = format!("{real} already exists. Replace it? [Yes/No] <No>: ");
|
||||
// Enter keeps the file: the name is asked again. Yes replaces it.
|
||||
s.cmdline("(setq f (getfiled \"Save\" \"\" \"dxf\" 1))").unwrap();
|
||||
s.cmdline(&real).unwrap();
|
||||
assert!(s.lisp_running());
|
||||
assert_eq!(s.prompt_text(), ask);
|
||||
s.input(crate::Input::Enter).unwrap();
|
||||
assert!(s.lisp_running());
|
||||
assert_eq!(s.prompt_text(), "Save: ");
|
||||
s.cmdline(&real).unwrap();
|
||||
s.cmdline("yes").unwrap();
|
||||
assert!(!s.lisp_running());
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), format!("\"{real}\""));
|
||||
// No: another name, taken.
|
||||
s.cmdline("(setq f (getfiled \"Save\" \"\" \"dxf\" 1))").unwrap();
|
||||
s.cmdline(&real).unwrap();
|
||||
s.cmdline("n").unwrap();
|
||||
assert_eq!(s.prompt_text(), "Save: ");
|
||||
s.cmdline("other").unwrap();
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), "\"other.dxf\"");
|
||||
// Flag 32 with flag 1: no question.
|
||||
s.cmdline("(setq f (getfiled \"Save\" \"\" \"dxf\" 33))").unwrap();
|
||||
s.cmdline(&real).unwrap();
|
||||
assert!(!s.lisp_running());
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), format!("\"{real}\""));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A default ending in a path delimiter, or any default with flag 16, is the folder relative
|
||||
/// names are in, not a file name Enter takes.
|
||||
#[test]
|
||||
fn getfiled_default_folder() {
|
||||
let mut s = session();
|
||||
s.cmdline("(setq f (getfiled \"Save\" \"plans/\" \"dxf\" 1))").unwrap();
|
||||
assert_eq!(s.prompt_text(), "Save: ");
|
||||
s.cmdline("site").unwrap();
|
||||
assert_eq!(to_text(&s.lisp_var("F"), false), "plans/site.dxf");
|
||||
s.cmdline("(setq f (getfiled \"Save\" \"plans\" \"dxf\" 17))").unwrap();
|
||||
s.cmdline("site").unwrap();
|
||||
assert_eq!(to_text(&s.lisp_var("F"), false), std::path::Path::new("plans").join("site.dxf").to_string_lossy());
|
||||
// Enter with only a folder: no name, nil.
|
||||
s.cmdline("(setq f (getfiled \"Save\" \"plans/\" \"dxf\" 1))").unwrap();
|
||||
s.input(crate::Input::Enter).unwrap();
|
||||
assert!(!s.lisp_running());
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn osnap_finds_the_snap_near_a_point() {
|
||||
let mut s = session();
|
||||
add(&mut s, "e", EntityKind::Line(Line { a: v3(0.0, 0.0, 0.0), b: v3(10.0, 0.0, 0.0) }));
|
||||
is_t(&mut s, "(equal (osnap '(0.0001 0.0001) \"_end\") '(0.0 0.0) 1e-9)");
|
||||
is_t(&mut s, "(equal (osnap '(5.0001 0.0001 0.0) \"_mid,_end\") '(5.0 0.0 0.0) 1e-9)");
|
||||
assert_eq!(ok(&mut s, "(osnap '(5 0) \"nosuchmode\")"), "nil");
|
||||
assert_eq!(ok(&mut s, "(osnap '(500 500) \"_end\")"), "nil", "nothing within the aperture");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_numbers_and_strings() {
|
||||
let mut s = session();
|
||||
assert_eq!(ok(&mut s, "(list (boole 1 12 10) (boole 6 12 10) (boole 7 12 10) (boole 8 0 0))"), "(8 6 14 -1)");
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
"(list (vl-string-position 97 \"banana\") (vl-string-position 97 \"banana\" 2) (vl-string-position 97 \"banana\" 0 T) (vl-string-position 122 \"banana\"))"
|
||||
),
|
||||
"(1 3 5 nil)"
|
||||
);
|
||||
assert_eq!(ok(&mut s, "(vl-string-elt \"abc\" 1)"), "98");
|
||||
assert!(eval(&mut s, "(vl-string-elt \"abc\" 3)").is_err());
|
||||
assert_eq!(ok(&mut s, "(list (vl-string-mismatch \"VL-FUN\" \"VL-VAR\") (vl-string-mismatch \"abc\" \"ABD\" 0 0 T))"), "(3 2)");
|
||||
assert_eq!(
|
||||
ok(&mut s, "(list (snvalid \"Layer 1\") (snvalid \"a<b\") (snvalid \"\") (snvalid \"a|b\") (snvalid \"a|b\" 1))"),
|
||||
"(T nil nil nil T)"
|
||||
);
|
||||
assert_eq!(ok(&mut s, "(list (getcname \"line\") (getcname \"_line\") (getcname \"nosuchcommandanywhere\"))"), "(\"_LINE\" \"LINE\" nil)");
|
||||
assert_eq!(ok(&mut s, "(atoms-family 1 '(\"CAR\" \"NOSUCHSYMBOLANYWHERE\"))"), "(\"CAR\" nil)");
|
||||
assert_eq!(ok(&mut s, "(list (acad-push-dbmod) (acad-pop-dbmod) (textscr) (graphscr))"), "(T T nil nil)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_arguments_are_errors_not_crashes() {
|
||||
let mut s = session();
|
||||
add(&mut s, "e", EntityKind::Line(Line { a: v3(0.0, 0.0, 0.0), b: v3(1.0, 0.0, 0.0) }));
|
||||
for code in [
|
||||
"(vlax-curve-getPointAtParam e 1e308)",
|
||||
"(vlax-curve-getPointAtDist e -1e308)",
|
||||
"(vlax-curve-getClosestPointTo e '(1e308 -1e308))",
|
||||
"(vlax-curve-getClosestPointToProjection e '(0 0 0) '(0 0 0))",
|
||||
"(vlax-curve-getParamAtPoint e \"x\")",
|
||||
"(vlax-curve-getFirstDeriv e nil)",
|
||||
"(vlax-curve-getArea nil)",
|
||||
"(vl-file-copy 1 2)",
|
||||
"(vl-directory-files 1 2 3)",
|
||||
"(vl-directory-files \".\" \"*\" 7)",
|
||||
"(getenv 1)",
|
||||
"(setenv \"A\" 1)",
|
||||
"(osnap 1 2)",
|
||||
"(osnap '(0 0) \"\")",
|
||||
"(boole 1)",
|
||||
"(boole 1 1.5 2)",
|
||||
"(vl-string-position -1 \"abc\")",
|
||||
"(vl-string-position 97 \"abc\" -4)",
|
||||
"(vl-string-elt \"abc\" -1)",
|
||||
"(vl-string-mismatch \"a\" \"b\" -1)",
|
||||
"(snvalid nil)",
|
||||
"(getcname nil)",
|
||||
"(atoms-family 2)",
|
||||
"(read-char 5)",
|
||||
"(write-char -1)",
|
||||
"(write-char 1114112)",
|
||||
"(getfiled 1 2 3 4)",
|
||||
"(getfiled \"a\" \"b\" \"c\")",
|
||||
] {
|
||||
// Any outcome but a panic.
|
||||
let _ = eval(&mut s, code);
|
||||
}
|
||||
// A degenerate polyline and a zero-radius circle measure as points.
|
||||
add(
|
||||
&mut s,
|
||||
"p",
|
||||
EntityKind::LwPolyline(LwPolyline {
|
||||
vertices: vec![PolyVertex::new(Vec2::new(1.0, 1.0))],
|
||||
closed: false,
|
||||
const_width: 0.0,
|
||||
elevation: 0.0,
|
||||
plinegen: false,
|
||||
}),
|
||||
);
|
||||
is_t(&mut s, "(equal (vlax-curve-getDistAtParam p 0) 0.0 1e-12)");
|
||||
add(&mut s, "c", EntityKind::Circle(Circle { center: v3(0.0, 0.0, 0.0), radius: 0.0 }));
|
||||
is_t(&mut s, "(equal (vlax-curve-getClosestPointTo c '(3 4)) '(0.0 0.0 0.0) 1e-12)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curves_through_entsel_ssget_and_the_lisp_command() {
|
||||
let mut s = session();
|
||||
let h = s.add_entity(EntityKind::Circle(Circle { center: v3(5.0, 5.0, 0.0), radius: 1.0 })).unwrap();
|
||||
// A routine walking a selection set, as real ones do.
|
||||
let code = "(setq ss (ssget \"X\" '((0 . \"CIRCLE\"))) tot 0.0 i 0)
|
||||
(repeat (sslength ss) (setq e (ssname ss i) tot (+ tot (vlax-curve-getDistAtParam e (vlax-curve-getEndParam e))) i (1+ i)))
|
||||
tot";
|
||||
is_t(&mut s, &format!("(equal (progn {code}) (* 2 pi) 1e-12)"));
|
||||
// Programmatically (scripts, the control channel, MCP): the same answer.
|
||||
let r = s.execute("lisp", &serde_json::json!({"code": format!("(vlax-curve-getArea (handent \"{}\"))", h.hex())})).unwrap();
|
||||
assert_eq!(r["value"], "3.14159", "{r}");
|
||||
// An erased object is no longer a curve.
|
||||
ok(&mut s, &format!("(setq c (handent \"{}\"))", h.hex()));
|
||||
s.execute("erase", &serde_json::json!({"handles": [h.hex()]})).unwrap();
|
||||
assert!(eval(&mut s, "(vlax-curve-getArea c)").is_err());
|
||||
// vl-catch-all-apply turns the error into a value, as routines guard these calls.
|
||||
assert_eq!(ok(&mut s, "(vl-catch-all-error-p (vl-catch-all-apply 'vlax-curve-getArea (list c)))"), "T");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn getfiled_extensions_spaces_and_cancel() {
|
||||
let mut s = session();
|
||||
// The first of several extensions, with or without its dot; a name with spaces stays whole.
|
||||
s.cmdline("(setq f (getfiled \"Save\" \"\" \"dwg;dxf\" 1))").unwrap();
|
||||
s.cmdline("my plans/site plan").unwrap();
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), "\"my plans/site plan.dwg\"");
|
||||
s.cmdline("(setq f (getfiled \"Save\" \"\" \".csv\" 1))").unwrap();
|
||||
s.cmdline("\"quoted name\"").unwrap();
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), "\"quoted name.csv\"");
|
||||
// A name with its own extension keeps it; "*" adds none.
|
||||
s.cmdline("(setq f (getfiled \"Save\" \"\" \"dxf\" 1))").unwrap();
|
||||
s.cmdline("report.txt").unwrap();
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), "\"report.txt\"");
|
||||
s.cmdline("(setq f (getfiled \"Save\" \"\" \"*\" 1))").unwrap();
|
||||
s.cmdline("README").unwrap();
|
||||
assert_eq!(to_text(&s.lisp_var("F"), true), "\"README\"");
|
||||
// An existing file is found.
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-getfiled-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("tool.lsp"), "(princ)").unwrap();
|
||||
let base = dir.join("tool").to_string_lossy().replace('\\', "/");
|
||||
s.cmdline("(setq f (getfiled \"Load\" \"\" \"lsp\" 0))").unwrap();
|
||||
s.cmdline(&base).unwrap();
|
||||
assert!(!s.lisp_running());
|
||||
assert_eq!(to_text(&s.lisp_var("F"), false), format!("{base}.lsp"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
// Esc stops the routine, as at any prompt; *error* hears "Function cancelled".
|
||||
s.cmdline("(defun *error* (m) (setq why m))").unwrap();
|
||||
s.cmdline("(setq f (getfiled \"Open\" \"\" \"lsp\" 0))").unwrap();
|
||||
assert!(s.lisp_running());
|
||||
s.cancel();
|
||||
assert!(!s.lisp_running());
|
||||
assert_eq!(to_text(&s.lisp_var("WHY"), true), "\"Function cancelled\"");
|
||||
// A programmatic run has no one to ask: nil.
|
||||
assert_eq!(ok(&mut s, "(getfiled \"Open\" \"\" \"lsp\" 0)"), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn osnap_modes_and_heights() {
|
||||
let mut s = session();
|
||||
add(&mut s, "c", EntityKind::Circle(Circle { center: v3(20.0, 0.0, 0.0), radius: 3.0 }));
|
||||
// A 3D point keeps its height; a 2D one gives a 2D point.
|
||||
is_t(&mut s, "(equal (osnap '(23.0001 0.0001 7.0) \"_qua\") '(23.0 0.0 7.0) 1e-9)");
|
||||
is_t(&mut s, "(equal (osnap '(23.0001 0.0001) \"QUA\") '(23.0 0.0) 1e-9)");
|
||||
is_t(&mut s, "(equal (osnap '(20.0001 0.0001) \"_cen\") '(20.0 0.0) 1e-9)");
|
||||
assert_eq!(ok(&mut s, "(osnap '(23 0) \"_non\")"), "nil", "NONE snaps to nothing");
|
||||
assert_eq!(ok(&mut s, "(osnap '(23 0) \"\")"), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_with_spaces_and_unicode_names() {
|
||||
let mut s = session();
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft lisp ünï {}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let d = dir.to_string_lossy().replace('\\', "/");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-mkdir \"{d}\")")), "T");
|
||||
ok(&mut s, &format!("(setq f (open \"{d}/plan é.txt\" \"w\")) (write-line \"x\" f) (close f)"));
|
||||
assert_eq!(ok(&mut s, &format!("(vl-directory-files \"{d}\" \"*.TXT\" 1)")), "(\"plan é.txt\")", "patterns ignore case");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-size \"{d}/plan é.txt\")")), "2");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-file-delete \"{d}/plan é.txt\")")), "T");
|
||||
assert_eq!(ok(&mut s, &format!("(vl-directory-files \"{d}\" nil 1)")), "nil", "nothing left");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
// The current folder lists without arguments.
|
||||
assert!(ok(&mut s, "(listp (vl-directory-files))") == "T");
|
||||
// getenv reaches the system's own variables.
|
||||
assert_eq!(ok(&mut s, "(eq (type (getenv \"PATH\")) 'STR)"), "T");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_functions_are_listed_and_print() {
|
||||
let mut s = session();
|
||||
for name in ["VLAX-CURVE-GETAREA", "VL-FILE-COPY", "GETFILED", "OSNAP", "GETENV", "BOOLE"] {
|
||||
assert_eq!(ok(&mut s, &format!("(type {name})")), "SUBR", "{name}");
|
||||
assert_eq!(ok(&mut s, &format!("(atoms-family 1 '(\"{name}\"))")), format!("(\"{name}\")"));
|
||||
}
|
||||
// write-char goes to the command line without a file.
|
||||
ok(&mut s, "(write-char 65) (write-char 10)");
|
||||
assert!(s.log.iter().any(|l| l.contains('A')), "{:?}", s.log);
|
||||
}
|
||||
@@ -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) => Value::str(s),
|
||||
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) | craft_dxf::Value::Invalid(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)),
|
||||
@@ -836,9 +836,6 @@ pub fn regapp(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
Ok(Flow::Value(Value::str(name.trim())))
|
||||
}
|
||||
|
||||
/// The most bytes of text `textbox` measures.
|
||||
const MAX_TEXTBOX_TEXT: usize = 64 << 10;
|
||||
|
||||
/// `(textbox elist)`: the smallest box around a TEXT that `elist` describes (an `entget` list, or
|
||||
/// a partial one with at least the string, group 1), as its lower-left and upper-right corners
|
||||
/// relative to the insertion point, the text unrotated and left-justified. Groups the list
|
||||
@@ -859,13 +856,6 @@ pub fn textbox(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
if group(1).is_none() || group(0).is_some_and(|k| !matches!(&k, Value::Str(s) if s.eq_ignore_ascii_case("TEXT"))) {
|
||||
return nil();
|
||||
}
|
||||
// Shaping makes many points for each character, which the run's string budget does not
|
||||
// count: a text too long to measure in bounded memory is an error, not a box.
|
||||
if let Some(Value::Str(s)) = group(1)
|
||||
&& s.len() > MAX_TEXTBOX_TEXT
|
||||
{
|
||||
return Err(LispError::new(format!("textbox: text longer than {MAX_TEXTBOX_TEXT} bytes")));
|
||||
}
|
||||
let Ok(d) = ctx.s.doc() else { return nil() };
|
||||
let style = match group(7) {
|
||||
Some(Value::Str(s)) => s.to_string(),
|
||||
|
||||
@@ -33,6 +33,10 @@ pub enum GetKind {
|
||||
spaces: bool,
|
||||
},
|
||||
Kword,
|
||||
/// `getfiled`: a file name typed; `new`: it may name a file that doesn't exist yet.
|
||||
File {
|
||||
new: bool,
|
||||
},
|
||||
/// `entsel` / `nentsel`: an object picked.
|
||||
EntSel,
|
||||
}
|
||||
@@ -46,6 +50,59 @@ pub struct GetRequest {
|
||||
pub initget: Initget,
|
||||
/// `getdist`/`getangle` without a base point: the first point given, the second to come.
|
||||
pub first: Option<[f64; 3]>,
|
||||
/// `getfiled`'s extension, default and folder (boxed: it keeps [`Need`](super::eval::Need) small).
|
||||
pub file: Box<FileAsk>,
|
||||
}
|
||||
|
||||
/// `getfiled`: the extension a bare name gets, the name Enter gives, and the folder a relative
|
||||
/// name is in.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FileAsk {
|
||||
pub ext: String,
|
||||
pub default: String,
|
||||
/// The default folder (a default ending in a path delimiter, or any default with flag 16).
|
||||
pub dir: String,
|
||||
/// New-file mode asks before an existing file is replaced (flag 32 clear).
|
||||
pub confirm: bool,
|
||||
/// A new file's name that already exists, waiting for Yes to replace it.
|
||||
pub replace: Option<String>,
|
||||
}
|
||||
|
||||
impl FileAsk {
|
||||
/// `name` with the extension when it has none, in the default folder when relative (`None`
|
||||
/// for an empty name).
|
||||
fn complete(&self, name: &str) -> Option<String> {
|
||||
let name = name.trim().trim_matches('"');
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let has_ext = std::path::Path::new(name).extension().is_some();
|
||||
let name = if has_ext || self.ext.is_empty() { name.to_string() } else { format!("{name}.{}", self.ext) };
|
||||
Some(if self.dir.is_empty() || std::path::Path::new(&name).is_absolute() {
|
||||
name
|
||||
} else {
|
||||
std::path::Path::new(&self.dir).join(name).to_string_lossy().into_owned()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `getfiled`'s answer `name`, typed or the default taken with Enter: open mode (`new` false)
|
||||
/// asks again for a file that isn't there, and new-file mode asks before replacing one that is
|
||||
/// (unless flag 32 says not to), where files can be checked. In the browser (wasm32) there is no
|
||||
/// file system to look in, so the name is taken as given, and opening it then fails the way every
|
||||
/// file function there does (`open` gives nil).
|
||||
fn file_answer(req: &GetRequest, name: String, new: bool) -> Result<Value, Again> {
|
||||
if cfg!(not(target_arch = "wasm32")) {
|
||||
let exists = super::builtins::file_exists(&name);
|
||||
if !new && !exists {
|
||||
return Err(format!("Can't find file {name}.").as_str().into());
|
||||
}
|
||||
if new && exists && req.file.confirm {
|
||||
let file = FileAsk { replace: Some(name), ..(*req.file).clone() };
|
||||
return Err(Again::Ask(Box::new(GetRequest { file: Box::new(file), ..req.clone() })));
|
||||
}
|
||||
}
|
||||
Ok(Value::str(&name))
|
||||
}
|
||||
|
||||
impl GetRequest {
|
||||
@@ -56,12 +113,13 @@ impl GetRequest {
|
||||
GetKind::Point | GetKind::Corner | GetKind::EntSel => Accept { text: any, ..Accept::POINT },
|
||||
GetKind::Dist | GetKind::Angle { .. } => Accept { text: any, ..Accept::POINT_OR_NUMBER },
|
||||
GetKind::Real | GetKind::Int => Accept { text: any, ..Accept::NUMBER },
|
||||
GetKind::String { .. } | GetKind::Kword => Accept::TEXT,
|
||||
GetKind::String { .. } | GetKind::Kword | GetKind::File { .. } => Accept::TEXT,
|
||||
};
|
||||
let message = match (&self.first, self.message.is_empty()) {
|
||||
(Some(_), _) => "Specify second point: ".to_string(),
|
||||
(None, true) => default_message(self.kind).to_string(),
|
||||
(None, false) => self.message.clone(),
|
||||
let message = match (&self.file.replace, &self.first, self.message.is_empty()) {
|
||||
(Some(name), _, _) => format!("{name} already exists. Replace it? [Yes/No] <No>: "),
|
||||
(None, Some(_), _) => "Specify second point: ".to_string(),
|
||||
(None, None, true) => default_message(self.kind).to_string(),
|
||||
(None, None, false) => self.message.clone(),
|
||||
};
|
||||
let base = self.first.or(self.base).map(|p| ucs.to_wcs(Vec2::new(p[0], p[1])));
|
||||
let mut p = Prompt::new(message, accept).base_opt(base);
|
||||
@@ -83,6 +141,7 @@ impl GetRequest {
|
||||
Ok(v) => Answer::Value(v),
|
||||
Err(Again::Second(p)) => Answer::Second(p),
|
||||
Err(Again::Msg(m)) => Answer::Again(m),
|
||||
Err(Again::Ask(r)) => Answer::Ask(r),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,6 +170,7 @@ impl GetRequest {
|
||||
Ok(v) => Answer::Value(v),
|
||||
Err(Again::Second(p)) => Answer::Second(p),
|
||||
Err(Again::Msg(m)) => Answer::Again(m),
|
||||
Err(Again::Ask(r)) => Answer::Ask(r),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,6 +192,19 @@ impl GetRequest {
|
||||
}
|
||||
|
||||
fn answer_value(&self, s: &mut Session, input: Input) -> Result<Value, Again> {
|
||||
if let (GetKind::File { .. }, Some(name)) = (self.kind, &self.file.replace) {
|
||||
// Replace the file that is there? Yes gives its name; No (the default) asks for a name again.
|
||||
let yes = |t: &str| matches!(t.trim().to_ascii_lowercase().as_str(), "y" | "yes");
|
||||
let no = |t: &str| matches!(t.trim().to_ascii_lowercase().as_str(), "n" | "no");
|
||||
let again = || Again::Ask(Box::new(GetRequest { file: Box::new(FileAsk { replace: None, ..(*self.file).clone() }), ..self.clone() }));
|
||||
return match input {
|
||||
Input::Text(t) | Input::Keyword(t) if yes(&t) => Ok(Value::str(name)),
|
||||
Input::Text(t) | Input::Keyword(t) if no(&t) => Err(again()),
|
||||
Input::Enter => Err(again()),
|
||||
Input::Cancel => Err("*Cancel*".into()),
|
||||
_ => Err("Answer Yes or No.".into()),
|
||||
};
|
||||
}
|
||||
let ig = &self.initget;
|
||||
let no_null = ig.bits & 1 != 0;
|
||||
match input {
|
||||
@@ -139,6 +212,14 @@ impl GetRequest {
|
||||
if matches!(self.kind, GetKind::String { .. }) {
|
||||
return Ok(Value::str(""));
|
||||
}
|
||||
if let GetKind::File { new } = self.kind {
|
||||
// Enter takes the default name (checked as a typed one is), or cancels the choice
|
||||
// (nil) without one.
|
||||
return match self.file.complete(&self.file.default) {
|
||||
Some(name) => file_answer(self, name, new),
|
||||
None => Ok(Value::Nil),
|
||||
};
|
||||
}
|
||||
if no_null {
|
||||
return Err(match self.kind {
|
||||
GetKind::Int => "Requires an integer value.",
|
||||
@@ -206,6 +287,7 @@ impl GetRequest {
|
||||
GetKind::Int => "Requires an integer value.",
|
||||
GetKind::Kword => "Invalid option keyword.",
|
||||
GetKind::String { .. } => "Requires a string.",
|
||||
GetKind::File { .. } => "Requires a file name.",
|
||||
_ => "Requires numeric value.",
|
||||
}
|
||||
.into()),
|
||||
@@ -225,6 +307,10 @@ impl GetRequest {
|
||||
}
|
||||
GetKind::Kword if any => Ok(Value::str(t)),
|
||||
GetKind::Kword => Err("Invalid option keyword.".into()),
|
||||
GetKind::File { new } => {
|
||||
let Some(name) = self.file.complete(t).or_else(|| self.file.complete(&self.file.default)) else { return Ok(Value::Nil) };
|
||||
file_answer(self, name, new)
|
||||
}
|
||||
GetKind::Int => match t.trim().parse::<i32>() {
|
||||
Ok(i) if (-32768..=32767).contains(&i) => self.check_number(f64::from(i), true),
|
||||
Ok(_) => Err("Value must be between -32768 and 32767.".into()),
|
||||
@@ -280,11 +366,14 @@ pub enum Answer {
|
||||
Again(String),
|
||||
/// `getdist`/`getangle` without a base point got its first point: ask for the second.
|
||||
Second([f64; 3]),
|
||||
/// The prompt goes on as this request (`getfiled`: whether to replace a file, or a name again).
|
||||
Ask(Box<GetRequest>),
|
||||
}
|
||||
|
||||
enum Again {
|
||||
Msg(String),
|
||||
Second([f64; 3]),
|
||||
Ask(Box<GetRequest>),
|
||||
}
|
||||
|
||||
impl From<String> for Again {
|
||||
@@ -358,6 +447,10 @@ fn point_and_message(args: &[Value], name: &str) -> Result<(Option<[f64; 3]>, St
|
||||
}
|
||||
|
||||
fn wait(ctx: &mut Ctx<'_>, kind: GetKind, message: String, base: Option<[f64; 3]>) -> Result<Flow, LispError> {
|
||||
wait_with(ctx, kind, message, base, FileAsk::default())
|
||||
}
|
||||
|
||||
fn wait_with(ctx: &mut Ctx<'_>, kind: GetKind, message: String, base: Option<[f64; 3]>, file: FileAsk) -> Result<Flow, LispError> {
|
||||
let initget = ctx.env.initget.take().unwrap_or_default();
|
||||
// Text printed so far shows before the prompt.
|
||||
let printed = std::mem::take(&mut ctx.env.out);
|
||||
@@ -367,7 +460,33 @@ fn wait(ctx: &mut Ctx<'_>, kind: GetKind, message: String, base: Option<[f64; 3]
|
||||
ctx.env.printed_at = Some(ctx.s.log.len());
|
||||
}
|
||||
}
|
||||
Ok(Flow::Wait(Need::Get(GetRequest { kind, message, base, initget, first: None })))
|
||||
Ok(Flow::Wait(Need::Get(GetRequest { kind, message, base, initget, first: None, file: Box::new(file) })))
|
||||
}
|
||||
|
||||
/// `(getfiled title default ext flags)`: a file name, asked at the command line (no dialog opens
|
||||
/// from LISP, as with FILEDIA 0). A bare name gets `ext`; Enter takes `default`, or gives nil
|
||||
/// without one. Flag 1 asks for a new file (Save As), and an existing one is replaced only after
|
||||
/// Yes unless flag 32 is set; otherwise the file must exist. With flag 16, or a default ending in a
|
||||
/// path delimiter, the default is the folder relative names are in.
|
||||
pub fn getfiled(ctx: &mut Ctx<'_>, args: Vec<Value>) -> Result<Flow, LispError> {
|
||||
let [title, default, ext, flags] = args.as_slice() else { return Err(args_err(args.len() < 4)) };
|
||||
let s = |v: &Value| match v {
|
||||
Value::Str(s) => Ok(s.to_string()),
|
||||
Value::Nil => Ok(String::new()),
|
||||
other => Err(LispError::bad_arg("stringp", other)),
|
||||
};
|
||||
let (title, default, ext) = (s(title)?, s(default)?, s(ext)?);
|
||||
let Value::Int(flags) = flags else { return Err(LispError::bad_arg("fixnump", flags)) };
|
||||
// The first of "dwg;dxf", without its dot; "*" or "" adds none.
|
||||
let ext = ext.split(';').next().unwrap_or("").trim().trim_start_matches('.').to_string();
|
||||
let ext = if ext == "*" { String::new() } else { ext };
|
||||
let title = if title.is_empty() { "Enter file name".to_string() } else { title.trim_end_matches([' ', ':']).to_string() };
|
||||
// Flag 16, or a default ending in a path delimiter: the default is a folder, not a file name.
|
||||
let (dir, default) = if flags & 16 != 0 || default.ends_with(['/', '\\']) { (default, String::new()) } else { (String::new(), default) };
|
||||
let message = if default.is_empty() { format!("{title}: ") } else { format!("{title} <{default}>: ") };
|
||||
// Flag 32: a new file may replace one that is there without asking.
|
||||
let file = FileAsk { ext, default, dir, confirm: flags & 32 == 0, replace: None };
|
||||
wait_with(ctx, GetKind::File { new: flags & 1 != 0 }, message, None, file)
|
||||
}
|
||||
|
||||
pub fn getpoint(ctx: &mut Ctx<'_>, args: Vec<Value>) -> Result<Flow, LispError> {
|
||||
|
||||
@@ -0,0 +1,743 @@
|
||||
//! Files and folders (`vl-file-*`, `vl-directory-files`, `vl-mkdir`), environment variables
|
||||
//! (`getenv`, `setenv`), object snaps (`osnap`), command and symbol names (`getcname`,
|
||||
//! `snvalid`, `atoms-family`) and small helpers (`boole`, `vl-string-position`,
|
||||
//! `vl-string-elt`, `vl-string-mismatch`, `read-char`, `write-char`).
|
||||
//!
|
||||
//! The file functions answer nil where the file system says no, as AutoLISP does; the web build
|
||||
//! has no file system, so there they always do.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, OnceLock, PoisonError};
|
||||
|
||||
use cadcraft_geom::Vec2;
|
||||
|
||||
use super::LispError;
|
||||
use super::builtins::{args_err, emit};
|
||||
use super::eval::{Ctx, Flow};
|
||||
use super::value::{Sym, Value, charge_bytes, check_string_len};
|
||||
|
||||
type R = Result<Value, LispError>;
|
||||
|
||||
fn arity(a: &[Value], min: usize, max: usize) -> Result<(), LispError> {
|
||||
if a.len() < min {
|
||||
return Err(args_err(true));
|
||||
}
|
||||
if a.len() > max {
|
||||
return Err(args_err(false));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn string(v: &Value) -> Result<String, LispError> {
|
||||
match v {
|
||||
Value::Str(s) => Ok(s.to_string()),
|
||||
other => Err(LispError::bad_arg("stringp", other)),
|
||||
}
|
||||
}
|
||||
|
||||
fn int(v: &Value) -> Result<i32, LispError> {
|
||||
match v {
|
||||
Value::Int(i) => Ok(*i),
|
||||
other => Err(LispError::bad_arg("fixnump", other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Most names `vl-directory-files` lists.
|
||||
const MAX_DIR_ENTRIES: usize = 100_000;
|
||||
|
||||
// ---------------- files and folders ----------------
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod fs {
|
||||
use std::path::Path;
|
||||
|
||||
use crate::file_access::{check_read, check_write};
|
||||
|
||||
pub fn copy(src: &str, dst: &str, append: bool) -> Option<u64> {
|
||||
check_read(src).ok()?;
|
||||
check_write(dst).ok()?;
|
||||
if !Path::new(src).is_file() {
|
||||
return None;
|
||||
}
|
||||
if append {
|
||||
// Streamed through a fixed buffer, never read whole. Appending a file to itself (the
|
||||
// same file under another name, by symlink) is refused, and the copy stops at the
|
||||
// source's size when it began, so a hard link to the destination can't grow forever.
|
||||
let canon = |p: &str| std::fs::canonicalize(p).ok();
|
||||
let (cs, cd) = (canon(src)?, canon(dst)?);
|
||||
if cs == cd {
|
||||
return None;
|
||||
}
|
||||
let from = std::fs::File::open(src).ok()?;
|
||||
let len = from.metadata().ok()?.len();
|
||||
let mut to = std::fs::OpenOptions::new().append(true).open(dst).ok()?;
|
||||
std::io::copy(&mut std::io::Read::take(from, len), &mut to).ok()
|
||||
} else if Path::new(dst).exists() {
|
||||
// Never over an existing file.
|
||||
None
|
||||
} else {
|
||||
std::fs::copy(src, dst).ok()
|
||||
}
|
||||
}
|
||||
pub fn delete(p: &str) -> bool {
|
||||
check_write(p).is_ok() && Path::new(p).is_file() && std::fs::remove_file(p).is_ok()
|
||||
}
|
||||
pub fn rename(from: &str, to: &str) -> bool {
|
||||
check_write(from).is_ok()
|
||||
&& check_write(to).is_ok()
|
||||
&& Path::new(from).exists()
|
||||
&& !Path::new(to).exists()
|
||||
&& std::fs::rename(from, to).is_ok()
|
||||
}
|
||||
pub fn size(p: &str) -> Option<u64> {
|
||||
check_read(p).ok()?;
|
||||
let m = std::fs::metadata(p).ok()?;
|
||||
Some(if m.is_dir() { 0 } else { m.len() })
|
||||
}
|
||||
pub fn modified(p: &str) -> Option<i64> {
|
||||
check_read(p).ok()?;
|
||||
let m = std::fs::metadata(p).ok()?.modified().ok()?;
|
||||
let d = m.duration_since(std::time::UNIX_EPOCH).ok()?;
|
||||
i64::try_from(d.as_millis()).ok()
|
||||
}
|
||||
pub fn is_dir(p: &str) -> bool {
|
||||
check_read(p).is_ok() && Path::new(p).is_dir()
|
||||
}
|
||||
pub fn mkdir(p: &str) -> bool {
|
||||
check_write(p).is_ok() && !Path::new(p).exists() && std::fs::create_dir(p).is_ok()
|
||||
}
|
||||
/// (name, is a folder) of every entry, `.` and `..` first, up to `max`.
|
||||
pub fn list(dir: &str, max: usize) -> Option<Vec<(String, bool)>> {
|
||||
let dir = if dir.is_empty() { "." } else { dir };
|
||||
check_read(dir).ok()?;
|
||||
let rd = std::fs::read_dir(dir).ok()?;
|
||||
let mut out = vec![(".".to_string(), true), ("..".to_string(), true)];
|
||||
for e in rd.flatten().take(max) {
|
||||
let is_dir = e.file_type().is_ok_and(|t| t.is_dir());
|
||||
out.push((e.file_name().to_string_lossy().into_owned(), is_dir));
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod fs {
|
||||
pub fn copy(_src: &str, _dst: &str, _append: bool) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
pub fn delete(_p: &str) -> bool {
|
||||
false
|
||||
}
|
||||
pub fn rename(_from: &str, _to: &str) -> bool {
|
||||
false
|
||||
}
|
||||
pub fn size(_p: &str) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
pub fn modified(_p: &str) -> Option<i64> {
|
||||
None
|
||||
}
|
||||
pub fn is_dir(_p: &str) -> bool {
|
||||
false
|
||||
}
|
||||
pub fn mkdir(_p: &str) -> bool {
|
||||
false
|
||||
}
|
||||
pub fn list(_dir: &str, _max: usize) -> Option<Vec<(String, bool)>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn int_value(n: u64) -> Value {
|
||||
Value::Int(i32::try_from(n).unwrap_or(i32::MAX))
|
||||
}
|
||||
|
||||
/// `(vl-file-copy source dest [append])`: the bytes copied, or nil. An existing `dest` is only
|
||||
/// ever appended to.
|
||||
pub(super) fn vl_file_copy(a: &[Value]) -> R {
|
||||
arity(a, 2, 3)?;
|
||||
let append = a.get(2).is_some_and(|v| !v.is_nil());
|
||||
Ok(fs::copy(&string(&a[0])?, &string(&a[1])?, append).map(int_value).unwrap_or_default())
|
||||
}
|
||||
pub(super) fn vl_file_delete(a: &[Value]) -> R {
|
||||
arity(a, 1, 1)?;
|
||||
Ok(Value::bool(fs::delete(&string(&a[0])?)))
|
||||
}
|
||||
pub(super) fn vl_file_rename(a: &[Value]) -> R {
|
||||
arity(a, 2, 2)?;
|
||||
Ok(Value::bool(fs::rename(&string(&a[0])?, &string(&a[1])?)))
|
||||
}
|
||||
/// `(vl-file-size file)`: its size in bytes, 0 for a folder, nil when there is none.
|
||||
pub(super) fn vl_file_size(a: &[Value]) -> R {
|
||||
arity(a, 1, 1)?;
|
||||
Ok(fs::size(&string(&a[0])?).map(int_value).unwrap_or_default())
|
||||
}
|
||||
pub(super) fn vl_file_directory_p(a: &[Value]) -> R {
|
||||
arity(a, 1, 1)?;
|
||||
Ok(Value::bool(fs::is_dir(&string(&a[0])?)))
|
||||
}
|
||||
pub(super) fn vl_mkdir(a: &[Value]) -> R {
|
||||
arity(a, 1, 1)?;
|
||||
Ok(Value::bool(fs::mkdir(&string(&a[0])?)))
|
||||
}
|
||||
|
||||
/// `(vl-file-systime file)`: when it was last changed, in the computer's local time, as
|
||||
/// `(year month weekday day hours minutes seconds)` on Windows and
|
||||
/// `(year month weekday day hours minutes seconds milliseconds)` elsewhere (weekday 0 is Sunday).
|
||||
/// When the zone lookup fails the time is given in UTC, so an existing file never reads as missing.
|
||||
pub(super) fn vl_file_systime(a: &[Value]) -> R {
|
||||
arity(a, 1, 1)?;
|
||||
let Some(ms) = fs::modified(&string(&a[0])?) else { return Ok(Value::Nil) };
|
||||
let Some(parts) = systime(ms, local_offset_secs(ms).unwrap_or(0)) else { return Ok(Value::Nil) };
|
||||
let n = if cfg!(windows) { 7 } else { 8 };
|
||||
Ok(Value::list(parts.into_iter().take(n).map(|v| Value::Int(v as i32)).collect::<Vec<_>>()))
|
||||
}
|
||||
|
||||
/// `ms` clamped to years 1601..=9999, the range every platform's zone lookup handles.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn zone_lookup_ms(ms: i64) -> i64 {
|
||||
use chrono::NaiveDate;
|
||||
let ends = |y, mo, d, h, mi, s| NaiveDate::from_ymd_opt(y, mo, d).and_then(|d| d.and_hms_opt(h, mi, s)).map(|t| t.and_utc().timestamp_millis());
|
||||
match (ends(1601, 1, 1, 0, 0, 0), ends(9999, 12, 31, 23, 59, 59)) {
|
||||
(Some(lo), Some(hi)) => ms.clamp(lo, hi),
|
||||
_ => ms,
|
||||
}
|
||||
}
|
||||
|
||||
/// The computer's offset from UTC at the instant `ms` (milliseconds since 1970), in seconds east
|
||||
/// of UTC; 0 where there is no time zone to ask (the web); `None` when the zone lookup fails (the
|
||||
/// caller then uses UTC). The instant is clamped to years 1601..=9999 first.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn local_offset_secs(ms: i64) -> Option<i32> {
|
||||
use chrono::{Local, Offset, TimeZone};
|
||||
let t = chrono::DateTime::from_timestamp_millis(zone_lookup_ms(ms))?.naive_utc();
|
||||
// The clamp avoids chrono's known panics in the local-zone lookup; catch_unwind only guards the
|
||||
// unknown ones (the crash-report hook still fires if it ever triggers).
|
||||
std::panic::catch_unwind(|| Local.offset_from_utc_datetime(&t).fix().local_minus_utc()).ok()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn local_offset_secs(_ms: i64) -> Option<i32> {
|
||||
Some(0)
|
||||
}
|
||||
|
||||
/// Milliseconds since 1970 as (year month weekday day hours minutes seconds ms) at `offset_secs`
|
||||
/// east of UTC; `None` outside the calendar's range or for an offset of a day or more.
|
||||
fn systime(ms: i64, offset_secs: i32) -> Option<[i64; 8]> {
|
||||
use chrono::{Datelike, Timelike};
|
||||
let zone = chrono::FixedOffset::east_opt(offset_secs)?;
|
||||
// Checked addition: the shifted instant may fall off the end of the calendar.
|
||||
let t = chrono::DateTime::from_timestamp_millis(ms)?
|
||||
.naive_utc()
|
||||
.checked_add_signed(chrono::TimeDelta::try_seconds(i64::from(zone.local_minus_utc()))?)?;
|
||||
Some([
|
||||
i64::from(t.year()),
|
||||
i64::from(t.month()),
|
||||
i64::from(t.weekday().num_days_from_sunday()),
|
||||
i64::from(t.day()),
|
||||
i64::from(t.hour()),
|
||||
i64::from(t.minute()),
|
||||
i64::from(t.second()),
|
||||
i64::from(t.nanosecond() / 1_000_000),
|
||||
])
|
||||
}
|
||||
|
||||
/// `(vl-directory-files [directory pattern what])`: the names in a folder matching `pattern`
|
||||
/// (`*` and `?`, case-insensitive); `what` -1 lists folders only, 1 files only, nil or 0 both.
|
||||
/// Sorted, so a routine sees the same order on every system.
|
||||
pub(super) fn vl_directory_files(a: &[Value]) -> R {
|
||||
arity(a, 0, 3)?;
|
||||
let dir = match a.first() {
|
||||
None | Some(Value::Nil) => String::new(),
|
||||
Some(v) => string(v)?,
|
||||
};
|
||||
let pattern = match a.get(1) {
|
||||
None | Some(Value::Nil) => "*".to_string(),
|
||||
Some(v) => string(v)?,
|
||||
};
|
||||
let what = match a.get(2) {
|
||||
None | Some(Value::Nil) => 0,
|
||||
Some(v) => int(v)?,
|
||||
};
|
||||
let Some(entries) = fs::list(&dir, MAX_DIR_ENTRIES) else { return Ok(Value::Nil) };
|
||||
let pattern = if pattern == "*.*" { "*".to_string() } else { pattern };
|
||||
let mut names: Vec<String> = entries
|
||||
.into_iter()
|
||||
.filter(|(_, is_dir)| match what {
|
||||
-1 => *is_dir,
|
||||
1 => !*is_dir,
|
||||
_ => true,
|
||||
})
|
||||
.map(|(n, _)| n)
|
||||
.filter(|n| glob(&n.to_lowercase(), &pattern.to_lowercase()))
|
||||
.collect();
|
||||
names.sort();
|
||||
let mut out = Vec::with_capacity(names.len());
|
||||
for n in names {
|
||||
charge_bytes(n.len())?;
|
||||
out.push(Value::str(&n));
|
||||
}
|
||||
Ok(if out.is_empty() { Value::Nil } else { Value::list(out) })
|
||||
}
|
||||
|
||||
/// `*` and `?` file-name matching.
|
||||
fn glob(text: &str, pattern: &str) -> bool {
|
||||
let (t, p): (Vec<char>, Vec<char>) = (text.chars().collect(), pattern.chars().collect());
|
||||
let (mut ti, mut pi) = (0usize, 0usize);
|
||||
let mut star: Option<(usize, usize)> = None;
|
||||
while ti < t.len() {
|
||||
match p.get(pi) {
|
||||
Some('*') => {
|
||||
star = Some((pi, ti));
|
||||
pi += 1;
|
||||
}
|
||||
Some(c) if *c == '?' || Some(c) == t.get(ti) => {
|
||||
pi += 1;
|
||||
ti += 1;
|
||||
}
|
||||
_ => match star {
|
||||
Some((sp, st)) => {
|
||||
pi = sp + 1;
|
||||
ti = st + 1;
|
||||
star = Some((sp, st + 1));
|
||||
}
|
||||
None => return false,
|
||||
},
|
||||
}
|
||||
}
|
||||
p.get(pi..).is_some_and(|rest| rest.iter().all(|c| *c == '*'))
|
||||
}
|
||||
|
||||
// ---------------- environment ----------------
|
||||
|
||||
/// Variables `setenv` set this session, by upper-case name. AutoCAD keeps them in its own
|
||||
/// settings; here they live as long as the program.
|
||||
fn env_table() -> &'static Mutex<HashMap<String, String>> {
|
||||
static T: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
|
||||
T.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
/// Most variables `setenv` keeps.
|
||||
const MAX_ENV_VARS: usize = 4096;
|
||||
|
||||
/// `(getenv name)`: what `setenv` set, else the operating system's variable, else nil.
|
||||
pub(super) fn getenv(a: &[Value]) -> R {
|
||||
arity(a, 1, 1)?;
|
||||
let name = string(&a[0])?;
|
||||
let set = env_table().lock().unwrap_or_else(PoisonError::into_inner).get(&name.to_ascii_uppercase()).cloned();
|
||||
Ok(set.or_else(|| std::env::var(&name).ok()).map(|v| Value::str(&v)).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// `(setenv name value)`: `value`.
|
||||
pub(super) fn setenv(a: &[Value]) -> R {
|
||||
arity(a, 2, 2)?;
|
||||
let (name, value) = (string(&a[0])?, string(&a[1])?);
|
||||
if name.is_empty() {
|
||||
return Err(LispError::bad_arg("variable name", &a[0]));
|
||||
}
|
||||
check_string_len(name.len().saturating_add(value.len()))?;
|
||||
let mut t = env_table().lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let key = name.to_ascii_uppercase();
|
||||
if t.len() >= MAX_ENV_VARS && !t.contains_key(&key) {
|
||||
return Err(LispError::new("too many environment variables"));
|
||||
}
|
||||
t.insert(key, value);
|
||||
Ok(a[1].clone())
|
||||
}
|
||||
|
||||
// ---------------- object snaps ----------------
|
||||
|
||||
/// `(osnap point modes)`: the snap point the modes ("_end,_mid", "cen"…) find within the
|
||||
/// aperture of `point`, or nil.
|
||||
pub(super) fn osnap(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
let p = a[0].as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &a[0]))?;
|
||||
let modes = string(&a[1])?;
|
||||
let mut bits = 0u32;
|
||||
for m in modes.split(',').map(str::trim).filter(|m| !m.is_empty()) {
|
||||
match crate::pointmod::parse_snap(m) {
|
||||
Some(b) => bits |= b,
|
||||
None => return Ok(Flow::Value(Value::Nil)),
|
||||
}
|
||||
}
|
||||
if bits == 0 {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let aperture = ctx.s.settings.aperture.max(1.0) * ctx.s.pixel_size();
|
||||
let Ok(space) = ctx.s.state().map(|st| st.edit_space()) else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let hit = crate::snap::osnap(d, &space, Vec2::new(p[0], p[1]), aperture, bits, None, false);
|
||||
let two_d = a[0].iter().count() == 2;
|
||||
Ok(Flow::Value(match hit {
|
||||
Some(h) if two_d => Value::point(&[h.point.x, h.point.y]),
|
||||
Some(h) => Value::point(&[h.point.x, h.point.y, p[2]]),
|
||||
None => Value::Nil,
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------------- names ----------------
|
||||
|
||||
/// `(getcname name)`: a command's other name, as AutoLISP's English and global names pair them:
|
||||
/// `"line"` gives `"_LINE"`, `"_line"` gives `"LINE"`; nil for a name no command has.
|
||||
pub(super) fn getcname(a: &[Value]) -> R {
|
||||
arity(a, 1, 1)?;
|
||||
let name = string(&a[0])?;
|
||||
let (global, bare) = match name.strip_prefix('_') {
|
||||
Some(b) => (true, b),
|
||||
None => (false, name.as_str()),
|
||||
};
|
||||
let bare = bare.trim_start_matches(['.', '+']);
|
||||
if bare.is_empty() || crate::cmd::find_command(bare).is_none() {
|
||||
return Ok(Value::Nil);
|
||||
}
|
||||
let up = bare.to_ascii_uppercase();
|
||||
Ok(Value::str(&if global { up } else { format!("_{up}") }))
|
||||
}
|
||||
|
||||
/// `(snvalid name [flag])`: whether `name` may name a symbol table entry (a layer, a style…).
|
||||
/// With flag 1 a `|` is allowed inside the name, as in an xref-dependent one.
|
||||
pub(super) fn snvalid(a: &[Value]) -> R {
|
||||
arity(a, 1, 2)?;
|
||||
let name = string(&a[0])?;
|
||||
let bar_ok = a.get(1).is_some_and(|v| matches!(v, Value::Int(1)));
|
||||
let ok = !name.is_empty()
|
||||
&& name.chars().count() <= 255
|
||||
&& !name.starts_with(' ')
|
||||
&& !name.ends_with(' ')
|
||||
&& name.chars().all(|c| !c.is_control() && !"<>/\\\":;?*,=`".contains(c))
|
||||
&& (if bar_ok { !name.starts_with('|') && !name.ends_with('|') } else { !name.contains('|') });
|
||||
Ok(Value::bool(ok))
|
||||
}
|
||||
|
||||
/// `(atoms-family format [names])`: the symbols with a value (format 0: symbols, 1: names). With
|
||||
/// `names`, each name that has one, nil for each that hasn't.
|
||||
pub(super) fn atoms_family(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 2)?;
|
||||
let as_names = match int(&a[0])? {
|
||||
0 => false,
|
||||
1 => true,
|
||||
_ => return Err(LispError::bad_arg("format", &a[0])),
|
||||
};
|
||||
let show = |s: &Sym| if as_names { Value::str(s.name()) } else { Value::Sym(s.clone()) };
|
||||
let out = match a.get(1) {
|
||||
None | Some(Value::Nil) => {
|
||||
let mut syms: Vec<&Sym> = ctx.env.globals.keys().collect();
|
||||
syms.sort_by(|x, y| x.name().cmp(y.name()));
|
||||
syms.into_iter().map(show).collect::<Vec<_>>()
|
||||
}
|
||||
Some(list) => {
|
||||
let mut out = Vec::new();
|
||||
for v in list.iter() {
|
||||
let s = Sym::new(&string(&v)?.to_ascii_uppercase());
|
||||
out.push(if ctx.env.globals.contains_key(&s) { show(&s) } else { Value::Nil });
|
||||
}
|
||||
out
|
||||
}
|
||||
};
|
||||
Ok(Flow::Value(Value::list(out)))
|
||||
}
|
||||
|
||||
// ---------------- numbers and strings ----------------
|
||||
|
||||
/// `(boole op int1 int2 …)`: a bitwise function given as its truth table: bit 1 where both
|
||||
/// are set, 2 where only the first is, 4 where only the second is, 8 where neither is (1 AND,
|
||||
/// 6 XOR, 7 OR, 8 NOR).
|
||||
pub(super) fn boole(a: &[Value]) -> R {
|
||||
arity(a, 2, usize::MAX)?;
|
||||
let op = int(&a[0])?;
|
||||
let mut acc = int(&a[1])?;
|
||||
for v in &a[2..] {
|
||||
let x = int(v)?;
|
||||
let mut r = 0i32;
|
||||
for (bit, set) in [(1, acc & x), (2, acc & !x), (4, !acc & x), (8, !acc & !x)] {
|
||||
if op & bit != 0 {
|
||||
r |= set;
|
||||
}
|
||||
}
|
||||
acc = r;
|
||||
}
|
||||
Ok(Value::Int(acc))
|
||||
}
|
||||
|
||||
/// `(vl-string-position code string [start [from-end]])`: where character `code` is, or nil.
|
||||
pub(super) fn vl_string_position(a: &[Value]) -> R {
|
||||
arity(a, 2, 4)?;
|
||||
let code = int(&a[0])?;
|
||||
let s: Vec<char> = string(&a[1])?.chars().collect();
|
||||
let start = match a.get(2) {
|
||||
None | Some(Value::Nil) => 0,
|
||||
Some(v) => usize::try_from(int(v)?).map_err(|_| LispError::bad_arg("fixnump", v))?,
|
||||
};
|
||||
let from_end = a.get(3).is_some_and(|v| !v.is_nil());
|
||||
let Some(want) = u32::try_from(code).ok().and_then(char::from_u32) else { return Ok(Value::Nil) };
|
||||
let found = if from_end {
|
||||
// From the end, looking no further back than `start`.
|
||||
s.iter().enumerate().rev().take_while(|(i, _)| *i >= start).find(|(_, c)| **c == want).map(|(i, _)| i)
|
||||
} else {
|
||||
s.iter().enumerate().skip(start).find(|(_, c)| **c == want).map(|(i, _)| i)
|
||||
};
|
||||
Ok(found.map(|i| Value::Int(i32::try_from(i).unwrap_or(i32::MAX))).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// `(vl-string-elt string position)`: the code of the character at `position` (from 0).
|
||||
pub(super) fn vl_string_elt(a: &[Value]) -> R {
|
||||
arity(a, 2, 2)?;
|
||||
let s = string(&a[0])?;
|
||||
let i = int(&a[1])?;
|
||||
let c = usize::try_from(i).ok().and_then(|i| s.chars().nth(i));
|
||||
match c {
|
||||
Some(c) => Ok(Value::Int(i32::try_from(u32::from(c)).unwrap_or(0))),
|
||||
None => Err(LispError::new(format!("bad argument value: string position out of range {i}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `(vl-string-mismatch str1 str2 [pos1 pos2 ignore-case])`: how many characters, from `pos1`
|
||||
/// and `pos2`, the two have in common.
|
||||
pub(super) fn vl_string_mismatch(a: &[Value]) -> R {
|
||||
arity(a, 2, 5)?;
|
||||
let (s1, s2) = (string(&a[0])?, string(&a[1])?);
|
||||
let pos = |v: Option<&Value>| -> Result<usize, LispError> {
|
||||
match v {
|
||||
None | Some(Value::Nil) => Ok(0),
|
||||
Some(v) => usize::try_from(int(v)?).map_err(|_| LispError::bad_arg("fixnump", v)),
|
||||
}
|
||||
};
|
||||
let (p1, p2) = (pos(a.get(2))?, pos(a.get(3))?);
|
||||
let fold = a.get(4).is_some_and(|v| !v.is_nil());
|
||||
let same = |x: char, y: char| if fold { x.to_lowercase().eq(y.to_lowercase()) } else { x == y };
|
||||
let n = s1.chars().skip(p1).zip(s2.chars().skip(p2)).take_while(|(x, y)| same(*x, *y)).count();
|
||||
Ok(Value::Int(i32::try_from(n).unwrap_or(i32::MAX)))
|
||||
}
|
||||
|
||||
/// `(read-char [file])`: the next character's code from a file opened for reading (10 at each
|
||||
/// line end, but none after a last line the file leaves unterminated), nil at its end or
|
||||
/// without a file.
|
||||
pub(super) fn read_char(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 0, 1)?;
|
||||
let Some(Value::File(id)) = a.first() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let Some(f) = ctx.env.files.get_mut(id).filter(|f| !f.writing) else { return Err(LispError::bad_arg("streamp", &a[0])) };
|
||||
let Some(line) = f.lines.front() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
// From a cursor into the line, so reading a long line a character at a time stays linear.
|
||||
match line.get(f.pos..).and_then(|rest| rest.chars().next()) {
|
||||
Some(c) => {
|
||||
f.pos += c.len_utf8();
|
||||
Ok(Flow::Value(Value::Int(i32::try_from(u32::from(c)).unwrap_or(0))))
|
||||
}
|
||||
None => {
|
||||
let last_unterminated = f.at_unterminated_last();
|
||||
f.lines.pop_front();
|
||||
f.pos = 0;
|
||||
if last_unterminated {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
Ok(Flow::Value(Value::Int(10)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `(write-char code [file])`: writes one character; `code`.
|
||||
pub(super) fn write_char(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 2)?;
|
||||
let code = int(&a[0])?;
|
||||
let c = u32::try_from(code).ok().and_then(char::from_u32).ok_or_else(|| LispError::bad_arg("character code", &a[0]))?;
|
||||
emit(ctx, &c.to_string(), a.get(1))?;
|
||||
Ok(Flow::Value(Value::Int(code)))
|
||||
}
|
||||
|
||||
pub(super) fn t(_a: &[Value]) -> R {
|
||||
Ok(Value::t())
|
||||
}
|
||||
pub(super) fn nil(_a: &[Value]) -> R {
|
||||
Ok(Value::Nil)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn file_builtins_honor_automation_roots() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let fixture = std::env::temp_dir().join(format!("cadcraft-lisp-roots-{}", std::process::id()));
|
||||
let allowed = fixture.join("allowed");
|
||||
std::fs::create_dir_all(&allowed).unwrap();
|
||||
let path = |parent: &std::path::Path, name| parent.join(name).to_string_lossy().into_owned();
|
||||
let source = path(&allowed, "source.txt");
|
||||
let destination = path(&allowed, "destination.txt");
|
||||
let outside = path(&fixture, "fixture.txt");
|
||||
let outside_destination = path(&fixture, "outside-destination.txt");
|
||||
let outside_folder = path(&fixture, "outside-folder");
|
||||
std::fs::write(&source, b"sample").unwrap();
|
||||
std::fs::write(&outside, b"fixture").unwrap();
|
||||
|
||||
let roots = AutomationRoots::new(Some(&allowed), Some(&allowed)).unwrap();
|
||||
confine(roots.as_ref(), || {
|
||||
assert_eq!(fs::size(&source), Some(6));
|
||||
assert_eq!(fs::size(&outside), None);
|
||||
assert_eq!(fs::modified(&outside), None);
|
||||
assert!(!fs::is_dir(&fixture.to_string_lossy()));
|
||||
assert!(fs::list(&fixture.to_string_lossy(), 10).is_none());
|
||||
assert!(!fs::delete(&outside));
|
||||
assert!(!fs::rename(&outside, &destination));
|
||||
assert!(!fs::rename(&source, &outside_destination));
|
||||
assert_eq!(fs::copy(&outside, &destination, false), None);
|
||||
assert_eq!(fs::copy(&source, &outside_destination, false), None);
|
||||
assert!(!fs::mkdir(&outside_folder));
|
||||
|
||||
assert_eq!(fs::copy(&source, &destination, false), Some(6));
|
||||
assert!(fs::delete(&destination));
|
||||
});
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), b"fixture");
|
||||
assert!(!std::path::Path::new(&outside_destination).exists());
|
||||
assert!(!std::path::Path::new(&outside_folder).exists());
|
||||
std::fs::remove_dir_all(fixture).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn systime_turns_milliseconds_into_a_utc_date() {
|
||||
// 2026-10-16 09:05:07.250 UTC, a Friday.
|
||||
let ms = 1_792_141_507_250;
|
||||
assert_eq!(systime(ms, 0), Some([2026, 10, 5, 16, 9, 5, 7, 250]));
|
||||
assert_eq!(systime(0, 0), Some([1970, 1, 4, 1, 0, 0, 0, 0]));
|
||||
// Before 1970 and on a leap day.
|
||||
assert_eq!(systime(-86_400_000, 0), Some([1969, 12, 3, 31, 0, 0, 0, 0]));
|
||||
assert_eq!(systime(951_782_400_000, 0), Some([2000, 2, 2, 29, 0, 0, 0, 0]));
|
||||
assert_eq!(systime(i64::MAX, 0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn systime_applies_the_local_offset() {
|
||||
// 2026-10-16 23:30:00 UTC, a Friday: two hours east is 01:30 on Saturday the 17th.
|
||||
let late = 1_792_193_400_000;
|
||||
assert_eq!(systime(late, 2 * 3600), Some([2026, 10, 6, 17, 1, 30, 0, 0]));
|
||||
// 2026-10-16 02:00:00 UTC: five hours west is 21:00 on Thursday the 15th.
|
||||
let early = 1_792_116_000_000;
|
||||
assert_eq!(systime(early, -5 * 3600), Some([2026, 10, 4, 15, 21, 0, 0, 0]));
|
||||
// A half-hour zone keeps its minutes.
|
||||
assert_eq!(systime(early, 5 * 3600 + 1800), Some([2026, 10, 5, 16, 7, 30, 0, 0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn systime_at_the_calendar_ends_is_none_not_an_overflow() {
|
||||
let max = chrono::DateTime::<chrono::Utc>::MAX_UTC.timestamp_millis();
|
||||
let min = chrono::DateTime::<chrono::Utc>::MIN_UTC.timestamp_millis();
|
||||
assert_eq!(systime(max, 3600), None);
|
||||
assert_eq!(systime(min, -3600), None);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn zone_lookup_ms_keeps_instants_in_range() {
|
||||
// 1601-01-01T00:00:00Z and 9999-12-31T23:59:59Z in milliseconds since 1970.
|
||||
let (lo, hi) = (-11_644_473_600_000, 253_402_300_799_000);
|
||||
for ms in [
|
||||
i64::MAX,
|
||||
i64::MIN,
|
||||
chrono::DateTime::<chrono::Utc>::MAX_UTC.timestamp_millis(),
|
||||
chrono::DateTime::<chrono::Utc>::MIN_UTC.timestamp_millis(),
|
||||
] {
|
||||
let c = zone_lookup_ms(ms);
|
||||
assert!((lo..=hi).contains(&c), "{ms} -> {c}");
|
||||
}
|
||||
assert_eq!(zone_lookup_ms(i64::MAX), hi);
|
||||
assert_eq!(zone_lookup_ms(i64::MIN), lo);
|
||||
// 2020-01-01T00:00:00Z is left alone.
|
||||
assert_eq!(zone_lookup_ms(1_577_836_800_000), 1_577_836_800_000);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn local_offset_secs_is_a_real_offset_on_extreme_instants() {
|
||||
for ms in [
|
||||
chrono::DateTime::<chrono::Utc>::MAX_UTC.timestamp_millis(),
|
||||
chrono::DateTime::<chrono::Utc>::MIN_UTC.timestamp_millis(),
|
||||
i64::MAX,
|
||||
i64::MIN,
|
||||
0,
|
||||
] {
|
||||
let offset = local_offset_secs(ms);
|
||||
assert!(offset.is_some_and(|o| o.abs() < 86_400), "{ms}: {offset:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn vl_file_systime_lists_an_existing_file() {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-systime-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("a.txt");
|
||||
std::fs::write(&file, b"x").unwrap();
|
||||
let got = vl_file_systime(&[Value::str(&file.to_string_lossy())]).unwrap();
|
||||
let n = if cfg!(windows) { 7 } else { 8 };
|
||||
assert_eq!(got.to_vec().len(), n);
|
||||
assert!(matches!(got.to_vec().first(), Some(Value::Int(y)) if *y >= 2020));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn systime_refuses_hostile_input() {
|
||||
for offset in [-25 * 3600, 25 * 3600, i32::MIN, i32::MAX, 86_400, -86_400] {
|
||||
assert_eq!(systime(0, offset), None, "offset {offset}");
|
||||
}
|
||||
for ms in [i64::MAX, i64::MIN] {
|
||||
assert_eq!(systime(ms, 25 * 3600), None);
|
||||
assert_eq!(systime(ms, -25 * 3600), None);
|
||||
assert_eq!(systime(ms, 3600), None);
|
||||
assert_eq!(systime(ms, 0), None);
|
||||
}
|
||||
}
|
||||
|
||||
/// A file appended to itself, or to another name for it, is refused and left as it was; a
|
||||
/// large source is streamed in (the appended bytes are all there), and the existing rules hold:
|
||||
/// no append to a missing file, no copy over an existing one.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn copy_streams_and_never_grows_a_file_into_itself() {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-copy-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let p = |n: &str| dir.join(n).to_string_lossy().into_owned();
|
||||
let (a, b, c) = (p("a.bin"), p("b.bin"), p("c.bin"));
|
||||
|
||||
// 9 MiB of a repeating pattern: more than any one buffer.
|
||||
let chunk: Vec<u8> = (0..=255u8).collect();
|
||||
let mut data = Vec::new();
|
||||
for _ in 0..(9 << 12) {
|
||||
data.extend_from_slice(&chunk);
|
||||
}
|
||||
std::fs::write(&a, &data).unwrap();
|
||||
std::fs::write(&b, b"head").unwrap();
|
||||
assert_eq!(fs::copy(&a, &b, true), Some(data.len() as u64));
|
||||
let got = std::fs::read(&b).unwrap();
|
||||
assert_eq!((got.len(), got.get(..4), got.get(4..)), (data.len() + 4, Some(&b"head"[..]), Some(&data[..])));
|
||||
|
||||
// Itself: refused, unchanged.
|
||||
assert_eq!(fs::copy(&a, &a, true), None);
|
||||
assert_eq!(std::fs::metadata(&a).unwrap().len(), data.len() as u64);
|
||||
// Itself under another path (a dot segment).
|
||||
let alias = format!("{}{}.{}a.bin", dir.to_string_lossy(), std::path::MAIN_SEPARATOR, std::path::MAIN_SEPARATOR);
|
||||
assert_eq!(fs::copy(&a, &alias, true), None);
|
||||
assert_eq!(std::fs::metadata(&a).unwrap().len(), data.len() as u64);
|
||||
|
||||
// Without append: a new file is made, an existing one is never overwritten; append needs
|
||||
// the destination to exist.
|
||||
assert_eq!(fs::copy(&a, &c, false), Some(data.len() as u64));
|
||||
assert_eq!(fs::copy(&a, &c, false), None);
|
||||
assert_eq!(fs::copy(&a, &p("missing.bin"), true), None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glob_matches_stars_and_question_marks() {
|
||||
assert!(glob("plan.lsp", "*.lsp"));
|
||||
assert!(glob("plan.lsp", "p?an.*"));
|
||||
assert!(!glob("plan.dwg", "*.lsp"));
|
||||
assert!(glob("a", "*"));
|
||||
assert!(glob("", "*"));
|
||||
assert!(!glob("ab", "a"));
|
||||
assert!(glob("abcabc", "*bc"));
|
||||
}
|
||||
}
|
||||
@@ -498,8 +498,8 @@ fn drawn_text(d: &Drawing, e: &Entity) -> Option<Vec<Vec<Vec2>>> {
|
||||
let e = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Plain => e,
|
||||
cadcraft_doc::AnnoDraw::Hidden => return None,
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) => {
|
||||
scaled = cadcraft_doc::anno_scaled(e, f);
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } => {
|
||||
scaled = cadcraft_doc::anno_placed(e, factor, by);
|
||||
&scaled
|
||||
}
|
||||
};
|
||||
|
||||
@@ -720,6 +720,41 @@ 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 {
|
||||
|
||||
@@ -110,6 +110,8 @@ 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,
|
||||
@@ -207,6 +209,7 @@ impl Default for Settings {
|
||||
highlight: true,
|
||||
selectioneffect: 1,
|
||||
selectionpreview: 3,
|
||||
selectionannodisplay: true,
|
||||
previeweffect: 2,
|
||||
previewfilter: 3,
|
||||
grips: 1,
|
||||
|
||||
+82
-20
@@ -713,7 +713,7 @@ fn leaves_with_sources(
|
||||
sink: &mut Sink<'_>,
|
||||
src: &mut Sources,
|
||||
) {
|
||||
block_leaves(d, ins, &Mat3::IDENTITY, z, 0, budget, frozen, &mut |be, m, z| leaf_with_source(be, m, z, handle, sink, src));
|
||||
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));
|
||||
}
|
||||
|
||||
/// The snaps on `be`, an object drawn inside the drawing's object `handle` and placed by `m` and
|
||||
@@ -1013,8 +1013,9 @@ fn distance_to_prim(p: &Prim, cursor: Vec2) -> f64 {
|
||||
prim_segments(p).iter().map(|s| fix_circle(s).closest(cursor).dist(cursor)).fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// Upper bound on the block-reference objects one snap query looks at (hostile files).
|
||||
const MAX_BLOCK_LEAVES: usize = 20_000;
|
||||
/// 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;
|
||||
|
||||
/// Collects snap candidates and the primitives near the cursor.
|
||||
struct Sink<'a> {
|
||||
@@ -1166,7 +1167,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, frozen, &mut |be, m, _| {
|
||||
block_leaves(d, &dimension_reference(blk, dm), &Mat3::IDENTITY, None, 0, budget, Inside::drawn(frozen), &mut |be, m, _| {
|
||||
self.object(&be.kind, Some(m))
|
||||
});
|
||||
}
|
||||
@@ -1210,20 +1211,50 @@ 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.
|
||||
/// the way is in plan (`z`, from [`plan_z`]), how its Z maps to the drawing's. `inside` says
|
||||
/// which of them come ([`Inside`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn block_leaves(
|
||||
pub(crate) fn block_leaves(
|
||||
d: &Drawing,
|
||||
ins: &Insert,
|
||||
m: &Mat3,
|
||||
z: Option<(f64, f64)>,
|
||||
depth: usize,
|
||||
budget: &mut usize,
|
||||
frozen: &[String],
|
||||
inside: Inside<'_>,
|
||||
f: &mut dyn FnMut(&Entity, &Mat3, Option<(f64, f64)>),
|
||||
) {
|
||||
if depth >= MAX_BLOCK_DEPTH {
|
||||
@@ -1249,22 +1280,33 @@ fn block_leaves(
|
||||
return;
|
||||
}
|
||||
*budget -= 1;
|
||||
if !drawn_inside(d, be, frozen) {
|
||||
if !drawn_inside(d, be, inside.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, frozen, f);
|
||||
block_leaves(d, inner, &mm, zz, depth + 1, budget, inside, f);
|
||||
}
|
||||
// A dimension draws its block, as at the top level.
|
||||
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) => {
|
||||
EntityKind::Dimension(dm) if let Some(blk) = dm.block.as_ref().filter(|_| inside.expand).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, frozen, f);
|
||||
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);
|
||||
}
|
||||
EntityKind::Unknown(u) => graphics_leaves(d, u, &mm, z, depth + 1, budget, frozen, f),
|
||||
_ => f(be, &mm, z),
|
||||
}
|
||||
}
|
||||
@@ -1310,20 +1352,30 @@ fn graphics_leaves(
|
||||
frozen: &[String],
|
||||
f: &mut dyn FnMut(&Entity, &Mat3, Option<(f64, f64)>),
|
||||
) {
|
||||
for g in &u.graphics {
|
||||
if matches!(g.kind, EntityKind::Hatch(_)) || !drawn_inside(d, g, frozen) {
|
||||
continue;
|
||||
}
|
||||
for g in drawn_graphics(d, u, frozen) {
|
||||
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, frozen, f);
|
||||
block_leaves(d, inner, m, zz, depth, budget, Inside::drawn(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).
|
||||
@@ -1356,9 +1408,19 @@ 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.
|
||||
fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
|
||||
/// 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 {
|
||||
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)))),
|
||||
@@ -1385,7 +1447,7 @@ 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: m.apply_vec(*dir).normalized(), ray: *ray },
|
||||
Prim::Infinite { base, dir, ray } => Prim::Infinite { base: m.apply(*base), dir: placed_dir(*dir, m), ray: *ray },
|
||||
Prim::Fill(f) => Prim::Fill(f.iter().map(|q| m.apply(*q)).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ const SESSION_VARS: &[&str] = &[
|
||||
"HIGHLIGHT",
|
||||
"SELECTIONEFFECT",
|
||||
"SELECTIONPREVIEW",
|
||||
"SELECTIONANNODISPLAY",
|
||||
"PREVIEWEFFECT",
|
||||
"PREVIEWFILTER",
|
||||
"GRIPS",
|
||||
@@ -185,6 +186,7 @@ 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),
|
||||
@@ -234,7 +236,10 @@ 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),
|
||||
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
|
||||
// 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("'")),
|
||||
"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
|
||||
@@ -244,7 +249,8 @@ 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)),
|
||||
"CMDACTIVE" => json!(i32::from(s.running.is_some())),
|
||||
// 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())),
|
||||
"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.
|
||||
@@ -478,6 +484,7 @@ 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)?,
|
||||
|
||||
@@ -965,6 +965,33 @@ 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();
|
||||
|
||||
@@ -0,0 +1,659 @@
|
||||
//! #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();
|
||||
}
|
||||
@@ -10,8 +10,7 @@ use cadcraft_engine::cmd::file::MAX_ALIASES;
|
||||
use cadcraft_engine::cmd::resolve_alias;
|
||||
use serde_json::json;
|
||||
|
||||
#[path = "support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
use crate::temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
//! 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());
|
||||
}
|
||||
@@ -6,8 +6,7 @@ use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Hatch};
|
||||
use serde_json::json;
|
||||
|
||||
#[path = "support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
use crate::temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
|
||||
@@ -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) => json!(s),
|
||||
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) | craft_dxf::Value::Invalid(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)),
|
||||
|
||||
@@ -57,14 +57,6 @@ fn textbox_measures_text_as_drawn() {
|
||||
let blank = textbox(&mut s, "'((1 . \" \"))").expect("spaces");
|
||||
assert!(blank[0] == 0.0 && blank[1] == 0.0 && blank[2] > 0.0 && blank[3] > 0.0, "{blank:?}");
|
||||
|
||||
// A text too long to shape in bounded memory is an error that names the function, and one
|
||||
// well under the limit still measures.
|
||||
let long_text = |n: usize| json!({ "code": format!("(textbox '((1 . \"{}\")))", "8".repeat(n)) });
|
||||
let refused = s.execute("lisp", &long_text(1_000_000)).unwrap();
|
||||
assert!(refused["error"].as_str().is_some_and(|e| e.contains("textbox")), "{refused}");
|
||||
let measured = s.execute("lisp", &long_text(1_000)).unwrap();
|
||||
assert!(measured["error"].is_null() && measured["value"] != "nil", "{measured}");
|
||||
|
||||
// Not a text: nil.
|
||||
assert_eq!(textbox(&mut s, "'((0 . \"LINE\") (10 0.0 0.0 0.0) (11 5.0 5.0 0.0) (1 . \"x\"))"), None);
|
||||
assert_eq!(textbox(&mut s, "'((0 . \"TEXT\") (40 . 1.0))"), None, "no string");
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
mod temp_dir;
|
||||
|
||||
mod acadver;
|
||||
mod aliases;
|
||||
mod angle_prompts;
|
||||
mod angle_settings;
|
||||
mod annotate_options;
|
||||
@@ -14,6 +15,7 @@ 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;
|
||||
@@ -22,6 +24,7 @@ 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;
|
||||
@@ -33,6 +36,7 @@ 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;
|
||||
@@ -50,18 +54,23 @@ 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;
|
||||
@@ -73,6 +82,7 @@ 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;
|
||||
@@ -100,6 +110,7 @@ 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;
|
||||
@@ -107,18 +118,22 @@ 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;
|
||||
@@ -136,6 +151,8 @@ 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;
|
||||
@@ -158,6 +175,7 @@ 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;
|
||||
@@ -174,14 +192,18 @@ 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;
|
||||
@@ -204,7 +226,9 @@ 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;
|
||||
@@ -215,18 +239,25 @@ 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
-1
@@ -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,
|
||||
@@ -0,0 +1,143 @@
|
||||
//! 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);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! 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}");
|
||||
}
|
||||
@@ -47,3 +47,27 @@ 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)));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,594 @@
|
||||
//! #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:#?}");
|
||||
}
|
||||
@@ -7,23 +7,24 @@ use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, set_io, set_write_as};
|
||||
use serde_json::json;
|
||||
|
||||
/// A 2018 DXF with one mental ray render settings object, stored as `90 2` (class version 1 in the
|
||||
/// 2013+ form).
|
||||
/// A 2018 DXF with plain and mental ray settings. Both store base class version 2.
|
||||
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\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\nOBJECTS\n\
|
||||
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n3\nPlain\n350\n22\n\
|
||||
0\nMENTALRAYRENDERSETTINGS\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n\
|
||||
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nENDSEC\n0\nEOF\n";
|
||||
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";
|
||||
|
||||
/// The `AcDbRenderSettings` class version in a written DXF.
|
||||
fn class_version(path: &std::path::Path) -> Option<i64> {
|
||||
fn class_versions(path: &std::path::Path) -> [Option<i64>; 2] {
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
let l: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = l.windows(2).position(|w| w == ["0", "MENTALRAYRENDERSETTINGS"])?;
|
||||
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
|
||||
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
|
||||
["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())
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -43,13 +44,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_version(&path)
|
||||
class_versions(&path)
|
||||
};
|
||||
|
||||
assert_eq!(save(&mut s, "2018.dxf", "2018"), Some(2), "same version: as read");
|
||||
assert_eq!(save(&mut s, "2000.dxf", "2000"), Some(1), "the 2000 form is one lower");
|
||||
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");
|
||||
s.execute("qsave", &json!({})).unwrap();
|
||||
assert_eq!(class_version(&dir.join("2000.dxf")), Some(1), "QSAVE keeps the 2000 form");
|
||||
assert_eq!(save(&mut s, "back.dxf", "2018"), Some(2), "back to 2018: the 2018 file's value, not one higher");
|
||||
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");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
//! 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};
|
||||
@@ -98,7 +101,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!({})).unwrap();
|
||||
s.execute("qsave", &json!({ "overwrite": true })).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
|
||||
@@ -106,11 +109,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!({})).unwrap();
|
||||
s.execute("qsave", &json!({ "overwrite": true })).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!({})).unwrap();
|
||||
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
|
||||
assert_eq!(circles(&backup_path(&path)), 1, "a DWG's tag alone");
|
||||
|
||||
// ISAVEBAK 0: the backup is left as it was.
|
||||
@@ -234,7 +237,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!({})).unwrap();
|
||||
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
|
||||
assert_eq!(circles(&backup_path(&path)), 1, "{version}: the cut-off file didn't replace it");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -255,7 +258,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!({})).unwrap();
|
||||
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
|
||||
assert_eq!(std::fs::read(backup_path(&path)).unwrap(), odd);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -281,14 +284,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!({})).unwrap();
|
||||
s.execute("qsave", &json!({ "overwrite": true })).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!({})).unwrap();
|
||||
s.execute("qsave", &json!({ "overwrite": true })).unwrap();
|
||||
assert_eq!(std::fs::read(backup_path(&path)).unwrap(), old, "cut off: nothing was promised");
|
||||
|
||||
cadcraft_engine::autosave::set_isavebak(false);
|
||||
|
||||
+109
-28
@@ -55,18 +55,20 @@ fn gauss(a: f64, b: f64, f: impl Fn(f64) -> f64) -> f64 {
|
||||
const MAX_GAUSS_DEPTH: usize = 10;
|
||||
|
||||
/// `gauss` over [a, b], halving until the two halves agree with the whole: a fixed panel count
|
||||
/// is far off on a tight bend, and the arc-length inverse must agree with the measure.
|
||||
/// is far off on a tight bend, and the arc-length inverse must agree with the measure. `floor`
|
||||
/// is the smallest size the agreement is measured against, for an integrand that may sum to
|
||||
/// about zero (a signed area); 0 for one that can't (a length).
|
||||
#[expect(
|
||||
clippy::many_single_char_names,
|
||||
reason = "Adaptive quadrature keeps the panel endpoints, midpoint and left/right integrals in mathematical notation."
|
||||
)]
|
||||
fn adaptive_gauss(a: f64, b: f64, whole: f64, f: &impl Fn(f64) -> f64, depth: usize) -> f64 {
|
||||
fn adaptive_gauss(a: f64, b: f64, whole: f64, f: &impl Fn(f64) -> f64, depth: usize, floor: f64) -> f64 {
|
||||
let m = f64::midpoint(a, b);
|
||||
let (l, r) = (gauss(a, m, f), gauss(m, b, f));
|
||||
if depth == 0 || !(l + r).is_finite() || (l + r - whole).abs() <= 1e-10 * (l + r).abs() {
|
||||
if depth == 0 || !(l + r).is_finite() || (l + r - whole).abs() <= 1e-10 * (l + r).abs().max(floor) {
|
||||
return l + r;
|
||||
}
|
||||
adaptive_gauss(a, m, l, f, depth - 1) + adaptive_gauss(m, b, r, f, depth - 1)
|
||||
adaptive_gauss(a, m, l, f, depth - 1, floor) + adaptive_gauss(m, b, r, f, depth - 1, floor)
|
||||
}
|
||||
|
||||
/// Clamped knots over Bézier pieces meeting at `breaks`, for degree `p`.
|
||||
@@ -560,13 +562,37 @@ impl Spline {
|
||||
out
|
||||
}
|
||||
|
||||
/// Arc length of one integration panel, at the speed of `derivative`. The spline is validated
|
||||
/// once by the callers ([`Spline::integrated_length`]/[`Spline::param_at_length`]) before any
|
||||
/// panel is measured, so the derivative is an unchecked one, to avoid re-scanning the knots per
|
||||
/// sample.
|
||||
fn panel_length(&self, a: f64, b: f64, derivative: fn(&Spline, f64) -> Vec2) -> f64 {
|
||||
let speed = |t: f64| derivative(self, t).len();
|
||||
adaptive_gauss(a, b, gauss(a, b, speed), &speed, MAX_GAUSS_DEPTH)
|
||||
/// Arc length of one integration panel, at [`Spline::velocity`] (so an overflowing speed shows
|
||||
/// as a non-finite length, not as 0). The spline is validated once by the callers
|
||||
/// ([`Spline::integrated_length`]/[`Spline::param_at_length`]) before any panel is measured,
|
||||
/// to avoid re-scanning the knots per sample.
|
||||
fn panel_length(&self, a: f64, b: f64) -> f64 {
|
||||
let speed = |t: f64| self.velocity(t).len();
|
||||
adaptive_gauss(a, b, gauss(a, b, speed), &speed, MAX_GAUSS_DEPTH, 0.0)
|
||||
}
|
||||
|
||||
/// ∫ ((x − o.x) dy − (y − o.y) dx) / 2 from parameter `a` to `b`, `o` being `origin`: the
|
||||
/// signed area the curve sweeps as seen from `origin` (adaptive Gauss–Legendre over each knot
|
||||
/// span, as for the arc length). From the start point, a whole spline's term is the area it
|
||||
/// encloses with the chord back from its end.
|
||||
pub fn area_term_between(&self, a: f64, b: f64, origin: Vec2) -> f64 {
|
||||
if !self.is_valid() || !(a.is_finite() && b.is_finite() && origin.x.is_finite() && origin.y.is_finite()) {
|
||||
return 0.0;
|
||||
}
|
||||
let (lo, hi) = self.domain();
|
||||
let (a, b, sign) = if a <= b { (a, b, 1.0) } else { (b, a, -1.0) };
|
||||
let (a, b) = (a.clamp(lo, hi), b.clamp(lo, hi));
|
||||
let f = |t: f64| {
|
||||
// Validated once above: no per-sample validity scan (it walks the knots).
|
||||
let (p, d) = (self.eval_valid(t, lo, hi) - origin, self.derivative_unchecked(t));
|
||||
(p.x * d.y - p.y * d.x) / 2.0
|
||||
};
|
||||
// A panel sweeping next to no area is judged against the size of the whole curve.
|
||||
let size = self.control.iter().map(|c| c.dist(origin)).fold(0.0, f64::max);
|
||||
let spans = self.length_intervals(lo, hi).len().max(1);
|
||||
let floor = 1e-3 * size * size / spans as f64;
|
||||
let s: f64 = self.length_intervals(a, b).into_iter().map(|(x, y)| adaptive_gauss(x, y, gauss(x, y, f), &f, MAX_GAUSS_DEPTH, floor)).sum();
|
||||
if s.is_finite() { sign * s } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Arc length between parameters `a` and `b` (adaptive Gauss–Legendre over each knot span).
|
||||
@@ -597,20 +623,21 @@ impl Spline {
|
||||
}
|
||||
let (lo, hi) = self.domain();
|
||||
let (a, b) = (a.min(b).clamp(lo, hi), a.max(b).clamp(lo, hi));
|
||||
self.length_intervals(a, b).into_iter().map(|(x, y)| self.panel_length(x, y, Spline::velocity)).sum()
|
||||
self.length_intervals(a, b).into_iter().map(|(x, y)| self.panel_length(x, y)).sum()
|
||||
}
|
||||
|
||||
/// The parameter `len` along the curve from parameter `from` (forward for positive `len`,
|
||||
/// backward for negative), clamped to the domain.
|
||||
pub fn param_at_length(&self, from: f64, len: f64) -> f64 {
|
||||
/// backward for negative), clamped to the domain. `None` when the length along the way
|
||||
/// overflows (where [`Spline::checked_length`] is `None`).
|
||||
pub fn param_at_length(&self, from: f64, len: f64) -> Option<f64> {
|
||||
let (lo, hi) = self.domain();
|
||||
if !self.is_valid() {
|
||||
// Checked before `clamp`: an invalid spline's bounds may be reversed or NaN.
|
||||
return if from.is_finite() { from } else { lo };
|
||||
return Some(if from.is_finite() { from } else { lo });
|
||||
}
|
||||
let from = if from.is_finite() { from.clamp(lo, hi) } else { lo };
|
||||
if !len.is_finite() || len == 0.0 {
|
||||
return from;
|
||||
return Some(from);
|
||||
}
|
||||
let (a, b, target) = if len > 0.0 { (from, hi, len) } else { (lo, from, -len) };
|
||||
let mut ivs = self.length_intervals(a, b);
|
||||
@@ -619,7 +646,10 @@ impl Spline {
|
||||
}
|
||||
let mut acc = 0.0;
|
||||
for (x0, x1) in ivs {
|
||||
let l = self.panel_length(x0, x1, Spline::derivative_unchecked);
|
||||
let l = self.panel_length(x0, x1);
|
||||
if !(acc + l).is_finite() {
|
||||
return None;
|
||||
}
|
||||
if acc + l >= target && l > 0.0 {
|
||||
// Bisect inside this interval, measuring from its near end.
|
||||
let rest = target - acc;
|
||||
@@ -627,18 +657,18 @@ impl Spline {
|
||||
let (mut s0, mut s1) = (near, far);
|
||||
for _ in 0..60 {
|
||||
let m = f64::midpoint(s0, s1);
|
||||
let lm = self.panel_length(near.min(m), near.max(m), Spline::derivative_unchecked);
|
||||
let lm = self.panel_length(near.min(m), near.max(m));
|
||||
if lm < rest {
|
||||
s0 = m;
|
||||
} else {
|
||||
s1 = m;
|
||||
}
|
||||
}
|
||||
return f64::midpoint(s0, s1);
|
||||
return Some(f64::midpoint(s0, s1));
|
||||
}
|
||||
acc += l;
|
||||
}
|
||||
if len > 0.0 { hi } else { lo }
|
||||
Some(if len > 0.0 { hi } else { lo })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -666,7 +696,7 @@ impl Ellipse {
|
||||
let l: f64 = (0..n)
|
||||
.map(|i| {
|
||||
let (a, b) = (t0 + h * i as f64, t0 + h * (i + 1) as f64);
|
||||
adaptive_gauss(a, b, gauss(a, b, speed), &speed, MAX_GAUSS_DEPTH)
|
||||
adaptive_gauss(a, b, gauss(a, b, speed), &speed, MAX_GAUSS_DEPTH, 0.0)
|
||||
})
|
||||
.sum();
|
||||
if l.is_finite() { l } else { 0.0 }
|
||||
@@ -971,11 +1001,11 @@ mod tests {
|
||||
let q = Spline::from_conic_arc(Vec2::ZERO, Vec2::X * 2.0, Vec2::Y * 2.0, 0.0, std::f64::consts::PI).unwrap();
|
||||
assert!((q.length() - 2.0 * std::f64::consts::PI).abs() < 1e-6);
|
||||
let (lo, hi) = q.domain();
|
||||
let t = q.param_at_length(lo, std::f64::consts::PI);
|
||||
let t = q.param_at_length(lo, std::f64::consts::PI).unwrap();
|
||||
assert!(q.eval(t).near(Vec2::new(0.0, 2.0), 1e-6));
|
||||
let t = q.param_at_length(hi, -std::f64::consts::PI / 2.0);
|
||||
let t = q.param_at_length(hi, -std::f64::consts::PI / 2.0).unwrap();
|
||||
assert!(q.eval(t).near(Vec2::new(-2f64.sqrt(), 2f64.sqrt()), 1e-6));
|
||||
assert_eq!(q.param_at_length(lo, 1e9).to_bits(), hi.to_bits());
|
||||
assert_eq!(q.param_at_length(lo, 1e9), Some(hi));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1006,13 +1036,64 @@ mod tests {
|
||||
assert!((s.length() - 26.708_124_545_291_4).abs() < 1e-6, "{}", s.length());
|
||||
for frac in [0.25, 0.5, 0.9] {
|
||||
let want = s.length() * frac;
|
||||
let t = s.param_at_length(lo, want);
|
||||
let t = s.param_at_length(lo, want).unwrap();
|
||||
assert!((s.length_between(lo, t) - want).abs() < 1e-6, "{frac}: {}", s.length_between(lo, t));
|
||||
let t = s.param_at_length(hi, -want);
|
||||
let t = s.param_at_length(hi, -want).unwrap();
|
||||
assert!((s.length_between(t, hi) - want).abs() < 1e-6, "{frac}: {}", s.length_between(t, hi));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn param_at_length_inverts_length_between() {
|
||||
let pts = [(0.0, 0.0), (3.0, 5.0), (7.0, -4.0), (10.0, 1.0)];
|
||||
let s = Spline::from_control(pts.iter().map(|&(x, y)| Vec2::new(x, y)).collect(), 3);
|
||||
let (lo, _) = s.domain();
|
||||
let total = s.length();
|
||||
for frac in [0.25, 0.5, 0.75] {
|
||||
let d = total * frac;
|
||||
let t = s.param_at_length(lo, d).unwrap();
|
||||
assert!((s.length_between(lo, t) - d).abs() < 1e-6 * total, "{frac}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn param_at_length_is_none_when_the_speed_overflows() {
|
||||
let ends = vec![Vec2::new(-1e308, 0.0), Vec2::new(1e308, 0.0)];
|
||||
let huge = Spline { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], control: ends, ..Spline::default() };
|
||||
assert_eq!(huge.param_at_length(0.0, 1.0), None);
|
||||
assert_eq!(huge.param_at_length(1.0, -1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spline_area_term() {
|
||||
let pi = std::f64::consts::PI;
|
||||
// A rational half circle of radius 2 closed by its diameter: half the disc.
|
||||
let q = Spline::from_conic_arc(Vec2::ZERO, Vec2::X * 2.0, Vec2::Y * 2.0, 0.0, pi).unwrap();
|
||||
let (lo, hi) = q.domain();
|
||||
assert!((q.area_term_between(lo, hi, q.eval(lo)) - 2.0 * pi).abs() < 1e-10);
|
||||
// Backwards is the same area turning the other way.
|
||||
assert!((q.area_term_between(hi, lo, q.eval(lo)) + 2.0 * pi).abs() < 1e-10);
|
||||
// The whole circle, seen from its centre or from a point on it.
|
||||
let c = Spline::from_conic_arc(Vec2::new(5.0, -1.0), Vec2::X * 2.0, Vec2::Y * 2.0, 0.0, TAU).unwrap();
|
||||
let (lo, hi) = c.domain();
|
||||
assert!((c.area_term_between(lo, hi, Vec2::new(5.0, -1.0)) - 4.0 * pi).abs() < 1e-10);
|
||||
assert!((c.area_term_between(lo, hi, c.eval(lo)) - 4.0 * pi).abs() < 1e-10);
|
||||
// A cubic and its chord, against a polygon through 200 000 points on it.
|
||||
let s = cubic();
|
||||
let (lo, hi) = s.domain();
|
||||
let pts: Vec<Vec2> = (0..=200_000).map(|i| s.eval(lo + (hi - lo) * i as f64 / 200_000.0)).collect();
|
||||
let want = crate::shoelace(&pts);
|
||||
let got = s.area_term_between(lo, hi, s.eval(lo));
|
||||
assert!((got - want).abs() < 1e-8 * want.abs().max(1.0), "{got} vs {want}");
|
||||
// Split anywhere, the parts add up.
|
||||
let m = lo + (hi - lo) * 0.37;
|
||||
let o = Vec2::new(-3.0, 7.0);
|
||||
assert!((s.area_term_between(lo, m, o) + s.area_term_between(m, hi, o) - s.area_term_between(lo, hi, o)).abs() < 1e-10);
|
||||
// Nothing to measure: zero, not NaN.
|
||||
assert_eq!(s.area_term_between(f64::NAN, hi, o), 0.0);
|
||||
assert_eq!(s.area_term_between(lo, hi, Vec2::new(f64::INFINITY, 0.0)), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn param_at_length_on_invalid_domain_does_not_panic() {
|
||||
// Reversed bounds (knots out of order) and a NaN bound both make the spline invalid; a
|
||||
@@ -1024,8 +1105,8 @@ mod tests {
|
||||
nan.knots[nan.degree] = f64::NAN;
|
||||
assert!(!nan.is_valid() && nan.domain().0.is_nan());
|
||||
for s in [reversed, nan] {
|
||||
assert_eq!(s.param_at_length(0.5, 1.0).to_bits(), 0.5_f64.to_bits());
|
||||
assert_eq!(s.param_at_length(0.5, -1.0).to_bits(), 0.5_f64.to_bits());
|
||||
assert_eq!(s.param_at_length(0.5, 1.0), Some(0.5));
|
||||
assert_eq!(s.param_at_length(0.5, -1.0), Some(0.5));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -138,7 +138,7 @@ impl Spline {
|
||||
/// `eval` on a spline `is_valid` has accepted, given its `domain()`, so sampling many points
|
||||
/// validates once (`is_valid` walks the knot vector).
|
||||
#[expect(clippy::many_single_char_names, reason = "De Boor evaluation keeps the standard p/w/b/k notation shared with basis_ref.")]
|
||||
fn eval_valid(&self, t: f64, lo: f64, hi: f64) -> Vec2 {
|
||||
pub(crate) fn eval_valid(&self, t: f64, lo: f64, hi: f64) -> Vec2 {
|
||||
let n = self.control.len().saturating_sub(1);
|
||||
let t = t.clamp(lo, hi);
|
||||
let span = find_span(n, self.degree, t, &self.knots);
|
||||
@@ -168,7 +168,59 @@ impl Spline {
|
||||
if !self.is_valid() {
|
||||
return self.control.clone();
|
||||
}
|
||||
self.samples(self.sample_count(tol)).collect()
|
||||
let spans: Vec<_> = self
|
||||
.indexed_knot_spans()
|
||||
.take(MAX_SAMPLES + 1)
|
||||
.map(|(j, a, b)| {
|
||||
let length: f64 = self
|
||||
.control
|
||||
.get(j..=j + self.degree)
|
||||
.unwrap_or(&[])
|
||||
.windows(2)
|
||||
.filter_map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)))
|
||||
.sum();
|
||||
(a, b, self.segments_for(length / tol.max(1e-9)).max(1))
|
||||
})
|
||||
.collect();
|
||||
if spans.is_empty() || spans.len() > MAX_SAMPLES {
|
||||
return self.samples(self.sample_count(tol).max(1)).collect();
|
||||
}
|
||||
// Each span gets the samples its own control polygon calls for when they fit. If their
|
||||
// sum exceeds the global cap, reserve one segment for each and share the rest in
|
||||
// proportion to the remaining per-span requests.
|
||||
let requested: usize = spans.iter().map(|s| s.2).sum();
|
||||
let base = spans.len();
|
||||
let available = MAX_SAMPLES - base;
|
||||
let requested_extra = requested - base;
|
||||
let extra = requested_extra.min(available);
|
||||
let (lo, hi) = self.domain();
|
||||
let mut out = Vec::with_capacity(base + extra + 1);
|
||||
let (mut acc, mut used) = (0usize, 0usize);
|
||||
for (a, b, wanted) in spans {
|
||||
acc += wanted - 1;
|
||||
let upto = if requested_extra == 0 {
|
||||
0
|
||||
} else {
|
||||
let numerator = u64::try_from(extra).unwrap_or(u64::MAX) * u64::try_from(acc).unwrap_or(u64::MAX);
|
||||
let denominator = u64::try_from(requested_extra).unwrap_or(u64::MAX);
|
||||
usize::try_from(numerator / denominator).unwrap_or(extra)
|
||||
};
|
||||
let seg = 1 + upto - used;
|
||||
used = upto;
|
||||
let divisor = u32::try_from(seg).map(f64::from).unwrap_or(1.0);
|
||||
out.push(self.eval_valid(a, lo, hi));
|
||||
let mut previous = a;
|
||||
for i in 1..seg {
|
||||
let step = u32::try_from(i).map(f64::from).unwrap_or(0.0);
|
||||
let t = a + (b - a) * step / divisor;
|
||||
if t > previous && t < b {
|
||||
out.push(self.eval_valid(t, lo, hi));
|
||||
previous = t;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(self.eval_valid(hi, lo, hi));
|
||||
out
|
||||
}
|
||||
|
||||
/// How many segments a tessellation at `tol` takes: the control-polygon length guides it,
|
||||
|
||||
@@ -223,7 +223,7 @@ fn tessellate_spans_measures_narrow_knot_spans() {
|
||||
let control = vec![Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::ZERO];
|
||||
let s = Spline { degree: 1, knots: vec![0.0, 0.0, 1e-9, 2e-9, 1.0, 1.0], control, ..Spline::default() };
|
||||
assert!(s.is_valid());
|
||||
assert!(crate::shoelace(&s.tessellate(1e-3)).abs() < 1e-6);
|
||||
assert!((crate::shoelace(&s.tessellate(1e-3)).abs() - 0.5).abs() < 1e-6);
|
||||
let pts = s.tessellate_spans(1e-3);
|
||||
assert!(pts.iter().any(|p| p.near(Vec2::new(1.0, 0.0), 1e-12)), "{pts:?}");
|
||||
assert!((crate::shoelace(&pts).abs() - 0.5).abs() < 1e-12);
|
||||
@@ -475,6 +475,52 @@ fn banded_solve_matches_the_dense_sweep_bit_for_bit() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A 20 × 12 rectangle as one closed cubic with triple internal knots at irrational
|
||||
/// parameters (#2055): every corner is a C0 knot no uniform parameter grid hits.
|
||||
fn rectangle(scale: f64) -> Spline {
|
||||
let (a, b, c) = (2f64.sqrt() / 100.0, 3f64.sqrt() / 50.0, 5f64.sqrt() / 40.0);
|
||||
let mut knots = vec![0.0; 4];
|
||||
for k in [a, b, c] {
|
||||
knots.extend([k; 3]);
|
||||
}
|
||||
knots.extend([1.0; 4]);
|
||||
let pts = [
|
||||
(0.0, 0.0),
|
||||
(20.0 / 3.0, 0.0),
|
||||
(40.0 / 3.0, 0.0),
|
||||
(20.0, 0.0),
|
||||
(20.0, 4.0),
|
||||
(20.0, 8.0),
|
||||
(20.0, 12.0),
|
||||
(40.0 / 3.0, 12.0),
|
||||
(20.0 / 3.0, 12.0),
|
||||
(0.0, 12.0),
|
||||
(0.0, 8.0),
|
||||
(0.0, 4.0),
|
||||
(0.0, 0.0),
|
||||
];
|
||||
let control = pts.iter().map(|&(x, y)| Vec2::new(x * scale, y * scale)).collect();
|
||||
Spline { degree: 3, knots, control, weights: vec![1.0; 13], closed: true, ..Spline::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tessellation_keeps_repeated_knot_corners() {
|
||||
for scale in [1.0, 1000.0] {
|
||||
let s = rectangle(scale);
|
||||
assert!(s.is_valid());
|
||||
let corners = [(0.0, 0.0), (20.0, 0.0), (20.0, 12.0), (0.0, 12.0)].map(|(x, y)| Vec2::new(x * scale, y * scale));
|
||||
for tol in [0.1, 0.01, 0.001, 1e-6] {
|
||||
let pts = s.tessellate(tol * scale);
|
||||
assert!(pts.len() <= MAX_SAMPLES + 1, "{} points", pts.len());
|
||||
for c in corners {
|
||||
let near = pts.iter().map(|p| p.dist(c)).fold(f64::INFINITY, f64::min);
|
||||
assert!(near <= 1e-9 * scale, "corner {c:?} missing at tol {tol}, nearest vertex {near}");
|
||||
}
|
||||
assert!(pts.windows(2).all(|w| w[0] != w[1]), "zero-length join at tol {tol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solve_handles_negative_zeros_signed_zero_sums_and_hostile_values() {
|
||||
let mut seed = 77_u64;
|
||||
@@ -604,6 +650,26 @@ fn the_cyclic_matrix_of_a_closed_fit_keeps_the_full_sweep() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tessellation_of_a_smooth_rational_span_stays_within_tolerance() {
|
||||
// A quarter circle as a rational quadratic Bezier.
|
||||
let h = std::f64::consts::FRAC_1_SQRT_2;
|
||||
let s = Spline {
|
||||
degree: 2,
|
||||
knots: vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
|
||||
control: vec![Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)],
|
||||
weights: vec![1.0, h, 1.0],
|
||||
..Spline::default()
|
||||
};
|
||||
for tol in [0.1, 0.01, 0.001] {
|
||||
let pts = s.tessellate(tol);
|
||||
for w in pts.windows(2) {
|
||||
let mid = (w[0] + w[1]) * 0.5;
|
||||
assert!(10.0 - mid.dist(Vec2::ZERO) <= tol, "chord sag over {tol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Control points count as copies only where they repeat: a closed spline whose knots wrap but
|
||||
/// whose last control points don't repeat the first ones keeps every control point its own.
|
||||
#[test]
|
||||
@@ -636,3 +702,58 @@ fn only_repeated_control_points_are_copies() {
|
||||
assert_eq!(first_again.distinct_controls(), first_again.control.len());
|
||||
assert_eq!(first_again.control_copies(0), [0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_parameter_span_keeps_its_curved_peak() {
|
||||
let s = Spline {
|
||||
degree: 2,
|
||||
knots: vec![0.0, 0.0, 0.0, 0.05, 0.05, 0.08, 0.08, 1.0, 1.0, 1.0],
|
||||
control: vec![
|
||||
Vec2::new(0.0, 0.0),
|
||||
Vec2::new(1.0, 0.0),
|
||||
Vec2::new(2.0, 0.0),
|
||||
Vec2::new(3.0, 10.0),
|
||||
Vec2::new(4.0, 0.0),
|
||||
Vec2::new(5.0, 0.0),
|
||||
Vec2::new(6.0, 0.0),
|
||||
],
|
||||
..Spline::default()
|
||||
};
|
||||
// At this tolerance the old parameter-length allocation gives the middle span one segment.
|
||||
let points = s.tessellate(0.2);
|
||||
let peak = s.eval(0.065);
|
||||
assert!(points.iter().any(|p| p.y > 0.95 * peak.y), "short curved span lost its peak: {points:?}");
|
||||
for knot in [0.05, 0.08] {
|
||||
assert!(points.iter().any(|p| p.near(s.eval(knot), 1e-9)), "missing repeated knot {knot}");
|
||||
}
|
||||
assert!(points.len() <= MAX_SAMPLES + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_collinear_span_that_doubles_back_is_not_flattened_to_its_endpoints() {
|
||||
let s = Spline {
|
||||
degree: 3,
|
||||
knots: vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0],
|
||||
control: vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(-10.0, 0.0), Vec2::new(0.0, 0.0)],
|
||||
..Spline::default()
|
||||
};
|
||||
let points = s.tessellate(0.1);
|
||||
assert!(points.iter().any(|p| p.x > 2.0));
|
||||
assert!(points.iter().any(|p| p.x < -2.0));
|
||||
assert!(points.len() <= MAX_SAMPLES + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tessellation_with_nonfinite_control_coordinates_does_not_underflow_the_span_budget() {
|
||||
for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
let s = Spline {
|
||||
degree: 2,
|
||||
knots: vec![0.0, 0.0, 0.0, 0.05, 0.05, 1.0, 1.0, 1.0],
|
||||
control: vec![Vec2::new(0.0, 0.0), Vec2::new(value, 1.0), Vec2::new(2.0, 0.0), Vec2::new(3.0, 1.0), Vec2::new(4.0, 0.0)],
|
||||
..Spline::default()
|
||||
};
|
||||
assert!(s.is_valid());
|
||||
let points = s.tessellate(0.1);
|
||||
assert!(!points.is_empty() && points.len() <= MAX_SAMPLES + 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +164,19 @@ fn huge_circle_secants_remain_finite() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spline_tessellation_preserves_adjacent_knot_spans_without_duplicate_samples() {
|
||||
let a = 0.5_f64;
|
||||
let b = f64::from_bits(a.to_bits() + 1);
|
||||
let control = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(2.0, 1.0)];
|
||||
let spline = Spline { degree: 1, knots: vec![0.0, 0.0, a, b, 1.0, 1.0], control: control.clone(), ..Spline::default() };
|
||||
let points = spline.tessellate(0.1);
|
||||
assert!(points.windows(2).all(|pair| pair[0] != pair[1]), "duplicate samples: {points:?}");
|
||||
for boundary in control {
|
||||
assert!(points.contains(&boundary), "missing span boundary {boundary:?}: {points:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spline_interpolates_fit_points() {
|
||||
let fit = [Vec2::new(0.0, 0.0), Vec2::new(1.0, 2.0), Vec2::new(3.0, 1.0), Vec2::new(4.0, 4.0), Vec2::new(6.0, 0.0)];
|
||||
|
||||
@@ -35,8 +35,6 @@ 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).
|
||||
# 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.
|
||||
# Use the same fork revision as craft-dwg so these fixtures exercise its DWG representation.
|
||||
[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 = "5d5c482b3fcb3dc77e8281474461760f32959436" }
|
||||
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "468b9d8e317755209020d5d3f2f1c8a76210c47f" }
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
+12
-24
@@ -1861,37 +1861,25 @@ fn unknown_handles(d: &Drawing) -> HashSet<String> {
|
||||
all_entities(d).filter(|e| matches!(e.kind, EntityKind::Unknown(_))).map(|e| e.handle.hex()).collect()
|
||||
}
|
||||
|
||||
/// Render settings (`RENDERSETTINGS`, `MENTALRAYRENDERSETTINGS`, `RAPIDRTRENDERSETTINGS`) store
|
||||
/// their `AcDbRenderSettings` class version (the first group 90 after that marker) in the form of
|
||||
/// the file's version: a 2013+ file stores it one higher, and a 2013 file stores a rapid RT one
|
||||
/// one lower, as acadrust reads and writes them (`write_render_settings_dxf` in acadrust 0.6.6's
|
||||
/// `io/dxf/writer/section_writer.rs`, and its DWG class-object reader and writer; the test
|
||||
/// `render_settings_class_version_matches_what_acadrust_writes` fails if the two drift apart). A
|
||||
/// kept object carries the form of the file it was read from ([`Foreign::version`], not the
|
||||
/// drawing's `$ACADVER`, which SAVEAS changes); written into a file read as another version, it
|
||||
/// takes that version's form. The DWG bridge's R2000 text is read as the version the kept objects
|
||||
/// came from (craft-dwg's `encode_kept_noted`), so there they stay as read (#907, #2471).
|
||||
///
|
||||
/// Only that first group 90 is converted, on purpose: the group 90 that starts a kind's own
|
||||
/// subclass (`AcDbMentalRayRenderSettings`, `AcDbRapidRTRenderSettings`) is that kind's version,
|
||||
/// stored the same in every file version, and is left as read.
|
||||
/// 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.
|
||||
pub(crate) fn render_settings_versions(tags: &mut [Tag], source: Option<Version>, declared: Version) {
|
||||
let Some(source) = source.filter(|s| *s != declared) else { return };
|
||||
let shift = |rapid: bool, v: Version| if rapid { -i64::from(v == Version::R2013) } else { i64::from(v >= Version::R2013) };
|
||||
let (mut kind, mut in_base) = (String::new(), false);
|
||||
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);
|
||||
for t in tags.iter_mut() {
|
||||
match t.code {
|
||||
0 => {
|
||||
kind = up(&t.str());
|
||||
plain = t.str().trim().eq_ignore_ascii_case("RENDERSETTINGS");
|
||||
in_base = false;
|
||||
}
|
||||
100 if matches!(kind.as_str(), "RENDERSETTINGS" | "MENTALRAYRENDERSETTINGS" | "RAPIDRTRENDERSETTINGS") => {
|
||||
in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings");
|
||||
}
|
||||
100 if plain => in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings"),
|
||||
90 if in_base => {
|
||||
let rapid = kind == "RAPIDRTRENDERSETTINGS";
|
||||
let logical = t.i64().saturating_sub(shift(rapid, source));
|
||||
*t = Tag::i(90, logical.saturating_add(shift(rapid, declared)));
|
||||
*t = Tag::i(90, t.i64().saturating_add(delta));
|
||||
in_base = false;
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -48,6 +48,7 @@ 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.
|
||||
@@ -177,7 +178,12 @@ 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_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS, None)
|
||||
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)
|
||||
}
|
||||
|
||||
/// A block definition read from BLOCKS: name, base point, description, entities (owner, paper
|
||||
@@ -191,7 +197,13 @@ 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>) -> Result<Drawing> {
|
||||
fn read_budgeted(
|
||||
bytes: &[u8],
|
||||
mut table_cells_left: usize,
|
||||
curve_points: usize,
|
||||
entities_refused_past: Option<usize>,
|
||||
from_dwg: bool,
|
||||
) -> 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() {
|
||||
@@ -201,8 +213,13 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize,
|
||||
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, ..Rx::default() };
|
||||
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 blocks: Vec<BlockDef> = Vec::new();
|
||||
let mut layout_objs: Vec<LayoutDef> = Vec::new();
|
||||
let mut entities = Vec::new();
|
||||
@@ -426,7 +443,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).unwrap();
|
||||
let d = read_budgeted(dxf.as_bytes(), 2, hatch::MAX_READ_CURVE_POINTS, None, false).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>(),
|
||||
@@ -470,10 +487,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).unwrap();
|
||||
let full = read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, None, false).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).unwrap();
|
||||
let d = read_budgeted(dxf.as_bytes(), 4_000_000, 1000, None, false).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));
|
||||
@@ -604,7 +621,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);
|
||||
let open = |refused_past| read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, refused_past, false);
|
||||
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}");
|
||||
|
||||
@@ -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);
|
||||
let mut kindent = entity_with_table_budget(kind, tags, table_cells_left, &mut rx.curves, rx.from_dwg);
|
||||
if let Some((c, _)) = kindent.as_mut()
|
||||
&& let Some(n) = entity_plot_style(tags, rx)
|
||||
{
|
||||
|
||||
@@ -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]) -> Vec<RawTag> {
|
||||
fn viewport_extra(tags: &[Tag], from_dwg: bool) -> 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,7 +137,17 @@ fn viewport_extra(tags: &[Tag]) -> Vec<RawTag> {
|
||||
out.push(RawTag { code, value });
|
||||
}
|
||||
}
|
||||
let keep: Vec<bool> = out.iter().map(|t| !at_default(&out, t.code, &t.value)).collect();
|
||||
// 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 mut keep = keep.into_iter();
|
||||
out.retain(|_| keep.next().unwrap_or(true));
|
||||
out
|
||||
@@ -145,7 +155,7 @@ fn viewport_extra(tags: &[Tag]) -> 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())
|
||||
entity_with_table_budget(kind, tags, &mut 4_000_000, &mut CurvePoints::default(), false)
|
||||
}
|
||||
|
||||
/// Parse one entity while charging materialized table cells to the caller's shared import budget.
|
||||
@@ -286,6 +296,7 @@ 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) {
|
||||
@@ -493,7 +504,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),
|
||||
extra: viewport_extra(tags, from_dwg),
|
||||
}
|
||||
}),
|
||||
"WIPEOUT" => {
|
||||
|
||||
@@ -215,12 +215,22 @@ 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 = edge_value(tags, *index + 5).to_radians();
|
||||
let end_angle = edge_value(tags, *index + 6).to_radians();
|
||||
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 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) };
|
||||
|
||||
@@ -96,11 +96,14 @@ 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: head.iter().find(|t| t.code == 280).map(Tag::i64).unwrap_or(0) == 0,
|
||||
title: properties.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(),
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user