mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-04 19:57:57 -06:00
Compare commits
157
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d08ea7b74 | ||
|
|
9d85a971f4 | ||
|
|
40d4098375 | ||
|
|
a24fb6f930 | ||
|
|
586f3d38b5 | ||
|
|
d327547208 | ||
|
|
246aaf35de | ||
|
|
c15cec8a98 | ||
|
|
5586822f8a | ||
|
|
f48ae711e1 | ||
|
|
f78ca4e722 | ||
|
|
52ab5d2549 | ||
|
|
3b95d0510c | ||
|
|
07bec9df31 | ||
|
|
e785adb63d | ||
|
|
c870f83900 | ||
|
|
0be750a98a | ||
|
|
20ad85efc4 | ||
|
|
d9f7de77e0 | ||
|
|
6681531546 | ||
|
|
97fed2970c | ||
|
|
44fa197bcc | ||
|
|
36e8c31f0d | ||
|
|
17fb7a3c43 | ||
|
|
5ab5e6f343 | ||
|
|
5a7182240e | ||
|
|
8698649da1 | ||
|
|
4610454c58 | ||
|
|
a6add77c5a | ||
|
|
e90f00dcf3 | ||
|
|
e7d05e1b42 | ||
|
|
d55ac7ba7a | ||
|
|
7afe6b3b78 | ||
|
|
0623c42d10 | ||
|
|
738230f7ea | ||
|
|
17e0c81967 | ||
|
|
adca169651 | ||
|
|
d049a1cf7f | ||
|
|
db4f07655b | ||
|
|
5c2a897abc | ||
|
|
b760962907 | ||
|
|
489df47647 | ||
|
|
23354c91f5 | ||
|
|
901e5fb6fd | ||
|
|
16b3732b63 | ||
|
|
272dc5cecf | ||
|
|
c6974ad9dd | ||
|
|
bf0936ff65 | ||
|
|
4ecd4aed42 | ||
|
|
636dd26f07 | ||
|
|
0d70d25f07 | ||
|
|
15c8926c97 | ||
|
|
300a64f711 | ||
|
|
27a9b91f3c | ||
|
|
e48f8805a5 | ||
|
|
9bbe7b69a3 | ||
|
|
8cde239e64 | ||
|
|
15c3c9564a | ||
|
|
f288082ff3 | ||
|
|
0fd046c4c1 | ||
|
|
7bd33b7ff1 | ||
|
|
9ce7cde286 | ||
|
|
0cf540495f | ||
|
|
6050f3c396 | ||
|
|
3371028cdf | ||
|
|
206d40bc0d | ||
|
|
f796d5c8fc | ||
|
|
03bf451124 | ||
|
|
2659b44569 | ||
|
|
e5f62c9546 | ||
|
|
f5a70b0e98 | ||
|
|
13aa3a5cc6 | ||
|
|
3fe6d7e954 | ||
|
|
5950cbce24 | ||
|
|
88a3069ea2 | ||
|
|
20e2efebf7 | ||
|
|
a193f64e04 | ||
|
|
494dbd965b | ||
|
|
bea1843497 | ||
|
|
f9284510ea | ||
|
|
723997489a | ||
|
|
0bc5f721fb | ||
|
|
7aaee29277 | ||
|
|
334bcc3dc0 | ||
|
|
3944964adf | ||
|
|
41928f5611 | ||
|
|
f9c31fe169 | ||
|
|
9f7d3fa401 | ||
|
|
e9ac879b83 | ||
|
|
ffde4b3bbe | ||
|
|
0db2d73e02 | ||
|
|
fcb2188143 | ||
|
|
ab183249f9 | ||
|
|
cd4912b003 | ||
|
|
61d1f267cf | ||
|
|
b9c9162b14 | ||
|
|
bbf613e944 | ||
|
|
91acccc36a | ||
|
|
dec54a9ded | ||
|
|
38a239b1e9 | ||
|
|
60ac79d4b5 | ||
|
|
a65a9b36b5 | ||
|
|
808ae34499 | ||
|
|
f8769d9650 | ||
|
|
0b2cfae274 | ||
|
|
c647cb4eb9 | ||
|
|
0314c8bf2a | ||
|
|
71f4879f9c | ||
|
|
472d3661ce | ||
|
|
ca90388ff3 | ||
|
|
ded4122de0 | ||
|
|
fe3b20a37a | ||
|
|
9746b6999a | ||
|
|
0ca0af9026 | ||
|
|
6971715295 | ||
|
|
5bfba91aa8 | ||
|
|
080c96aa06 | ||
|
|
a2f732118f | ||
|
|
c2af11dfa7 | ||
|
|
b1dcb46e08 | ||
|
|
c00bc59949 | ||
|
|
1b577e9eed | ||
|
|
29bf02b6ce | ||
|
|
1998da2643 | ||
|
|
28ed9c58a7 | ||
|
|
a3560a1442 | ||
|
|
c40ff9603e | ||
|
|
595ccf2b06 | ||
|
|
8acdceeb61 | ||
|
|
4ce72c668a | ||
|
|
ebeee968b5 | ||
|
|
2eaf90df4b | ||
|
|
d8cf5fbb62 | ||
|
|
bf3e607bd6 | ||
|
|
6042310fc7 | ||
|
|
1ec5d20c84 | ||
|
|
723810f768 | ||
|
|
60e22f38c4 | ||
|
|
ba63055fd3 | ||
|
|
cec2e0c04a | ||
|
|
8fb5e95f15 | ||
|
|
5f4a17cb7c | ||
|
|
1c02f239c3 | ||
|
|
ea0d0e9595 | ||
|
|
5c24bc3dcf | ||
|
|
5689203791 | ||
|
|
b99ea8905e | ||
|
|
c1c97ed00e | ||
|
|
a551f206e8 | ||
|
|
b70c8609c9 | ||
|
|
55ec024e31 | ||
|
|
64cb95d8ec | ||
|
|
4a0063f5f6 | ||
|
|
f4f0702d08 | ||
|
|
98401d6de2 | ||
|
|
97fbaf7da4 | ||
|
|
90a239b410 |
+3
-2
@@ -30,9 +30,10 @@ Generated-in-code assets are original and have no file to list:
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `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`. |
|
||||
|
||||
Generated
+396
-139
File diff suppressed because it is too large
Load Diff
+49
-38
@@ -1,6 +1,8 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
# Patched third-party crates under [patch.crates-io], not ours to lint or test.
|
||||
exclude = ["vendor/wgpu-hal"]
|
||||
# default-members
|
||||
|
||||
[workspace.package]
|
||||
@@ -14,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" }
|
||||
@@ -29,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"] }
|
||||
@@ -75,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 }
|
||||
@@ -91,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 }
|
||||
|
||||
@@ -123,23 +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.
|
||||
|
||||
@@ -396,6 +396,20 @@ RISC-V (riscv64) packages are `cadcraft-<ver>-linux-riscv64.deb`,
|
||||
`cadcraft-<ver>-linux-riscv64.rpm`, and `cadcraft-<ver>-linux-riscv64.tar.gz`. They are
|
||||
cross-compiled and need glibc 2.39 or newer (Ubuntu 24.04+, Debian 13+).
|
||||
|
||||
**Wayland:** on a Wayland desktop the app uses the native Wayland backend, which is sharp at
|
||||
fractional scales, works with input methods and accepts files dropped from the file manager. If
|
||||
the native backend misbehaves on your desktop, run the app through XWayland instead with
|
||||
`CADCRAFT_X11=1` (this needs the X11 libraries: libX11, libX11-xcb, libXcursor, libXi and
|
||||
libxkbcommon-x11):
|
||||
|
||||
```sh
|
||||
CADCRAFT_X11=1 cadcraft
|
||||
```
|
||||
|
||||
GNOME on Wayland draws no window frames, so there CADCraft's title bar carries the window
|
||||
buttons, in GNOME's order. **Options ▸ Display ▸ Use system title bar** shows a basic frame
|
||||
instead. `CADCRAFT_TITLEBAR=app` or `CADCRAFT_TITLEBAR=system` overrides the detection.
|
||||
|
||||
### FreeBSD
|
||||
|
||||
| Build | File |
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -40,6 +40,12 @@ winresource = "0.1"
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
# Checks that the X11 libraries are installed before choosing XWayland (see main.rs). Already in
|
||||
# the build through winit, at this version.
|
||||
x11-dl = "2.21"
|
||||
# Checks for libxkbcommon-x11 too, which winit's X11 backend needs for the keyboard and panics
|
||||
# without. Already in the build through winit, at this version and with this feature.
|
||||
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
|
||||
# View ▸ Theme ▸ System: the desktop's light/dark choice from the XDG desktop portal
|
||||
# (desktop_theme.rs). Already in Cargo.lock through accesskit; pinned to that version so nothing
|
||||
# is built twice.
|
||||
@@ -47,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"] }
|
||||
|
||||
@@ -12,7 +12,7 @@ const CONFIG_DIR: &str = "CADCRAFT_CONFIG_DIR";
|
||||
const LOCALE: &str = "CADCRAFT_LOCALE";
|
||||
const VSYNC: &str = "CADCRAFT_VSYNC";
|
||||
const STENCIL: &str = "CADCRAFT_STENCIL";
|
||||
const WAYLAND: &str = "CADCRAFT_WAYLAND";
|
||||
const X11: &str = "CADCRAFT_X11";
|
||||
const NO_NATIVE_MENU: &str = "CADCRAFT_NO_NATIVE_MENU";
|
||||
const SYSTEM_CURSOR: &str = "CADCRAFT_SYSTEM_CURSOR";
|
||||
const FONTALT: &str = "CADCRAFT_FONTALT";
|
||||
@@ -27,7 +27,7 @@ pub(crate) const VARS: &[(&str, &str)] = &[
|
||||
STENCIL,
|
||||
"0 opens the window without a stencil buffer, 1 keeps it on every attempt; unset, a start that can't draw with it drops it (clipped layout viewports then draw unclipped)",
|
||||
),
|
||||
(WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"),
|
||||
(X11, "1 runs through XWayland instead of the native Wayland backend, as a fallback, when the X11 libraries load; 0 or unset is off"),
|
||||
(NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"),
|
||||
(SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"),
|
||||
(FONTALT, "the font that replaces a missing one"),
|
||||
@@ -54,9 +54,9 @@ pub(crate) struct Env {
|
||||
/// `renderer`). Some old drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a
|
||||
/// stencil pass and then present a black window.
|
||||
pub(crate) stencil: Switch,
|
||||
/// Keep the native Wayland backend instead of XWayland.
|
||||
/// Run through XWayland instead of the native Wayland backend.
|
||||
#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]
|
||||
pub(crate) wayland: Switch,
|
||||
pub(crate) x11: Switch,
|
||||
/// macOS: keep the menus inside the window.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
pub(crate) no_native_menu: Switch,
|
||||
@@ -121,7 +121,7 @@ impl Env {
|
||||
locale: text(LOCALE),
|
||||
vsync: switch(VSYNC),
|
||||
stencil: switch(STENCIL),
|
||||
wayland: switch(WAYLAND),
|
||||
x11: switch(X11),
|
||||
no_native_menu: switch(NO_NATIVE_MENU),
|
||||
system_cursor: switch(SYSTEM_CURSOR),
|
||||
font_alt: text(FONTALT),
|
||||
@@ -223,7 +223,7 @@ mod tests {
|
||||
(LOCALE, "cs-CZ"),
|
||||
(VSYNC, " On "),
|
||||
(STENCIL, "No"),
|
||||
(WAYLAND, "0"),
|
||||
(X11, "0"),
|
||||
(NO_NATIVE_MENU, "yes"),
|
||||
(SYSTEM_CURSOR, "maybe"),
|
||||
(FONTALT, "Noto Sans"),
|
||||
@@ -238,7 +238,7 @@ mod tests {
|
||||
locale: Some("cs-CZ".into()),
|
||||
vsync: Switch::On,
|
||||
stencil: Switch::Off,
|
||||
wayland: Switch::Off,
|
||||
x11: Switch::Off,
|
||||
no_native_menu: Switch::On,
|
||||
system_cursor: Switch::Default,
|
||||
font_alt: Some("Noto Sans".into()),
|
||||
@@ -249,7 +249,7 @@ mod tests {
|
||||
let read = Env::from_vars(env(&blank));
|
||||
assert_eq!(read.config_dir, None, "an empty variable means no directory, not the working directory");
|
||||
assert_eq!((read.locale, read.font_alt, read.font_fallback), (None, None, None));
|
||||
assert_eq!([read.vsync, read.stencil, read.wayland, read.no_native_menu, read.system_cursor], [Switch::Default; 5]);
|
||||
assert_eq!([read.vsync, read.stencil, read.x11, read.no_native_menu, read.system_cursor], [Switch::Default; 5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+108
-7
@@ -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()
|
||||
@@ -498,6 +524,38 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
Some(launch.passthrough_args)
|
||||
}
|
||||
|
||||
/// Whether the libraries winit's X11 backend opens at startup are installed (libX11, libXcursor,
|
||||
/// libX11-xcb and libXi; libX11-xcb brings in libxcb; and libxkbcommon-x11, for the keyboard).
|
||||
/// The deb and rpm only recommend them, and a forced X11 backend without them fails to start
|
||||
/// (winit panics when libxkbcommon-x11 is missing).
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn x11_libraries_load() -> bool {
|
||||
use x11_dl::{xcursor::Xcursor, xinput2::XInput2, xlib::Xlib, xlib_xcb::Xlib_xcb};
|
||||
let missing = [Xlib::open().err(), Xcursor::open().err(), Xlib_xcb::open().err(), XInput2::open().err()];
|
||||
let mut missing: Vec<String> = missing.into_iter().flatten().map(|e| e.to_string()).collect();
|
||||
if xkbcommon_dl::x11::xkbcommon_x11_option().is_none() {
|
||||
missing.push("libxkbcommon-x11.so.0 could not be loaded".into());
|
||||
}
|
||||
if !missing.is_empty() {
|
||||
log::warn!("CADCRAFT_X11: X11 libraries missing, using the native Wayland backend: {}", missing.join("; "));
|
||||
}
|
||||
missing.is_empty()
|
||||
}
|
||||
|
||||
/// Whether to force winit's X11 backend (XWayland on a Wayland desktop): an X display is there,
|
||||
/// `CADCRAFT_X11` is on, and the X11 libraries load. The libraries are probed last, only when X11
|
||||
/// would otherwise be chosen.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn use_x11(display: bool, setting: Switch, x11_libraries_load: impl FnOnce() -> bool) -> bool {
|
||||
display && setting == Switch::On && x11_libraries_load()
|
||||
}
|
||||
|
||||
/// Whether a display variable names something: set and not empty, as winit reads them.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn set(v: Option<&std::ffi::OsStr>) -> bool {
|
||||
v.is_some_and(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
|
||||
fn main() -> eframe::Result {
|
||||
// A copy of this program started to read or write a DWG file does only that. It is started
|
||||
@@ -589,9 +647,21 @@ fn main() -> eframe::Result {
|
||||
cadcraft_engine::fonts::ttf::set_fallback_fonts(list);
|
||||
}
|
||||
let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos"))));
|
||||
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
|
||||
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
|
||||
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
|
||||
// winit runs natively on a Wayland desktop: sharp at fractional scales, with working input
|
||||
// methods, and file drops from the file manager through storytold/winit's W15 patch.
|
||||
// CADCRAFT_X11=1 runs through XWayland instead, as a fallback where the native backend
|
||||
// misbehaves; 0, off or unset leaves it off. The X11 libraries are only recommended by the
|
||||
// packages, so without them the setting is ignored rather than failing.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let forced_x11 = use_x11(set(std::env::var_os("DISPLAY").as_deref()), vars.x11, x11_libraries_load);
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
let forced_x11 = false;
|
||||
// Read before the window opens: Use system title bar decides the window's frame.
|
||||
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
|
||||
// Where the desktop leaves the window frame to the app (GNOME on Wayland), the framework's title
|
||||
// bar carries the window buttons, unless Options ▸ Display ▸ Use system title bar is on.
|
||||
let title_bar = cadcraft_ui_egui::title_bar::decide(forced_x11, restored.as_ref().is_some_and(|ui| ui.system_title_bar));
|
||||
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11).or_else(|| title_bar.as_ref().map(|t| t.decision().clone()));
|
||||
let persistence_path = vars
|
||||
.portable_storage_file
|
||||
.clone()
|
||||
@@ -620,9 +690,6 @@ fn main() -> eframe::Result {
|
||||
d
|
||||
});
|
||||
}
|
||||
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
|
||||
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
|
||||
// keeps the native Wayland backend.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if forced_x11 {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
@@ -666,7 +733,6 @@ fn main() -> eframe::Result {
|
||||
{
|
||||
app.services.start_pick = Some(start_pick(cc.egui_ctx.clone()));
|
||||
}
|
||||
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
|
||||
if let Some(ui) = restored {
|
||||
app.ui = ui;
|
||||
}
|
||||
@@ -716,6 +782,9 @@ fn main() -> eframe::Result {
|
||||
app.session.set_lisp_support_dir(Some(support));
|
||||
}
|
||||
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
|
||||
if let Some(title_bar) = title_bar {
|
||||
app.set_title_bar(title_bar);
|
||||
}
|
||||
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
|
||||
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
|
||||
}
|
||||
@@ -725,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!({}));
|
||||
}
|
||||
@@ -781,6 +851,37 @@ mod tests {
|
||||
use super::{filters_for_save, follow_desktop, nightly_version_line, saved_window, version_string, window_options, without_tiny_window};
|
||||
use crate::renderer::STENCIL_BITS;
|
||||
|
||||
/// A Wayland desktop without the X11 libraries (libxkbcommon-x11 removed, or a package
|
||||
/// installed without its recommendations) crashed at startup: X11 was forced through XWayland
|
||||
/// and winit panicked loading them. Native Wayland is now the default, `CADCRAFT_X11=1` asks
|
||||
/// for X11 only when the libraries load, and probing them never panics, whichever of them
|
||||
/// this machine has.
|
||||
#[test]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn x11_only_when_asked_for_and_the_libraries_load() {
|
||||
use super::{use_x11, x11_libraries_load};
|
||||
use cadcraft_ui_egui::switch::Switch;
|
||||
let unprobed = || -> bool { panic!("the libraries are probed only when X11 would be chosen") };
|
||||
assert!(!use_x11(true, Switch::Default, unprobed), "native Wayland by default");
|
||||
assert!(!use_x11(true, Switch::Off, unprobed), "CADCRAFT_X11=0 leaves it off");
|
||||
assert!(!use_x11(false, Switch::On, unprobed), "no X display");
|
||||
assert!(use_x11(true, Switch::On, || true));
|
||||
assert!(!use_x11(true, Switch::On, || false), "missing X11 libraries: native Wayland, no crash");
|
||||
let loaded = x11_libraries_load();
|
||||
assert_eq!(use_x11(true, Switch::On, || loaded), loaded);
|
||||
}
|
||||
|
||||
/// An empty `DISPLAY` names no X server, so `CADCRAFT_X11=1` can't force X11 with it.
|
||||
#[test]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn an_empty_display_is_no_display() {
|
||||
use super::set;
|
||||
use std::ffi::OsStr;
|
||||
assert!(set(Some(OsStr::new(":0"))));
|
||||
assert!(!set(Some(OsStr::new(""))));
|
||||
assert!(!set(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
|
||||
let first = |name: &str| filters_for_save(name)[0].1;
|
||||
|
||||
@@ -50,6 +50,7 @@ fn snapshot(ui: &UiState) -> Result<Value, String> {
|
||||
"propertiesAll": ui.properties_all,
|
||||
"inWindowMenu": ui.in_window_menu,
|
||||
"historyLines": ui.history_lines,
|
||||
"systemTitleBar": ui.system_title_bar,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -219,6 +220,7 @@ mod tests {
|
||||
ui.toolset_tab = "Modeling".into();
|
||||
ui.collapsed_groups = vec!["Solid".into()];
|
||||
ui.history_lines = 5;
|
||||
ui.system_title_bar = true;
|
||||
ui.dialog = Some("layers".into());
|
||||
ui.start_tab = true;
|
||||
first.save_if_changed(&ui, Instant::now()).unwrap();
|
||||
@@ -226,6 +228,7 @@ mod tests {
|
||||
let value: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert!(value["workspace"].get("dialog").is_none());
|
||||
assert!(value["workspace"].get("startTab").is_none());
|
||||
assert_eq!(value["workspace"]["systemTitleBar"], true, "read before the window opens");
|
||||
let (_, restored, error) = Workspace::at(Some(path.clone()));
|
||||
assert!(error.is_none());
|
||||
let restored = restored.unwrap();
|
||||
@@ -340,6 +343,7 @@ mod tests {
|
||||
assert_eq!(restored.toolset_tab, "Modeling");
|
||||
assert_eq!(restored.collapsed_groups, ["Draw"]);
|
||||
assert_eq!(restored.history_lines, 7);
|
||||
assert!(!restored.system_title_bar, "older files keep the app's window buttons");
|
||||
assert_eq!(serde_json::to_value(restored.docking).unwrap(), serde_json::to_value(UiState::default().docking).unwrap());
|
||||
}
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
|
||||
+131
-6
@@ -7,9 +7,15 @@
|
||||
//! it draws at paper size × that view's annotation scale, and only in views whose scale it
|
||||
//! supports unless `ANNOALLVISIBLE` is 1. Model space is seen at `CANNOSCALE`, a layout viewport
|
||||
//! at its viewport scale, and paper space itself at 1:1.
|
||||
//!
|
||||
//! An object supporting several scales can sit somewhere else at one of them ([`AnnoMove`]): its
|
||||
//! grips move it at the current scale only, and ANNORESET puts every scale back where the current
|
||||
//! one is. What moves is the object's position ([`shift_position`]).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use cadcraft_geom::{Mat3, Vec2};
|
||||
|
||||
use crate::{Common, Drawing, Entity, EntityKind};
|
||||
|
||||
/// A named annotation scale: `paper_units` on paper show `drawing_units` of the drawing.
|
||||
@@ -87,6 +93,13 @@ pub fn imperial_scales() -> Vec<AnnoScale> {
|
||||
v
|
||||
}
|
||||
|
||||
/// How far an annotative object sits from its shared position at the scale named `scale`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnnoMove {
|
||||
pub scale: String,
|
||||
pub by: Vec2,
|
||||
}
|
||||
|
||||
/// Kinds that can be annotative.
|
||||
pub fn can_be_annotative(k: &EntityKind) -> bool {
|
||||
matches!(
|
||||
@@ -105,6 +118,7 @@ pub fn is_annotative(e: &Entity) -> bool {
|
||||
pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
|
||||
if !on {
|
||||
e.common.anno_scales.clear();
|
||||
e.common.anno_moves.clear();
|
||||
} else if can_be_annotative(&e.kind) && e.common.anno_scales.is_empty() {
|
||||
e.common.anno_scales.push(current.clone());
|
||||
}
|
||||
@@ -115,8 +129,9 @@ pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
|
||||
pub enum AnnoDraw {
|
||||
/// Not annotative: as stored.
|
||||
Plain,
|
||||
/// Annotative, at this factor (drawing units per paper unit).
|
||||
Scaled(f64),
|
||||
/// Annotative, at `factor` (drawing units per paper unit), its position moved `by` at that
|
||||
/// scale.
|
||||
Scaled { factor: f64, by: Vec2 },
|
||||
/// Annotative and not supporting the view's scale, with `ANNOALLVISIBLE` 0.
|
||||
Hidden,
|
||||
}
|
||||
@@ -130,6 +145,76 @@ impl Common {
|
||||
pub fn supports_scale(&self, name: &str) -> bool {
|
||||
self.anno_scales.iter().any(|s| s.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// How far the object sits from its shared position at the scale named `name`.
|
||||
pub fn moved_at(&self, name: &str) -> Vec2 {
|
||||
self.anno_moves.iter().find(|m| m.scale.eq_ignore_ascii_case(name)).map(|m| m.by).filter(|v| v.is_finite()).unwrap_or(Vec2::ZERO)
|
||||
}
|
||||
/// How far the object sits from its shared position at its scale with the ratio `factor`.
|
||||
pub fn moved_at_factor(&self, factor: f64) -> Vec2 {
|
||||
self.anno_scales.iter().find(|s| s.has_factor(factor)).map_or(Vec2::ZERO, |s| self.moved_at(&s.name))
|
||||
}
|
||||
/// Move the object `by` at the scale named `name` only (an offset that comes to nothing is
|
||||
/// dropped).
|
||||
pub fn move_at(&mut self, name: &str, by: Vec2) {
|
||||
if !by.is_finite() {
|
||||
return;
|
||||
}
|
||||
let to = self.moved_at(name) + by;
|
||||
self.anno_moves.retain(|m| !m.scale.eq_ignore_ascii_case(name));
|
||||
if to.len() > 1e-12 * (1.0 + by.len()) && self.anno_moves.len() < MAX_SCALES {
|
||||
self.anno_moves.push(AnnoMove { scale: name.to_string(), by: to });
|
||||
}
|
||||
}
|
||||
/// Turn the offsets with `m`'s linear part (MOVE leaves them, ROTATE turns them, SCALE sizes
|
||||
/// them, MIRROR mirrors them), as the shared position goes through `m`.
|
||||
pub fn transform_moves(&mut self, m: &Mat3) {
|
||||
for mv in &mut self.anno_moves {
|
||||
let v = m.apply_vec(mv.by);
|
||||
mv.by = if v.is_finite() { v } else { Vec2::ZERO };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the position of `k` by `by`: a text's, MText's or block reference's whole object, a
|
||||
/// multileader's landing and content (its arrowheads stay), a dimension's text. Other kinds stay.
|
||||
pub fn shift_position(k: &mut EntityKind, by: Vec2) {
|
||||
if !by.is_finite() || by == Vec2::ZERO {
|
||||
return;
|
||||
}
|
||||
let add = |p: &mut cadcraft_geom::Vec3| {
|
||||
p.x += by.x;
|
||||
p.y += by.y;
|
||||
};
|
||||
match k {
|
||||
EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_) => k.transform(&Mat3::translate(by)),
|
||||
EntityKind::MLeader(m) => {
|
||||
add(&mut m.landing);
|
||||
if let Some(t) = &mut m.text {
|
||||
add(&mut t.insert);
|
||||
}
|
||||
if let Some(b) = &mut m.block {
|
||||
add(&mut b.insert);
|
||||
}
|
||||
}
|
||||
EntityKind::Dimension(d) => {
|
||||
add(&mut d.text_mid);
|
||||
d.user_text_pos = true;
|
||||
d.block = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether grip `index` of `k` is its position grip: moving it moves what [`shift_position`]
|
||||
/// moves.
|
||||
pub fn is_position_grip(k: &EntityKind, index: usize) -> bool {
|
||||
match k {
|
||||
EntityKind::Text(_) | EntityKind::MText(_) => true,
|
||||
EntityKind::Insert(_) => index == 0,
|
||||
EntityKind::Dimension(_) => index == 3,
|
||||
EntityKind::MLeader(m) => index == m.leaders.iter().map(Vec::len).sum::<usize>(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How `e` draws in a view whose annotation scale is `view` (drawing units per paper unit). An
|
||||
@@ -139,14 +224,23 @@ pub fn anno_draw(e: &Entity, view: f64, all_visible: bool) -> AnnoDraw {
|
||||
return AnnoDraw::Plain;
|
||||
}
|
||||
if e.common.supports_factor(view) {
|
||||
return AnnoDraw::Scaled(if view.is_finite() && view > 0.0 { view } else { 1.0 });
|
||||
let factor = if view.is_finite() && view > 0.0 { view } else { 1.0 };
|
||||
return AnnoDraw::Scaled { factor, by: e.common.moved_at_factor(view) };
|
||||
}
|
||||
match e.common.anno_scales.first() {
|
||||
Some(s) if all_visible => AnnoDraw::Scaled(s.factor()),
|
||||
Some(s) if all_visible => AnnoDraw::Scaled { factor: s.factor(), by: e.common.moved_at(&s.name) },
|
||||
_ => AnnoDraw::Hidden,
|
||||
}
|
||||
}
|
||||
|
||||
/// `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 {
|
||||
let mut out = anno_scaled(e, f);
|
||||
shift_position(&mut out.kind, by);
|
||||
out
|
||||
}
|
||||
|
||||
/// `e` as it draws at annotation scale `f`: its paper sizes (text height and width, dimension
|
||||
/// overall scale, multileader arrow, landing and content, hatch pattern scale, block scale and
|
||||
/// attributes) multiplied by `f`. A dimension is drawn from its definition at that scale, not
|
||||
@@ -225,13 +319,44 @@ impl Drawing {
|
||||
/// (paper space shows every annotative object), elsewhere (model space, or an object not in
|
||||
/// the drawing yet) as [`anno_draw`] at the current annotation scale.
|
||||
pub fn anno_draw(&self, e: &Entity) -> AnnoDraw {
|
||||
self.anno_draw_in(e, None)
|
||||
}
|
||||
/// How top-level object `e` draws where it is edited: through an active viewport whose
|
||||
/// annotation scale is `view` (drawing units per paper unit, the viewport's scale, as the
|
||||
/// renderer draws model space there), else as [`Drawing::anno_draw`].
|
||||
pub fn anno_draw_in(&self, e: &Entity, view: Option<f64>) -> AnnoDraw {
|
||||
if !is_annotative(e) {
|
||||
return AnnoDraw::Plain;
|
||||
}
|
||||
if !self.model.contains(e.handle) && self.layouts.iter().any(|l| l.entities.contains(e.handle)) {
|
||||
return AnnoDraw::Scaled(1.0);
|
||||
return AnnoDraw::Scaled { factor: 1.0, by: e.common.moved_at_factor(1.0) };
|
||||
}
|
||||
let view = view.filter(|f| f.is_finite() && *f > 0.0).unwrap_or_else(|| self.current_anno_scale().factor());
|
||||
anno_draw(e, view, self.anno_all_visible())
|
||||
}
|
||||
/// The scale `e` shows at outside a viewport (see [`Drawing::anno_draw`]): its name and
|
||||
/// factor, `None` when `e` isn't annotative or doesn't show.
|
||||
pub fn anno_shown_scale(&self, e: &Entity) -> Option<AnnoScale> {
|
||||
self.anno_shown_scale_in(e, None)
|
||||
}
|
||||
/// The scale `e` shows at in view `view` (see [`Drawing::anno_draw_in`]).
|
||||
pub fn anno_shown_scale_in(&self, e: &Entity, view: Option<f64>) -> Option<AnnoScale> {
|
||||
match self.anno_draw_in(e, view) {
|
||||
AnnoDraw::Scaled { factor, .. } => e.common.anno_scales.iter().find(|s| s.has_factor(factor)).cloned(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `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 {
|
||||
self.anno_shown_in(e, None)
|
||||
}
|
||||
/// `e` as it draws in view `view` (see [`Drawing::anno_draw_in`]).
|
||||
pub fn anno_shown_in(&self, e: &Entity, view: Option<f64>) -> EntityKind {
|
||||
match self.anno_draw_in(e, view) {
|
||||
AnnoDraw::Scaled { factor, by } => anno_placed(e, factor, by).kind,
|
||||
_ => e.kind.clone(),
|
||||
}
|
||||
anno_draw(e, self.current_anno_scale().factor(), self.anno_all_visible())
|
||||
}
|
||||
/// Whether new objects of this kind are annotative: text and MText with an annotative text
|
||||
/// style, dimensions with an annotative dimension style, multileaders with an annotative
|
||||
|
||||
@@ -98,6 +98,10 @@ pub struct Common {
|
||||
/// The annotation scales an annotative object supports (empty: not annotative).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub anno_scales: Vec<crate::AnnoScale>,
|
||||
/// Where an annotative object sits apart from its shared position at some of its scales
|
||||
/// (moved with its grips at that scale; ANNORESET clears them).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub anno_moves: Vec<crate::AnnoMove>,
|
||||
/// Other applications' extended data (xdata) as read from the drawing file: whole
|
||||
/// applications, each from its `1001` group on. It is part of the object, so a copy of the
|
||||
/// object (COPY, MIRROR, ARRAY, paste) carries it, as in AutoCAD.
|
||||
@@ -119,6 +123,7 @@ impl Default for Common {
|
||||
extrusion: Vec3::Z,
|
||||
plot_style: "ByLayer".into(),
|
||||
anno_scales: Vec::new(),
|
||||
anno_moves: Vec::new(),
|
||||
xdata: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,7 +645,9 @@ fn bounds_of<'a>(
|
||||
match d.anno_draw(e) {
|
||||
crate::AnnoDraw::Plain => {}
|
||||
crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
|
||||
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen),
|
||||
crate::AnnoDraw::Scaled { factor, by } => {
|
||||
return bounds_in(d, &crate::anno_placed(e, factor, by), 0, blocks, in_drawing, off_counts, frozen);
|
||||
}
|
||||
}
|
||||
}
|
||||
bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen)
|
||||
|
||||
@@ -45,6 +45,31 @@ pub struct ForeignExtra {
|
||||
/// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled
|
||||
/// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them.
|
||||
pub tail: Vec<RawTag>,
|
||||
/// A lightweight polyline's vertex identifiers (group 91, DXF 2010 and later) as read: one per
|
||||
/// vertex in the polyline's order; empty when the file gave none. Geometric constraints name the
|
||||
/// polyline's segments by them, so they are written back while the polyline's vertices are
|
||||
/// where they were read ([`vertex_ids_for`]).
|
||||
pub vertex_ids: Vec<VertexId>,
|
||||
}
|
||||
|
||||
/// A vertex of a lightweight polyline as it was read: its identifier and its point as the
|
||||
/// polyline has it once read (a polyline whose normal points down is read mirrored in x).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct VertexId {
|
||||
/// The identifier (group 91); 0 for a vertex without one.
|
||||
pub id: i32,
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
}
|
||||
|
||||
/// The identifiers `kept` gives the vertices at `points`, in their order, while every vertex is
|
||||
/// where it was read. `None` once a vertex was added, removed, moved or the order changed: the
|
||||
/// identifiers no longer say which vertex is which.
|
||||
pub fn vertex_ids_for(kept: &[VertexId], points: impl ExactSizeIterator<Item = (f64, f64)> + Clone) -> Option<Vec<i32>> {
|
||||
if kept.is_empty() || kept.len() != points.len() {
|
||||
return None;
|
||||
}
|
||||
kept.iter().zip(points).all(|(k, (x, y))| k.x == x && k.y == y).then(|| kept.iter().map(|k| k.id).collect())
|
||||
}
|
||||
|
||||
impl ForeignExtra {
|
||||
@@ -55,6 +80,7 @@ impl ForeignExtra {
|
||||
&& self.color_book.is_none()
|
||||
&& self.props.is_empty()
|
||||
&& self.tail.is_empty()
|
||||
&& self.vertex_ids.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -154,6 +154,8 @@ impl Header {
|
||||
// Annotation scale of model space; annotative objects of other scales show (1) or not.
|
||||
h.set_str("CANNOSCALE", "1:1");
|
||||
h.set_i64("ANNOALLVISIBLE", 1);
|
||||
// Written to DXF as $REGENMODE; a header variable the drawing lacks is not written.
|
||||
h.set_i64("REGENMODE", 1);
|
||||
h
|
||||
}
|
||||
|
||||
|
||||
+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"))]));
|
||||
}
|
||||
|
||||
@@ -19,6 +19,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 }
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
//! objects show (ANNOALLVISIBLE) and the current annotation scale (CANNOSCALE with
|
||||
//! ANNOAUTOSCALE).
|
||||
|
||||
use cadcraft_doc::geom::Vec2;
|
||||
use cadcraft_doc::{AnnoScale, Drawing, EntityKind, Handle, MAX_SCALES, is_annotative};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -136,6 +137,7 @@ fn remove_scale(d: &mut Drawing, h: Handle, name: &str) -> Removed {
|
||||
return;
|
||||
}
|
||||
e.common.anno_scales.retain(|s| !s.name.eq_ignore_ascii_case(name));
|
||||
e.common.anno_moves.retain(|m| !m.scale.eq_ignore_ascii_case(name));
|
||||
r = Removed::Yes;
|
||||
});
|
||||
r
|
||||
@@ -216,8 +218,27 @@ fn with_handles(s: &Session, p: &Value, mut extra: Value) -> Value {
|
||||
|
||||
fn run_annoreset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (hs, _) = annotative_targets(s, p, "annoreset")?;
|
||||
// One position serves every scale of an object, so they are always in step.
|
||||
Ok(json!({ "objects": hs.len(), "message": format!("{} annotative object(s) synchronized", hs.len()) }))
|
||||
// Every scale goes where the object shows now (in the active viewport, at its scale): that
|
||||
// offset becomes the shared position.
|
||||
let view = s.anno_view();
|
||||
let d = s.doc_mut()?;
|
||||
let mut moved = 0;
|
||||
for h in &hs {
|
||||
let Some(e) = d.entity(*h) else { continue };
|
||||
if e.common.anno_moves.is_empty() || d.layer(&e.common.layer).is_some_and(|l| l.locked) {
|
||||
continue;
|
||||
}
|
||||
let by = match d.anno_draw_in(e, view) {
|
||||
cadcraft_doc::AnnoDraw::Scaled { by, .. } => by,
|
||||
_ => Vec2::ZERO,
|
||||
};
|
||||
d.modify_entity(*h, |e| {
|
||||
cadcraft_doc::shift_position(&mut e.kind, by);
|
||||
e.common.anno_moves.clear();
|
||||
})?;
|
||||
moved += 1;
|
||||
}
|
||||
Ok(json!({ "objects": hs.len(), "reset": moved, "message": format!("{} annotative object(s) synchronized", hs.len()) }))
|
||||
}
|
||||
|
||||
fn run_annoupdate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -86,6 +86,7 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result<Vec<Handle>> {
|
||||
let old_h = e.handle;
|
||||
let mut e = adopt(d, e, &renames);
|
||||
e.kind.transform(m);
|
||||
e.common.transform_moves(m);
|
||||
d.ensure_layer(&e.common.layer);
|
||||
out.push(e.handle);
|
||||
copies.push((old_h, e.handle));
|
||||
|
||||
@@ -343,6 +343,11 @@ fn eq_variants(o: &TanObj) -> Vec<Eq3> {
|
||||
|
||||
/// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations).
|
||||
pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
||||
ttt_where(objs, |_| true)
|
||||
}
|
||||
|
||||
/// [`ttt`] among the circles `ok` accepts.
|
||||
pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Option<Circle> {
|
||||
let [(o1, p1), (o2, p2), (o3, p3)] = objs;
|
||||
let mut starts: Vec<[f64; 3]> = Vec::new();
|
||||
let cen = (p1 + p2 + p3) / 3.0;
|
||||
@@ -350,6 +355,20 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
||||
starts.push([cen.x, cen.y, rad.max(1e-3)]);
|
||||
if let Some(c) = Circle::from_3_points(p1, p2, p3) {
|
||||
starts.push([c.center.x, c.center.y, c.radius]);
|
||||
} else {
|
||||
// The picks lie in one line. When the circles picked are centred on it too, every Newton
|
||||
// step from a start on that line stays on it: start off it as well, on both sides, from
|
||||
// the circle through the two picks farthest apart and a point beside them.
|
||||
let (a, b) = [(p1, p2), (p1, p3), (p2, p3)].into_iter().max_by(|x, y| x.0.dist(x.1).total_cmp(&y.0.dist(y.1))).unwrap_or((p1, p3));
|
||||
let span = a.dist(b);
|
||||
let n = (b - a).normalized().perp();
|
||||
if span.is_finite() && span > 0.0 && n.is_finite() {
|
||||
for side in [1.0, -1.0] {
|
||||
if let Some(c) = Circle::from_3_points(a, b, (a + b) / 2.0 + n * (span * side)) {
|
||||
starts.push([c.center.x, c.center.y, c.radius]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut best: Option<(f64, Circle)> = None;
|
||||
let scale = rad.max(p1.dist(p2)).max(1e-6);
|
||||
@@ -379,6 +398,9 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
|
||||
continue;
|
||||
}
|
||||
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
|
||||
if !ok(&c) {
|
||||
continue;
|
||||
}
|
||||
let sc = score(&c, &objs);
|
||||
if best.is_none_or(|(b, _)| sc < b - 1e-12) {
|
||||
best = Some((sc, c));
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::{
|
||||
Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number,
|
||||
point_param, size_param,
|
||||
};
|
||||
use crate::snap;
|
||||
|
||||
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = if let Some(center) = point_param(p, "center") {
|
||||
@@ -51,6 +52,8 @@ pub(super) fn run_arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) struct CircleM {
|
||||
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
|
||||
pts: Vec<Vec2>,
|
||||
/// 3P: the circle or arc each point was picked on with a tangent snap, by point.
|
||||
tans: Vec<Option<snap::SnapCurve>>,
|
||||
diameter: bool,
|
||||
/// The `Ttr` option hands over to the tangent-circle machine.
|
||||
delegate: Option<Box<dyn Interactive>>,
|
||||
@@ -69,18 +72,22 @@ impl Interactive for CircleM {
|
||||
match (self.mode, n) {
|
||||
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
|
||||
(0, _) if self.diameter => {
|
||||
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance()
|
||||
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance().deferred()
|
||||
}
|
||||
(0, _) => {
|
||||
let p =
|
||||
Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER).kw(&["Diameter"]).base_opt(self.pts.first().copied()).distance();
|
||||
let p = Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER)
|
||||
.kw(&["Diameter"])
|
||||
.base_opt(self.pts.first().copied())
|
||||
.distance()
|
||||
.deferred();
|
||||
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
|
||||
}
|
||||
(1, k) => Prompt::new(
|
||||
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
|
||||
Accept::POINT,
|
||||
)
|
||||
.base_opt(self.pts.last().copied()),
|
||||
.base_opt(self.pts.last().copied())
|
||||
.deferred(),
|
||||
(2, k) => Prompt::new(
|
||||
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
|
||||
Accept::POINT,
|
||||
@@ -120,7 +127,14 @@ impl Interactive for CircleM {
|
||||
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
|
||||
Some(Circle::new(*c, r))
|
||||
}
|
||||
1 if self.pts.len() == 3 => Circle::from_3_points(self.pts[0], self.pts[1], self.pts[2]),
|
||||
1 if self.pts.len() == 3 => match self.three_points() {
|
||||
Some(c) => Some(c),
|
||||
None => {
|
||||
self.pts.pop();
|
||||
self.tans.truncate(self.pts.len());
|
||||
return Err(crate::EngineError::Other("Circle does not exist.".into()));
|
||||
}
|
||||
},
|
||||
2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])),
|
||||
_ => None,
|
||||
};
|
||||
@@ -130,6 +144,29 @@ impl Interactive for CircleM {
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
// 3P: a point picked with a tangent snap makes the circle tangent to that curve (#1512).
|
||||
Input::Deferred(d) if self.mode == 1 => {
|
||||
let tan = (d.mode == snap::mode::TAN && !matches!(d.curve, snap::SnapCurve::Line { .. })).then_some(d.curve);
|
||||
self.tans.resize(self.pts.len(), None);
|
||||
self.tans.push(tan);
|
||||
self.input(s, Input::Point(d.at))
|
||||
}
|
||||
// A tangent picked for the radius: the circle around the center that touches the
|
||||
// curve, on the side it was picked (#1512).
|
||||
Input::Deferred(d) if self.mode == 0 && self.pts.len() == 1 => {
|
||||
let Some(&c) = self.pts.first() else { return Ok(Step::Continue) };
|
||||
// Around the picked curve's own center the circle would lie on it, not touch it.
|
||||
let concentric =
|
||||
matches!(d.curve, snap::SnapCurve::Circle { center, .. } | snap::SnapCurve::Arc { center, .. } if center.near(c, 1e-9));
|
||||
let touch = d.curve.perpendiculars(c, d.at).into_iter().filter(|_| !concentric).min_by(|a, b| a.dist(d.at).total_cmp(&b.dist(d.at)));
|
||||
match touch.map(|t| c.dist(t)).filter(|r| *r > 1e-12 && r.is_finite()) {
|
||||
Some(r) => {
|
||||
finish_circle(s, Circle::new(c, r))?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
None => Err(crate::EngineError::Other("No circle around the center is tangent there.".into())),
|
||||
}
|
||||
}
|
||||
Input::Text(t) if self.mode == 0 && self.pts.len() == 1 => {
|
||||
let v = number(&t).ok_or_else(|| crate::EngineError::Other("Requires numeric distance or second point.".into()))?;
|
||||
let r = if self.diameter { v / 2.0 } else { v };
|
||||
@@ -174,6 +211,38 @@ impl Interactive for CircleM {
|
||||
}
|
||||
}
|
||||
|
||||
impl CircleM {
|
||||
/// The 3P circle: through the three points, or tangent to the curves picked with TAN.
|
||||
fn three_points(&self) -> Option<Circle> {
|
||||
let [a, b, c] = <[Vec2; 3]>::try_from(self.pts.as_slice()).ok()?;
|
||||
if self.tans.iter().all(Option::is_none) {
|
||||
return Circle::from_3_points(a, b, c);
|
||||
}
|
||||
let tan = |i: usize| self.tans.get(i).copied().flatten();
|
||||
// A plain point is a circle of radius zero to pass through; an arc is solved as its circle.
|
||||
let target = |i: usize, p: Vec2| {
|
||||
let circle = match tan(i) {
|
||||
Some(snap::SnapCurve::Circle { center, radius } | snap::SnapCurve::Arc { center, radius, .. }) => Circle::new(center, radius),
|
||||
_ => Circle::new(p, 0.0),
|
||||
};
|
||||
crate::cmd::curves::TanObj::Circle(circle)
|
||||
};
|
||||
let pts = [a, b, c];
|
||||
// The circle must touch an arc within its sweep, not elsewhere on the arc's circle, and
|
||||
// not be the picked circle itself (which lies on it rather than touching it).
|
||||
let touches = |found: &Circle| {
|
||||
pts.iter().enumerate().all(|(i, p)| {
|
||||
tan(i).is_none_or(|t| {
|
||||
let same = matches!(target(i, *p), crate::cmd::curves::TanObj::Circle(o)
|
||||
if o.center.dist(found.center) + (o.radius - found.radius).abs() <= 1e-9 * o.radius);
|
||||
!same && t.contains(target(i, *p).touch(found))
|
||||
})
|
||||
})
|
||||
};
|
||||
crate::cmd::curves::ttt_where([(target(0, a), a), (target(1, b), b), (target(2, c), c)], touches)
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_circle(s: &mut Session, c: Circle) -> Result<()> {
|
||||
s.add_entity(circle(c.center, c.radius))?;
|
||||
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
//! `grip.*` commands: the undoable, scriptable form of grip editing (see `crate::grips`).
|
||||
|
||||
use cadcraft_doc::{Entity, EntityKind, Handle};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle};
|
||||
use cadcraft_geom::{Mat3, Vec2, Vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::curves;
|
||||
use super::{CommandSpec, bad, bool_or, point_param, point_req, str_param, targets};
|
||||
|
||||
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, stretch_grip};
|
||||
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, shown_grips, stretch_shown};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -46,25 +46,28 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other("The object is on a locked layer.".into()));
|
||||
}
|
||||
let e = curves::entity(s, h)?;
|
||||
let k = stretch_grip(&e.kind, i, to).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
|
||||
let mut edits = vec![(h, k)];
|
||||
let view = s.anno_view();
|
||||
let doc = s.doc()?;
|
||||
let ne = stretch_shown(doc, &e, i, to, view).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
|
||||
let mut edits = vec![(h, ne)];
|
||||
// The other `handles` with a grip on the same point stretch with it (connected objects stay
|
||||
// connected); locked ones and edits that would be degenerate are left alone.
|
||||
let from = e.kind.grips().get(i).copied().unwrap_or(to);
|
||||
let from = shown_grips(doc, &e, view).get(i).copied().unwrap_or(to);
|
||||
let tol = 1e-9 * (1.0 + from.len());
|
||||
for o in targets(s, p)? {
|
||||
if o == h || edits.iter().any(|(x, _)| *x == o) || curves::is_locked(s, o) {
|
||||
continue;
|
||||
}
|
||||
let Ok(oe) = curves::entity(s, o) else { continue };
|
||||
if let Some(j) = oe.kind.grips().iter().position(|g| g.near(from, tol))
|
||||
&& let Some(k) = stretch_grip(&oe.kind, j, to)
|
||||
if let Some(j) = shown_grips(doc, &oe, view).iter().position(|g| g.near(from, tol))
|
||||
&& let Some(ne) = stretch_shown(doc, &oe, j, to, view)
|
||||
{
|
||||
edits.push((o, k));
|
||||
edits.push((o, ne));
|
||||
}
|
||||
}
|
||||
let d = s.doc_mut()?;
|
||||
for (o, k) in &mut edits {
|
||||
for (o, ne) in &mut edits {
|
||||
let (k, moves) = (&mut ne.kind, &ne.common.anno_moves);
|
||||
// A dimension's text moved by its grip: with DIMTMOVE 0 the dimension line follows.
|
||||
if let cadcraft_doc::EntityKind::Dimension(dm) = k
|
||||
&& let Some(cadcraft_doc::EntityKind::Dimension(old)) = d.entity(*o).map(|e| &e.kind)
|
||||
@@ -73,14 +76,17 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
|
||||
let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
|
||||
st.follow_text(dm, d.header.f64("DIMSCALE", 1.0));
|
||||
}
|
||||
d.modify_entity(*o, |e| e.kind = k.clone())?;
|
||||
d.modify_entity(*o, |e| {
|
||||
e.kind = k.clone();
|
||||
e.common.anno_moves = moves.clone();
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// Z coordinate of grip `index` on `kind` (matching `EntityKind::grips()` order), when the
|
||||
/// entity stores a 3D position for that grip.
|
||||
pub(super) fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
|
||||
fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
|
||||
let text_z = |t: &cadcraft_doc::Text| match (t.halign, t.valign) {
|
||||
(cadcraft_doc::HAlign::Left, cadcraft_doc::VAlign::Baseline) | (cadcraft_doc::HAlign::Aligned | cadcraft_doc::HAlign::Fit, _) => t.insert.z,
|
||||
_ => t.align_pt.unwrap_or(t.insert).z,
|
||||
@@ -151,10 +157,17 @@ fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2>
|
||||
.or_else(|| hs.first().copied())
|
||||
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
|
||||
let i = index_param(cmd, p)?;
|
||||
let g = curves::entity(s, h)?.kind.grips();
|
||||
let g = shown_grips(s.doc()?, &curves::entity(s, h)?, s.anno_view());
|
||||
g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))
|
||||
}
|
||||
|
||||
/// The displayed grip's planar point and its Z, when the entity has one.
|
||||
pub(super) fn shown_grip_location(d: &Drawing, e: &Entity, index: usize, view: Option<f64>) -> Option<(Vec2, Option<f64>)> {
|
||||
let kind = d.anno_shown_in(e, view);
|
||||
let point = kind.grips().get(index).copied()?;
|
||||
Some((point, grip_z(&kind, index)))
|
||||
}
|
||||
|
||||
/// 3D base point for SCALE: explicit `base` (with optional Z or ELEVATION), or the selected grip's
|
||||
/// full 3D position so the grip stays stationary in all three coordinates.
|
||||
fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec3> {
|
||||
@@ -169,8 +182,8 @@ fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec
|
||||
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
|
||||
let i = index_param(cmd, p)?;
|
||||
let e = curves::entity(s, h)?;
|
||||
let g = e.kind.grips().get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))?;
|
||||
Ok(match grip_z(&e.kind, i) {
|
||||
let (g, z) = shown_grip_location(s.doc()?, &e, i, s.anno_view()).ok_or_else(|| bad(cmd, "no such grip"))?;
|
||||
Ok(match z {
|
||||
Some(z) => Vec3::new(g.x, g.y, z),
|
||||
None => super::modify::at_elevation(s, g),
|
||||
})
|
||||
@@ -201,7 +214,7 @@ fn run_grip_stretch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => {
|
||||
let base = match point_param(p, "base") {
|
||||
Some(b) => b,
|
||||
None => curves::entity(s, h0)?.kind.grips().get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
|
||||
None => shown_grips(s.doc()?, &curves::entity(s, h0)?, s.anno_view()).get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
|
||||
};
|
||||
point_req(cmd, p, "to")? - base
|
||||
}
|
||||
@@ -245,8 +258,9 @@ const MAX_GRIPS: usize = 1000;
|
||||
/// The objects as they'd be after moving the grips `hot` by `delta`, with the grips of `others`
|
||||
/// that sit on a hot grip's point (connected objects stay connected). Locked objects and edits
|
||||
/// that would be degenerate are left out; several hot grips of one object move together.
|
||||
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, EntityKind)> {
|
||||
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, Entity)> {
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
let view = s.anno_view();
|
||||
// Every grip to move, per object, with its target point.
|
||||
let mut moves: Vec<(Handle, Vec<(usize, Vec2)>)> = Vec::new();
|
||||
let mut add = |h: Handle, i: usize, to: Vec2| match moves.iter_mut().find(|(x, _)| *x == h) {
|
||||
@@ -258,14 +272,14 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
|
||||
None => moves.push((h, vec![(i, to)])),
|
||||
};
|
||||
for &(h, i) in hot.iter().take(MAX_GRIPS) {
|
||||
let Some(from) = d.entity(h).and_then(|e| e.kind.grips().get(i).copied()) else { continue };
|
||||
let Some(from) = d.entity(h).and_then(|e| shown_grips(d, e, view).get(i).copied()) else { continue };
|
||||
add(h, i, from + delta);
|
||||
let tol = 1e-9 * (1.0 + from.len());
|
||||
for &o in others.iter().take(MAX_GRIPS) {
|
||||
if o == h {
|
||||
continue;
|
||||
}
|
||||
if let Some(j) = d.entity(o).and_then(|e| e.kind.grips().iter().position(|g| g.near(from, tol))) {
|
||||
if let Some(j) = d.entity(o).and_then(|e| shown_grips(d, e, view).iter().position(|g| g.near(from, tol))) {
|
||||
add(o, j, from + delta);
|
||||
}
|
||||
}
|
||||
@@ -276,16 +290,16 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
|
||||
continue;
|
||||
}
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let mut k = e.kind.clone();
|
||||
let mut ne = (**e).clone();
|
||||
let mut changed = false;
|
||||
for (i, to) in mv {
|
||||
if let Some(nk) = stretch_grip(&k, i, to) {
|
||||
k = nk;
|
||||
if let Some(n) = stretch_shown(d, &ne, i, to, view) {
|
||||
ne = n;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
out.push((h, k));
|
||||
out.push((h, ne));
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -297,16 +311,19 @@ pub(super) fn stretch_grips(s: &mut Session, hot: &[(Handle, usize)], others: &[
|
||||
let edits = stretched(s, hot, others, delta);
|
||||
let d = s.doc_mut()?;
|
||||
let mut out = Vec::new();
|
||||
for (h, k) in edits {
|
||||
for (h, ne) in edits {
|
||||
if copy {
|
||||
let (Some(sp), Some(e)) = (d.space_of(h), d.entity(h).map(|e| (**e).clone())) else { continue };
|
||||
let Some(sp) = d.space_of(h) else { continue };
|
||||
let nh = d.new_handle();
|
||||
if let Some(st) = d.space_mut(&sp) {
|
||||
st.push(Entity { handle: nh, kind: k, ..e });
|
||||
st.push(Entity { handle: nh, ..ne });
|
||||
out.push(nh);
|
||||
}
|
||||
} else {
|
||||
d.modify_entity(h, |e| e.kind = k)?;
|
||||
d.modify_entity(h, |e| {
|
||||
e.kind = ne.kind;
|
||||
e.common.anno_moves = ne.common.anno_moves;
|
||||
})?;
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,14 +104,16 @@ impl GripEdit {
|
||||
if self.hot.contains(&(h, i)) || self.hot.len() >= MAX_HOT {
|
||||
return Ok(());
|
||||
}
|
||||
let p = s.grips_of(h)?.get(i).copied().ok_or_else(|| other("no such grip"))?;
|
||||
let d = s.doc()?;
|
||||
let e = d.entity(h).ok_or_else(|| other("no such object"))?;
|
||||
let (p, z) = super::gripcmds::shown_grip_location(d, e, i, s.anno_view()).ok_or_else(|| other("no such grip"))?;
|
||||
// After the lookup: a missing object or grip stays the error it was.
|
||||
if !shown(s, h) {
|
||||
return Ok(());
|
||||
}
|
||||
if self.hot.is_empty() {
|
||||
self.base = p;
|
||||
self.base_z = s.doc().ok().and_then(|d| d.entity(h)).and_then(|e| super::gripcmds::grip_z(&e.kind, i));
|
||||
self.base_z = z;
|
||||
self.targets.push(h);
|
||||
self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x)));
|
||||
} else if !self.targets.contains(&h) {
|
||||
@@ -131,7 +133,7 @@ impl GripEdit {
|
||||
continue;
|
||||
}
|
||||
let Some(e) = st.doc.entity(h).filter(|e| st.shows(e)) else { continue };
|
||||
let gs = e.kind.grips();
|
||||
let gs = crate::grips::shown_grips(&st.doc, e, s.anno_view());
|
||||
// The nearest grip of this object within the tolerance.
|
||||
let best = gs
|
||||
.iter()
|
||||
@@ -491,7 +493,11 @@ impl Interactive for GripEdit {
|
||||
};
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
let mut out: Vec<EntityKind> = if self.mode == GripMode::Stretch {
|
||||
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base).into_iter().take(500).map(|(_, k)| k).collect()
|
||||
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base)
|
||||
.into_iter()
|
||||
.take(500)
|
||||
.map(|(_, e)| d.anno_shown_in(&e, s.anno_view()))
|
||||
.collect()
|
||||
} else {
|
||||
match self.matrix(c) {
|
||||
Some(m) => self
|
||||
|
||||
@@ -603,6 +603,64 @@ fn plot_path_extension_picks_the_format_like_export() {
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn osnap_in_mspace_skips_vplayer_frozen_layers() {
|
||||
let mut s = Session::new();
|
||||
s.execute("layer.new", &json!({"name": "Hidden"})).unwrap();
|
||||
s.execute("line", &json!({"points": [[60, -25], [70, -25]]})).unwrap();
|
||||
let line_h = s.doc().unwrap().model.iter().last().unwrap().handle;
|
||||
s.execute("properties.set", &json!({"handles": [line_h], "layer": "Hidden"})).unwrap();
|
||||
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
|
||||
s.execute("mview", &json!({"p1": [20, 20], "p2": [220, 120]})).unwrap();
|
||||
let vp_h = viewports(&s, "Layout1").last().unwrap().0;
|
||||
s.execute("vplayer", &json!({"handles": [vp_h], "freeze": ["Hidden"]})).unwrap();
|
||||
s.execute("mspace", &json!({"handle": vp_h})).unwrap();
|
||||
|
||||
let ap = s.pixel_size() * s.settings.aperture.max(1.0);
|
||||
let d = ap * 0.5;
|
||||
let model_before = s.doc().unwrap().model.len();
|
||||
for (ovr, pt, name) in [
|
||||
("end", format!("{},-25", 60.0 + d), "Endpoint"),
|
||||
("mid", format!("{},-25", 65.0 + d), "Midpoint"),
|
||||
("nea", format!("63,{}", -25.0 + d), "Nearest"),
|
||||
] {
|
||||
s.cmdline("line").unwrap();
|
||||
s.cmdline(ovr).unwrap();
|
||||
s.cmdline(&pt).unwrap();
|
||||
assert_eq!(
|
||||
s.log.last().map(String::as_str),
|
||||
Some(format!("No {name} found for specified point.").as_str()),
|
||||
"{ovr} should not snap to a line on a VPLAYER-frozen layer; log: {:?}",
|
||||
s.log
|
||||
);
|
||||
s.cmdline("").unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().model.len(), model_before, "no new line should be created");
|
||||
|
||||
// Running osnaps through snap_cursor must also ignore the VPLAYER-frozen layer.
|
||||
s.settings.osmode = crate::snap::mode::END | crate::snap::mode::MID | crate::snap::mode::NEA;
|
||||
let cs = s.snap_cursor(
|
||||
cadcraft_geom::Vec2::new(60.0 + d, -25.0),
|
||||
&crate::snap::tracking::CursorQuery { base: None, deferred: false, corner: false, aperture: ap, tol: ap, now: 0.0, shift: false },
|
||||
);
|
||||
assert!(cs.snap.is_none(), "running osnap should not snap to a VPLAYER-frozen line: {:?}", cs.snap);
|
||||
|
||||
// A block reference on layer "0" containing an entity on "Hidden" must also not snap.
|
||||
s.execute("block", &json!({"name": "B", "base": [60, -25], "handles": [line_h]})).unwrap();
|
||||
let model_with_block = s.doc().unwrap().model.len();
|
||||
s.cmdline("line").unwrap();
|
||||
s.cmdline("end").unwrap();
|
||||
s.cmdline(&format!("{},-25", 60.0 + d)).unwrap();
|
||||
assert_eq!(
|
||||
s.log.last().map(String::as_str),
|
||||
Some("No Endpoint found for specified point."),
|
||||
"end should not snap to a block entity on a VPLAYER-frozen layer; log: {:?}",
|
||||
s.log
|
||||
);
|
||||
s.cmdline("").unwrap();
|
||||
assert_eq!(s.doc().unwrap().model.len(), model_with_block);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_set_frames_extents_away_from_origin() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -190,10 +190,11 @@ pub(crate) fn explode_kind(d: &cadcraft_doc::Drawing, e: &Entity) -> Option<Vec<
|
||||
// An annotative object explodes into plain objects as it draws at the current annotation scale.
|
||||
if cadcraft_doc::is_annotative(e) {
|
||||
let mut se = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) => cadcraft_doc::anno_scaled(e, f),
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } => cadcraft_doc::anno_placed(e, factor, by),
|
||||
_ => e.clone(),
|
||||
};
|
||||
se.common.anno_scales.clear();
|
||||
se.common.anno_moves.clear();
|
||||
return explode_kind(d, &se);
|
||||
}
|
||||
match &e.kind {
|
||||
|
||||
@@ -7,7 +7,10 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, er
|
||||
|
||||
pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Vec<Handle>> {
|
||||
refuse_ole_frames(s, hs, m, copy)?;
|
||||
edit_entities(s, hs, copy, |e| e.kind.transform(m))
|
||||
edit_entities(s, hs, copy, |e| {
|
||||
e.kind.transform(m);
|
||||
e.common.transform_moves(m);
|
||||
})
|
||||
}
|
||||
|
||||
/// MIRROR's default hatch policy retains the fill direction while reflecting its boundary.
|
||||
@@ -40,6 +43,7 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64,
|
||||
refuse_ole_frames(s, hs, &m, copy)?;
|
||||
edit_entities(s, hs, copy, |e| {
|
||||
e.kind.transform(&m);
|
||||
e.common.transform_moves(&m);
|
||||
e.kind.scale_heights(base.z, f);
|
||||
e.common.thickness *= f;
|
||||
})
|
||||
|
||||
@@ -202,6 +202,7 @@ fn chspace(s: &mut Session, hs: &[Handle], to: Option<&str>, vp: Option<Handle>)
|
||||
}
|
||||
let mut e = e;
|
||||
e.kind.transform(&m);
|
||||
e.common.transform_moves(&m);
|
||||
d.remove_entity(*h);
|
||||
if let Some(st) = d.space_mut(&target) {
|
||||
st.push(e);
|
||||
|
||||
@@ -70,8 +70,8 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
|
||||
// Annotative text and dimensions are drawn scaled to the current annotation scale: the box
|
||||
// follows what is drawn. Multiline text keeps its stored height (it is written back from it).
|
||||
let scaled = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
|
||||
Some(cadcraft_doc::anno_scaled(e, f))
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
|
||||
Some(cadcraft_doc::anno_placed(e, factor, by))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -237,7 +237,7 @@ impl Interactive for SetvarM {
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &Value::String(t)) {
|
||||
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &crate::sysvars::typed_value(&n, t)) {
|
||||
Ok(()) => {
|
||||
s.touch();
|
||||
Ok(Step::Done)
|
||||
|
||||
@@ -171,6 +171,12 @@ impl DocState {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// The annotation scale model space is edited at in the active MSPACE viewport: the
|
||||
/// viewport's scale (drawing units per paper unit, as the renderer draws it there); `None`
|
||||
/// outside one (the current annotation scale applies).
|
||||
pub fn anno_view(&self) -> Option<f64> {
|
||||
self.active_viewport().map(|(_, v)| v.view_height / v.height).filter(|f| f.is_finite() && *f > 0.0)
|
||||
}
|
||||
/// The layers frozen in the active MSPACE viewport (VPLAYER, "VP Freeze"): that viewport does
|
||||
/// not draw their objects, so picks, selections and grips made through it leave them out.
|
||||
/// Empty in paper space and on the Model tab.
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -185,8 +185,9 @@ pub fn grip_dims(s: &Session) -> Vec<GripDim> {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some((h, i)) = s.current_prompt().and_then(|p| p.grip) else { return Vec::new() };
|
||||
let Some(e) = s.doc().ok().and_then(|d| d.entity(h)) else { return Vec::new() };
|
||||
let all = dims_of(&e.kind, i);
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
let Some(e) = d.entity(h) else { return Vec::new() };
|
||||
let all = dims_of(&d.anno_shown_in(e, s.anno_view()), i);
|
||||
let st = &s.settings;
|
||||
match st.dyndivis {
|
||||
0 => all.into_iter().take(1).collect(),
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! The UI calls [`Session::grip_edit`]; every edit runs through a `grip.*` command so it is
|
||||
//! undoable and reachable from scripts, the control channel and MCP.
|
||||
|
||||
use cadcraft_doc::{DimKind, EntityKind, Handle, LwPolyline};
|
||||
use cadcraft_doc::{DimKind, Drawing, Entity, EntityKind, Handle, LwPolyline};
|
||||
use cadcraft_geom::{Arc, EPS, Mat3, Polyline, Vec2, Vec3, norm_angle};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
@@ -564,10 +564,59 @@ impl Session {
|
||||
|
||||
/// Grip points of an object (the indices `grip_edit` takes).
|
||||
pub fn grips_of(&self, handle: Handle) -> Result<Vec<Vec2>> {
|
||||
self.doc()?.entity(handle).map(|e| e.kind.grips()).ok_or_else(|| EngineError::Other("no such object".into()))
|
||||
let d = self.doc()?;
|
||||
d.entity(handle).map(|e| shown_grips(d, e, self.anno_view())).ok_or_else(|| EngineError::Other("no such object".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The grip points of `e` as it shows (the indices `grip_edit` takes): an annotative object's at
|
||||
/// the annotation scale it shows at and its position there. `view`: the active viewport's scale
|
||||
/// in MSPACE ([`crate::DocState::anno_view`]), else the current annotation scale applies.
|
||||
pub fn shown_grips(d: &Drawing, e: &Entity, view: Option<f64>) -> Vec<Vec2> {
|
||||
d.anno_shown_in(e, view).grips()
|
||||
}
|
||||
|
||||
/// `e` with grip `index` of [`shown_grips`] moved to `to`, or `None` when that grip can't move
|
||||
/// there. An annotative object's position grip moves it at the scale it shows at only when it
|
||||
/// supports several scales; its other grips change its shape at every scale (the edit is taken
|
||||
/// back to paper size).
|
||||
pub fn stretch_shown(d: &Drawing, e: &Entity, index: usize, to: Vec2, view: Option<f64>) -> Option<Entity> {
|
||||
let with = |kind: EntityKind| Some(Entity { kind, ..e.clone() });
|
||||
let (Some(scale), cadcraft_doc::AnnoDraw::Scaled { factor, by }) = (d.anno_shown_scale_in(e, view), d.anno_draw_in(e, view)) else {
|
||||
return with(stretch_grip(&e.kind, index, to)?);
|
||||
};
|
||||
let shown = cadcraft_doc::anno_placed(e, factor, by).kind;
|
||||
let from = *shown.grips().get(index)?;
|
||||
let delta = to - from;
|
||||
if !delta.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if cadcraft_doc::is_position_grip(&e.kind, index) {
|
||||
if e.common.anno_scales.len() > 1 {
|
||||
let mut out = e.clone();
|
||||
out.common.move_at(&scale.name, delta);
|
||||
return Some(out);
|
||||
}
|
||||
let stored = *e.kind.grips().get(index)?;
|
||||
return with(stretch_grip(&e.kind, index, stored + delta)?);
|
||||
}
|
||||
// A shape grip: stretch the object as it shows, then take it back to paper size.
|
||||
let mut k = stretch_grip(&shown, index, to)?;
|
||||
cadcraft_doc::shift_position(&mut k, -by);
|
||||
let k = match (k, &e.kind) {
|
||||
(EntityKind::Dimension(mut dm), EntityKind::Dimension(old)) => {
|
||||
// A dimension's geometry isn't scaled: only its style scale was.
|
||||
dm.overrides = old.overrides.clone();
|
||||
if by != Vec2::ZERO {
|
||||
dm.user_text_pos = old.user_text_pos;
|
||||
}
|
||||
EntityKind::Dimension(dm)
|
||||
}
|
||||
(k, _) => cadcraft_doc::anno_scaled(&Entity { kind: k, ..e.clone() }, 1.0 / factor).kind,
|
||||
};
|
||||
with(k)
|
||||
}
|
||||
|
||||
/// Polyline helper kept public for the UI: segment midpoints are grips too.
|
||||
pub fn polyline_grip_count(p: &LwPolyline) -> usize {
|
||||
p.vertices.len() + Polyline { vertices: p.vertices.clone(), closed: p.closed }.segments().len().min(p.vertices.len())
|
||||
|
||||
@@ -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;
|
||||
@@ -416,6 +418,11 @@ impl Session {
|
||||
Ok(h)
|
||||
}
|
||||
|
||||
/// The annotation scale of the active MSPACE viewport ([`DocState::anno_view`]).
|
||||
pub fn anno_view(&self) -> Option<f64> {
|
||||
self.state().ok().and_then(DocState::anno_view)
|
||||
}
|
||||
|
||||
/// World units per pixel at the current view.
|
||||
pub fn pixel_size(&self) -> f64 {
|
||||
let v = self.state().map(DocState::view).unwrap_or_default();
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -126,14 +126,36 @@ pub fn snap_name(m: u32) -> &'static str {
|
||||
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
|
||||
}
|
||||
|
||||
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
|
||||
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
|
||||
/// first, then deferred snaps, then Nearest), without repeats.
|
||||
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
|
||||
/// first, then every other snap of the modes in `osmode` under the aperture (each endpoint of
|
||||
/// each object, each intersection …; [`crate::snap::osnap_all`]), best first, without repeats.
|
||||
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
|
||||
snap_candidates_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||
}
|
||||
|
||||
/// [`snap_candidates`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn snap_candidates_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> Vec<SnapHit> {
|
||||
// A base that is not a number would give meaningless perpendiculars and tangents.
|
||||
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 || base.is_some_and(|b| !b.is_finite()) {
|
||||
return Vec::new();
|
||||
}
|
||||
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
|
||||
let mut out: Vec<SnapHit> = crate::snap::osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen).into_iter().collect();
|
||||
for h in crate::snap::osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen) {
|
||||
if !out.iter().any(|o| o.same(&h, aperture)) {
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
|
||||
@@ -356,12 +378,15 @@ impl Session {
|
||||
Frame::Snap { mode } => {
|
||||
// Snap the point with this mode alone, within the aperture.
|
||||
let prompt = self.current_prompt();
|
||||
let space = self.space();
|
||||
let (doc, space, frozen) = {
|
||||
let st = self.state()?;
|
||||
(st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec())
|
||||
};
|
||||
let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
|
||||
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
|
||||
let base = prompt.as_ref().and_then(|q| q.base);
|
||||
let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
|
||||
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred);
|
||||
let hit = crate::snap::osnap_with_frozen(&doc, &space, p, aperture, mode | hatch, base, deferred, &frozen);
|
||||
match hit {
|
||||
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
|
||||
Some(h) => {
|
||||
|
||||
@@ -76,8 +76,9 @@ pub struct Prompt {
|
||||
/// Rubber-band origin (for direct distance entry, ortho and polar).
|
||||
pub base: Option<Vec2>,
|
||||
/// The command resolves deferred tangent/perpendicular snaps ([`Input::Deferred`]) at this
|
||||
/// prompt (a point with no base yet, e.g. the first point of a line). Elsewhere a deferred
|
||||
/// pick arrives as the plain point it was picked at.
|
||||
/// prompt (a point with no base yet, e.g. the first point of a line; with a base, only
|
||||
/// tangents, e.g. a circle's radius). Elsewhere a deferred pick arrives as the plain point it
|
||||
/// was picked at.
|
||||
pub deferred: bool,
|
||||
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
|
||||
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
||||
|
||||
@@ -360,15 +360,16 @@ fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> {
|
||||
if !is_blank_mtext(text) {
|
||||
return None;
|
||||
}
|
||||
let f = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Plain => 1.0,
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f,
|
||||
cadcraft_doc::AnnoDraw::Scaled(_) => 1.0,
|
||||
// As it is drawn: at the current scale, where that scale places it.
|
||||
let (f, by) = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Plain => (1.0, Vec2::ZERO),
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } if factor.is_finite() && factor > 0.0 => (factor, by),
|
||||
cadcraft_doc::AnnoDraw::Scaled { .. } => (1.0, Vec2::ZERO),
|
||||
cadcraft_doc::AnnoDraw::Hidden => return None,
|
||||
};
|
||||
let scaled;
|
||||
let e = if f != 1.0 {
|
||||
scaled = cadcraft_doc::anno_scaled(e, f);
|
||||
let e = if f != 1.0 || by != Vec2::ZERO {
|
||||
scaled = cadcraft_doc::anno_placed(e, f, by);
|
||||
&scaled
|
||||
} else {
|
||||
e
|
||||
@@ -497,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
|
||||
}
|
||||
};
|
||||
|
||||
@@ -149,6 +149,9 @@ pub struct Settings {
|
||||
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
|
||||
/// dialog; on by default, as in AutoCAD (Initial value 1).
|
||||
pub attdia: bool,
|
||||
/// TEXTEVAL: 1 lets a routine's input be read as LISP where it would be text (default: 0).
|
||||
/// Kept for routines that switch it around their prompts; no prompt reads it yet.
|
||||
pub texteval: bool,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
@@ -220,6 +223,7 @@ impl Default for Settings {
|
||||
auditctl: false,
|
||||
attreq: true,
|
||||
attdia: true,
|
||||
texteval: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+581
-217
@@ -90,6 +90,24 @@ pub struct BlockLeaf {
|
||||
}
|
||||
|
||||
impl SnapHit {
|
||||
fn plain(mode: u32, point: Vec2) -> SnapHit {
|
||||
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None, source: None }
|
||||
}
|
||||
|
||||
/// The same snap as `o`, for a Tab list without repeats: the same mode at the same point
|
||||
/// (within a millionth of `aperture`), deferred or not alike (and if deferred, on the same
|
||||
/// curve), and from the same source (this space, or one viewport). Overlapping viewports can
|
||||
/// show different model points at one paper point; each stays a candidate, since DIST
|
||||
/// measures in the model units of the viewport picked.
|
||||
pub(crate) fn same(&self, o: &SnapHit, aperture: f64) -> bool {
|
||||
self.mode == o.mode
|
||||
// Deferred snaps on different curves at one provisional point stay apart: the line
|
||||
// drawn from each depends on its curve.
|
||||
&& self.deferred.map(|d| d.curve) == o.deferred.map(|d| d.curve)
|
||||
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
|
||||
&& self.point.near(o.point, aperture * 1e-6)
|
||||
}
|
||||
|
||||
/// The command input a pick at this snap gives: a deferred snap or a plain point.
|
||||
pub fn input(&self) -> crate::Input {
|
||||
match self.deferred {
|
||||
@@ -97,33 +115,6 @@ impl SnapHit {
|
||||
None => crate::Input::Point(self.point),
|
||||
}
|
||||
}
|
||||
|
||||
fn plain(mode: u32, point: Vec2) -> SnapHit {
|
||||
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None, source: None }
|
||||
}
|
||||
|
||||
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
|
||||
/// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest.
|
||||
fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) {
|
||||
let class = if self.deferred.is_some() {
|
||||
1
|
||||
} else if self.mode == mode::NEA {
|
||||
2
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(class, snap_score(self.mode, self.point, cursor, aperture))
|
||||
}
|
||||
|
||||
/// The same snap as `o`: mode and point, from the same source (paper space, or one
|
||||
/// viewport). Overlapping viewports can show different model points at one paper point;
|
||||
/// each stays a candidate, since DIST measures in the model units of the viewport picked.
|
||||
fn same(&self, o: &SnapHit) -> bool {
|
||||
self.mode == o.mode
|
||||
&& self.deferred.is_some() == o.deferred.is_some()
|
||||
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
|
||||
&& self.point.near(o.point, 1e-9 * (1.0 + self.point.len()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The curve a deferred snap refers to.
|
||||
@@ -162,12 +153,16 @@ impl SnapCurve {
|
||||
}
|
||||
/// Points on the curve whose perpendicular passes through `p`; `picked` is where the curve
|
||||
/// was picked, kept when `p` is the center of a circle or arc (every radius is perpendicular).
|
||||
fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
|
||||
pub(crate) fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
|
||||
match self {
|
||||
SnapCurve::Circle { center, radius } | SnapCurve::Arc { center, radius, .. } => {
|
||||
let u = (p - *center).normalized();
|
||||
if u == Vec2::ZERO {
|
||||
vec![Circle::new(*center, *radius).closest(picked)]
|
||||
// On an arc, the point within its sweep.
|
||||
vec![match *self {
|
||||
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(picked),
|
||||
_ => Circle::new(*center, *radius).closest(picked),
|
||||
}]
|
||||
} else {
|
||||
[*center + u * *radius, *center - u * *radius].into_iter().filter(|q| self.contains(*q)).collect()
|
||||
}
|
||||
@@ -254,23 +249,34 @@ fn prim_segments(p: &Prim) -> Vec<Segment> {
|
||||
/// Tangent and perpendicular snaps need the base point (the other end of the line). With no
|
||||
/// base and `deferred` set (the prompt says it can resolve them, `Prompt.deferred`),
|
||||
/// they snap as *deferred*: the hit carries the curve and is resolved once the other end is
|
||||
/// known. Deferred hits only win where no other snap does (they are as unspecific as Nearest).
|
||||
/// known. With a base and `deferred` set, tangents to circles and circular arcs are deferred too
|
||||
/// (CIRCLE's radius: the circle around the base that touches the curve, #1512); an elliptical arc
|
||||
/// or a spline keeps its ordinary tangent from the base. Deferred hits only win
|
||||
/// where no other snap does (they are as unspecific as Nearest).
|
||||
pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Option<SnapHit> {
|
||||
osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||
}
|
||||
|
||||
/// [`osnap`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn osnap_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> Option<SnapHit> {
|
||||
if osmode == 0 || osmode & mode::OFF != 0 {
|
||||
return None;
|
||||
}
|
||||
let ix = crate::spatial::index(d, space);
|
||||
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
|
||||
}
|
||||
|
||||
/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest
|
||||
/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest.
|
||||
/// Snaps seen through layout viewports are included.
|
||||
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0
|
||||
osnap_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred, frozen).0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn osnap_with(
|
||||
d: &Drawing,
|
||||
@@ -282,7 +288,7 @@ pub(crate) fn osnap_with(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> Option<SnapHit> {
|
||||
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred).0
|
||||
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred, &[]).0
|
||||
}
|
||||
|
||||
/// Find the best object snap and retain the local-space primitives gathered for that query.
|
||||
@@ -296,40 +302,21 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
|
||||
let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred);
|
||||
(all.into_iter().next(), prims)
|
||||
}
|
||||
|
||||
/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_all_with_neighborhood(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> (Vec<SnapHit>, Option<Vec<Prim>>) {
|
||||
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
|
||||
return (Vec::new(), None);
|
||||
return (None, None);
|
||||
}
|
||||
let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
||||
Some((hits, prims)) => (hits, Some(prims)),
|
||||
None => (Vec::new(), None),
|
||||
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, None) {
|
||||
Some((hit, prims)) => (hit, Some(prims)),
|
||||
None => (None, None),
|
||||
};
|
||||
let views = viewport::near(d, space, cursor, aperture);
|
||||
if views.is_empty() {
|
||||
return (all, near_prims);
|
||||
return (best.map(|(h, _)| h), near_prims);
|
||||
}
|
||||
let model = Space::Model;
|
||||
let model_ix = crate::spatial::index(d, &model);
|
||||
// What a click picks across spaces stays as it was: each space's best snap, and a viewport's
|
||||
// replaces the best so far only when it scores closer. A paper-space Nearest can therefore
|
||||
// beat an Endpoint seen through a viewport, which `ranked` alone would put first.
|
||||
let mut pick = all.first().copied();
|
||||
for view in views {
|
||||
let model_cursor = view.to_model(cursor);
|
||||
let model_aperture = aperture / view.scale;
|
||||
@@ -337,66 +324,50 @@ fn osnap_all_with_neighborhood(
|
||||
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let hits = osnap_in(
|
||||
d,
|
||||
&model,
|
||||
&model_ix,
|
||||
model_cursor,
|
||||
model_aperture,
|
||||
osmode,
|
||||
model_base,
|
||||
deferred,
|
||||
&view.viewport.frozen_layers,
|
||||
Some(view.model_clip),
|
||||
);
|
||||
if let Some(hit) = hits.first().and_then(|h| view.hit(*h))
|
||||
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
|
||||
let Some((cands, prims, src)) = collect_in(d, &model, &model_ix, model_cursor, model_aperture, osmode, &view.viewport.frozen_layers) else {
|
||||
continue;
|
||||
};
|
||||
let clip = Some(view.model_clip);
|
||||
// The rank was found in model units: paper units are model units times the scale.
|
||||
let project = |(h, r): (SnapHit, Rank)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }));
|
||||
let first = finish(cands.clone(), &prims, &src, model_cursor, model_aperture, osmode, model_base, deferred, clip);
|
||||
// The model clip is the box round the viewport as the model sees it, larger than the
|
||||
// viewport when it is twisted: a snap inside it can still fall off the viewport. Then the
|
||||
// best of the others that is on it, as Tab ranks them.
|
||||
let hit = first.and_then(|f| {
|
||||
project(f).or_else(|| {
|
||||
finish_all(cands, &prims, &src, model_cursor, model_aperture, osmode, model_base, deferred, clip).into_iter().find_map(project)
|
||||
})
|
||||
});
|
||||
if let Some((hit, rank)) = hit
|
||||
&& best.as_ref().is_none_or(|(_, b)| rank.beats(b))
|
||||
{
|
||||
pick = Some(hit);
|
||||
}
|
||||
all.extend(hits.into_iter().filter_map(|h| view.hit(h)));
|
||||
}
|
||||
let mut out = ranked(all, cursor, aperture);
|
||||
if let Some(pick) = pick {
|
||||
out.retain(|h| !h.same(&pick));
|
||||
out.insert(0, pick);
|
||||
}
|
||||
(out, near_prims)
|
||||
}
|
||||
|
||||
/// `hits` best first ([`SnapHit::rank`]), without repeats.
|
||||
fn ranked(mut hits: Vec<SnapHit>, cursor: Vec2, aperture: f64) -> Vec<SnapHit> {
|
||||
hits.sort_by(|a, b| {
|
||||
let (ca, sa) = a.rank(cursor, aperture);
|
||||
let (cb, sb) = b.rank(cursor, aperture);
|
||||
ca.cmp(&cb).then(sa.total_cmp(&sb))
|
||||
});
|
||||
let mut out: Vec<SnapHit> = Vec::with_capacity(hits.len());
|
||||
for h in hits {
|
||||
if !out.iter().any(|o| o.same(&h)) {
|
||||
out.push(h);
|
||||
best = Some((hit, rank));
|
||||
}
|
||||
}
|
||||
out
|
||||
(best.map(|(h, _)| h), near_prims)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_in(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Vec<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
|
||||
/// How a hit ranks against the hits of another space (paper space, another viewport) and, for
|
||||
/// Tab, against the other candidates: first the order [`finish`] tries them in (snap points, then
|
||||
/// a perpendicular or tangent on the object under the cursor or a center found from its curve,
|
||||
/// then deferred snaps, then Nearest), then its score within that tier, in the units of the cursor.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Rank {
|
||||
tier: u8,
|
||||
score: f64,
|
||||
}
|
||||
|
||||
impl Rank {
|
||||
fn cmp(&self, other: &Rank) -> std::cmp::Ordering {
|
||||
self.tier.cmp(&other.tier).then(self.score.total_cmp(&other.score))
|
||||
}
|
||||
|
||||
fn beats(&self, other: &Rank) -> bool {
|
||||
self.cmp(other).is_lt()
|
||||
}
|
||||
}
|
||||
|
||||
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_in_with_prims(
|
||||
d: &Drawing,
|
||||
@@ -409,7 +380,92 @@ fn osnap_in_with_prims(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
|
||||
) -> Option<(Option<(SnapHit, Rank)>, Vec<Prim>)> {
|
||||
let (cands, near_prims, src) = collect_in(d, space, ix, cursor, aperture, osmode, frozen)?;
|
||||
let hit = finish(cands, &near_prims, &src, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hit, near_prims))
|
||||
}
|
||||
|
||||
/// Every snap of `osmode` under the aperture round `cursor`, best first: Tab cycles through
|
||||
/// these. Each mode's points of every object nearby, the intersections, perpendicular and
|
||||
/// tangent points from `base`, the centers found from their curves, the deferred snaps and the
|
||||
/// nearest point of each object, ranked as [`osnap`] ranks them, without repeats and at most
|
||||
/// [`MAX_CYCLE`]; in viewports too, as [`osnap`] snaps.
|
||||
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
|
||||
}
|
||||
|
||||
/// [`osnap_all`] skipping entities (and block leaves) on `frozen` layers in `space`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn osnap_all_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
) -> Vec<SnapHit> {
|
||||
if osmode == 0
|
||||
|| osmode & mode::OFF != 0
|
||||
|| !cursor.is_finite()
|
||||
|| !(aperture.is_finite() && aperture > 0.0)
|
||||
|| base.is_some_and(|b| !b.is_finite())
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let mut out: Vec<(SnapHit, Rank)> = Vec::new();
|
||||
if let Some((cands, prims, src)) = collect_in(d, space, &ix, cursor, aperture, osmode, frozen) {
|
||||
out = finish_all(cands, &prims, &src, cursor, aperture, osmode, base, deferred, None);
|
||||
}
|
||||
let model = Space::Model;
|
||||
let views = viewport::near(d, space, cursor, aperture);
|
||||
if !views.is_empty() {
|
||||
let model_ix = crate::spatial::index(d, &model);
|
||||
for view in views {
|
||||
let (mc, ma, mb) = (view.to_model(cursor), aperture / view.scale, base.map(|p| view.to_model(p)));
|
||||
if !mc.is_finite() || !(ma.is_finite() && ma > 0.0) || mb.is_some_and(|p| !p.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let Some((cands, prims, src)) = collect_in(d, &model, &model_ix, mc, ma, osmode, &view.viewport.frozen_layers) else { continue };
|
||||
// The rank was found in model units: paper units are model units times the scale.
|
||||
out.extend(
|
||||
finish_all(cands, &prims, &src, mc, ma, osmode, mb, deferred, Some(view.model_clip))
|
||||
.into_iter()
|
||||
.filter_map(|(h, r)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }))),
|
||||
);
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.1.cmp(&b.1));
|
||||
let mut unique: Vec<SnapHit> = Vec::with_capacity(out.len().min(MAX_CYCLE));
|
||||
for (h, _) in out {
|
||||
if unique.len() >= MAX_CYCLE {
|
||||
break;
|
||||
}
|
||||
if !unique.iter().any(|u| u.same(&h, aperture)) {
|
||||
unique.push(h);
|
||||
}
|
||||
}
|
||||
unique
|
||||
}
|
||||
|
||||
/// Most snaps [`osnap_all`] offers.
|
||||
const MAX_CYCLE: usize = 256;
|
||||
|
||||
/// The candidate snap points near `cursor` (each with its mode) and the primitives near it:
|
||||
/// [`gather_in`]'s, plus the intersections between those primitives, and what each lies on.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn collect_in(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
frozen: &[String],
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>, Sources)> {
|
||||
let (mut cands, near_prims, mut src) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
|
||||
// Intersections between nearby primitives; Apparent Intersection also where their extensions
|
||||
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
|
||||
@@ -449,8 +505,7 @@ fn osnap_in_with_prims(
|
||||
}
|
||||
}
|
||||
}
|
||||
let hits = finish(cands, &near_prims, src, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hits, near_prims))
|
||||
Some((cands, near_prims, src))
|
||||
}
|
||||
|
||||
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
|
||||
@@ -492,26 +547,26 @@ pub(crate) fn extendable(p: &Prim) -> bool {
|
||||
matches!(p, Prim::Seg(_) | Prim::Circle(_) | Prim::Infinite { .. })
|
||||
}
|
||||
|
||||
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
|
||||
/// when the drawing can't be searched.
|
||||
pub(crate) fn gather(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
|
||||
gather_in(d, space, ix, cursor, aperture, osmode, &[], None).map(|(cands, prims, _)| (cands, prims))
|
||||
}
|
||||
|
||||
/// The entity each gathered candidate and nearby primitive comes from (parallel to them).
|
||||
#[derive(Default)]
|
||||
struct Sources {
|
||||
pub(crate) struct Sources {
|
||||
cands: Vec<Option<SnapSource>>,
|
||||
prims: Vec<Option<SnapSource>>,
|
||||
}
|
||||
|
||||
/// What the nearby primitive `i` lies on.
|
||||
fn prim_source(src: &Sources, i: usize) -> Option<SnapSource> {
|
||||
src.prims.get(i).copied().flatten()
|
||||
}
|
||||
|
||||
/// What each candidate lies on: the `n` gathered candidates' sources, then the object of each
|
||||
/// point found from the base point.
|
||||
fn candidate_sources(n: usize, src: &Sources, from_base: &[FromBase]) -> Vec<Option<SnapSource>> {
|
||||
let mut out: Vec<Option<SnapSource>> = (0..n).map(|i| src.cands.get(i).copied().flatten()).collect();
|
||||
out.extend(from_base.iter().map(|f| prim_source(src, f.prim)));
|
||||
out
|
||||
}
|
||||
|
||||
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
|
||||
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
|
||||
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
|
||||
@@ -562,8 +617,10 @@ pub(crate) fn nearest_with_direction(
|
||||
best.map(|(_, at, dir)| (at, dir))
|
||||
}
|
||||
|
||||
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
|
||||
/// when the drawing can't be searched.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn gather_in(
|
||||
pub(crate) fn gather_in(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
@@ -673,89 +730,225 @@ fn leaf_with_source(be: &Entity, m: &Mat3, z: Option<(f64, f64)>, handle: Handle
|
||||
src.prims.resize(sink.near.len(), from);
|
||||
}
|
||||
|
||||
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
|
||||
/// snaps, the deferred snaps and Nearest.
|
||||
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps, with
|
||||
/// its [`Rank`].
|
||||
///
|
||||
/// In order of preference (the rank's tier):
|
||||
/// 0. the snap point within `aperture` of the cursor that scores best (see [`snap_score`]),
|
||||
/// perpendicular and tangent points from the base point included;
|
||||
/// 1. with a base point, a perpendicular or tangent on an object that passes within `aperture`,
|
||||
/// wherever its point lies (see [`from_base_on_objects`]), or the center of a circle, arc or
|
||||
/// ellipse under the cursor (see [`curve_centers`]): the object nearest the cursor;
|
||||
/// 2. a deferred perpendicular or tangent (no base point yet);
|
||||
/// 3. Nearest.
|
||||
///
|
||||
/// [`finish_all`] keeps every candidate in this order, for Tab.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish(
|
||||
mut cands: Vec<(u32, Vec2)>,
|
||||
near_prims: &[Prim],
|
||||
mut src: Sources,
|
||||
src: &Sources,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
clip: Option<Bounds2>,
|
||||
) -> Vec<SnapHit> {
|
||||
// Perpendicular / tangent from the base point.
|
||||
if let Some(bp) = base {
|
||||
for (p, from) in near_prims.iter().zip(&src.prims) {
|
||||
if osmode & mode::PER != 0 {
|
||||
match p {
|
||||
Prim::Seg(Segment::Line(l)) => cands.push((mode::PER, l.project(bp))),
|
||||
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
|
||||
// not offered, and the far side is still found.
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => {
|
||||
let curve = SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end };
|
||||
cands.extend(curve.perpendiculars(bp, bp).into_iter().map(|q| (mode::PER, q)));
|
||||
}
|
||||
Prim::Circle(c) => cands.push((mode::PER, c.closest(bp))),
|
||||
Prim::Infinite { base: b0, dir, .. } => cands.push((mode::PER, *b0 + *dir * (bp - *b0).dot(*dir))),
|
||||
Prim::Ellipse(e) => cands.extend(curves::ellipse_perpendiculars(e, bp).into_iter().map(|q| (mode::PER, q))),
|
||||
Prim::Spline(s) => cands.extend(curves::spline_perpendiculars(s, bp).into_iter().map(|q| (mode::PER, q))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if osmode & mode::TAN != 0 {
|
||||
let pts = match p {
|
||||
// Only the tangent points that lie on the arc itself (not its circle).
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
|
||||
.tangent_points(bp)
|
||||
.into_iter()
|
||||
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
|
||||
.collect(),
|
||||
Prim::Circle(c) => c.tangent_points(bp),
|
||||
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
|
||||
Prim::Spline(s) => curves::spline_tangents(s, bp),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
cands.extend(pts.into_iter().map(|t| (mode::TAN, t)));
|
||||
}
|
||||
src.cands.resize(cands.len(), *from);
|
||||
}
|
||||
}
|
||||
) -> Option<(SnapHit, Rank)> {
|
||||
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
|
||||
let sources = candidate_sources(cands.len(), src, &from_base);
|
||||
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
|
||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||
let mut hits: Vec<SnapHit> = cands
|
||||
.into_iter()
|
||||
.zip(src.cands.iter().copied().chain(std::iter::repeat(None)))
|
||||
// Prefer more specific modes when nearly equidistant.
|
||||
let best = cands
|
||||
.iter()
|
||||
.zip(&sources)
|
||||
.filter(|((_, p), _)| visible(*p) && p.dist(cursor) <= aperture)
|
||||
.map(|((m, p), from)| SnapHit { source: from, ..SnapHit::plain(m, p) })
|
||||
.collect();
|
||||
if base.is_none() && deferred {
|
||||
hits.extend(deferred_hits(near_prims, &src.prims, cursor, aperture, osmode, clip));
|
||||
.map(|((m, p), from)| (snap_score(*m, *p, cursor, aperture), *m, *p, *from))
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if let Some((score, m, p, from)) = best {
|
||||
return Some((SnapHit { source: from, ..SnapHit::plain(m, p) }, Rank { tier: 0, score }));
|
||||
}
|
||||
// A perpendicular or tangent on the object under the cursor, or the center found from its
|
||||
// curve, only when no snap point is in the aperture: the Midpoint or Quadrant under the cursor
|
||||
// wins over the center of the same curve, as in AutoCAD. Of the two, the object nearer the
|
||||
// cursor; on a tie (the same curve), the perpendicular or tangent.
|
||||
let on_object = from_base_on_objects(&from_base, near_prims, &src.prims, cursor, aperture, visible)
|
||||
.into_iter()
|
||||
.min_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)))
|
||||
.map(|(h, r, _)| (h, r));
|
||||
let center = curve_centers(near_prims, cursor, aperture, osmode)
|
||||
.into_iter()
|
||||
.filter(|(_, c, _)| visible(*c))
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0))
|
||||
.map(|(score, c, i)| (SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::CEN, c) }, Rank { tier: 1, score }));
|
||||
match (on_object, center) {
|
||||
(Some(o), Some(c)) => return Some(if c.1.beats(&o.1) { c } else { o }),
|
||||
(Some(h), None) | (None, Some(h)) => return Some(h),
|
||||
(None, None) => {}
|
||||
}
|
||||
// With a base, perpendiculars are resolved from it above; only tangents are left to defer.
|
||||
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
|
||||
if deferred && let Some(h) = deferred_hit(near_prims, &src.prims, cursor, aperture, deferrable, clip) {
|
||||
let score = h.point.dist(cursor);
|
||||
return Some((h, Rank { tier: 2, score }));
|
||||
}
|
||||
if osmode & mode::NEA != 0 {
|
||||
// The closest point of all nearby objects, whatever their drawing order.
|
||||
let mut nb: Option<(f64, Vec2, Option<SnapSource>)> = None;
|
||||
let mut consider = |c: Vec2, from: Option<SnapSource>| {
|
||||
let dd = c.dist(cursor);
|
||||
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, ..)| dd < bd) {
|
||||
nb = Some((dd, c, from));
|
||||
}
|
||||
};
|
||||
for (p, from) in near_prims.iter().zip(&src.prims) {
|
||||
for s in prim_segments(p) {
|
||||
consider(fix_circle(&s).closest(cursor), *from);
|
||||
}
|
||||
if let Prim::Circle(c) = p {
|
||||
consider(c.closest(cursor), *from);
|
||||
}
|
||||
}
|
||||
if let Some((_, p, source)) = nb {
|
||||
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None, source });
|
||||
let nb = near_prims
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, p)| nearest_point(p, cursor, aperture, &visible).map(|(score, q)| (score, q, i)))
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if let Some((score, p, i)) = nb {
|
||||
return Some((SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::NEA, p) }, Rank { tier: 3, score }));
|
||||
}
|
||||
}
|
||||
ranked(hits, cursor, aperture)
|
||||
None
|
||||
}
|
||||
|
||||
/// [`finish`], keeping every candidate with its [`Rank`], in the order [`finish`] prefers them:
|
||||
/// the snap points best first, then the perpendiculars and tangents on the objects under the
|
||||
/// cursor and the centers found from their curves, then the deferred snaps, then the nearest point
|
||||
/// of each object nearby.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish_all(
|
||||
mut cands: Vec<(u32, Vec2)>,
|
||||
near_prims: &[Prim],
|
||||
src: &Sources,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
clip: Option<Bounds2>,
|
||||
) -> Vec<(SnapHit, Rank)> {
|
||||
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
|
||||
let sources = candidate_sources(cands.len(), src, &from_base);
|
||||
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
|
||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||
let mut out: Vec<(SnapHit, Rank)> = cands
|
||||
.iter()
|
||||
.zip(&sources)
|
||||
.filter(|((_, p), _)| visible(*p) && p.dist(cursor) <= aperture)
|
||||
.map(|((m, p), from)| (SnapHit { source: *from, ..SnapHit::plain(*m, *p) }, Rank { tier: 0, score: snap_score(*m, *p, cursor, aperture) }))
|
||||
.collect();
|
||||
// Of several points on one object (a circle's two tangents), the one nearer the cursor first,
|
||||
// as `finish` picks it; the sort below is stable.
|
||||
let mut on_object = from_base_on_objects(&from_base, near_prims, &src.prims, cursor, aperture, visible);
|
||||
on_object.sort_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)));
|
||||
out.extend(on_object.into_iter().map(|(h, r, _)| (h, r)));
|
||||
out.extend(
|
||||
curve_centers(near_prims, cursor, aperture, osmode)
|
||||
.into_iter()
|
||||
.filter(|(_, c, _)| visible(*c))
|
||||
.map(|(score, c, i)| (SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::CEN, c) }, Rank { tier: 1, score })),
|
||||
);
|
||||
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
|
||||
if deferred {
|
||||
let hits = deferred_hits(near_prims, &src.prims, cursor, aperture, deferrable, clip);
|
||||
out.extend(hits.into_iter().map(|h| (h, Rank { tier: 2, score: h.point.dist(cursor) })));
|
||||
}
|
||||
if osmode & mode::NEA != 0 {
|
||||
let near = near_prims.iter().enumerate().filter_map(|(i, p)| nearest_point(p, cursor, aperture, &visible).map(|(score, q)| (score, q, i)));
|
||||
out.extend(near.map(|(score, p, i)| (SnapHit { source: prim_source(src, i), ..SnapHit::plain(mode::NEA, p) }, Rank { tier: 3, score })));
|
||||
}
|
||||
out.sort_by(|a, b| a.1.cmp(&b.1));
|
||||
out
|
||||
}
|
||||
|
||||
/// The point of `p` closest to `cursor` among its visible points within `aperture`, with its
|
||||
/// distance: each segment's closest point is checked before the closest is chosen, so a curve
|
||||
/// whose closest point is clipped away (outside a viewport) still offers the visible one.
|
||||
fn nearest_point(p: &Prim, cursor: Vec2, aperture: f64, visible: &impl Fn(Vec2) -> bool) -> Option<(f64, Vec2)> {
|
||||
let mut nb: Option<(f64, Vec2)> = None;
|
||||
let mut consider = |c: Vec2| {
|
||||
let dd = c.dist(cursor);
|
||||
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
|
||||
nb = Some((dd, c));
|
||||
}
|
||||
};
|
||||
for s in prim_segments(p) {
|
||||
consider(fix_circle(&s).closest(cursor));
|
||||
}
|
||||
if let Prim::Circle(c) = p {
|
||||
consider(c.closest(cursor));
|
||||
}
|
||||
nb
|
||||
}
|
||||
|
||||
/// The perpendicular and tangent points from the base point `base` (none without one), each
|
||||
/// with the index in `near_prims` of the object it lies on. At a `deferred` prompt the tangents to
|
||||
/// circles and arcs are left out: the prompt resolves them itself (CIRCLE's radius, #1512).
|
||||
fn base_snaps(near_prims: &[Prim], osmode: u32, base: Option<Vec2>, cursor: Vec2, deferred: bool) -> Vec<FromBase> {
|
||||
let mut from_base: Vec<FromBase> = Vec::new();
|
||||
let Some(bp) = base else { return from_base };
|
||||
for (prim, p) in near_prims.iter().enumerate() {
|
||||
let mut found = |mode: u32, points: Vec<Vec2>| from_base.extend(points.into_iter().map(|point| FromBase { mode, point, prim }));
|
||||
if osmode & mode::PER != 0 {
|
||||
let pts = match p {
|
||||
Prim::Seg(Segment::Line(l)) => vec![l.project(bp)],
|
||||
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
|
||||
// not offered, and the far side is still found. From the centre, the point of
|
||||
// the arc under the cursor.
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => {
|
||||
SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end }.perpendiculars(bp, cursor)
|
||||
}
|
||||
// Both antipodes too, so a pick on the far side of the circle snaps there
|
||||
// rather than across it. From the centre every point is perpendicular: the
|
||||
// one under the cursor.
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius }.perpendiculars(bp, cursor),
|
||||
Prim::Infinite { base: b0, dir, .. } => vec![*b0 + *dir * (bp - *b0).dot(*dir)],
|
||||
Prim::Ellipse(e) => curves::ellipse_perpendiculars(e, bp),
|
||||
Prim::Spline(s) => curves::spline_perpendiculars(s, bp),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
found(mode::PER, pts);
|
||||
}
|
||||
if osmode & mode::TAN != 0 {
|
||||
let pts = match p {
|
||||
// A deferred prompt resolves tangents to circles and arcs itself.
|
||||
Prim::Seg(Segment::Arc { .. }) | Prim::Circle(_) if deferred => Vec::new(),
|
||||
// Only the tangent points that lie on the arc itself (not its circle).
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
|
||||
.tangent_points(bp)
|
||||
.into_iter()
|
||||
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
|
||||
.collect(),
|
||||
Prim::Circle(c) => c.tangent_points(bp),
|
||||
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
|
||||
Prim::Spline(s) => curves::spline_tangents(s, bp),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
found(mode::TAN, pts);
|
||||
}
|
||||
}
|
||||
from_base
|
||||
}
|
||||
|
||||
/// Center, as in AutoCAD: with the cursor over a circle, an arc (also a polyline's) or an
|
||||
/// ellipse, the running Center snap finds its center however far away it is. Each center comes
|
||||
/// with how far the curve is from `cursor` (its score); [`finish`] tries them only when no snap
|
||||
/// point is in the aperture. Empty unless Center is among `osmode`.
|
||||
fn curve_centers(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32) -> Vec<(f64, Vec2, usize)> {
|
||||
let mut out = Vec::new();
|
||||
if osmode & mode::CEN == 0 {
|
||||
return out;
|
||||
}
|
||||
// The work limit counts the curves only, so straight segments before them can't hide them.
|
||||
let curves = prims.iter().enumerate().filter_map(|(i, p)| match p {
|
||||
Prim::Circle(c) => Some((c.center, c.closest(cursor), i)),
|
||||
Prim::Seg(s @ Segment::Arc { arc, .. }) => Some((arc.center, fix_circle(s).closest(cursor), i)),
|
||||
Prim::Ellipse(e) => Some((e.center, e.closest(cursor), i)),
|
||||
_ => None,
|
||||
});
|
||||
for (center, on, i) in curves.take(2000) {
|
||||
let d = on.dist(cursor);
|
||||
if center.is_finite() && d.is_finite() && d <= aperture {
|
||||
out.push((d, center, i));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Prefer more specific modes when nearly equidistant.
|
||||
@@ -763,6 +956,63 @@ fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
|
||||
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A perpendicular ([`mode::PER`]) or tangent ([`mode::TAN`]) point found from the base point,
|
||||
/// with the index in `near_prims` of the object it lies on.
|
||||
struct FromBase {
|
||||
mode: u32,
|
||||
point: Vec2,
|
||||
prim: usize,
|
||||
}
|
||||
|
||||
/// The perpendiculars and tangents from the base point on the objects that pass within
|
||||
/// `aperture` of the cursor, wherever the foot or tangent point lies (#2800), each with its
|
||||
/// [`Rank`] (tier 1, scored by the cursor's distance to the object) and its distance to the cursor.
|
||||
///
|
||||
/// These snaps name an object, not a spot on it: you can't know in advance where the foot of a
|
||||
/// perpendicular will be, so, as in AutoCAD, hovering anywhere over the object finds it and the
|
||||
/// point jumps there. [`finish`] asks for this only when no snap point lies within the aperture,
|
||||
/// so an endpoint, midpoint or intersection under the cursor still wins.
|
||||
///
|
||||
/// [`finish`] takes the object nearest the cursor; of several points on it (an arc's two
|
||||
/// antipodes, a circle's two tangents), the one nearest the cursor.
|
||||
fn from_base_on_objects(
|
||||
found: &[FromBase],
|
||||
near_prims: &[Prim],
|
||||
sources: &[Option<SnapSource>],
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
visible: impl Fn(Vec2) -> bool,
|
||||
) -> Vec<(SnapHit, Rank, f64)> {
|
||||
let mut out = Vec::new();
|
||||
if found.is_empty() {
|
||||
return out;
|
||||
}
|
||||
// `near_prims` holds every object whose box comes near the cursor, so the true distance is
|
||||
// checked here. It is measured once per object, and only for objects with a point to offer:
|
||||
// an ellipse or a spline is measured on its tessellation.
|
||||
let mut reach: Vec<Option<f64>> = vec![None; near_prims.len()];
|
||||
for f in found.iter().filter(|f| visible(f.point)) {
|
||||
let Some(slot) = reach.get_mut(f.prim) else { continue };
|
||||
let to_object = *slot.get_or_insert_with(|| near_prims.get(f.prim).map_or(f64::INFINITY, |p| distance_to_prim(p, cursor)));
|
||||
// A NaN distance (from a degenerate object) never qualifies.
|
||||
if to_object.is_nan() || to_object > aperture {
|
||||
continue;
|
||||
}
|
||||
let source = sources.get(f.prim).copied().flatten();
|
||||
out.push((SnapHit { source, ..SnapHit::plain(f.mode, f.point) }, Rank { tier: 1, score: to_object }, f.point.dist(cursor)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The distance from `cursor` to the nearest point of `p`, measured as Nearest measures it.
|
||||
fn distance_to_prim(p: &Prim, cursor: Vec2) -> f64 {
|
||||
// A ray runs one way from its start (an xline both ways, as its segment does).
|
||||
if let Prim::Infinite { base, dir, ray: true } = p {
|
||||
return (*base + *dir * (cursor - *base).dot(*dir).max(0.0)).dist(cursor);
|
||||
}
|
||||
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;
|
||||
|
||||
@@ -1140,11 +1390,15 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
|
||||
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
|
||||
/// perpendicular on the same circle. `sources` is parallel to `prims`.
|
||||
/// Every deferred tangent and perpendicular within `aperture` of `cursor`, for Tab: one per curve
|
||||
/// and mode, in drawing order (the caller ranks them), so Tab can go from the tangent to the
|
||||
/// perpendicular on the same circle, and to the deferred snap of each curve nearby. A click takes
|
||||
/// the nearest one ([`deferred_hit`]).
|
||||
fn deferred_hits(prims: &[Prim], sources: &[Option<SnapSource>], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
|
||||
let mut hits = Vec::new();
|
||||
if osmode & (mode::TAN | mode::PER) == 0 {
|
||||
return hits;
|
||||
}
|
||||
for (i, p) in prims.iter().enumerate() {
|
||||
let curve = match p {
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||
@@ -1178,6 +1432,46 @@ fn deferred_hits(prims: &[Prim], sources: &[Option<SnapSource>], cursor: Vec2, a
|
||||
hits
|
||||
}
|
||||
|
||||
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
|
||||
fn deferred_hit(prims: &[Prim], sources: &[Option<SnapSource>], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
|
||||
let mut best: Option<(f64, SnapHit)> = None;
|
||||
for (i, p) in prims.iter().enumerate() {
|
||||
let curve = match p {
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end },
|
||||
Prim::Seg(Segment::Line(l)) => SnapCurve::Line { a: l.a, b: l.b },
|
||||
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
|
||||
_ => continue,
|
||||
};
|
||||
let (m, name, at) = match curve {
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
|
||||
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
|
||||
let l = cadcraft_geom::Line::new(a, b);
|
||||
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let dd = at.dist(cursor);
|
||||
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
|
||||
let source = sources.get(i).copied().flatten();
|
||||
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }), source }));
|
||||
}
|
||||
}
|
||||
best.map(|(_, h)| h)
|
||||
}
|
||||
|
||||
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
|
||||
/// endpoints (in the order given), or `None` when there is no such line (a point inside the
|
||||
/// circle it should be tangent to, concentric circles, non-parallel lines both perpendicular to
|
||||
@@ -1449,7 +1743,7 @@ mod tests {
|
||||
let frozen = ["vp".to_string()];
|
||||
let end = |x: f64, y: f64| {
|
||||
let at = Vec2::new(x, y);
|
||||
osnap_in(&d, &Space::Model, &None, at + Vec2::new(0.02, -0.01), 0.5, mode::END, None, false, &frozen, None)
|
||||
osnap_all_with_frozen(&d, &Space::Model, at + Vec2::new(0.02, -0.01), 0.5, mode::END, None, false, &frozen)
|
||||
.into_iter()
|
||||
.any(|h| h.point.dist(at) < 1e-9)
|
||||
};
|
||||
@@ -1632,21 +1926,22 @@ mod tests {
|
||||
assert_eq!(h.name, "Intersection");
|
||||
}
|
||||
|
||||
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection
|
||||
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap`
|
||||
/// picks.
|
||||
/// Tab cycling sees every snap within the aperture: snap points nearest first (Intersection
|
||||
/// favoured), then Nearest on each object, and no snap twice; the first is what `osnap` picks.
|
||||
/// On a circle with no base point, its quadrant, then the deferred tangent and the deferred
|
||||
/// perpendicular at the same spot.
|
||||
#[test]
|
||||
fn osnap_all_ranks_every_candidate() {
|
||||
let d = drawing();
|
||||
let modes = mode::END | mode::MID | mode::INT | mode::NEA;
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false);
|
||||
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}");
|
||||
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point);
|
||||
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot.
|
||||
let (cursor, modes) = (Vec2::new(5.2, 0.2), mode::END | mode::MID | mode::INT | mode::NEA);
|
||||
let all = osnap_all(&d, &Space::Model, cursor, 0.5, modes, None, false);
|
||||
// Both lines' midpoints are the intersection point: one Midpoint. Each line has its Nearest.
|
||||
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA, mode::NEA], "{all:?}");
|
||||
assert_eq!(all.first().map(|h| h.point), osnap(&d, &Space::Model, cursor, 0.5, modes, None, false).map(|h| h.point));
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
|
||||
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
|
||||
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
|
||||
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, modes, None, false).is_empty());
|
||||
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, mode::QUA | mode::TAN | mode::PER, None, true).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1665,6 +1960,70 @@ mod tests {
|
||||
assert!(h.point.near(Vec2::new(3.0, 0.0), 1e-9));
|
||||
}
|
||||
|
||||
/// #2800: hovering anywhere over the line finds the perpendicular, though its foot (2,0) is
|
||||
/// six units from the cursor; it used to snap only within the aperture of the foot.
|
||||
#[test]
|
||||
fn perpendicular_from_base_anywhere_on_the_line() {
|
||||
let d = drawing();
|
||||
let h = osnap(&d, &Space::Model, Vec2::new(8.0, 0.1), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(2.0, 0.0), 1e-9), "{h:?}");
|
||||
assert_eq!(h.mode, mode::PER);
|
||||
}
|
||||
|
||||
/// #2800: the tangent point is found from anywhere on the circle; of its two tangent points
|
||||
/// from the base, the one nearer the cursor.
|
||||
#[test]
|
||||
fn tangent_from_base_anywhere_on_the_circle() {
|
||||
let d = drawing();
|
||||
// From (30,0), 10 from the centre (20,0) of the radius-2 circle: the tangent points are
|
||||
// at cos = 2/10 from the line to the base, (20.4, ±1.9596).
|
||||
let upper = Vec2::new(20.4, 2.0 * (1.0f64 - 0.04).sqrt());
|
||||
let on_circle = Vec2::new(20.0 - 2.0 * std::f64::consts::FRAC_1_SQRT_2, 2.0 * std::f64::consts::FRAC_1_SQRT_2);
|
||||
let h = osnap(&d, &Space::Model, on_circle, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
|
||||
assert!(h.point.near(upper, 1e-9), "{h:?}");
|
||||
let mirrored = Vec2::new(on_circle.x, -on_circle.y);
|
||||
let h = osnap(&d, &Space::Model, mirrored, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(upper.x, -upper.y), 1e-9), "{h:?}");
|
||||
}
|
||||
|
||||
/// A circle offers both perpendicular points from the base, so a pick on its far side snaps
|
||||
/// there, not to the near side across the circle (CodeRabbit on #2825).
|
||||
#[test]
|
||||
fn perpendicular_from_base_on_a_circle_takes_the_side_under_the_cursor() {
|
||||
let d = drawing();
|
||||
// The circle at (20,0), radius 2, seen from (30,0): perpendicular at (22,0) and (18,0).
|
||||
let base = Some(Vec2::new(30.0, 0.0));
|
||||
let far = osnap(&d, &Space::Model, Vec2::new(18.1, 0.1), 0.5, mode::PER, base, false).unwrap();
|
||||
assert!(far.point.near(Vec2::new(18.0, 0.0), 1e-9), "{far:?}");
|
||||
// Away from both points, at (19, √3) on the circle: 2 from (18,0) and √12 from (22,0).
|
||||
let top = osnap(&d, &Space::Model, Vec2::new(19.0, 3.0f64.sqrt()), 0.5, mode::PER, base, false).unwrap();
|
||||
assert!(top.point.near(Vec2::new(18.0, 0.0), 1e-9), "{top:?}");
|
||||
let near = osnap(&d, &Space::Model, Vec2::new(21.9, 0.1), 0.5, mode::PER, base, false).unwrap();
|
||||
assert!(near.point.near(Vec2::new(22.0, 0.0), 1e-9), "{near:?}");
|
||||
}
|
||||
|
||||
/// With several objects under the aperture, the one nearest the cursor gives the
|
||||
/// perpendicular, even when another object's foot is nearer.
|
||||
#[test]
|
||||
fn perpendicular_from_base_takes_the_object_nearest_the_cursor() {
|
||||
let d = drawing();
|
||||
// 0.4 above the horizontal line and 0.2 right of the vertical one: the vertical line wins,
|
||||
// with its foot (5,4) farther from the cursor than the horizontal line's (2,0).
|
||||
let h = osnap(&d, &Space::Model, Vec2::new(5.2, 0.4), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(5.0, 4.0), 1e-9), "{h:?}");
|
||||
}
|
||||
|
||||
/// A snap point under the cursor still beats a perpendicular whose foot is away from it, and
|
||||
/// an object outside the aperture gives none, though its box is near.
|
||||
#[test]
|
||||
fn perpendicular_from_base_yields_to_points_under_the_cursor() {
|
||||
let d = drawing();
|
||||
let base = Some(Vec2::new(2.0, 4.0));
|
||||
let h = osnap(&d, &Space::Model, Vec2::new(9.9, 0.05), 0.5, mode::END | mode::PER, base, false).unwrap();
|
||||
assert_eq!((h.point, h.mode), (Vec2::new(10.0, 0.0), mode::END));
|
||||
assert!(osnap(&d, &Space::Model, Vec2::new(8.0, 0.7), 0.5, mode::PER, base, false).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ortho_and_polar() {
|
||||
assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0));
|
||||
@@ -1707,9 +2066,14 @@ mod tests {
|
||||
let df = h.deferred.unwrap();
|
||||
assert_eq!(df.curve, SnapCurve::Circle { center: Vec2::new(20.0, 0.0), radius: 2.0 });
|
||||
assert_eq!(h.input(), crate::Input::Deferred(df));
|
||||
// With a base it is an ordinary tangent.
|
||||
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
|
||||
// With a base it is an ordinary tangent, unless the prompt resolves it (CIRCLE's radius).
|
||||
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), false).unwrap();
|
||||
assert!(t.deferred.is_none() && t.name == "Tangent");
|
||||
let t = osnap(&d, &Space::Model, at, 0.5, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
|
||||
assert_eq!(t.name, "Deferred Tangent");
|
||||
// A perpendicular from the base is still resolved from it.
|
||||
let p = osnap(&d, &Space::Model, Vec2::new(2.0, 0.2), 0.5, mode::PER, Some(Vec2::new(2.0, 5.0)), true).unwrap();
|
||||
assert!(p.deferred.is_none() && p.point.near(Vec2::new(2.0, 0.0), 1e-9));
|
||||
// A specific snap still wins over a deferred one.
|
||||
let q = osnap(&d, &Space::Model, at, 0.5, mode::TAN | mode::QUA, None, true).unwrap();
|
||||
assert_eq!(q.mode, mode::QUA);
|
||||
|
||||
@@ -482,13 +482,38 @@ impl Tracker {
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
) -> Option<Track> {
|
||||
let t = self.find(d, space, cursor, aperture, tol, cfg, base);
|
||||
self.track_with_frozen(d, space, cursor, aperture, tol, cfg, base, &[])
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn track_with_frozen(
|
||||
&mut self,
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
tol: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
frozen: &[String],
|
||||
) -> Option<Track> {
|
||||
let t = self.find(d, space, cursor, aperture, tol, cfg, base, frozen);
|
||||
self.last = t.clone();
|
||||
t
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn find(&self, d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, tol: f64, cfg: &TrackConfig, base: Option<Vec2>) -> Option<Track> {
|
||||
fn find(
|
||||
&self,
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
tol: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
frozen: &[String],
|
||||
) -> Option<Track> {
|
||||
if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) {
|
||||
return None;
|
||||
}
|
||||
@@ -538,7 +563,7 @@ impl Tracker {
|
||||
// 2. A path crossing an object.
|
||||
if cfg.running(mode::INT | mode::APP) {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
|
||||
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p, _)| p).unwrap_or_default();
|
||||
for prim in prims.iter().take(200) {
|
||||
let extend = cfg.running(mode::APP) && super::extendable(prim);
|
||||
for seg in super::prim_segments(prim) {
|
||||
@@ -588,12 +613,26 @@ pub fn candidate(
|
||||
aperture: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
) -> Option<Acquired> {
|
||||
candidate_with_frozen(d, space, cursor, hit, aperture, cfg, base, &[])
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn candidate_with_frozen(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
cursor: Vec2,
|
||||
hit: Option<&SnapHit>,
|
||||
aperture: f64,
|
||||
cfg: &TrackConfig,
|
||||
base: Option<Vec2>,
|
||||
frozen: &[String],
|
||||
) -> Option<Acquired> {
|
||||
if !can_acquire(cursor, aperture, cfg) {
|
||||
return None;
|
||||
}
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
|
||||
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p, _)| p).unwrap_or_default();
|
||||
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
|
||||
}
|
||||
|
||||
@@ -789,7 +828,7 @@ impl crate::Session {
|
||||
s.orthomode ^= q.shift;
|
||||
let angbase = self.angle_settings().angbase;
|
||||
let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } };
|
||||
let (doc, space) = (st.doc.clone(), st.edit_space());
|
||||
let (doc, space, frozen) = (st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec());
|
||||
if !raw.is_finite() {
|
||||
return CursorSnap { point: raw, ..Default::default() };
|
||||
}
|
||||
@@ -798,10 +837,10 @@ impl crate::Session {
|
||||
let cfg = TrackConfig::relative_to(&s, angbase, last);
|
||||
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
|
||||
let ix = crate::spatial::index(&doc, &space);
|
||||
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred);
|
||||
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred, &frozen);
|
||||
let cand = match (osmode & mode::HATCH, near_prims.as_deref()) {
|
||||
(0, Some(prims)) => candidate_with_prims(raw, hit.as_ref(), q.aperture, &cfg, q.base, prims),
|
||||
_ => candidate(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base),
|
||||
_ => candidate_with_frozen(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base, &frozen),
|
||||
};
|
||||
let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift);
|
||||
if let Some(h) = hit {
|
||||
@@ -816,7 +855,7 @@ impl crate::Session {
|
||||
let (origin, angle) = super::grid_frame_in(&doc, &space);
|
||||
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
|
||||
}
|
||||
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) {
|
||||
if let Some(mut t) = self.tracking.track_with_frozen(&doc, &space, p, q.aperture, q.tol, &cfg, q.base, &frozen) {
|
||||
// PolarSnap (SNAPTYPE 1): steps of POLARDIST, or of the snap X spacing when it is 0.
|
||||
let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
|
||||
if s.snapmode
|
||||
|
||||
@@ -7,7 +7,14 @@ use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_
|
||||
|
||||
mod table;
|
||||
|
||||
/// ACADVER: the program's release, as a text AutoCAD documents it and `atof` reads back as a
|
||||
/// number. A drawing's `$ACADVER` header is its file version, which is what a save writes, so the
|
||||
/// two are separate values: `get` gives this text, `list` too, and the header stays as read.
|
||||
pub const ACADVER_TEXT: &str = "24.3s (CADCraft)";
|
||||
|
||||
const SESSION_VARS: &[&str] = &[
|
||||
// The release text, with or without a drawing (the header's `$ACADVER` is the file version).
|
||||
"ACADVER",
|
||||
"AUDITCTL",
|
||||
"ATTREQ",
|
||||
"OSMODE",
|
||||
@@ -81,10 +88,54 @@ const SESSION_VARS: &[&str] = &[
|
||||
"SAVETIME",
|
||||
"SAVEFILEPATH",
|
||||
"ISAVEBAK",
|
||||
"DIMASO",
|
||||
"TEXTEVAL",
|
||||
"POPUPS",
|
||||
];
|
||||
|
||||
pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
/// The DIMASSOC mode DIMASO turned off, kept in the drawing's header so undo restores it.
|
||||
/// `CADCRAFT_` names are not listed by SYSVARS and no file writes this one.
|
||||
const DIMASO_MODE: &str = "CADCRAFT_DIMASO_MODE";
|
||||
|
||||
/// The header key above, under any number of `$`: no variable of that name exists.
|
||||
fn is_internal(n: &str) -> bool {
|
||||
n.trim_start_matches('$') == DIMASO_MODE
|
||||
}
|
||||
|
||||
/// The names this session also answers with DXF's `$` in front: the header writes them that way
|
||||
/// (`$DIMASO`, `$TEXTEVAL`, `$REGENMODE`, `$POPUPS`), so a routine may type either form.
|
||||
const DOLLAR_VARS: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"];
|
||||
|
||||
/// [`set`] takes only a number for these: a program's or a routine's text is refused. A value
|
||||
/// typed at the command line arrives as text and goes through [`typed_value`] first.
|
||||
const NUMBER_ONLY: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE"];
|
||||
|
||||
/// The value of `text` typed at a SETVAR prompt for `name`: typed digits are a number for the
|
||||
/// [`NUMBER_ONLY`] variables. Anything else stays text.
|
||||
pub(crate) fn typed_value(name: &str, text: String) -> Value {
|
||||
if NUMBER_ONLY.contains(&bare_name(name).as_str())
|
||||
&& let Ok(number) = text.trim().parse::<i64>()
|
||||
{
|
||||
return json!(number);
|
||||
}
|
||||
Value::String(text)
|
||||
}
|
||||
|
||||
/// `name` trimmed and upper case, without the `$` those names take. Every other name keeps the
|
||||
/// `$` it was typed with: `$ANGBASE` stays a name of its own (LISP converts radians only for the
|
||||
/// plain name) and `$OSMODE` is not the session's OSMODE.
|
||||
fn bare_name(name: &str) -> String {
|
||||
let n = name.trim().to_ascii_uppercase();
|
||||
// Every leading `$`, as the header drops them all when it stores a value.
|
||||
let rest = n.trim_start_matches('$');
|
||||
if rest.len() < n.len() && DOLLAR_VARS.contains(&rest) { rest.to_string() } else { n }
|
||||
}
|
||||
|
||||
pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
let n = bare_name(name);
|
||||
if is_internal(&n) {
|
||||
return None;
|
||||
}
|
||||
let st = &s.settings;
|
||||
let v = match n.as_str() {
|
||||
"OSMODE" => json!(st.osmode),
|
||||
@@ -177,6 +228,12 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
"SAVETIME" => json!(crate::autosave::savetime()),
|
||||
"SAVEFILEPATH" => json!(crate::autosave::savefilepath()),
|
||||
"ISAVEBAK" => json!(i32::from(crate::autosave::isavebak())),
|
||||
// DIMASO is obsolete in AutoCAD and has no value of its own: it reports DIMASSOC.
|
||||
"DIMASO" => json!(i32::from(matches!(dimassoc(s)?, 1 | 2))),
|
||||
// Whether a prompt reads typed text as LISP (routines switch it around their prompts).
|
||||
"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()),
|
||||
"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)),
|
||||
@@ -189,6 +246,9 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
"DWGTITLED" => json!(s.state().map(|d| i32::from(d.path.is_some())).unwrap_or(0)),
|
||||
"CMDACTIVE" => json!(i32::from(s.running.is_some())),
|
||||
"TILEMODE" => json!(i32::from(s.state().is_ok_and(|d| d.space.layout().is_none()))),
|
||||
// The release number as AutoCAD reports it, so `(atof (getvar "ACADVER"))` is 24.3; the
|
||||
// drawing's own `$ACADVER` (its file version) is left alone for the save version.
|
||||
"ACADVER" => json!(ACADVER_TEXT),
|
||||
"PLATFORM" => json!(std::env::consts::OS),
|
||||
"BLOCKEDITOR" => json!(i32::from(s.state().is_ok_and(|d| d.block_edit.is_some()))),
|
||||
// The template NEW/QNEW start from (a profile setting, like FONTALT; "" = none).
|
||||
@@ -257,6 +317,11 @@ fn dwg_prefix(path: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// DIMASSOC's value (0 off, 1 or 2 associative), read where DIMASO reports it from.
|
||||
fn dimassoc(s: &Session) -> Option<i64> {
|
||||
table::get(s, "DIMASSOC")?.as_i64()
|
||||
}
|
||||
|
||||
fn as_bool(v: &Value) -> Option<bool> {
|
||||
v.as_bool().or_else(|| v.as_i64().map(|i| i != 0)).or_else(|| v.as_str().and_then(|s| s.trim().parse::<i64>().ok()).map(|i| i != 0))
|
||||
}
|
||||
@@ -277,6 +342,7 @@ fn as_pt(v: &Value) -> Option<cadcraft_geom::Vec2> {
|
||||
|
||||
/// Variables `get` reports from session or drawing state that `set` can't change.
|
||||
const READ_ONLY: &[&str] = &[
|
||||
"ACADVER",
|
||||
"CMDNAMES",
|
||||
"DWGNAME",
|
||||
"DWGPREFIX",
|
||||
@@ -304,10 +370,15 @@ const READ_ONLY: &[&str] = &[
|
||||
"UCSXDIR",
|
||||
"UCSYDIR",
|
||||
"WORLDUCS",
|
||||
// Dialogs: a session always has them, so the variable is fixed (not saved).
|
||||
"POPUPS",
|
||||
];
|
||||
|
||||
pub fn is_read_only(name: &str) -> bool {
|
||||
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(name.trim())) || table::is_read_only(&name.trim().to_ascii_uppercase())
|
||||
// A header name's `$` is ignored: the header drops it when it stores a value, so `$ACADVER`
|
||||
// would otherwise change ACADVER, and with it the version a save writes.
|
||||
let n = name.trim().trim_start_matches('$').trim();
|
||||
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(n)) || table::is_read_only(&n.to_ascii_uppercase())
|
||||
}
|
||||
|
||||
/// POLARADDANG as typed: up to ten angles in degrees separated by `;` (radians out); `None` when
|
||||
@@ -325,11 +396,17 @@ pub fn format_angle_list(angles: &[f64]) -> String {
|
||||
|
||||
/// Set a system variable, refusing values out of its range and folders the automation roots can't hold.
|
||||
pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
|
||||
let n = name.trim().to_ascii_uppercase();
|
||||
let n = bare_name(name);
|
||||
if is_internal(&n) {
|
||||
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("unknown variable `{n}`") });
|
||||
}
|
||||
if is_read_only(&n) {
|
||||
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("{n} is read-only") });
|
||||
}
|
||||
let bad = || EngineError::BadParams { cmd: "setvar".into(), msg: format!("invalid value for {n}") };
|
||||
if NUMBER_ONLY.contains(&n.as_str()) && !v.is_number() {
|
||||
return Err(bad());
|
||||
}
|
||||
let st = &mut s.settings;
|
||||
match n.as_str() {
|
||||
"OSMODE" => {
|
||||
@@ -436,6 +513,35 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
|
||||
}
|
||||
"SAVEFILEPATH" => crate::autosave::set_savefilepath(v.as_str().ok_or_else(bad)?),
|
||||
"ISAVEBAK" => crate::autosave::set_isavebak(as_bool(v).ok_or_else(bad)?),
|
||||
// DIMASO has no value of its own: 0 turns DIMASSOC off (remembering the mode it had),
|
||||
// 1 restores that mode (2 when none was seen), and 1 while it is on changes nothing. The
|
||||
// mode it remembers is in the drawing's header ([`DIMASO_MODE`]), so each open drawing
|
||||
// keeps its own and undo restores it with DIMASSOC; no file writes it.
|
||||
"DIMASO" => {
|
||||
let on = as_i(v).filter(|i| matches!(i, 0 | 1)).ok_or_else(bad)? == 1;
|
||||
let mode = dimassoc(s).ok_or_else(bad)?;
|
||||
// The drawing is touched only when DIMASSOC changes, so it is not marked modified
|
||||
// and no undo step is left for a value it already has.
|
||||
match (on, mode) {
|
||||
(true, 1 | 2) | (false, 0) => {}
|
||||
// Turned back on, from off or from a file's unknown mode: the mode it had.
|
||||
(true, _) => {
|
||||
let h = &mut s.doc_mut()?.header;
|
||||
// Only a mode DIMASSOC takes: a file's value of anything else restores 2.
|
||||
let restore = h.i64(DIMASO_MODE, 2);
|
||||
h.set_i64("DIMASSOC", if matches!(restore, 1 | 2) { restore } else { 2 });
|
||||
}
|
||||
(false, _) => {
|
||||
let h = &mut s.doc_mut()?.header;
|
||||
if matches!(mode, 1 | 2) {
|
||||
h.set_i64(DIMASO_MODE, mode);
|
||||
}
|
||||
h.set_i64("DIMASSOC", 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Stored for routines that switch it around their prompts; no prompt reads it yet.
|
||||
"TEXTEVAL" => st.texteval = small(v, 1).ok_or_else(bad)? == 1,
|
||||
// A number is in degrees; text is an angle typed in AUNITS (SETVAR at the command line).
|
||||
"ANGBASE" => {
|
||||
let a = match v {
|
||||
|
||||
@@ -73,6 +73,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
|
||||
("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)),
|
||||
("POLYSIDES", Kind::Int(3, 1024), Def::Int(4)),
|
||||
("PROJMODE", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
|
||||
// 1 regenerates the drawing after a command that changes it (stored, nothing reads it yet).
|
||||
("REGENMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
|
||||
("REVCLOUDARCLEN", Kind::Real { min: 0.0, strict: true }, Def::Units(0.5, 15.0)),
|
||||
("SPLINESEGS", Kind::Int(-32768, 32767), Def::Int(8)),
|
||||
("SPLKNOTS", Kind::Choice(&[0, 1, 2]), Def::Int(0)),
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! ACADVER is the program's release as text, as AutoCAD documents it, so `(atof (getvar
|
||||
//! "ACADVER"))` reads a number from it. It is read-only, and the drawing's `$ACADVER` stays the
|
||||
//! file version a save writes, so a drawing read from a 2000 DXF saves as one.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::lisp::value::Value;
|
||||
use serde_json::json;
|
||||
|
||||
/// The release text `getvar` and `(getvar "ACADVER")` report.
|
||||
const RELEASE: &str = "24.3s (CADCraft)";
|
||||
|
||||
/// A 2000 DXF (`$ACADVER` `AC1015`) holding one line.
|
||||
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nENTITIES\n\
|
||||
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n10.0\n21\n0.0\n31\n0.0\n\
|
||||
0\nENDSEC\n0\nEOF\n";
|
||||
|
||||
/// A LISP expression's value, or its error message.
|
||||
fn lisp(s: &mut Session, code: &str) -> Result<Value, String> {
|
||||
match s.lisp_eval(code, false, true, Vec::new()) {
|
||||
Ok(Some(Ok(v))) => Ok(v),
|
||||
Ok(Some(Err(e))) => Err(e),
|
||||
Ok(None) => Err("did not finish".into()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// GETVAR's value.
|
||||
fn getvar(s: &mut Session, name: &str) -> serde_json::Value {
|
||||
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
|
||||
}
|
||||
|
||||
/// The `$ACADVER` a DXF text declares.
|
||||
fn file_version(text: &str) -> Option<String> {
|
||||
let l: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = l.windows(2).position(|w| w == ["9", "$ACADVER"])?;
|
||||
l.get(at + 2).filter(|c| **c == "1").and_then(|_| l.get(at + 3)).map(|v| (*v).to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn getvar_gives_the_release_text_and_atof_reads_the_number() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||
assert_eq!(getvar(&mut s, "acadver"), json!(RELEASE), "lower-case names work");
|
||||
assert!(matches!(lisp(&mut s, "(getvar \"ACADVER\")"), Ok(Value::Str(t)) if &*t == RELEASE), "a LISP string");
|
||||
assert!(matches!(lisp(&mut s, "(atof (getvar \"ACADVER\"))"), Ok(Value::Real(r)) if (r - 24.3).abs() < 1e-9), "(atof) reads the release number");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setvar_refuses_acadver_and_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
let before = s.state().unwrap().doc.header.str("ACADVER", "");
|
||||
let e = s.execute("setvar", &json!({ "name": "ACADVER", "value": "AC1027" })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "{e}");
|
||||
assert!(lisp(&mut s, "(setvar \"ACADVER\" \"AC1027\")").is_err(), "AutoLISP's setvar too");
|
||||
// Typed at the command line, SETVAR reports the variable as read-only at its name prompt.
|
||||
s.cmdline("setvar acadver").unwrap();
|
||||
assert!(s.log.iter().any(|l| l == &format!("ACADVER = {RELEASE} (read only)")), "{:?}", s.log);
|
||||
// Neither the release text nor the drawing's file version moved.
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), before);
|
||||
assert_eq!(before, "AC1032");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2000_drawing_saves_as_2000() {
|
||||
crate::refedit_xref::hooks();
|
||||
let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("acadver-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("r2000.dxf");
|
||||
let name = path.to_string_lossy().into_owned();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "r2000.dxf", Some(name.clone()));
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015", "read as 2000");
|
||||
assert_eq!(cadcraft_io::save_version(&s.state().unwrap().doc), cadcraft_io::Version::R2000);
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE), "still the release text");
|
||||
|
||||
s.execute("qsave", &json!({})).unwrap();
|
||||
let saved = std::fs::read_to_string(&path).unwrap();
|
||||
assert_eq!(file_version(&saved).as_deref(), Some("AC1015"), "the file keeps its 2000 version");
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015");
|
||||
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
|
||||
assert_eq!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.str("ACADVER", ""), "AC1015", "and reopens as 2000");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dollar_name_cannot_change_the_file_version() {
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("setvar", &json!({ "name": "$ACADVER", "value": "AC1027" })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "{e}");
|
||||
assert!(lisp(&mut s, "(setvar \"$ACADVER\" \"AC1015\")").is_err(), "AutoLISP's setvar too");
|
||||
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1032", "the save version did not move");
|
||||
assert!(cadcraft_engine::sysvars::is_read_only("$acadver"), "SETVAR's prompt sees it as read-only too");
|
||||
// Other `$` names still reach the header as before, in LISP's units.
|
||||
assert!(lisp(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
|
||||
assert!(matches!(lisp(&mut s, "(getvar \"$ANGBASE\")"), Ok(Value::Real(r)) if (r - std::f64::consts::FRAC_PI_2).abs() < 1e-9));
|
||||
let r = s.execute("setvar", &json!({ "name": "$OSMODE", "value": 9 })).unwrap();
|
||||
assert_eq!(r["value"], json!(9), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listings_show_the_release_text_without_a_drawing() {
|
||||
let mut s = Session::empty();
|
||||
let all = s.execute("sysvars", &json!({})).unwrap();
|
||||
let text = all.to_string();
|
||||
assert!(text.contains(RELEASE), "{text}");
|
||||
let mut s = Session::new();
|
||||
let all = s.execute("sysvars", &json!({})).unwrap().to_string();
|
||||
assert!(all.contains(RELEASE) && !all.contains("\"AC1032\""), "{all}");
|
||||
}
|
||||
@@ -81,7 +81,7 @@ fn unsupported_scale_hides_unless_annoallvisible() {
|
||||
let (mut s, h) = with_text();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:20"));
|
||||
// ANNOALLVISIBLE 1 (the default): shown, at the object's own scale.
|
||||
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled(1.0));
|
||||
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled { factor: 1.0, by: cadcraft_engine::geom::Vec2::ZERO });
|
||||
assert!(drawn_height(s.doc().unwrap(), h).is_some());
|
||||
s.execute("annovisible.current", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().header.i64("ANNOALLVISIBLE", 1), 0);
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
//! An annotative object can sit somewhere else at one of its scales: its grips move it at the
|
||||
//! current annotation scale only (when it supports several), MOVE and ROTATE move every scale,
|
||||
//! and ANNORESET puts every scale back where the current one is.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{AnnoDraw, 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 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()
|
||||
}
|
||||
|
||||
/// Annotative text at the origin supporting 1:1 and 1:50, with 1:50 current.
|
||||
fn two_scales() -> (Session, Handle) {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
|
||||
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).unwrap();
|
||||
(s, h)
|
||||
}
|
||||
|
||||
/// Where `h` shows at annotation scale `name`.
|
||||
fn shown_at(s: &mut Session, h: Handle, name: &str) -> Vec2 {
|
||||
setvar(s, "CANNOSCALE", json!(name));
|
||||
let d = s.doc().unwrap();
|
||||
match d.anno_shown(d.entity(h).unwrap()) {
|
||||
EntityKind::Text(t) => t.insert.xy(),
|
||||
EntityKind::MText(t) => t.insert.xy(),
|
||||
EntityKind::MLeader(m) => m.landing.xy(),
|
||||
EntityKind::Dimension(dm) => dm.text_mid.xy(),
|
||||
k => panic!("{k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn near(a: Vec2, b: Vec2) -> bool {
|
||||
a.dist(b) < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grip_moves_text_at_the_current_scale_only() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
// The grips show where the object is.
|
||||
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::ZERO));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grip_scale_keeps_the_displayed_annotation_pivot_and_its_elevation() {
|
||||
let (mut s, h) = two_scales();
|
||||
let (z, other_z) = (7.0, 2.0);
|
||||
s.doc_mut().unwrap().header.set_f64("ELEVATION", other_z);
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
let EntityKind::Text(t) = &mut e.kind else { panic!("expected text") };
|
||||
t.insert.z = z;
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
let pivot = s.grips_of(h).unwrap()[0];
|
||||
assert!(near(pivot, Vec2::new(5.0, 5.0)));
|
||||
let EntityKind::Text(before) = entity(&s, h).kind else { panic!("expected text") };
|
||||
s.execute("grip.scale", &json!({ "handles": [h.hex()], "baseHandle": h.hex(), "index": 0, "factor": 2.0 })).unwrap();
|
||||
let EntityKind::Text(after) = entity(&s, h).kind else { panic!("expected text") };
|
||||
assert!(near(s.grips_of(h).unwrap()[0], pivot), "the displayed grip is stationary");
|
||||
assert!((after.insert.z - z).abs() < 1e-9, "the selected grip's Z is stationary, not ELEVATION");
|
||||
assert!((after.height - 2.0 * before.height).abs() < 1e-9, "the scale operation actually took effect");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_takes_a_move_at_one_scale_back() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
assert_eq!(entity(&s, h).common.anno_moves.len(), 1);
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
assert!(entity(&s, h).common.anno_moves.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_and_rotate_carry_every_scale() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
s.execute("move", &json!({ "handles": [h.hex()], "delta": [1, 0] })).unwrap();
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(6.0, 5.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(1.0, 0.0)));
|
||||
s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 90 })).unwrap();
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(-5.0, 6.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(0.0, 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn annoreset_puts_every_scale_at_the_current_one() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
let r = s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(r["reset"], 1, "{r}");
|
||||
assert!(entity(&s, h).common.anno_moves.is_empty());
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(5.0, 5.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_scale_drops_its_position() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
s.execute("objectscale", &json!({ "handles": [h.hex()], "delete": "1:50" })).unwrap();
|
||||
assert!(entity(&s, h).common.anno_moves.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_with_one_scale_moves_everywhere() {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
let e = entity(&s, h);
|
||||
assert!(e.common.anno_moves.is_empty());
|
||||
let EntityKind::Text(t) = &e.kind else { panic!() };
|
||||
assert!(near(t.insert.xy(), Vec2::new(5.0, 5.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multileader_moves_its_content_and_keeps_its_arrowhead() {
|
||||
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:50"));
|
||||
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).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();
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), to));
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), m.landing.xy()));
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
let d = s.doc().unwrap();
|
||||
let EntityKind::MLeader(shown) = d.anno_shown(d.entity(h).unwrap()) else { panic!() };
|
||||
assert!(near(shown.leaders[0][0].xy(), Vec2::ZERO), "the arrowhead stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dimension_moves_its_text_at_one_scale() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimstyle", &json!({ "name": "Anno", "annotative": true, "current": true })).unwrap();
|
||||
let h = handle(&s.execute("dimaligned", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 2] })).unwrap());
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:2"));
|
||||
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:2" })).unwrap();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 3, "to": [20, 20] })).unwrap();
|
||||
assert!(near(shown_at(&mut s, h, "1:2"), Vec2::new(20.0, 20.0)));
|
||||
let e = entity(&s, h);
|
||||
let EntityKind::Dimension(dm) = &e.kind else { panic!() };
|
||||
assert!(!near(dm.text_mid.xy(), Vec2::new(20.0, 20.0)), "the shared text position stays");
|
||||
assert_eq!(e.common.anno_moves.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shown_draws_through_the_offset() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
let d = s.doc().unwrap();
|
||||
assert!(matches!(d.anno_draw(d.entity(h).unwrap()), AnnoDraw::Scaled { by, .. } if near(by, Vec2::new(5.0, 5.0))));
|
||||
let b = cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0);
|
||||
assert!(b.min.x > 4.0 && b.min.y > 4.0, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_offsets_never_panic() {
|
||||
let (mut s, h) = two_scales();
|
||||
for to in [json!([1e308, -1e308]), json!([f64::MAX, 0]), json!(["x", 1])] {
|
||||
let _ = s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": to }));
|
||||
}
|
||||
s.doc_mut().unwrap().modify_entity(h, |e| e.common.move_at("1:50", Vec2::new(f64::NAN, 1.0))).unwrap();
|
||||
let _ = s.execute("annoreset", &json!({ "handles": [h.hex()] }));
|
||||
let _ = s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 1e300 }));
|
||||
let d = s.doc().unwrap();
|
||||
let _ = cadcraft_engine::render::build(d, &cadcraft_engine::doc::Space::Model, &Default::default());
|
||||
let _ = bounds(d, h);
|
||||
}
|
||||
|
||||
fn bounds(d: &cadcraft_engine::doc::Drawing, h: Handle) -> cadcraft_engine::geom::Bounds2 {
|
||||
cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_a_viewport_grips_and_annoreset_use_the_viewport_s_scale() {
|
||||
// The text moved at 1:50; CANNOSCALE is 1:1 while a 1:50 viewport is active (MSPACE): the
|
||||
// grips show where the viewport draws it, a grip moves it at 1:50, ANNORESET takes 1:50's place.
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:1"));
|
||||
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
|
||||
let vp = s.execute("mview", &json!({ "p1": [0, 0], "p2": [200, 100] })).unwrap();
|
||||
let vh = vp["viewports"][0].as_str().and_then(Handle::parse_hex).unwrap();
|
||||
s.execute("viewport.set", &json!({ "handle": vh.hex(), "scale": "1:50", "center": [0, 0] })).unwrap();
|
||||
s.execute("mspace", &json!({ "handle": vh.hex() })).unwrap();
|
||||
assert!((s.anno_view().unwrap() - 50.0).abs() < 1e-9);
|
||||
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)), "{:?}", s.grips_of(h));
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [7, 7] })).unwrap();
|
||||
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(7.0, 7.0)));
|
||||
s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
s.execute("pspace", &json!({})).unwrap();
|
||||
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
|
||||
// 1:1 was never moved by the grips, and now sits where 1:50 is.
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(7.0, 7.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(7.0, 7.0)));
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
//! Legacy system variables a LISP routine saves and restores around its work: DIMASO (obsolete in
|
||||
//! AutoCAD, which reports and sets DIMASSOC through it), TEXTEVAL, REGENMODE (kept in the drawing
|
||||
//! and its DXF header) and POPUPS (read-only). Before them `(getvar "DIMASO")` read nil, so
|
||||
//! `(setq o (getvar "DIMASO")) … (setvar "DIMASO" o)` failed and the routine left the drawing's
|
||||
//! associativity changed.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::lisp::value::{Value as LispValue, to_text};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn getvar(s: &mut Session, name: &str) -> Value {
|
||||
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
|
||||
}
|
||||
|
||||
fn setvar(s: &mut Session, name: &str, value: Value) -> bool {
|
||||
s.execute("setvar", &json!({ "name": name, "value": value })).is_ok()
|
||||
}
|
||||
|
||||
/// The value of a LISP expression, or the error it left.
|
||||
fn eval(s: &mut Session, src: &str) -> Result<LispValue, String> {
|
||||
match s.lisp_eval(src, false, true, Vec::new()) {
|
||||
Ok(Some(v)) => v,
|
||||
Ok(None) => Err("no value".into()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `(getvar name)` as the integer a routine receives.
|
||||
fn lisp_getvar(s: &mut Session, name: &str) -> i64 {
|
||||
let v = eval(s, &format!("(getvar \"{name}\")")).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
let n = v.as_number().unwrap_or_else(|| panic!("{name} is not a number"));
|
||||
assert_eq!(n.fract(), 0.0, "{name} is a whole number");
|
||||
n as i64
|
||||
}
|
||||
|
||||
/// `(setvar name value)` from LISP: whether it was accepted.
|
||||
fn lisp_setvar(s: &mut Session, name: &str, value: &str) -> bool {
|
||||
eval(s, &format!("(setvar \"{name}\" {value})")).is_ok()
|
||||
}
|
||||
|
||||
/// The DXF pairs `(group code, value)` of a file, both trimmed.
|
||||
fn pairs(text: &str) -> Vec<(i32, String)> {
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut out = Vec::new();
|
||||
for chunk in lines.chunks(2) {
|
||||
let [code, value] = chunk else { break };
|
||||
let Ok(c) = code.parse::<i32>() else { continue };
|
||||
out.push((c, (*value).to_string()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The HEADER variable names a DXF text writes (the value after each group code 9).
|
||||
fn header_names(text: &str) -> Vec<String> {
|
||||
pairs(text).iter().filter(|(c, _)| *c == 9).map(|(_, v)| v.trim_start_matches('$').to_string()).collect()
|
||||
}
|
||||
|
||||
/// The integer a header variable is written with, as `(group code, value)` after its name.
|
||||
fn header_int(text: &str, name: &str) -> Option<(i32, String)> {
|
||||
let ps = pairs(text);
|
||||
let i = ps.iter().position(|(c, v)| *c == 9 && v.trim_start_matches('$') == name)?;
|
||||
ps.get(i + 1).cloned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_values_are_integers_a_routine_reads() {
|
||||
let mut s = Session::new();
|
||||
for (name, want) in [("DIMASO", 1), ("TEXTEVAL", 0), ("REGENMODE", 1), ("POPUPS", 1)] {
|
||||
assert_eq!(getvar(&mut s, name), json!(want), "{name}");
|
||||
assert_eq!(lisp_getvar(&mut s, name), want, "{name} through getvar");
|
||||
let kind = eval(&mut s, &format!("(type (getvar \"{name}\"))")).unwrap();
|
||||
assert_eq!(to_text(&kind, true), "INT", "{name} is an integer to LISP");
|
||||
}
|
||||
// The list a routine sees (`SETVAR ?`) carries them too.
|
||||
let all = cadcraft_engine::sysvars::list(&s);
|
||||
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
|
||||
assert_eq!(all.get(name), Some(&getvar(&mut s, name)), "{name} listed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_routine_saving_and_restoring_each_one_leaves_it_as_it_was() {
|
||||
let mut s = Session::new();
|
||||
for (name, changed) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
|
||||
let before = lisp_getvar(&mut s, name);
|
||||
// (setq o (getvar X)) … (setvar X o) must give back exactly what it read.
|
||||
assert!(eval(&mut s, &format!("(setq o (getvar \"{name}\"))")).is_ok(), "{name} readable");
|
||||
assert!(lisp_setvar(&mut s, name, changed), "{name} takes {changed}");
|
||||
assert_ne!(lisp_getvar(&mut s, name), before, "{name} changed by {changed}");
|
||||
assert!(eval(&mut s, &format!("(setvar \"{name}\" o)")).is_ok(), "{name} restored");
|
||||
assert_eq!(lisp_getvar(&mut s, name), before, "{name} back to {before}");
|
||||
}
|
||||
// REGENMODE is the drawing's, kept in its header; TEXTEVAL only the session's.
|
||||
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimaso_restores_the_dimassoc_mode_it_turned_off() {
|
||||
// The routine's save/restore through DIMASO, for each associative mode.
|
||||
for mode in [1, 2] {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(mode)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1), "DIMASO follows DIMASSOC {mode}");
|
||||
let o = eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number().unwrap();
|
||||
assert!(lisp_setvar(&mut s, "DIMASO", "0"));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "DIMASO 0 turns associativity off");
|
||||
assert!(lisp_setvar(&mut s, "DIMASO", "1"));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number(), Some(o), "DIMASO 1 puts back the DIMASSOC {mode} the routine read");
|
||||
}
|
||||
// Set directly, without ever switching it off first, DIMASO 1 leaves the mode alone.
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
|
||||
// No non-zero mode was seen: turning associativity back on gives AutoCAD's 2.
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(0)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "none was seen: the default 2");
|
||||
// A drawing whose saved DIMASSOC is no mode DIMASO can restore (a hostile file) gives 2.
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
|
||||
// Such a mode is not associative, and DIMASO 1 turns associativity on from it too.
|
||||
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_setvar_still_takes_digits() {
|
||||
for (name, digits) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
|
||||
let want = json!(digits.parse::<i64>().unwrap());
|
||||
let dollar = format!("${name}");
|
||||
// SETVAR with the name, the bare name, and the `$` form, as typed at the command line.
|
||||
for lines in [vec!["setvar", name, digits], vec![name, digits], vec!["setvar", dollar.as_str(), digits]] {
|
||||
let mut s = Session::new();
|
||||
for line in &lines {
|
||||
s.cmdline(line).unwrap();
|
||||
}
|
||||
assert_eq!(getvar(&mut s, name), want, "typed {lines:?}");
|
||||
}
|
||||
// A routine that types the command passes its answers the same way.
|
||||
let mut s = Session::new();
|
||||
eval(&mut s, &format!("(command \"SETVAR\" \"{name}\" \"{digits}\")")).unwrap();
|
||||
assert_eq!(getvar(&mut s, name), want, "(command \"SETVAR\" {name})");
|
||||
// Typed words are still refused.
|
||||
let mut s = Session::new();
|
||||
let before = getvar(&mut s, name);
|
||||
for line in ["setvar", name, "two"] {
|
||||
s.cmdline(line).unwrap();
|
||||
}
|
||||
assert_eq!(getvar(&mut s, name), before, "typed word refused for {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_drawing_writes_regenmode() {
|
||||
let mut s = Session::new();
|
||||
// The first drawing, then a new metric and a new imperial one.
|
||||
for metric in [None, Some(true), Some(false)] {
|
||||
if let Some(metric) = metric {
|
||||
s.new_drawing(metric);
|
||||
}
|
||||
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "1".to_string())), "new drawing, metric {metric:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_values_are_refused_and_change_nothing() {
|
||||
let mut s = Session::new();
|
||||
for (name, v) in [
|
||||
("REGENMODE", json!(2)),
|
||||
("REGENMODE", json!(-1)),
|
||||
("REGENMODE", json!(1.5)),
|
||||
("REGENMODE", json!("two")),
|
||||
("REGENMODE", Value::Null),
|
||||
("TEXTEVAL", json!(-1)),
|
||||
("TEXTEVAL", json!(2)),
|
||||
("TEXTEVAL", json!("two")),
|
||||
("TEXTEVAL", Value::Null),
|
||||
("DIMASO", json!(3)),
|
||||
("DIMASO", json!(-1)),
|
||||
("DIMASO", json!(0.5)),
|
||||
("DIMASO", json!("two")),
|
||||
("DIMASO", Value::Null),
|
||||
// Text a program or a routine passes is refused even when it spells a number.
|
||||
("REGENMODE", json!("0")),
|
||||
("TEXTEVAL", json!("1")),
|
||||
("DIMASO", json!("0")),
|
||||
("TEXTEVAL", json!(true)),
|
||||
] {
|
||||
let before = getvar(&mut s, name);
|
||||
assert!(!setvar(&mut s, name, v.clone()), "{name} = {v} refused");
|
||||
assert_eq!(getvar(&mut s, name), before, "{name} unchanged by {v}");
|
||||
}
|
||||
// The drawing's associativity is untouched by a refused DIMASO.
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(!setvar(&mut s, "DIMASO", json!(3)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
|
||||
// The same through LISP, where nil and a NaN real arrive as values a variable can't take.
|
||||
assert!(!lisp_setvar(&mut s, "REGENMODE", "nil"), "nil refused");
|
||||
assert!(!lisp_setvar(&mut s, "DIMASO", "3"), "DIMASO 3 refused");
|
||||
assert!(!lisp_setvar(&mut s, "DIMASO", "\"two\""), "DIMASO text refused");
|
||||
for (name, v) in [("DIMASO", "\"0\""), ("TEXTEVAL", "\"1\""), ("REGENMODE", "\"0\"")] {
|
||||
assert!(!lisp_setvar(&mut s, name, v), "{name} text {v} refused");
|
||||
}
|
||||
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "-1"), "TEXTEVAL -1 refused");
|
||||
// (- (exp 1000) (exp 1000)) is NaN: not a number JSON can hold, so it is refused as one.
|
||||
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "(- (exp 1000) (exp 1000))"), "NaN refused");
|
||||
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popups_is_read_only() {
|
||||
let mut s = Session::new();
|
||||
assert!(cadcraft_engine::sysvars::is_read_only("popups"));
|
||||
for v in [json!(1), json!(0), json!("1")] {
|
||||
let e = s.execute("setvar", &json!({ "name": "POPUPS", "value": v })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "{v}: {e}");
|
||||
}
|
||||
assert!(!lisp_setvar(&mut s, "POPUPS", "0"));
|
||||
assert_eq!(getvar(&mut s, "POPUPS"), json!(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regenmode_is_saved_in_the_dxf_header_and_read_back() {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "REGENMODE", json!(0)));
|
||||
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
assert!(header_names(&text).contains(&"REGENMODE".to_string()), "$REGENMODE is in the header (has {:?})", header_names(&text));
|
||||
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "0".to_string())), "$REGENMODE is group 70, 0");
|
||||
// A reopened drawing has the value it was saved with, and saves it back.
|
||||
let mut back = Session::new();
|
||||
back.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "regenmode.dxf", None);
|
||||
assert_eq!(getvar(&mut back, "REGENMODE"), json!(0));
|
||||
let again = cadcraft_io::write_dxf(back.doc().unwrap());
|
||||
assert_eq!(header_int(&again, "REGENMODE"), Some((70, "0".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texteval_dimaso_and_popups_are_not_saved() {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "TEXTEVAL", json!(1)));
|
||||
let text = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
let names = header_names(&text);
|
||||
for name in ["TEXTEVAL", "DIMASO", "POPUPS"] {
|
||||
assert!(!names.contains(&name.to_string()), "{name} is not a header variable (has {names:?})");
|
||||
}
|
||||
// TEXTEVAL is the session's: a drawing opened in this session does not bring its own value.
|
||||
s.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "no_legacy_vars.dxf", None);
|
||||
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "opening a drawing leaves the session's value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimaso_remembers_the_mode_of_each_open_drawing() {
|
||||
// The mode DIMASO turns off is the drawing's, not the session's: two open drawings switched
|
||||
// between each put back the DIMASSOC mode they had.
|
||||
let mut s = Session::new();
|
||||
let first = s.active;
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
let second = s.new_drawing(true);
|
||||
assert_eq!(second, first + 1);
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(2)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
s.execute("document.switch", &json!({ "index": first })).unwrap();
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the first drawing restores its own mode");
|
||||
s.execute("document.switch", &json!({ "index": second })).unwrap();
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "the second drawing restores its own mode");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dollar_forms_are_the_same_variables() {
|
||||
// The DXF header writes these names with a `$` ($DIMASO, $TEXTEVAL, $REGENMODE, $POPUPS), so
|
||||
// the command line takes them that way too, in any case and with spaces around them.
|
||||
let mut s = Session::new();
|
||||
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
|
||||
let plain = getvar(&mut s, name);
|
||||
let dollar = format!("${name}");
|
||||
assert_eq!(getvar(&mut s, &dollar), plain, "{dollar} reads like {name}");
|
||||
let typed = format!(" ${} ", name.to_ascii_lowercase());
|
||||
assert_eq!(getvar(&mut s, &typed), plain, "{typed:?} reads like {name}");
|
||||
assert_eq!(cadcraft_engine::sysvars::is_read_only(&dollar), cadcraft_engine::sysvars::is_read_only(name), "{dollar} read-only as {name}");
|
||||
}
|
||||
// DIMASO through its DXF name still turns DIMASSOC off and puts its mode back.
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "$DIMASO", json!(0)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "$DIMASO 0 turns associativity off");
|
||||
assert!(setvar(&mut s, " $dimaso ", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "$DIMASO 1 puts the mode back");
|
||||
// TEXTEVAL: set under one name, read under the other.
|
||||
assert!(setvar(&mut s, "$TEXTEVAL", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "$TEXTEVAL set TEXTEVAL");
|
||||
assert!(setvar(&mut s, "TEXTEVAL", json!(0)));
|
||||
assert_eq!(getvar(&mut s, "$TEXTEVAL"), json!(0));
|
||||
// REGENMODE takes only the values its plain name takes, and stores the ones it takes.
|
||||
assert!(!setvar(&mut s, "$REGENMODE", json!(2)), "$REGENMODE 2 is out of range");
|
||||
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $REGENMODE changed nothing");
|
||||
assert!(!setvar(&mut s, "$REGENMODE", json!(-1)), "$REGENMODE -1 is out of range");
|
||||
assert!(setvar(&mut s, "$REGENMODE", json!(0)));
|
||||
assert_eq!(getvar(&mut s, "$REGENMODE"), json!(0));
|
||||
assert_eq!(getvar(&mut s, "REGENMODE"), json!(0));
|
||||
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 0, "$REGENMODE stored the drawing's value");
|
||||
// POPUPS is read-only under its DXF name too.
|
||||
for v in [json!(0), json!("1")] {
|
||||
let e = s.execute("setvar", &json!({ "name": "$POPUPS", "value": v })).unwrap_err().to_string();
|
||||
assert!(e.contains("read-only"), "$POPUPS {v}: {e}");
|
||||
}
|
||||
assert!(!lisp_setvar(&mut s, "$POPUPS", "0"));
|
||||
assert_eq!(getvar(&mut s, "$POPUPS"), json!(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_dollar_names_keep_their_own_handling() {
|
||||
// Only those four take a `$`: LISP's angle variables convert radians for the plain name, and
|
||||
// `$OSMODE` stays a name of its own rather than becoming the session's OSMODE.
|
||||
let mut s = Session::new();
|
||||
assert!(eval(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
|
||||
let base = eval(&mut s, "(getvar \"$ANGBASE\")").unwrap().as_number().unwrap_or(f64::NAN);
|
||||
assert!((base - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "(getvar \"$ANGBASE\") gives pi/2, not {base}");
|
||||
let osmode = eval(&mut s, "(setvar \"$OSMODE\" 9)").unwrap();
|
||||
assert_eq!(to_text(&osmode, true), "9", "(setvar \"$OSMODE\" 9) returns 9");
|
||||
assert_eq!(getvar(&mut s, "OSMODE"), json!(4133), "$OSMODE is not the session's OSMODE");
|
||||
assert_eq!(getvar(&mut s, "$OSMODE"), json!(9), "$OSMODE still reads back what it was set to");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_puts_back_the_mode_dimaso_remembers() {
|
||||
// The mode DIMASO remembers goes back with DIMASSOC when the changes are undone.
|
||||
let mut s = Session::new();
|
||||
for (name, v) in [("DIMASSOC", 1), ("DIMASO", 0), ("DIMASSOC", 2), ("DIMASO", 0)] {
|
||||
assert!(setvar(&mut s, name, json!(v)), "{name} {v}");
|
||||
}
|
||||
s.cmdline("u").unwrap();
|
||||
s.cmdline("u").unwrap();
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "back to after the first DIMASO 0");
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)));
|
||||
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the mode remembered then, not the later 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_dollars_are_the_same_variables() {
|
||||
let mut s = Session::new();
|
||||
assert!(!lisp_setvar(&mut s, "$$REGENMODE", "2"), "out of range under any number of $");
|
||||
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $$REGENMODE changed nothing");
|
||||
assert!(!setvar(&mut s, "$$$POPUPS", json!(0)), "read-only under any number of $");
|
||||
assert!(cadcraft_engine::sysvars::is_read_only("$$POPUPS"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimaso_on_while_already_on_leaves_the_drawing_unmodified() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "a fresh drawing");
|
||||
assert!(setvar(&mut s, "DIMASO", json!(1)), "already on");
|
||||
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "nothing changed, so not modified");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_remembered_mode_is_not_a_variable_and_is_not_reported_lost() {
|
||||
let mut s = Session::new();
|
||||
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
|
||||
assert!(setvar(&mut s, "DIMASO", json!(0)));
|
||||
for name in ["CADCRAFT_DIMASO_MODE", "$CADCRAFT_DIMASO_MODE", "cadcraft_dimaso_mode"] {
|
||||
assert!(s.execute("getvar", &json!({ "name": name })).is_err(), "{name} is not a variable");
|
||||
assert!(!setvar(&mut s, name, json!(2)), "{name} cannot be set");
|
||||
}
|
||||
assert!(eval(&mut s, "(getvar \"CADCRAFT_DIMASO_MODE\")").map_or(true, |v| to_text(&v, false) == "nil"));
|
||||
// Saved and read back, the drawing has lost nothing a save keeps.
|
||||
let before = s.doc().unwrap().clone();
|
||||
let after = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&before).as_bytes()).unwrap();
|
||||
let cmp = cadcraft_io::roundtrip::compare(&before, &after, &cadcraft_io::roundtrip::Options::default());
|
||||
assert!(!cmp.differences.iter().any(|d| d.place.contains("DIMASO")), "{:?}", cmp.differences.iter().map(|d| &d.place).collect::<Vec<_>>());
|
||||
}
|
||||
@@ -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)),
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
#[path = "../support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
mod acadver;
|
||||
mod angle_prompts;
|
||||
mod angle_settings;
|
||||
mod annotate_options;
|
||||
mod annotative;
|
||||
mod annotative_positions;
|
||||
mod arc_ctrl_direction;
|
||||
mod array_commands;
|
||||
mod array_counts;
|
||||
@@ -104,6 +106,7 @@ mod layout_prompts;
|
||||
mod leader_command;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod leader_text_scale;
|
||||
mod legacy_sysvars;
|
||||
mod lisp_answer_by_frames;
|
||||
mod lisp_corpus;
|
||||
mod lisp_findfile;
|
||||
@@ -135,6 +138,7 @@ mod offset_ellipse_side;
|
||||
mod offset_move;
|
||||
mod oops_command;
|
||||
mod options_profile;
|
||||
mod osnap_opened_drawings;
|
||||
mod overkill;
|
||||
mod parallel_display_list;
|
||||
mod pedit_heights;
|
||||
@@ -185,10 +189,12 @@ mod setvar_coverage;
|
||||
mod shapes;
|
||||
mod snap_annotations;
|
||||
mod snap_blocks;
|
||||
mod snap_center_on_curve;
|
||||
mod snap_curves;
|
||||
mod snap_intersections_aperture;
|
||||
mod snap_nearest;
|
||||
mod snap_overrides;
|
||||
mod snap_tab_cycling;
|
||||
mod snap_tracking;
|
||||
mod snap_z;
|
||||
mod snaps_more;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! DIST snaps to the model geometry displayed in paper-space viewports (#516).
|
||||
|
||||
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
||||
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Ellipse, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::pointmod::snap_candidates;
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
@@ -307,22 +308,22 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
|
||||
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
|
||||
}
|
||||
|
||||
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap
|
||||
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
|
||||
/// Across spaces a click takes the viewport's Endpoint over a paper-space Nearest that scores
|
||||
/// closer, as within one space a snap point beats Nearest. Tab starts at the click's snap and
|
||||
/// still reaches the paper-space Nearest.
|
||||
#[test]
|
||||
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
|
||||
fn a_viewport_endpoint_beats_a_closer_paper_space_nearest() {
|
||||
let (mut d, paper) = drawing();
|
||||
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
|
||||
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
|
||||
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
|
||||
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
|
||||
assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
|
||||
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
|
||||
let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false);
|
||||
assert!(hit.mode == mode::END && hit.viewport.is_some() && hit.point.near(Vec2::new(95.0, 50.0), 1e-9), "{hit:?}");
|
||||
let all = snap_candidates(&d, &paper, cursor, 0.5, modes, None, false);
|
||||
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
|
||||
assert!(
|
||||
all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
|
||||
"Tab reaches the viewport's endpoint: {all:?}"
|
||||
all.iter().any(|h| h.mode == mode::NEA && h.viewport.is_none() && h.point.near(Vec2::new(94.7, 50.0), 1e-9)),
|
||||
"Tab reaches the paper-space Nearest: {all:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -458,3 +459,50 @@ fn malformed_and_paper_space_viewports_are_not_snap_sources() {
|
||||
assert!(osnap(&d, &paper, Vec2::new(95.1, 50.1), 0.5, mode::END, None, false).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// Nearest on a curve that leaves the viewport: the curve's closest point to the cursor is outside
|
||||
/// the viewport, another point of it within the aperture is inside, and Nearest snaps there.
|
||||
#[test]
|
||||
fn nearest_takes_the_visible_part_of_a_curve_crossing_the_viewport_edge() {
|
||||
let (mut d, paper) = drawing();
|
||||
// The viewport shows model y up to 20. A tall ellipse peaks at (15, 20.1), just outside.
|
||||
let ellipse = Ellipse { center: Vec3::new(15.0, 0.0, 0.0), major: Vec3::new(0.0, 20.1, 0.0), ratio: 0.1, start: 0.0, end: std::f64::consts::TAU };
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Ellipse(ellipse)).unwrap();
|
||||
// The viewport's border is on a layer that is off, so it offers no Nearest of its own.
|
||||
d.layers.push(cadcraft_engine::doc::Layer { name: "Border".into(), on: false, ..Default::default() });
|
||||
let vp = viewport(&d, &paper);
|
||||
d.modify_entity(vp, |e| e.common.layer = "Border".into()).unwrap();
|
||||
// Model (15, 19.99): 0.11 from the peak, about 0.2 from where the ellipse comes back inside.
|
||||
let cursor = Vec2::new(102.5, 59.995);
|
||||
let hit = osnap(&d, &paper, cursor, 0.5, mode::NEA, None, false).expect("a visible nearest point");
|
||||
let model = hit.viewport.expect("seen through the viewport").point;
|
||||
assert!(model.y <= 20.0 + 1e-9 && model.dist(Vec2::new(15.0, 19.99)) <= 1.0, "{hit:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_twisted_viewport_offers_the_visible_perpendicular_when_a_nearer_one_is_off_the_sheet() {
|
||||
// A viewport twisted 45°, 20 square at 0,0 on the sheet, scale 1. Through it, a line along
|
||||
// y = 0 under the cursor and one along x = 9.3 (sheet coordinates). From the base 12,3 the
|
||||
// foot on the first, 12,0, is inside the turned model box but off the viewport; the foot on
|
||||
// the second, 9.3,3, is on it.
|
||||
let mut d = Drawing::new_imperial();
|
||||
let paper = Space::Paper("Layout1".into());
|
||||
let vp = Viewport {
|
||||
center: Vec3::ZERO,
|
||||
width: 20.0,
|
||||
height: 20.0,
|
||||
view_center: Vec2::ZERO,
|
||||
view_height: 20.0,
|
||||
id: 2,
|
||||
twist: std::f64::consts::FRAC_PI_4,
|
||||
..Viewport::default()
|
||||
};
|
||||
for (a, b) in [(Vec2::new(-9.0, 0.0), Vec2::new(30.0, 0.0)), (Vec2::new(9.3, -9.0), Vec2::new(9.3, 9.0))] {
|
||||
let (a, b) = (vp.paper_to_model(a), vp.paper_to_model(b));
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })).unwrap();
|
||||
}
|
||||
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||||
let hit = osnap(&d, &paper, Vec2::new(9.0, 0.0), 0.5, mode::PER, Some(Vec2::new(12.0, 3.0)), false).expect("the visible foot");
|
||||
assert_eq!(hit.mode, mode::PER);
|
||||
assert!(hit.point.near(Vec2::new(9.3, 3.0), 1e-9), "{hit:?}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Running object snaps in a fresh drawing and in drawings opened from DXF and DWG files, with
|
||||
//! AutoCAD's default modes (OSMODE 4133: Endpoint, Center, Intersection, Extension).
|
||||
//!
|
||||
//! Moving onto a circle, an arc or a polyline arc finds its Center. OSMODE is a profile setting,
|
||||
//! as in AutoCAD (saved in the registry there, not the drawing): a file's `$OSMODE` header
|
||||
//! variable, 0 included, never changes the running snaps.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Drawing;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_engine::snap::{mode, tracking::CursorQuery};
|
||||
use serde_json::json;
|
||||
|
||||
/// AutoCAD's default running snaps.
|
||||
const DEFAULT: u32 = 4133;
|
||||
|
||||
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
|
||||
let a = deg.to_radians();
|
||||
c + Vec2::new(r * a.cos(), r * a.sin())
|
||||
}
|
||||
|
||||
/// A line crossed by another, a circle, an arc and a polyline with a straight and an arc segment.
|
||||
fn draw(s: &mut Session) {
|
||||
s.execute("line", &json!({ "points": [[0, 0], [20, 0]] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[5, -5], [5, 5]] })).unwrap();
|
||||
s.execute("circle", &json!({ "center": [50, 0], "radius": 5 })).unwrap();
|
||||
s.execute("arc", &json!({ "center": [80, 0], "radius": 5, "start": 0, "end": 180 })).unwrap();
|
||||
// 100,0 to 110,0 straight, then a half circle (bulge 1) to 130,0 round 120,0, below the axis.
|
||||
s.execute("pline", &json!({ "vertices": [[100, 0], {"p": [110, 0], "bulge": 1.0}, [130, 0]] })).unwrap();
|
||||
}
|
||||
|
||||
fn drawing() -> Drawing {
|
||||
let mut s = Session::new();
|
||||
draw(&mut s);
|
||||
s.doc().unwrap().clone()
|
||||
}
|
||||
|
||||
/// Where a click at `cursor` lands while LINE asks for its first point (the drawing area's path).
|
||||
fn snap(s: &mut Session, cursor: Vec2) -> Option<(Vec2, u32)> {
|
||||
if s.running.is_none() {
|
||||
s.start("line").unwrap();
|
||||
}
|
||||
let q = CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
|
||||
let r = s.snap_cursor(cursor, &q);
|
||||
r.snap.map(|h| (r.point, h.mode))
|
||||
}
|
||||
|
||||
fn assert_snaps(s: &mut Session, what: &str) {
|
||||
assert_eq!(s.settings.osmode, DEFAULT, "{what}: the running snaps are the profile's");
|
||||
let cases = [
|
||||
("the line's end", Vec2::new(20.2, 0.1), Vec2::new(20.0, 0.0), &[mode::END][..]),
|
||||
("the lines' crossing", Vec2::new(5.2, 0.15), Vec2::new(5.0, 0.0), &[mode::INT][..]),
|
||||
("the circle", polar(Vec2::new(50.0, 0.0), 5.3, 45.0), Vec2::new(50.0, 0.0), &[mode::CEN][..]),
|
||||
("the arc", polar(Vec2::new(80.0, 0.0), 5.2, 90.0), Vec2::new(80.0, 0.0), &[mode::CEN][..]),
|
||||
("the arc's end", Vec2::new(85.2, 0.1), Vec2::new(85.0, 0.0), &[mode::END][..]),
|
||||
("the polyline's vertex", Vec2::new(110.2, 0.1), Vec2::new(110.0, 0.0), &[mode::END][..]),
|
||||
("the polyline's arc", polar(Vec2::new(120.0, 0.0), 10.2, 270.0), Vec2::new(120.0, 0.0), &[mode::CEN][..]),
|
||||
];
|
||||
for (name, cursor, want, modes) in cases {
|
||||
let (p, m) = snap(s, cursor).unwrap_or_else(|| panic!("{what}: no snap on {name}"));
|
||||
assert!(modes.contains(&m), "{what}, {name}: mode {m}");
|
||||
assert!(p.near(want, 1e-6), "{what}, {name}: {p:?}");
|
||||
}
|
||||
// Away from everything: nothing.
|
||||
assert_eq!(snap(s, Vec2::new(35.0, 20.0)), None, "{what}");
|
||||
// F3 off: nothing; on again: back.
|
||||
s.execute("osnap", &json!({})).unwrap();
|
||||
assert_eq!(snap(s, Vec2::new(20.2, 0.1)), None, "{what}: F3 off");
|
||||
s.execute("osnap", &json!({})).unwrap();
|
||||
assert_eq!(snap(s, Vec2::new(20.2, 0.1)).map(|h| h.1), Some(mode::END), "{what}: F3 on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_snaps_work_in_a_fresh_drawing() {
|
||||
let mut s = Session::new();
|
||||
draw(&mut s);
|
||||
assert_snaps(&mut s, "fresh drawing");
|
||||
}
|
||||
|
||||
/// `text` with `$OSMODE` set to `value` at the top of its header.
|
||||
fn with_osmode(text: &str, value: u32) -> String {
|
||||
let at = text.find("HEADER").expect("a header section") + "HEADER".len();
|
||||
let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
|
||||
let (head, tail) = text.split_at(at);
|
||||
format!("{head}{eol} 9{eol}$OSMODE{eol} 70{eol}{value}{tail}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dxf_with_osmode_0_keeps_the_running_snaps() {
|
||||
let clean = String::from_utf8(cadcraft_io::write(&drawing(), "snaps.dxf").unwrap()).unwrap();
|
||||
let text = with_osmode(&clean, 0);
|
||||
let d = cadcraft_io::read(text.as_bytes(), "snaps.dxf").unwrap();
|
||||
let mut s = Session::new();
|
||||
// OSMODE is the profile's: the user's own choice survives opening the file.
|
||||
s.execute("setvar", &json!({ "name": "OSMODE", "value": DEFAULT })).unwrap();
|
||||
s.open_drawing(d, "snaps.dxf", None);
|
||||
assert_snaps(&mut s, "DXF with $OSMODE 0");
|
||||
// Nor does a file change a profile without Center.
|
||||
let mut s = Session::new();
|
||||
s.execute("setvar", &json!({ "name": "OSMODE", "value": mode::END })).unwrap();
|
||||
let text = with_osmode(&clean, DEFAULT);
|
||||
assert_eq!(text.matches("$OSMODE").count(), 1, "one $OSMODE in the file");
|
||||
s.open_drawing(cadcraft_io::read(text.as_bytes(), "x.dxf").unwrap(), "x.dxf", None);
|
||||
assert_eq!(s.settings.osmode, mode::END);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_snaps_work_in_a_drawing_opened_from_dwg() {
|
||||
// The drawing is the test's own, so it is converted in this process.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let bytes = cadcraft_io::write(&drawing(), "snaps.dwg").unwrap();
|
||||
let d = cadcraft_io::read(&bytes, "snaps.dwg").unwrap();
|
||||
let mut s = Session::new();
|
||||
s.open_drawing(d, "snaps.dwg", None);
|
||||
assert_snaps(&mut s, "DWG");
|
||||
}
|
||||
@@ -11,7 +11,9 @@ use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, I
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn hooks() {
|
||||
/// The real file formats, for every test in this binary that opens or saves files (the hooks are
|
||||
/// process-wide and the first ones set stay).
|
||||
pub(crate) fn hooks() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Center snaps from the curve, as in AutoCAD: with the cursor over a circle, an arc, an
|
||||
//! ellipse or a polyline arc (also inside a block reference) the running Center snap finds its
|
||||
//! center, however far away it is. Before, the center was only found with the cursor on the
|
||||
//! center itself, so moving onto a circle with the default running snaps (END, CEN, INT, EXT)
|
||||
//! showed nothing.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Common, EntityKind, Insert, Space};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::pointmod::snap_candidates;
|
||||
use cadcraft_engine::snap::{self, mode};
|
||||
use serde_json::json;
|
||||
|
||||
/// AutoCAD's default running snaps (OSMODE 4133).
|
||||
const DEFAULT: u32 = 4133;
|
||||
|
||||
fn snap_at(s: &Session, cursor: Vec2, aperture: f64, osmode: u32) -> Option<(Vec2, u32)> {
|
||||
snap::osnap(s.doc().unwrap(), &Space::Model, cursor, aperture, osmode, None, false).map(|h| (h.point, h.mode))
|
||||
}
|
||||
|
||||
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
|
||||
let a = deg.to_radians();
|
||||
c + Vec2::new(r * a.cos(), r * a.sin())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_on_a_circle_snaps_to_its_center() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [100, 50], "radius": 20 })).unwrap();
|
||||
let c = Vec2::new(100.0, 50.0);
|
||||
for deg in [10.0, 45.0, 130.0, 250.0, 300.0] {
|
||||
// A hair off the circle, well inside the aperture; the center is 20 units away.
|
||||
let cursor = polar(c, 20.3, deg);
|
||||
let (p, m) = snap_at(&s, cursor, 1.0, DEFAULT).unwrap_or_else(|| panic!("no snap on the circle at {deg}°"));
|
||||
assert_eq!(m, mode::CEN, "at {deg}°");
|
||||
assert!(p.near(c, 1e-9), "at {deg}°: {p:?}");
|
||||
}
|
||||
// Away from the circle (outside the aperture) there is nothing.
|
||||
assert_eq!(snap_at(&s, polar(c, 23.0, 45.0), 1.0, DEFAULT), None);
|
||||
// Center off: no center.
|
||||
assert_eq!(snap_at(&s, polar(c, 20.3, 45.0), 1.0, mode::END), None);
|
||||
// On the center itself, as before.
|
||||
assert_eq!(snap_at(&s, c + Vec2::new(0.2, 0.1), 1.0, DEFAULT).map(|h| h.1), Some(mode::CEN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arcs_ellipses_and_polyline_arcs_snap_to_their_centers() {
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap();
|
||||
s.execute("ellipse", &json!({ "center": [50, 0], "major": [8, 0], "ratio": 0.5 })).unwrap();
|
||||
// A polyline with a half-circle bulge from (100,0) to (120,0): center (110,0), radius 10.
|
||||
s.execute("pline", &json!({ "vertices": [{"p": [100, 0], "bulge": 1.0}, [120, 0]] })).unwrap();
|
||||
let arc = snap_at(&s, polar(Vec2::ZERO, 10.2, 45.0), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(arc.1, mode::CEN);
|
||||
assert!(arc.0.near(Vec2::ZERO, 1e-9));
|
||||
// The arc runs 0°-90°: on its circle at 200° (not on the arc) there is no center.
|
||||
assert_eq!(snap_at(&s, polar(Vec2::ZERO, 10.2, 200.0), 1.0, DEFAULT), None);
|
||||
let el = snap_at(&s, Vec2::new(50.0, 4.2), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(el.1, mode::CEN);
|
||||
assert!(el.0.near(Vec2::new(50.0, 0.0), 1e-9));
|
||||
let pl = snap_at(&s, polar(Vec2::new(110.0, 0.0), 10.2, 270.0), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(pl.1, mode::CEN, "the bulge's arc");
|
||||
assert!(pl.0.near(Vec2::new(110.0, 0.0), 1e-9), "{:?}", pl.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nearer_endpoint_or_intersection_still_wins() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[10, 0], [30, 0]] })).unwrap();
|
||||
// At the line's end on the circle: Endpoint/Intersection, not the far center.
|
||||
let (p, m) = snap_at(&s, Vec2::new(10.2, 0.1), 1.0, DEFAULT).unwrap();
|
||||
assert!(m == mode::END || m == mode::INT, "{m}");
|
||||
assert!(p.near(Vec2::new(10.0, 0.0), 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_inside_block_references_snap_to_their_centers() {
|
||||
let mut s = Session::new();
|
||||
let c = s.execute("circle", &json!({ "center": [5, 0], "radius": 2 })).unwrap()["handle"].as_str().unwrap().to_string();
|
||||
s.execute("block", &json!({ "name": "H", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap();
|
||||
let kind = EntityKind::Insert(Insert {
|
||||
block: "H".into(),
|
||||
insert: Vec3::new(100.0, 100.0, 0.0),
|
||||
scale: Vec3::new(3.0, 3.0, 1.0),
|
||||
rotation: 0.0,
|
||||
attribs: Vec::new(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
col_spacing: 0.0,
|
||||
row_spacing: 0.0,
|
||||
clip: None,
|
||||
});
|
||||
s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap();
|
||||
// The circle lands at (115,100) with radius 6.
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(115.0, 100.0), 6.2, 60.0), 1.0, DEFAULT).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(115.0, 100.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_cycling_offers_the_center_from_the_curve() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
|
||||
let all = snap_candidates(s.doc().unwrap(), &Space::Model, polar(Vec2::ZERO, 10.2, 30.0), 1.0, DEFAULT, None, false);
|
||||
assert_eq!(all.iter().filter(|h| h.mode == mode::CEN && h.point.near(Vec2::ZERO, 1e-9)).count(), 1, "{all:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cursor_query_snaps_to_the_center_from_the_curve() {
|
||||
// The path the drawing area uses (Session::snap_cursor): the point a click would take.
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 50 })).unwrap();
|
||||
s.start("line").unwrap();
|
||||
let q = snap::tracking::CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
|
||||
let r = s.snap_cursor(polar(Vec2::ZERO, 50.4, 33.0), &q);
|
||||
assert_eq!(r.snap.map(|h| h.mode), Some(mode::CEN));
|
||||
assert!(r.point.near(Vec2::ZERO, 1e-9), "{:?}", r.point);
|
||||
}
|
||||
|
||||
/// The arc of the review of #2347 (and #1114's test): center (100,50), radius 80, 30°-150°.
|
||||
fn review_arc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &json!({ "center": [100, 50], "radius": 80, "start": 30, "end": 150 })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_midpoint_under_the_cursor_beats_the_center_from_the_curve() {
|
||||
let s = review_arc();
|
||||
// On the arc's midpoint (100,130) with Center and Midpoint running: Midpoint, as in AutoCAD.
|
||||
for cursor in [Vec2::new(100.05, 130.0), Vec2::new(100.2, 130.1)] {
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
|
||||
}
|
||||
// Elsewhere on the arc, with no snap point in the aperture, the center from the curve.
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(100.0, 50.0), 80.1, 70.0), 0.5, mode::CEN | mode::MID).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(100.0, 50.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quadrant_under_the_cursor_beats_the_center_from_the_curve() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [20, 0], "radius": 2 })).unwrap();
|
||||
let cursor = Vec2::new(20.1, 2.0);
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
|
||||
assert_eq!(snap_at(&s, cursor, 0.5, mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
|
||||
// Away from the quadrants the center from the curve.
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(20.0, 0.0), 2.1, 45.0), 0.5, mode::CEN | mode::QUA).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(20.0, 0.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_straight_segments_do_not_hide_a_circle_from_center() {
|
||||
// A polyline of 2,500 straight segments zigzagging over the cursor, then a circle: the
|
||||
// work limit counts circles and arcs only, so the circle's center is still found.
|
||||
let mut s = Session::new();
|
||||
let vertices: Vec<[f64; 2]> = (0..=2500).map(|i| [i as f64 * 0.04, if i % 2 == 0 { 0.0 } else { 100.0 }]).collect();
|
||||
s.execute("pline", &json!({ "vertices": vertices })).unwrap();
|
||||
s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap();
|
||||
let (p, m) = snap_at(&s, polar(Vec2::new(50.0, 50.0), 20.2, 100.0), 0.5, mode::CEN).unwrap();
|
||||
assert_eq!(m, mode::CEN);
|
||||
assert!(p.near(Vec2::new(50.0, 50.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_viewport_center_keeps_its_curve_distance_against_paper_space() {
|
||||
use cadcraft_engine::doc::{Circle, Drawing, Viewport};
|
||||
let mut d = Drawing::new_imperial();
|
||||
let paper = Space::Paper("Layout1".into());
|
||||
// Model circle (10,0) r16 seen through a viewport at half scale: paper center (100,50), radius 8.
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(10.0, 0.0, 0.0), radius: 16.0 })).unwrap();
|
||||
let vp = Viewport {
|
||||
center: Vec3::new(100.0, 50.0, 0.0),
|
||||
width: 20.0,
|
||||
height: 20.0,
|
||||
view_center: Vec2::new(10.0, 0.0),
|
||||
view_height: 40.0,
|
||||
id: 2,
|
||||
locked: false,
|
||||
frozen_layers: Vec::new(),
|
||||
layer_colors: Vec::new(),
|
||||
clip: None,
|
||||
on: true,
|
||||
twist: 0.0,
|
||||
..Default::default()
|
||||
};
|
||||
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||||
// A small paper-space circle whose curve passes 0.3 from the cursor and whose center is
|
||||
// nearer the cursor (3.3) than the model circle's (8).
|
||||
d.add(&paper, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(108.0, 53.3, 0.0), radius: 3.0 })).unwrap();
|
||||
// The cursor is on the model circle (0.1 off in paper units): its center wins.
|
||||
let h = snap::osnap(&d, &paper, Vec2::new(108.1, 50.0), 0.5, mode::CEN, None, false).unwrap();
|
||||
assert_eq!(h.mode, mode::CEN);
|
||||
assert!(h.point.near(Vec2::new(100.0, 50.0), 1e-9), "{h:?}");
|
||||
assert!(h.viewport.is_some());
|
||||
// On the paper circle, away from the model one: its center.
|
||||
let h = snap::osnap(&d, &paper, Vec2::new(108.0, 56.35), 0.5, mode::CEN, None, false).unwrap();
|
||||
assert!(h.point.near(Vec2::new(108.0, 53.3), 1e-9), "{h:?}");
|
||||
assert!(h.viewport.is_none());
|
||||
}
|
||||
@@ -70,6 +70,9 @@ fn elliptical_arc_perpendicular_and_tangent_from_a_base_point() {
|
||||
let (q, m) = along_quarter(&s, mode::TAN, Some(base)).expect("a tangent point on the arc");
|
||||
assert_eq!(m, mode::TAN);
|
||||
assert!(on_quarter(q) && Vec2::new(q.x / 16.0, q.y / 4.0).dot(q - base).abs() < 1e-9, "{q:?}");
|
||||
// The same tangent at a prompt that resolves deferred snaps (CIRCLE's 3P points, #1512).
|
||||
let h = snap::osnap(s.doc().unwrap(), &Space::Model, q, 0.3, mode::TAN, Some(base), true).expect("tangent at a deferred prompt");
|
||||
assert!(h.mode == mode::TAN && h.deferred.is_none() && h.point.near(q, 1e-9), "{h:?}");
|
||||
// Perpendicular from (10,10): the line from the base runs along the normal.
|
||||
let base = Vec2::new(10.0, 10.0);
|
||||
let (q, m) = along_quarter(&s, mode::PER, Some(base)).expect("a perpendicular foot on the arc");
|
||||
@@ -119,3 +122,28 @@ fn spline_midpoint_perpendicular_and_tangent() {
|
||||
let d = (sp.eval(i + 1e-6) - sp.eval(i - 1e-6)).normalized();
|
||||
assert!(d.cross((q - base).normalized()).abs() < 1e-3, "the line from the base runs along the curve at {q:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perpendicular_from_an_arcs_center_stays_on_the_arc() {
|
||||
// From the center of an arc every point is perpendicular: the one under the cursor, never a
|
||||
// point of its circle outside the sweep.
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &serde_json::json!({"center": [0, 0], "radius": 10, "start": 90, "end": 180})).unwrap();
|
||||
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, Vec2::new(-6.0, 8.0), 0.3, mode::PER, Some(Vec2::ZERO), false);
|
||||
let (p, m) = hit.map(|h| (h.point, h.mode)).expect("a perpendicular on the arc");
|
||||
assert_eq!(m, mode::PER);
|
||||
assert!(p.near(Vec2::new(-6.0, 8.0), 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perpendicular_to_a_ray_needs_the_cursor_on_the_ray() {
|
||||
// A ray along +X from the origin: behind its start the cursor is over nothing.
|
||||
let mut s = Session::new();
|
||||
s.execute("ray", &serde_json::json!({"base": [0, 0], "through": [10, 0]})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let base = Some(Vec2::new(5.0, 3.0));
|
||||
assert_eq!(snap::osnap(d, &Space::Model, Vec2::new(-2.0, 0.0), 0.5, mode::PER, base, false), None);
|
||||
// Over the ray, the foot is found.
|
||||
let hit = snap::osnap(d, &Space::Model, Vec2::new(2.0, 0.0), 0.5, mode::PER, base, false).expect("the foot on the ray");
|
||||
assert!(hit.point.near(Vec2::new(5.0, 0.0), 1e-9), "{hit:?}");
|
||||
}
|
||||
|
||||
@@ -21,6 +21,17 @@ fn last_line(s: &Session) -> (Vec2, Vec2) {
|
||||
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).last().unwrap()
|
||||
}
|
||||
|
||||
/// The last circle drawn as (center, radius).
|
||||
fn last_circle(s: &Session) -> (Vec2, f64) {
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some((c.center.xy(), c.radius)) } else { None })
|
||||
.last()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn near(p: Vec2, x: f64, y: f64) -> bool {
|
||||
p.near(Vec2::new(x, y), 1e-9)
|
||||
}
|
||||
@@ -80,6 +91,23 @@ fn nothing_to_snap_to_rejects_the_point() {
|
||||
assert!(near(s.last_point, 10.0, 10.0));
|
||||
}
|
||||
|
||||
/// #2800: a typed PER or TAN finds its point from a pick anywhere on the object, as in AutoCAD.
|
||||
/// The pick used to have to land within the aperture (0.125 here) of the foot or tangent point,
|
||||
/// which you can't know in advance; elsewhere it said "No Perpendicular found".
|
||||
#[test]
|
||||
fn typed_per_and_tan_snap_from_anywhere_on_the_object() {
|
||||
let mut s = drawing();
|
||||
// From (5,5), PER picked at (3,0) on the line 0,0–10,0: two units from the foot (5,0).
|
||||
s.script("LINE 5,5 PER 3,0\n\n").unwrap();
|
||||
let (a, b) = last_line(&s);
|
||||
assert!(near(a, 5.0, 5.0) && near(b, 5.0, 0.0), "{a:?} {b:?}");
|
||||
// From (30,20), TAN picked at the top of the circle (centre 20,20, radius 3): the tangent
|
||||
// points are at cos = 3/10 from the line to the base, and the upper one is nearer the pick.
|
||||
s.script("LINE 30,20 TAN 20,23\n\n").unwrap();
|
||||
let (a, b) = last_line(&s);
|
||||
assert!(near(a, 30.0, 20.0) && near(b, 20.9, 20.0 + 3.0 * 0.91f64.sqrt()), "{a:?} {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_nests_with_a_snap_override() {
|
||||
let mut s = drawing();
|
||||
@@ -116,3 +144,97 @@ fn a_command_keyword_wins_over_a_snap_word() {
|
||||
s.cmdline("arc _cen").unwrap();
|
||||
assert!(s.prompt_text().ends_with("Center of:"), "{}", s.prompt_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_circle_radius_touches_the_picked_circle() {
|
||||
// #1512: the circle around the center that touches the circle at 20,20 radius 3, on the side
|
||||
// it was picked: the near side (radius 7), the far side (13), and through Diameter.
|
||||
for (script, center, r) in [
|
||||
("CIRCLE 30,20 TAN 23.02,20.03\n", (30.0, 20.0), 7.0),
|
||||
("CIRCLE 30,20 TAN 16.98,19.97\n", (30.0, 20.0), 13.0),
|
||||
("CIRCLE 20,10 D TAN 20.03,17.02\n", (20.0, 10.0), 7.0),
|
||||
] {
|
||||
let mut s = drawing();
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
let (c, got) = last_circle(&s);
|
||||
assert!(near(c, center.0, center.1) && (got - r).abs() < 1e-9, "{script}: {c:?} r={got}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_touches_the_picked_circles() {
|
||||
// #1512: through two points and tangent to the circle at 20,20 radius 3, the tangent pick
|
||||
// first or last.
|
||||
for script in ["CIRCLE 3P 26,20 26,26 TAN 23.02,20.03\n", "CIRCLE 3P TAN 23.02,20.03 26,20 26,26\n"] {
|
||||
let mut s = drawing();
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
let (c, r) = last_circle(&s);
|
||||
assert!((c.dist(Vec2::new(26.0, 20.0)) - r).abs() < 1e-9 && (c.dist(Vec2::new(26.0, 26.0)) - r).abs() < 1e-9, "{script}");
|
||||
assert!((c.dist(Vec2::new(20.0, 20.0)) - (3.0 + r)).abs() < 1e-9, "{script}: {c:?} r={r}");
|
||||
}
|
||||
// Tan, Tan, Tan: the circle between three circles of radius 1, picked on their inner sides.
|
||||
let mut s = Session::new();
|
||||
s.script("CIRCLE 0,0 1\nCIRCLE 6,0 1\nCIRCLE 3,5 1\nCIRCLE 3P TAN 0.98,0.2 TAN 5.02,0.2 TAN 3.01,3.98\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (c, r) = last_circle(&s);
|
||||
for k in [(0.0, 0.0), (6.0, 0.0), (3.0, 5.0)] {
|
||||
assert!((c.dist(Vec2::new(k.0, k.1)) - (1.0 + r)).abs() < 1e-9, "{c:?} r={r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_touches_an_arc_within_its_sweep() {
|
||||
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
|
||||
// on the right or the far left, both off an arc swept from 90° to 100°: no circle.
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 90, "end": 100})).unwrap();
|
||||
s.script("CIRCLE 3P 26,20 26,26 TAN 19.74,22.99\n").unwrap();
|
||||
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
|
||||
assert!(!s.doc().unwrap().model.iter().any(|e| matches!(e.kind, EntityKind::Circle(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_takes_the_solution_that_touches_the_arc() {
|
||||
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
|
||||
// at about 29.6° and -103.3°. Picked at 20° on an arc swept from 200° to 25°, the 29.6°
|
||||
// circle is nearer the pick but off the arc: the -103.3° one (radius 6.0826) is drawn.
|
||||
let mut s = Session::new();
|
||||
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 200, "end": 25})).unwrap();
|
||||
s.script("CIRCLE 3P 26,20 26,26 TAN 22.82,21.03\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (c, r) = last_circle(&s);
|
||||
assert!((c.dist(Vec2::new(20.0, 20.0)) - (r - 3.0)).abs() < 1e-9 && (r - 6.082575694955838).abs() < 1e-9, "{c:?} r={r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_circle_radius_refuses_the_picked_circles_own_center() {
|
||||
// #1512: a circle around 20,20 would lie on the circle there, not touch it.
|
||||
let mut s = drawing();
|
||||
s.script("CIRCLE 20,20 TAN 23.02,20.03\n").unwrap();
|
||||
assert!(s.prompt_text().contains("radius of circle"), "{}", s.prompt_text());
|
||||
assert!(s.log.iter().any(|l| l.contains("No circle around the center is tangent there.")), "{:?}", s.log);
|
||||
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_refuses_the_picked_circle_itself() {
|
||||
// #1512: tangent twice to the circle and through a point on it is only the circle itself.
|
||||
let mut s = drawing();
|
||||
s.script("CIRCLE 3P TAN 23.02,20.03 TAN 16.98,20.03 20,23\n").unwrap();
|
||||
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
|
||||
assert!(s.log.iter().any(|l| l.contains("Circle does not exist.")), "{:?}", s.log);
|
||||
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tan_for_a_3p_circle_through_points_in_line_with_the_picked_circles_center() {
|
||||
// Through 3,0 and 5,0 and tangent to the unit circle at the origin: the two points and that
|
||||
// circle's center lie on one line, the circle that touches it does not (center 4,±√48, radius 7).
|
||||
let mut s = Session::new();
|
||||
s.script("CIRCLE 0,0 1\nCIRCLE 3P 3,0 5,0 TAN 1,0\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let (c, r) = last_circle(&s);
|
||||
assert!(near(Vec2::new(c.x, c.y.abs()), 4.0, 48f64.sqrt()) && (r - 7.0).abs() < 1e-9, "{c:?} r={r}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Tab cycling through object snaps: a crowd of candidates is capped, hostile cursors and
|
||||
//! apertures give no candidates, and the list never repeats a snap.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Space;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_engine::pointmod::snap_candidates;
|
||||
use cadcraft_engine::snap::mode;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn a_crowd_of_snaps_is_capped_and_never_repeats() {
|
||||
let mut s = Session::new();
|
||||
// 600 short lines fanning out from points packed round the origin: 1,200 endpoints.
|
||||
for i in 0..600 {
|
||||
let a = f64::from(i) * 0.01;
|
||||
let p = [1e-3 * a.cos(), 1e-3 * a.sin()];
|
||||
s.execute("line", &json!({ "points": [p, [a.cos(), a.sin()]] })).unwrap();
|
||||
}
|
||||
let d = s.doc().unwrap();
|
||||
let cands = snap_candidates(d, &Space::Model, Vec2::ZERO, 0.5, mode::END | mode::INT | mode::NEA, None, false);
|
||||
assert!(!cands.is_empty());
|
||||
assert!(cands.len() <= 257, "{} candidates", cands.len());
|
||||
for (i, a) in cands.iter().enumerate() {
|
||||
assert!(a.point.is_finite());
|
||||
assert!(!cands.iter().skip(i + 1).any(|b| b.mode == a.mode && b.point == a.point), "{a:?} repeats");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_cursor_and_aperture_give_no_candidates() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let space = Space::Model;
|
||||
let all = mode::END | mode::MID | mode::INT | mode::NEA | mode::PER;
|
||||
for (c, ap) in [
|
||||
(Vec2::new(f64::NAN, 0.0), 0.5),
|
||||
(Vec2::new(0.0, f64::INFINITY), 0.5),
|
||||
(Vec2::ZERO, f64::NAN),
|
||||
(Vec2::ZERO, 0.0),
|
||||
(Vec2::ZERO, -1.0),
|
||||
(Vec2::ZERO, f64::INFINITY),
|
||||
] {
|
||||
assert!(snap_candidates(d, &space, c, ap, all, None, false).is_empty(), "{c:?} {ap}");
|
||||
assert!(snap_candidates(d, &space, c, ap, all, Some(Vec2::new(f64::NAN, 1.0)), true).is_empty(), "{c:?} {ap}");
|
||||
}
|
||||
// A huge but finite aperture still answers, from the objects there are.
|
||||
let far = snap_candidates(d, &space, Vec2::ZERO, 1e300, mode::END, None, false);
|
||||
assert!(far.iter().all(|h| h.point.is_finite()));
|
||||
// Object snaps off (or only the OFF bit) offer nothing.
|
||||
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, 0, None, false).is_empty());
|
||||
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, mode::END | mode::OFF, None, false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_endpoint_under_the_aperture_is_offered_not_one_per_mode() {
|
||||
let mut s = Session::new();
|
||||
// Three line ends close together, all within the aperture of the cursor between them.
|
||||
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
|
||||
s.execute("line", &json!({ "points": [a, b] })).unwrap();
|
||||
}
|
||||
let d = s.doc().unwrap();
|
||||
let cands = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false);
|
||||
let ends: Vec<Vec2> = cands.iter().filter(|h| h.mode == mode::END).map(|h| h.point).collect();
|
||||
assert_eq!(ends.len(), 3, "{cands:?}");
|
||||
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
|
||||
assert!(ends.iter().any(|p| p.near(want, 1e-12)), "{want:?} in {ends:?}");
|
||||
}
|
||||
// The first is the snap a click would take.
|
||||
let first = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).first().map(|h| h.point);
|
||||
assert_eq!(first, cadcraft_engine::snap::osnap(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).map(|h| h.point));
|
||||
}
|
||||
|
||||
/// A base point that is not a number gives no candidates, though the cursor is on an endpoint: the
|
||||
/// perpendicular and tangent points from it would be meaningless, as a viewport already treats it.
|
||||
#[test]
|
||||
fn a_non_finite_base_gives_no_candidates() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let all = mode::END | mode::PER | mode::TAN | mode::NEA;
|
||||
for base in [Vec2::new(f64::NAN, 1.0), Vec2::new(1.0, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NAN)] {
|
||||
assert!(snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), false).is_empty(), "{base:?}");
|
||||
assert!(cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), true).is_empty(), "{base:?}");
|
||||
}
|
||||
// A finite base still offers them.
|
||||
assert!(!snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(Vec2::new(5.0, 5.0)), false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deferred_snaps_of_two_curves_at_one_point_are_both_offered() {
|
||||
// Two circles touching at the origin: each offers its own deferred tangent there, and the
|
||||
// line drawn from it depends on which circle it is.
|
||||
let mut s = Session::new();
|
||||
s.script("CIRCLE 0,1 1\nCIRCLE 0,-2 2\n").unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let all = cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(0.0, 0.1), 0.5, mode::TAN, None, true);
|
||||
let curves: Vec<_> = all.iter().filter_map(|h| h.deferred.map(|f| f.curve)).collect();
|
||||
assert_eq!(curves.len(), 2, "{all:?}");
|
||||
assert_ne!(curves.first(), curves.get(1), "{all:?}");
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,9 @@
|
||||
//! CADCraft keeps an annotative object at paper size with the list of scales it supports
|
||||
//! ([`cadcraft_doc::Common::anno_scales`]). It writes the object at its default scale with a
|
||||
//! context per scale ([`plan`], [`objects`]), and reads the scales and paper size back from the
|
||||
//! contexts ([`resolve`]). An object's position at each scale is the one the scale gives it:
|
||||
//! AutoCAD lets a context move an object at one scale only, which CADCraft doesn't model.
|
||||
//! contexts ([`resolve`]). A context can place the object somewhere else at its scale (moved with
|
||||
//! grips at that scale in AutoCAD or CADCraft): that is the object's offset at the scale
|
||||
//! ([`cadcraft_doc::AnnoMove`]), written into and read back from the context's position.
|
||||
//!
|
||||
//! Objects inside block definitions are left alone, and files older than AutoCAD 2007's format
|
||||
//! (before annotation scaling) don't get contexts.
|
||||
@@ -67,8 +68,16 @@ fn by_alignment(t: &Text) -> bool {
|
||||
|
||||
/// `e` at annotation scale `f`, as its groups are written there: sizes scaled (see
|
||||
/// [`cadcraft_doc::anno_scaled`]) and justified text's start point moved with its size about its
|
||||
/// alignment point. A dimension's definition gets that scale (DIMSCALE).
|
||||
/// alignment point. A dimension's definition gets that scale (DIMSCALE). The object's offset at
|
||||
/// that scale moves it there.
|
||||
pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity {
|
||||
let mut out = shared_at_scale(e, f);
|
||||
cadcraft_doc::shift_position(&mut out.kind, e.common.moved_at_factor(f));
|
||||
out
|
||||
}
|
||||
|
||||
/// [`at_scale`] at the object's shared position (without its offset there).
|
||||
fn shared_at_scale(e: &Entity, f: f64) -> Entity {
|
||||
let mut out = cadcraft_doc::anno_scaled(e, f);
|
||||
if let (EntityKind::Text(t), EntityKind::Text(paper)) = (&mut out.kind, &e.kind)
|
||||
&& by_alignment(paper)
|
||||
@@ -79,6 +88,47 @@ pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity {
|
||||
out
|
||||
}
|
||||
|
||||
/// The point that places `e` (as written at some scale): a text's start or alignment point, an
|
||||
/// MText's insertion point, a dimension's text position, a multileader's landing.
|
||||
fn anchor(d: &Drawing, e: &Entity) -> Option<cadcraft_geom::Vec2> {
|
||||
let p = match &e.kind {
|
||||
EntityKind::Text(t) if by_alignment(t) => t.align_pt?.xy(),
|
||||
EntityKind::Text(t) => t.insert.xy(),
|
||||
EntityKind::MText(t) => t.insert.xy(),
|
||||
EntityKind::Dimension(dm) if dm.user_text_pos => dm.text_mid.xy(),
|
||||
EntityKind::Dimension(dm) => cadcraft_render::dimension_in(d, dm).text_pos,
|
||||
EntityKind::MLeader(m) => m.landing.xy(),
|
||||
_ => return None,
|
||||
};
|
||||
p.is_finite().then_some(p)
|
||||
}
|
||||
|
||||
/// The same point as a context of `e` holds it (`g`: the context's groups after its SCALE
|
||||
/// handle).
|
||||
fn context_anchor(e: &Entity, g: &[Tag]) -> Option<cadcraft_geom::Vec2> {
|
||||
let xy = |code: i32| -> Option<cadcraft_geom::Vec2> {
|
||||
let i = g.iter().position(|t| t.code == code)?;
|
||||
let y = g.get(i + 1).filter(|t| t.code == code + 10)?;
|
||||
let v = cadcraft_geom::Vec2::new(g.get(i)?.f64(), y.f64());
|
||||
v.is_finite().then_some(v)
|
||||
};
|
||||
match &e.kind {
|
||||
EntityKind::Text(t) if by_alignment(t) => xy(11),
|
||||
EntityKind::Text(_) => xy(10),
|
||||
EntityKind::MText(_) => xy(11),
|
||||
// Only a text the user placed (294 = 0) holds its own position.
|
||||
EntityKind::Dimension(_) => g.iter().find(|t| t.code == 294).is_some_and(|t| t.i64() == 0).then(|| xy(10)).flatten(),
|
||||
EntityKind::MLeader(_) => {
|
||||
let mut tags = vec![Tag::s(100, "AcDbMLeader"), Tag::s(300, "CONTEXT_DATA{")];
|
||||
tags.extend(g.iter().cloned());
|
||||
tags.push(Tag::s(301, "}"));
|
||||
let p = crate::dxf_mleader::read(&tags).landing.xy();
|
||||
p.is_finite().then_some(p)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One context: its handle, the SCALE object's handle and the scale.
|
||||
pub(crate) struct Context {
|
||||
handle: String,
|
||||
@@ -347,6 +397,16 @@ pub(crate) fn mleader_at(tags: &mut [Tag], f: f64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A multileader's groups (as [`crate::dxf_mleader::entity_tags`] writes them) marked annotative:
|
||||
/// the entity's "enable annotation scale" (its 293, after the `CONTEXT_DATA{` block) is on.
|
||||
/// Without it AutoCAD keeps the contexts but its ANNORESET passes the multileader over.
|
||||
pub(crate) fn mleader_annotative(tags: &mut [Tag]) {
|
||||
let Some(close) = tags.iter().position(|t| t.code == 301) else { return };
|
||||
if let Some(t) = tags.iter_mut().skip(close + 1).find(|t| t.code == 293) {
|
||||
*t = Tag::i(293, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Reading
|
||||
|
||||
@@ -422,6 +482,7 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
.and_then(|s| objs.get(&s));
|
||||
let Some((_, dict)) = dict else { continue };
|
||||
let mut list: Vec<(AnnoScale, bool)> = Vec::new();
|
||||
let mut placed: Vec<(String, f64, cadcraft_geom::Vec2)> = Vec::new();
|
||||
for c in all_entries(dict) {
|
||||
let Some((_, t)) = objs.get(&c).filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) else { continue };
|
||||
let g = own(t);
|
||||
@@ -431,6 +492,10 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
&& !list.iter().any(|(x, _)| x.name.eq_ignore_ascii_case(&s.name))
|
||||
{
|
||||
list.push((s.clone(), default));
|
||||
let after = g.iter().position(|t| t.code == 340).map_or(&[][..], |i| g.get(i + 1..).unwrap_or(&[]));
|
||||
if let Some(at) = context_anchor(e, after) {
|
||||
placed.push((s.name.clone(), s.factor(), at));
|
||||
}
|
||||
}
|
||||
}
|
||||
if list.is_empty() {
|
||||
@@ -443,6 +508,23 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
e.common.anno_scales = list;
|
||||
to_paper(e, f);
|
||||
});
|
||||
// A context placing the object elsewhere than its scale would: its offset there.
|
||||
let Some(e) = d.entity(h).map(|e| (**e).clone()) else { continue };
|
||||
let moves: Vec<(String, cadcraft_geom::Vec2)> = placed
|
||||
.iter()
|
||||
.filter_map(|(name, f, at)| {
|
||||
let by = *at - anchor(d, &shared_at_scale(&e, *f))?;
|
||||
let tol = 1e-6 * (1.0 + at.len());
|
||||
(by.is_finite() && by.len() > tol).then(|| (name.clone(), by))
|
||||
})
|
||||
.collect();
|
||||
if !moves.is_empty() {
|
||||
let _ = d.modify_entity(h, |e| {
|
||||
for (name, by) in &moves {
|
||||
e.common.move_at(name, *by);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1024,6 +1024,11 @@ pub(crate) struct AnnoPayload {
|
||||
struct AnnoObject {
|
||||
handle: String,
|
||||
scales: Vec<cadcraft_doc::AnnoScale>,
|
||||
/// Where the object sits at a scale when it was moved there alone (see `Common::anno_moves`):
|
||||
/// a format without annotation scale contexts (or a DWG, whose bridge doesn't convert them
|
||||
/// yet) keeps them here.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
moves: Vec<cadcraft_doc::AnnoMove>,
|
||||
}
|
||||
|
||||
/// Most annotative objects read from one file.
|
||||
@@ -1041,7 +1046,7 @@ pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing, contexts: bool) -> Option<V
|
||||
.iter()
|
||||
.chain(d.layouts.iter().flat_map(|l| l.entities.iter()))
|
||||
.filter(|e| cadcraft_doc::is_annotative(e) && !(contexts && crate::dxf_anno::has_contexts(e)))
|
||||
.map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone() })
|
||||
.map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone(), moves: e.common.anno_moves.clone() })
|
||||
.collect();
|
||||
if cannoscale == "1:1" && annoallvisible == 1 && blocks.is_empty() && objects.is_empty() {
|
||||
return None;
|
||||
@@ -1102,9 +1107,18 @@ pub(crate) fn apply_anno(d: &mut cadcraft_doc::Drawing, p: AnnoPayload) {
|
||||
scales.push(s);
|
||||
}
|
||||
}
|
||||
// Each move once, for a scale the object keeps, by a finite offset.
|
||||
let mut moves: Vec<cadcraft_doc::AnnoMove> = Vec::new();
|
||||
for m in o.moves.into_iter().take(cadcraft_doc::MAX_SCALES) {
|
||||
let known = scales.iter().any(|s| s.name.eq_ignore_ascii_case(&m.scale));
|
||||
if known && m.by.is_finite() && !moves.iter().any(|x| x.scale.eq_ignore_ascii_case(&m.scale)) {
|
||||
moves.push(m);
|
||||
}
|
||||
}
|
||||
store.modify(h, |e| {
|
||||
if cadcraft_doc::can_be_annotative(&e.kind) {
|
||||
e.common.anno_scales = scales;
|
||||
e.common.anno_moves = moves;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+65
-25
@@ -16,7 +16,9 @@ use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
|
||||
use cadcraft_doc::foreign::{
|
||||
Foreign, ForeignExtra, ForeignKey, ForeignObject, VertexId, class_group, class_index, class_number, proxy_has_string_stream,
|
||||
};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
|
||||
use craft_dxf::{SectionRef, Tag, Version};
|
||||
|
||||
@@ -83,6 +85,8 @@ fn leader_acad_rest(chunk: &[Tag]) -> Vec<Tag> {
|
||||
|
||||
/// Most objects kept from one file.
|
||||
const MAX_OBJECTS: usize = 1_000_000;
|
||||
/// Most vertices of one polyline whose identifiers are kept.
|
||||
const MAX_VERTEX_IDS: usize = 1_000_000;
|
||||
/// Most xdata groups kept per record (AutoCAD allows 16 KB of xdata per object).
|
||||
const MAX_XDATA_GROUPS: usize = cadcraft_doc::MAX_XDATA_GROUPS;
|
||||
/// Longest ownership chain followed.
|
||||
@@ -345,9 +349,57 @@ fn extra(kind: &str, tags: &[Tag], entity: bool, unknown: bool, kept: &HashSet<S
|
||||
}
|
||||
x.props = props.iter().filter(|t| matches!(t.code, 347 | 284)).map(raw).collect();
|
||||
}
|
||||
if entity && !unknown && kind == "LWPOLYLINE" {
|
||||
x.vertex_ids = vertex_ids(tags);
|
||||
}
|
||||
x
|
||||
}
|
||||
|
||||
/// A LWPOLYLINE record's vertices with their identifiers (group 91 after a vertex's point): one
|
||||
/// per vertex, identifier 0 for a vertex without one; empty when no vertex has one
|
||||
/// ([`ForeignExtra::vertex_ids`]). The points are as the reader gives them: mirrored in x when
|
||||
/// the normal points down. Groups inside an application's `102 {` … `102 }` are not the
|
||||
/// polyline's.
|
||||
fn vertex_ids(tags: &[Tag]) -> Vec<VertexId> {
|
||||
let mut in_app = false;
|
||||
let own_tags: Vec<&Tag> = tags
|
||||
.iter()
|
||||
.take_while(|t| t.code < 1000)
|
||||
.filter(|t| {
|
||||
if t.code == 102 {
|
||||
in_app = t.str().trim_start().starts_with('{');
|
||||
return false;
|
||||
}
|
||||
!in_app
|
||||
})
|
||||
.collect();
|
||||
let own = || own_tags.iter().copied();
|
||||
let down = own().any(|t| t.code == 230 && t.f64() < 0.0);
|
||||
if !own().any(|t| t.code == 91 && t.i64() != 0) {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut ids: Vec<VertexId> = Vec::new();
|
||||
for t in own() {
|
||||
match t.code {
|
||||
// A polyline past the cap keeps none: identifiers for some of its vertices would be wrong.
|
||||
10 if ids.len() >= MAX_VERTEX_IDS => return Vec::new(),
|
||||
10 => ids.push(VertexId { id: 0, x: if down { -t.f64() } else { t.f64() }, y: 0.0 }),
|
||||
20 => {
|
||||
if let Some(last) = ids.last_mut() {
|
||||
last.y = t.f64();
|
||||
}
|
||||
}
|
||||
91 => {
|
||||
if let Some(last) = ids.last_mut() {
|
||||
last.id = i32::try_from(t.i64()).unwrap_or(0);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// Every entity of the drawing (model space, layouts, blocks).
|
||||
fn all_entities(d: &Drawing) -> impl Iterator<Item = &Entity> {
|
||||
std::iter::once(&d.model)
|
||||
@@ -1809,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(),
|
||||
};
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
use super::{
|
||||
Block, Color, Common, Dimension, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext,
|
||||
};
|
||||
use super::{Block, Color, Common, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext};
|
||||
|
||||
/// What happens to the dimension blocks read from a file (#495): a dimension that still names
|
||||
/// its block is written with that block, under its name, and `*D` blocks nothing else
|
||||
@@ -79,81 +77,6 @@ pub(super) fn reuse_handles(ents: &mut [Entity], old: &Block, taken: &mut std::c
|
||||
}
|
||||
}
|
||||
|
||||
/// Anonymous dimension blocks (`*D1`…) with the rendered geometry, as consumers expect.
|
||||
pub(super) fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Vec<Entity> {
|
||||
// The dimension as drawn: its overrides, DIMSCALE (0 = the drawing's) and text font.
|
||||
let style = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
|
||||
let g = cadcraft_render::dimension_in(d, dm);
|
||||
let mut out = Vec::new();
|
||||
// Each part in its style colour (DIMCLRD, DIMCLRE, DIMCLRT), ByBlock when the style says so,
|
||||
// as AutoCAD writes them: readers that draw the block drew every part ByBlock, i.e. in the
|
||||
// dimension's own colour (#1052).
|
||||
let in_color = |color: Color| Common { layer: layer.into(), color, ..Common::default() };
|
||||
let (dim_c, ext_c, text_c) = (in_color(style.dim_line_color), in_color(style.ext_line_color), in_color(style.text_color));
|
||||
let line_entities = |i: usize, l: &[Vec2]| -> Vec<Entity> {
|
||||
let c = match g.line_roles.get(i) {
|
||||
Some(cadcraft_render::LineRole::Ext) => &ext_c,
|
||||
_ => &dim_c,
|
||||
};
|
||||
l.windows(2)
|
||||
.filter_map(|seg| match seg {
|
||||
[a, b] => Some(Entity { handle: Handle(0), common: c.clone(), kind: EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) }) }),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// The text's marks (arc length symbol, DIMINSPECT frame) go after the text background.
|
||||
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| !g.text_marks.contains(i)) {
|
||||
out.extend(line_entities(i, l));
|
||||
}
|
||||
for t in &g.fills {
|
||||
if let [a, b, cc] = t.as_slice() {
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: dim_c.clone(),
|
||||
kind: EntityKind::Solid(Solid { corners: [a.to3(0.0), b.to3(0.0), cc.to3(0.0), cc.to3(0.0)] }),
|
||||
});
|
||||
}
|
||||
}
|
||||
// DIMTFILL 2: the text background in DIMTFILLCLR, under the text and its marks (SOLID
|
||||
// corners go 1, 2, 4, 3).
|
||||
if style.text_fill == 2
|
||||
&& let [p0, p1, p2, p3] = g.text_fill.as_slice()
|
||||
{
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: in_color(style.text_fill_color),
|
||||
kind: EntityKind::Solid(Solid { corners: [p0.to3(0.0), p1.to3(0.0), p3.to3(0.0), p2.to3(0.0)] }),
|
||||
});
|
||||
}
|
||||
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| g.text_marks.contains(i)) {
|
||||
out.extend(line_entities(i, l));
|
||||
}
|
||||
// The text, and the part after `\X` below the dimension line as a second MTEXT, as AutoCAD
|
||||
// writes it (#1055).
|
||||
let texts = std::iter::once((g.value.clone(), g.text_pos)).chain(g.below.clone());
|
||||
for (contents, at) in texts.filter(|(t, _)| !t.is_empty()) {
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: text_c.clone(),
|
||||
kind: EntityKind::MText(MText {
|
||||
insert: at.to3(0.0),
|
||||
height: g.text_height,
|
||||
width: 0.0,
|
||||
attach: 5,
|
||||
rotation: g.text_angle,
|
||||
style: style.text_style.clone(),
|
||||
contents: cadcraft_render::DimGeometry::mtext_code(&contents),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Rows and columns written for a table (bounded like the renderer).
|
||||
pub(super) fn table_size(t: &Table) -> (usize, usize) {
|
||||
(t.row_heights.len().min(10_000), t.col_widths.len().min(10_000))
|
||||
|
||||
@@ -169,7 +169,11 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
w.f(38, elevation);
|
||||
}
|
||||
thickness(w, e);
|
||||
for v in &p.vertices {
|
||||
// The vertex identifiers the file gave the polyline (DXF 2010 and later), while its
|
||||
// vertices are where they were read: geometric constraints name its segments by them.
|
||||
let kept = d.foreign.entities.get(&e.handle).map(|x| x.vertex_ids.as_slice()).filter(|_| cx.target >= Version::R2010);
|
||||
let ids = kept.and_then(|kept| cadcraft_doc::foreign::vertex_ids_for(kept, p.vertices.iter().map(|v| (v.p.x, v.p.y))));
|
||||
for (i, v) in p.vertices.iter().enumerate() {
|
||||
w.p2(10, v.p);
|
||||
if v.start_width != 0.0 || v.end_width != 0.0 {
|
||||
w.f(40, v.start_width);
|
||||
@@ -178,6 +182,9 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
if v.bulge != 0.0 {
|
||||
w.f(42, v.bulge);
|
||||
}
|
||||
if let Some(id) = ids.as_ref().and_then(|ids| ids.get(i)).filter(|id| **id != 0) {
|
||||
w.i(91, i64::from(*id));
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::MLine(m) => {
|
||||
@@ -671,6 +678,7 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap
|
||||
let mut tags = cx.mleader_tags(d, m);
|
||||
if let Some(o) = cx.anno.objs.get(&e.handle) {
|
||||
crate::dxf_anno::mleader_at(&mut tags, crate::dxf_anno::default_factor(o));
|
||||
crate::dxf_anno::mleader_annotative(&mut tags);
|
||||
}
|
||||
w.t.extend(tags);
|
||||
cx.anno_xdata(w, e);
|
||||
|
||||
@@ -51,6 +51,7 @@ const HEADER_VARS: &[(&str, i32)] = &[
|
||||
("PSTYLEMODE", 290),
|
||||
("INSUNITS", 70),
|
||||
("MEASUREMENT", 70),
|
||||
("REGENMODE", 70),
|
||||
("PSLTSCALE", 70),
|
||||
// The model view the drawing is saved at, as DXF keeps it in HEADER (the `*ACTIVE` VPORT
|
||||
// record below repeats it). Written so a drawing opened on its saved view saves it back.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::assoc::std_assoc_refs;
|
||||
use super::blocks::{arrow_block_entities, dim_block_entities, dim_block_plan, reuse_handles, table_block_entities};
|
||||
use super::blocks::{arrow_block_entities, dim_block_plan, reuse_handles, table_block_entities};
|
||||
use super::common::annotative_xdata;
|
||||
use super::ctx::{AssocObj, Ctx};
|
||||
use super::entity::{entity, hatch_reactors};
|
||||
@@ -11,6 +11,7 @@ use super::{
|
||||
Space, TableStyle, Tag, Ucs, Vec2, Vec3, Version, W, dxf_ext,
|
||||
};
|
||||
use super::{entity_handles, structural_start};
|
||||
use cadcraft_render::dim_block_entities;
|
||||
|
||||
struct TableWritePlan<'a> {
|
||||
d: &'a Drawing,
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
/// A DWG hatch's elliptic boundary edge angles, in degrees in the DXF the DWG is read through (#3332).
|
||||
mod dwg_hatch;
|
||||
/// What a DXF file holds that CADCraft doesn't model, kept and written back (#528).
|
||||
mod dxf_raw;
|
||||
|
||||
@@ -103,9 +101,7 @@ pub fn read(bytes: &[u8], name: impl AsRef<Path>) -> Result<Drawing> {
|
||||
pub(crate) fn read_source(bytes: &[u8], name: &Path) -> Result<(Drawing, Option<Vec<u8>>)> {
|
||||
if craft_dwg::is_dwg(bytes) {
|
||||
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(dwg_error)?;
|
||||
// The decoder writes an elliptic hatch edge's angles in radians; DXF keeps degrees.
|
||||
let dxf = dwg_hatch::elliptic_edge_degrees(dxf);
|
||||
let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?;
|
||||
let mut d = dxf_read::read_with_origin(&dxf, true).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?;
|
||||
d.read_notes = notes.into_iter().map(|note| cadcraft_dwg_message(¬e)).collect();
|
||||
return Ok((d, Some(dxf)));
|
||||
}
|
||||
@@ -136,8 +132,8 @@ pub fn write_with(d: &Drawing, name: impl AsRef<Path>, opts: &SaveOptions) -> Re
|
||||
// Before 2007 the text is in the code page the header declares.
|
||||
let code_page = dxf_write::code_page(d, version);
|
||||
Ok(match (opts.binary, version.utf8()) {
|
||||
(true, true) => craft_dxf::write_binary(&tags, true),
|
||||
(true, false) => craft_dxf::write_binary_in(&tags, &code_page),
|
||||
(true, true) => craft_dxf::write_binary(&tags, true).map_err(|e| IoError::Format(e.to_string()))?,
|
||||
(true, false) => craft_dxf::write_binary_in(&tags, &code_page).map_err(|e| IoError::Format(e.to_string()))?,
|
||||
(false, true) => craft_dxf::write_ascii_as(&tags, true).into_bytes(),
|
||||
(false, false) => craft_dxf::write_ascii_in(&tags, &code_page),
|
||||
})
|
||||
|
||||
@@ -287,8 +287,19 @@ impl<'o> Out<'o> {
|
||||
|
||||
/// Header variables that change on every save (time stamps, the handle seed, GUIDs): not
|
||||
/// compared.
|
||||
pub const VOLATILE_HEADER: &[&str] =
|
||||
&["HANDSEED", "TDCREATE", "TDUCREATE", "TDUPDATE", "TDUUPDATE", "TDINDWG", "TDUSRTIMER", "VERSIONGUID", "FINGERPRINTGUID"];
|
||||
/// `CADCRAFT_DIMASO_MODE` is the engine's memory of the mode DIMASO turned off; no file keeps it.
|
||||
pub const VOLATILE_HEADER: &[&str] = &[
|
||||
"HANDSEED",
|
||||
"TDCREATE",
|
||||
"TDUCREATE",
|
||||
"TDUPDATE",
|
||||
"TDUUPDATE",
|
||||
"TDINDWG",
|
||||
"TDUSRTIMER",
|
||||
"VERSIONGUID",
|
||||
"FINGERPRINTGUID",
|
||||
"CADCRAFT_DIMASO_MODE",
|
||||
];
|
||||
|
||||
/// Compare `before` (the drawing as first opened) with `after` (the same drawing saved and
|
||||
/// reopened). Differences are reported as what `after` lost, gained or changed.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! A hatch boundary stored in a DWG as an elliptic edge keeps its sweep: a circle (0 to 2π) stays a
|
||||
//! circle, so the hatch leaves the hole open. The DWG decoder writes the edge's angles in radians
|
||||
//! and DXF reads degrees, so the circle used to come out as an arc of 6.28 degrees.
|
||||
//! circle, so the hatch leaves the hole open. The DWG decoder used to write the edge's angles in radians
|
||||
//! while DXF reads degrees, so the circle came out as an arc of 6.28 degrees.
|
||||
|
||||
// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DXF still works.
|
||||
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
@@ -16,6 +16,10 @@ fn line(a: (f64, f64), b: (f64, f64)) -> BoundaryEdge {
|
||||
/// A DWG with a pattern hatch over a 100 x 100 square with a round hole of radius 10 stored as an
|
||||
/// elliptic edge from `start` to `end` radians.
|
||||
fn dwg_with_hole(start: f64, end: f64) -> Vec<u8> {
|
||||
dwg_with_elliptic_hole(start, end, 1.0)
|
||||
}
|
||||
|
||||
fn dwg_with_elliptic_hole(start: f64, end: f64, ratio: f64) -> Vec<u8> {
|
||||
let mut hatch = Hatch::new();
|
||||
hatch.is_solid = false;
|
||||
let mut outer = BoundaryPath::new();
|
||||
@@ -27,7 +31,7 @@ fn dwg_with_hole(start: f64, end: f64) -> Vec<u8> {
|
||||
hole.edges = vec![BoundaryEdge::EllipticArc(EllipticArcEdge {
|
||||
center: Vector2::new(50.0, 50.0),
|
||||
major_axis_endpoint: Vector2::new(-10.0, 0.0),
|
||||
minor_axis_ratio: 1.0,
|
||||
minor_axis_ratio: ratio,
|
||||
start_angle: start,
|
||||
end_angle: end,
|
||||
counter_clockwise: true,
|
||||
@@ -66,3 +70,10 @@ fn a_quarter_arc_stored_as_an_elliptic_edge_keeps_its_quarter() {
|
||||
// From the point at 0 degrees (60, 50) to the one at 90 degrees (50, 60), closed by a chord: x spans 10.
|
||||
assert!(max - min > 9.9 && max - min < 10.5, "the arc spans {} in x", max - min);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_circular_elliptic_arc_keeps_its_dwg_endpoints() {
|
||||
let (min, max) = hole_extent(&dwg_with_elliptic_hole(std::f64::consts::FRAC_PI_4, std::f64::consts::FRAC_PI_2, 0.5));
|
||||
let expected_min = 50.0 - 10.0 / 2.0_f64.sqrt();
|
||||
assert!((min - expected_min).abs() < 0.02 && (max - 50.0).abs() < 0.02, "arc x range {min}..{max}");
|
||||
}
|
||||
|
||||
@@ -798,3 +798,121 @@ fn the_current_scale_is_autocad_s_and_saving_keeps_it_current() {
|
||||
let var = recs.iter().find(|(k, _)| k == "DICTIONARYVAR").unwrap();
|
||||
assert_eq!(get(&var.1, 1), Some("1:1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_context_placing_the_object_elsewhere_reads_as_its_offset_there() {
|
||||
// The text sits 5 further right at 1:10 than its 1:2 position would put it.
|
||||
let src = FIXTURE.replacen("10 -40\n20 0\n11 30", "10 -35\n20 0\n11 35", 1);
|
||||
assert_ne!(src, FIXTURE);
|
||||
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
let e = d.entity(Handle::parse_hex("30").unwrap()).unwrap();
|
||||
assert_eq!(e.common.anno_moves.len(), 1, "{:?}", e.common.anno_moves);
|
||||
assert_eq!(e.common.anno_moves[0].scale, "1:10");
|
||||
assert!(e.common.anno_moves[0].by.dist(cadcraft_geom::Vec2::new(5.0, 0.0)) < 1e-9);
|
||||
// An unmoved fixture has none.
|
||||
assert!(read().model.iter().all(|e| e.common.anno_moves.is_empty()));
|
||||
// Written back, the 1:10 context keeps its own position.
|
||||
let text = save(&d);
|
||||
let starts: Vec<f64> = contexts_of(&text, "30").iter().map(|c| num(&c.tags, 11)).collect();
|
||||
assert_eq!(starts, [30.0, 35.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offsets_made_in_cadcraft_survive_a_save() {
|
||||
let mut d = made();
|
||||
let hs: Vec<Handle> = d.model.iter().map(|e| e.handle).collect();
|
||||
for h in &hs {
|
||||
d.modify_entity(*h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(3.0, 4.0))).unwrap();
|
||||
}
|
||||
let back = cadcraft_io::read_dxf(save(&d).as_bytes()).unwrap();
|
||||
for h in &hs {
|
||||
let (a, b) = (d.entity(*h).unwrap(), back.entity(*h).unwrap());
|
||||
for f in [1.0, 50.0] {
|
||||
let shown = |d: &Drawing, e: &cadcraft_doc::Entity| match cadcraft_doc::anno_draw(e, f, true) {
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } => match cadcraft_doc::anno_placed(e, factor, by).kind {
|
||||
EntityKind::Text(t) => t.insert.xy(),
|
||||
EntityKind::Dimension(dm) if dm.user_text_pos => dm.text_mid.xy(),
|
||||
EntityKind::Dimension(dm) => cadcraft_render::dimension_in(d, &dm).text_pos,
|
||||
k => panic!("{k:?}"),
|
||||
},
|
||||
m => panic!("{m:?}"),
|
||||
};
|
||||
let (p, q) = (shown(&d, a), shown(&back, b));
|
||||
assert!(p.dist(q) < 1e-6, "{h:?} at {f}: {p:?} vs {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The landing and text of multileader `e` as it shows at annotation scale `f`.
|
||||
fn mleader_shown(e: &cadcraft_doc::Entity, f: f64) -> (cadcraft_geom::Vec2, cadcraft_geom::Vec2) {
|
||||
let cadcraft_doc::AnnoDraw::Scaled { factor, by } = cadcraft_doc::anno_draw(e, f, true) else { panic!("hidden") };
|
||||
let EntityKind::MLeader(m) = cadcraft_doc::anno_placed(e, factor, by).kind else { panic!("multileader") };
|
||||
(m.landing.xy(), m.text.unwrap().insert.xy())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multileader_moved_at_one_scale_keeps_it_through_dxf() {
|
||||
let (mut d, h) = with_mleader();
|
||||
d.modify_entity(h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(2.0, -1.0))).unwrap();
|
||||
let dxf_back = cadcraft_io::read_dxf(save(&d).as_bytes()).unwrap();
|
||||
let a = d.entity(h).unwrap();
|
||||
{
|
||||
let back = &dxf_back;
|
||||
let b = back.model.iter().find(|e| matches!(e.kind, EntityKind::MLeader(_))).unwrap();
|
||||
for f in [1.0, 10.0] {
|
||||
let ((la, ta), (lb, tb)) = (mleader_shown(a, f), mleader_shown(b, f));
|
||||
assert!(la.dist(lb) < 1e-6 && ta.dist(tb) < 1e-6, "at {f}: {la:?} {ta:?} vs {lb:?} {tb:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A multileader moved at one scale alone is there again after a DWG round trip, carried by
|
||||
/// CADCraft's own record (the DWG bridge doesn't convert contexts yet, storytold/craft-libs#2005).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_multileader_moved_at_one_scale_keeps_it_through_dwg() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let (mut d, h) = with_mleader();
|
||||
d.modify_entity(h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(2.0, -1.0))).unwrap();
|
||||
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
|
||||
let dwg_back = cadcraft_io::read(&dwg, "x.dwg").unwrap();
|
||||
let a = d.entity(h).unwrap();
|
||||
{
|
||||
let back = &dwg_back;
|
||||
let b = back.model.iter().find(|e| matches!(e.kind, EntityKind::MLeader(_))).unwrap();
|
||||
for f in [1.0, 10.0] {
|
||||
let ((la, ta), (lb, tb)) = (mleader_shown(a, f), mleader_shown(b, f));
|
||||
assert!(la.dist(lb) < 1e-6 && ta.dist(tb) < 1e-6, "at {f}: {la:?} {ta:?} vs {lb:?} {tb:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The MULTILEADER entity's own 293 ("enable annotation scale", after its `CONTEXT_DATA{` block).
|
||||
fn mleader_enable_annotation_scale(text: &str) -> Option<String> {
|
||||
let recs = records(text);
|
||||
let (_, t) = recs.iter().find(|(k, _)| k == "MULTILEADER")?;
|
||||
let close = t.iter().position(|(c, _)| *c == 301)?;
|
||||
t.iter().skip(close + 1).find(|(c, _)| *c == 293).map(|(_, v)| v.trim().to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_annotative_multileader_has_annotation_scale_enabled() {
|
||||
// AutoCAD's ANNORESET passes over a multileader whose 293 is off, even with its contexts.
|
||||
let (d, h) = with_mleader();
|
||||
assert_eq!(mleader_enable_annotation_scale(&save(&d)).as_deref(), Some("1"));
|
||||
let mut plain = d.clone();
|
||||
plain.modify_entity(h, |e| e.common.anno_scales.clear()).unwrap();
|
||||
assert_eq!(mleader_enable_annotation_scale(&save(&plain)).as_deref(), Some("0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_context_positions_do_not_panic() {
|
||||
for bad in ["10 1e309\n20 nan\n11 inf", "10 x\n20 0\n11 -1e308", "10 -40\n20 0\n11 1e308"] {
|
||||
let src = FIXTURE.replacen("10 -40\n20 0\n11 30", bad, 1);
|
||||
let Ok(d) = cadcraft_io::read_dxf(dxf(&src).as_bytes()) else { continue };
|
||||
for e in d.model.iter() {
|
||||
assert!(e.common.anno_moves.iter().all(|m| m.by.is_finite()), "{:?}", e.common.anno_moves);
|
||||
}
|
||||
let _ = save(&d);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,6 +83,25 @@ fn vertices(edges: &[Edge]) -> Vec<PolyVertex> {
|
||||
loops.into_iter().next().map(|l| l.vertices).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// HATCH ellipse endpoints are circular ray angles, not the ellipse's eccentric parameters.
|
||||
#[test]
|
||||
fn a_non_circular_ellipse_edge_uses_ray_angles_in_both_directions() {
|
||||
let expected = 10.0 / 5.0_f64.sqrt(); // x = y at 45 degrees on x²/100 + y²/25 = 1
|
||||
let bounds = |l: &HatchLoop| l.vertices.iter().fold((f64::NEG_INFINITY, f64::INFINITY), |(max_x, min_y), v| (max_x.max(v.p.x), min_y.min(v.p.y)));
|
||||
for (start, end, ccw) in [(45.0, 90.0, true), (270.0, 315.0, false), (405.0, 450.0, true)] {
|
||||
let edge = Edge::Ellipse([0.0, 0.0], [10.0, 0.0], 0.5, start, end, ccw);
|
||||
let drawing = cadcraft_io::read(dxf(&[vec![edge]]).as_bytes(), "ellipse.dxf").unwrap();
|
||||
let loops = loops_of(&drawing);
|
||||
let (max_x, min_y) = bounds(&loops[0]);
|
||||
assert!((max_x - expected).abs() < 1e-8 && (min_y - expected).abs() < 1e-8, "{start} {end} {ccw}: {max_x} {min_y}");
|
||||
// CADCraft writes the sampled contour as a polyline; the geometry survives a DXF save.
|
||||
let saved = cadcraft_io::write_dxf(&drawing);
|
||||
let reopened = cadcraft_io::read(saved.as_bytes(), "ellipse.dxf").unwrap();
|
||||
let (x2, y2) = bounds(&loops_of(&reopened)[0]);
|
||||
assert!((x2 - max_x).abs() < 1e-6 && (y2 - min_y).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
/// The same vertices, up to the rounding of points and bulges computed from other stored values.
|
||||
fn assert_same(got: &[PolyVertex], expected: &[PolyVertex]) {
|
||||
let same = got.len() == expected.len() && got.iter().zip(expected).all(|(a, b)| a.p.near(b.p, 1e-9) && (a.bulge - b.bulge).abs() < 1e-12);
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! A lightweight polyline keeps its vertex identifiers (LWPOLYLINE group 91 after a vertex, DXF
|
||||
//! 2010 and later) through a save while its vertices are where they were read.
|
||||
//! Geometric constraints name a polyline's segments by these identifiers. CADCraft's polyline has
|
||||
//! none, so every save wrote the polyline without them, and what the constraints name was gone.
|
||||
//!
|
||||
//! The DWG is written here with acadrust, the identifiers out of order and the first vertex not
|
||||
//! the smallest, as on a polyline that was edited in another program. The harness builds this
|
||||
//! module only where acadrust builds (see `main.rs`).
|
||||
use std::io::Cursor;
|
||||
|
||||
use acadrust::entities::{EntityType, LwPolyline, LwVertex};
|
||||
use acadrust::{CadDocument, DxfVersion, Vector2};
|
||||
use cadcraft_io::{SaveOptions, Version, read, write_with};
|
||||
|
||||
const VERTEX_IDS: [i32; 4] = [2, 5, 7, 1];
|
||||
|
||||
fn polyline_dwg() -> Vec<u8> {
|
||||
polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], 1.0)
|
||||
}
|
||||
|
||||
/// A DWG with one closed polyline at `points`, its normal along `normal_z` Z.
|
||||
fn polyline_dwg_with(points: [(f64, f64); 4], normal_z: f64) -> Vec<u8> {
|
||||
let mut doc = CadDocument::with_version(DxfVersion::AC1032);
|
||||
let mut polyline = LwPolyline::new();
|
||||
polyline.is_closed = true;
|
||||
polyline.normal = acadrust::Vector3::new(0.0, 0.0, normal_z);
|
||||
for (id, (x, y)) in VERTEX_IDS.iter().zip(points) {
|
||||
polyline.vertices.push(LwVertex { vertex_id: *id, ..LwVertex::new(Vector2::new(x, y)) });
|
||||
}
|
||||
doc.add_entity(EntityType::LwPolyline(polyline)).expect("add the polyline");
|
||||
acadrust::DwgWriter::write_to_vec(&doc).expect("write the DWG")
|
||||
}
|
||||
|
||||
/// The vertex identifiers of the one lightweight polyline in DWG bytes.
|
||||
fn vertex_ids_of(dwg: &[u8]) -> Vec<i32> {
|
||||
let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.to_vec())).read().unwrap();
|
||||
doc.entities()
|
||||
.find_map(|e| match e {
|
||||
EntityType::LwPolyline(p) => Some(p.vertices.iter().map(|v| v.vertex_id).collect()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the polyline is in the DWG")
|
||||
}
|
||||
|
||||
/// The vertex identifiers (groups 91) of the one LWPOLYLINE record in a DXF text.
|
||||
fn dxf_vertex_ids(dxf: &[u8]) -> Vec<String> {
|
||||
let text = String::from_utf8_lossy(dxf);
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut pairs = lines.chunks(2).filter_map(|pair| Some((*pair.first()?, *pair.get(1)?)));
|
||||
let record = pairs.by_ref().skip_while(|pair| *pair != ("0", "LWPOLYLINE")).skip(1);
|
||||
record.take_while(|(code, _)| *code != "0").filter(|(code, _)| *code == "91").map(|(_, value)| value.to_string()).collect()
|
||||
}
|
||||
|
||||
fn save(d: &cadcraft_doc::Drawing, name: &str, version: Version) -> Vec<u8> {
|
||||
write_with(d, name, &SaveOptions { version: Some(version), binary: false }).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_keeps_its_vertex_identifiers_through_a_save() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let dwg = polyline_dwg();
|
||||
assert_eq!(vertex_ids_of(&dwg), VERTEX_IDS, "the fixture as acadrust reads it");
|
||||
let d = read(&dwg, "polyline.dwg").unwrap();
|
||||
for version in [Version::R2010, Version::R2018] {
|
||||
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", version)), VERTEX_IDS, "DWG {version:?}");
|
||||
}
|
||||
assert_eq!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2018)), ["2", "5", "7", "1"]);
|
||||
// A DXF before 2010 has no such group.
|
||||
assert!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2000)).is_empty());
|
||||
let back = read(&save(&d, "saved.dxf", Version::R2018), "saved.dxf").unwrap();
|
||||
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"], "read back from a DXF");
|
||||
}
|
||||
|
||||
/// Once a vertex is elsewhere, the order is another or a vertex is gone, the identifiers no longer
|
||||
/// say which vertex is which: none are written.
|
||||
#[test]
|
||||
fn an_edited_polyline_drops_its_vertex_identifiers() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read(&polyline_dwg(), "polyline.dwg").unwrap();
|
||||
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
|
||||
let mut after = |edit: fn(&mut cadcraft_doc::LwPolyline)| {
|
||||
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
|
||||
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
|
||||
edit(p);
|
||||
}
|
||||
}));
|
||||
vertex_ids_of(&save(&d, "edited.dwg", Version::R2018))
|
||||
};
|
||||
assert_eq!(after(|p| p.vertices.reverse()), [0; 4], "reversed");
|
||||
assert_eq!(after(|p| p.vertices.reverse()), VERTEX_IDS, "reversed back: every vertex is where it was read");
|
||||
assert_eq!(after(|p| p.vertices[1].p.x += 1.0), [0; 4], "a vertex moved");
|
||||
}
|
||||
|
||||
/// A polyline whose normal points down is read mirrored in x; untouched, it keeps its identifiers.
|
||||
#[test]
|
||||
fn a_polyline_facing_down_keeps_its_vertex_identifiers() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = read(&polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], -1.0), "down.dwg").unwrap();
|
||||
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), VERTEX_IDS);
|
||||
}
|
||||
|
||||
/// Reversed, a polyline symmetric about x = 0 has its mirror image's points: the identifiers still
|
||||
/// no longer say which vertex is which.
|
||||
#[test]
|
||||
fn a_reversed_symmetric_polyline_drops_its_vertex_identifiers() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read(&polyline_dwg_with([(-20.0, 0.0), (-20.0, 25.0), (20.0, 25.0), (20.0, 0.0)], 1.0), "sym.dwg").unwrap();
|
||||
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
|
||||
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
|
||||
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
|
||||
p.vertices.reverse();
|
||||
}
|
||||
}));
|
||||
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), [0; 4]);
|
||||
}
|
||||
|
||||
/// A group 91 inside an application's `102 {` group of the record is not a vertex identifier.
|
||||
#[test]
|
||||
fn a_91_inside_an_application_group_is_not_an_identifier() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let d = read(&polyline_dwg(), "polyline.dwg").unwrap();
|
||||
let dxf = String::from_utf8(save(&d, "saved.dxf", Version::R2018)).unwrap();
|
||||
let mut lines: Vec<&str> = dxf.lines().collect();
|
||||
let start = lines.windows(2).position(|pair| pair[0].trim() == "0" && pair[1].trim() == "LWPOLYLINE").unwrap();
|
||||
// After the first vertex's identifier.
|
||||
let at = (start..lines.len()).step_by(2).find(|i| lines[*i].trim() == "91").unwrap() + 2;
|
||||
lines.splice(at..at, ["102", "{SOMEAPP", " 91", "9", "102", "}"]);
|
||||
let back = read(lines.join("\n").as_bytes(), "app.dxf").unwrap();
|
||||
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"]);
|
||||
}
|
||||
@@ -62,6 +62,8 @@ mod low_handseed;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod ltype_dwg_dash_count;
|
||||
mod ltype_element_cap;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod lwpolyline_vertex_ids;
|
||||
mod minsert_marker;
|
||||
mod mleader_content;
|
||||
mod mleader_roundtrip;
|
||||
|
||||
@@ -5,20 +5,25 @@
|
||||
|
||||
use cadcraft_doc::EntityKind;
|
||||
|
||||
/// Stand-in OLE data as a DWG carries it: a two-byte marker, the frame's four corners (upper
|
||||
/// left, upper right, lower right, lower left; x, y, z doubles), then the object's bytes, here
|
||||
/// opaque text long enough to take several 310 groups.
|
||||
/// A saved-layout OLE frame header followed by opaque stand-in object bytes, long enough to
|
||||
/// take several 310 groups. The payload is not claimed to be a valid compound file.
|
||||
fn payload() -> Vec<u8> {
|
||||
let mut data = vec![0x80, 0x00];
|
||||
let mut data = 0x5580u16.to_le_bytes().to_vec();
|
||||
for [x, y] in [[10.0f64, 40.0], [70.0, 40.0], [70.0, 5.0], [10.0, 5.0]] {
|
||||
for v in [x, y, 0.0] {
|
||||
data.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
let mut extension = [0u8; 26];
|
||||
extension[16..20].copy_from_slice(&1u32.to_le_bytes()); // embedded object
|
||||
data.extend_from_slice(&extension);
|
||||
let mut object = vec![];
|
||||
for i in 0..12u8 {
|
||||
data.extend_from_slice(b"synthetic embedded object ");
|
||||
data.push(i);
|
||||
object.extend_from_slice(b"synthetic embedded object ");
|
||||
object.push(i);
|
||||
}
|
||||
data.extend_from_slice(&(object.len() as u32).to_le_bytes());
|
||||
data.extend_from_slice(&object);
|
||||
data
|
||||
}
|
||||
|
||||
|
||||
@@ -12,12 +12,16 @@ const LR: (f64, f64) = (35.27, -22.39);
|
||||
|
||||
/// The OLE data: the envelope with the frame's corners.
|
||||
fn blob() -> Vec<u8> {
|
||||
let mut b = vec![1u8, 0];
|
||||
let mut b = 0x5580u16.to_le_bytes().to_vec();
|
||||
for (x, y) in [UL, (LR.0, UL.1), LR, (UL.0, LR.1)] {
|
||||
for v in [x, y, 0.0] {
|
||||
b.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
let mut extension = [0u8; 26];
|
||||
extension[16..20].copy_from_slice(&1u32.to_le_bytes()); // embedded object
|
||||
b.extend_from_slice(&extension);
|
||||
b.extend_from_slice(&0u32.to_le_bytes()); // no compound-file bytes
|
||||
b
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
//! Render settings store their `AcDbRenderSettings` class version in the form of the file's
|
||||
//! version: a 2013+ file stores it one higher (a 2013 file stores a rapid RT one one lower), as
|
||||
//! acadrust reads and writes them. A kept object carries the form of the file it came from; written
|
||||
//! into a file declaring another version, it takes that version's form. The DWG bridge is an R2000
|
||||
//! DXF for a 2018 DWG: without this, a 2018 drawing's MENTALRAYRENDERSETTINGS went in with the 2018
|
||||
//! form, the DWG writer raised it once more, and BricsCAD refused the DWG ("Object improperly
|
||||
//! read", #907).
|
||||
//! Plain render settings use a version-specific base class version. Mental ray and rapid RT
|
||||
//! settings keep their stored value across both DXF and DWG versions (#907, #2471).
|
||||
|
||||
use cadcraft_io::{SaveOptions, Version};
|
||||
|
||||
@@ -50,7 +45,7 @@ fn written(d: &cadcraft_doc::Drawing, version: Version) -> String {
|
||||
|
||||
#[test]
|
||||
fn render_settings_class_version_takes_the_declared_versions_form() {
|
||||
let kind = "MENTALRAYRENDERSETTINGS";
|
||||
let kind = "RENDERSETTINGS";
|
||||
// From a 2018 file (stored 2 = class version 1 in the 2013+ form).
|
||||
let d = cadcraft_io::read_dxf(dxf("AC1032", kind, 2).as_bytes()).unwrap();
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2), "same version: as read");
|
||||
@@ -61,19 +56,19 @@ fn render_settings_class_version_takes_the_declared_versions_form() {
|
||||
let d = cadcraft_io::read_dxf(dxf("AC1015", kind, 1).as_bytes()).unwrap();
|
||||
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
|
||||
// Rapid RT settings: the 2013 file alone stores one lower.
|
||||
// Rapid RT keeps the stored base class version across file versions.
|
||||
let kind = "RAPIDRTRENDERSETTINGS";
|
||||
let d = cadcraft_io::read_dxf(dxf("AC1027", kind, 1).as_bytes()).unwrap();
|
||||
assert_eq!(class_version(&written(&d, Version::R2013), kind), Some(1));
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
|
||||
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(2));
|
||||
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(1));
|
||||
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
|
||||
}
|
||||
|
||||
/// A file that declares no `$ACADVER` gives no source form: its kept objects are written as read,
|
||||
/// not as if the new drawing's 2018 were their form.
|
||||
#[test]
|
||||
fn render_settings_without_a_declared_version_are_written_as_read() {
|
||||
let kind = "MENTALRAYRENDERSETTINGS";
|
||||
let kind = "RENDERSETTINGS";
|
||||
let text = dxf("AC1032", kind, 1).replace("9\n$ACADVER\n1\nAC1032\n", "");
|
||||
assert!(!text.contains("$ACADVER"));
|
||||
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
@@ -110,8 +105,7 @@ fn render_settings_class_version_matches_what_acadrust_writes() {
|
||||
(DxfVersion::AC1027, Version::R2013),
|
||||
(DxfVersion::AC1032, Version::R2018),
|
||||
];
|
||||
// As a 2018 file stores them: mental ray one higher than its class version, rapid RT as is.
|
||||
for (kind, stored) in [("MENTALRAYRENDERSETTINGS", 2), ("RAPIDRTRENDERSETTINGS", 2)] {
|
||||
for (kind, stored) in [("RENDERSETTINGS", 2), ("MENTALRAYRENDERSETTINGS", 2), ("RAPIDRTRENDERSETTINGS", 2)] {
|
||||
let source = std::io::Cursor::new(dxf("AC1032", kind, stored).into_bytes());
|
||||
let mut doc = acadrust::DxfReader::from_reader(source).unwrap().read().unwrap();
|
||||
let by_acadrust: Vec<(Version, String)> = versions
|
||||
@@ -122,7 +116,7 @@ fn render_settings_class_version_matches_what_acadrust_writes() {
|
||||
})
|
||||
.collect();
|
||||
let forms: Vec<Option<i64>> = by_acadrust.iter().map(|(_, text)| class_version(text, kind)).collect();
|
||||
let expected = if kind == "RAPIDRTRENDERSETTINGS" { [2, 2, 1, 2] } else { [1, 1, 2, 2] };
|
||||
let expected = if kind == "RENDERSETTINGS" { [1, 1, 2, 2] } else { [2, 2, 2, 2] };
|
||||
assert_eq!(forms, expected.map(Some), "{kind}: acadrust's own forms for 2000, 2010, 2013, 2018");
|
||||
for (read_from, text) in &by_acadrust {
|
||||
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Shared preservation assertions for ordered entities, authored blocks and referenced tables.
|
||||
//! Every field of the explicitly supported entities is checked; converted angles alone allow
|
||||
//! Every field of the explicitly supported entities is checked; converted angles and interpolated spline controls allow
|
||||
//! floating-point roundoff, never wrapping or geometric approximation. Blocks are visited once
|
||||
//! as stored definitions, not recursively expanded, so cyclic references remain bounded.
|
||||
//! Header defaults, generated objects and other drawing collections are outside this slice.
|
||||
@@ -12,8 +12,7 @@ fn equal<T: PartialEq + Debug>(expected: &T, actual: &T, context: &str, field: &
|
||||
assert_eq!(actual, expected, "{context}.{field}");
|
||||
}
|
||||
|
||||
fn angle(expected: f64, actual: f64, context: &str, field: &str) {
|
||||
// Two floating-point unit conversions, not a geometric approximation or angle wrapping.
|
||||
fn roundoff(expected: f64, actual: f64, context: &str, field: &str) {
|
||||
let tolerance = 8.0 * f64::EPSILON * expected.abs().max(1.0);
|
||||
assert!(
|
||||
expected.is_finite() && actual.is_finite() && (actual - expected).abs() <= tolerance,
|
||||
@@ -144,7 +143,7 @@ fn linetype(expected: Option<&cadcraft_doc::Linetype>, actual: Option<&cadcraft_
|
||||
equal(shape, &b.shape, &path, "shape");
|
||||
equal(style, &b.style, &path, "style");
|
||||
equal(scale, &b.scale, &path, "scale");
|
||||
angle(*rotation, b.rotation, &path, "rotation");
|
||||
roundoff(*rotation, b.rotation, &path, "rotation");
|
||||
equal(offset, &b.offset, &path, "offset");
|
||||
equal(absolute, &b.absolute, &path, "absolute");
|
||||
}
|
||||
@@ -167,8 +166,23 @@ fn entity(expected: &Entity, actual: &Entity, context: &str) {
|
||||
(EntityKind::Arc(Arc { center, radius, start, end }), EntityKind::Arc(b)) => {
|
||||
equal(center, &b.center, context, "arc.center");
|
||||
equal(radius, &b.radius, context, "arc.radius");
|
||||
angle(*start, b.start, context, "arc.start");
|
||||
angle(*end, b.end, context, "arc.end");
|
||||
roundoff(*start, b.start, context, "arc.start");
|
||||
roundoff(*end, b.end, context, "arc.end");
|
||||
}
|
||||
(EntityKind::Spline(a), EntityKind::Spline(b)) if !a.fit.is_empty() => {
|
||||
// DWG stores the fit points. The decoder interpolates the cubic controls for DXF.
|
||||
let cadcraft_geom::Spline { degree, knots, control, weights, fit, closed, fit_opts } = a;
|
||||
equal(degree, &b.degree, context, "spline.degree");
|
||||
equal(knots, &b.knots, context, "spline.knots");
|
||||
equal(weights, &b.weights, context, "spline.weights");
|
||||
equal(fit, &b.fit, context, "spline.fit");
|
||||
equal(closed, &b.closed, context, "spline.closed");
|
||||
equal(fit_opts, &b.fit_opts, context, "spline.fit_opts");
|
||||
equal(&control.len(), &b.control.len(), context, "spline.control.len");
|
||||
for (p, q) in control.iter().zip(&b.control) {
|
||||
roundoff(p.x, q.x, context, "spline.control.x");
|
||||
roundoff(p.y, q.y, context, "spline.control.y");
|
||||
}
|
||||
}
|
||||
(EntityKind::MText(a), EntityKind::MText(b)) => mtext(a, b, context),
|
||||
(EntityKind::AttDef(a), EntityKind::AttDef(b)) => attrib(a, b, context),
|
||||
@@ -204,8 +218,21 @@ fn entity(expected: &Entity, actual: &Entity, context: &str) {
|
||||
|
||||
fn common(expected: &Common, actual: &Common, context: &str) {
|
||||
// No `..`: adding a field requires deciding its preservation contract here.
|
||||
let Common { layer, color, linetype, lineweight, ltscale, transparency, visible, thickness, extrusion, plot_style, anno_scales, xdata } =
|
||||
expected;
|
||||
let Common {
|
||||
layer,
|
||||
color,
|
||||
linetype,
|
||||
lineweight,
|
||||
ltscale,
|
||||
transparency,
|
||||
visible,
|
||||
thickness,
|
||||
extrusion,
|
||||
plot_style,
|
||||
anno_scales,
|
||||
anno_moves,
|
||||
xdata,
|
||||
} = expected;
|
||||
equal(layer, &actual.layer, context, "layer");
|
||||
equal(color, &actual.color, context, "color");
|
||||
equal(linetype, &actual.linetype, context, "linetype");
|
||||
@@ -217,6 +244,7 @@ fn common(expected: &Common, actual: &Common, context: &str) {
|
||||
equal(extrusion, &actual.extrusion, context, "extrusion");
|
||||
equal(plot_style, &actual.plot_style, context, "plot_style");
|
||||
equal(anno_scales, &actual.anno_scales, context, "anno_scales");
|
||||
equal(anno_moves, &actual.anno_moves, context, "anno_moves");
|
||||
equal(xdata, &actual.xdata, context, "xdata");
|
||||
}
|
||||
|
||||
@@ -226,9 +254,9 @@ fn text(expected: &Text, actual: &Text, context: &str) {
|
||||
equal(align_pt, &actual.align_pt, context, "align_pt");
|
||||
equal(height, &actual.height, context, "height");
|
||||
equal(value, &actual.value, context, "value");
|
||||
angle(*rotation, actual.rotation, context, "rotation");
|
||||
roundoff(*rotation, actual.rotation, context, "rotation");
|
||||
equal(width_factor, &actual.width_factor, context, "width_factor");
|
||||
angle(*oblique, actual.oblique, context, "oblique");
|
||||
roundoff(*oblique, actual.oblique, context, "oblique");
|
||||
equal(style, &actual.style, context, "style");
|
||||
equal(halign, &actual.halign, context, "halign");
|
||||
equal(valign, &actual.valign, context, "valign");
|
||||
@@ -242,7 +270,7 @@ fn mtext(expected: &MText, actual: &MText, context: &str) {
|
||||
equal(height, &actual.height, context, "mtext.height");
|
||||
equal(width, &actual.width, context, "mtext.width");
|
||||
equal(attach, &actual.attach, context, "mtext.attach");
|
||||
angle(*rotation, actual.rotation, context, "mtext.rotation");
|
||||
roundoff(*rotation, actual.rotation, context, "mtext.rotation");
|
||||
equal(style, &actual.style, context, "mtext.style");
|
||||
equal(contents, &actual.contents, context, "mtext.contents");
|
||||
equal(line_spacing, &actual.line_spacing, context, "mtext.line_spacing");
|
||||
@@ -274,7 +302,7 @@ fn insert(expected: &Insert, actual: &Insert, context: &str) {
|
||||
equal(block, &actual.block, context, "insert.block");
|
||||
equal(insert, &actual.insert, context, "insert.insert");
|
||||
equal(scale, &actual.scale, context, "insert.scale");
|
||||
angle(*rotation, actual.rotation, context, "insert.rotation");
|
||||
roundoff(*rotation, actual.rotation, context, "insert.rotation");
|
||||
equal(cols, &actual.cols, context, "insert.cols");
|
||||
equal(rows, &actual.rows, context, "insert.rows");
|
||||
equal(col_spacing, &actual.col_spacing, context, "insert.col_spacing");
|
||||
@@ -375,9 +403,9 @@ fn comparison_rejects_block_and_attribute_dependency_losses() {
|
||||
|
||||
#[test]
|
||||
fn angle_tolerance_does_not_hide_real_changes_or_nonfinite_values() {
|
||||
angle(0.7, 0.7_f64.to_degrees().to_radians(), "self-test", "angle");
|
||||
roundoff(0.7, 0.7_f64.to_degrees().to_radians(), "self-test", "angle");
|
||||
for actual in [0.700001, f64::NAN, f64::INFINITY] {
|
||||
assert!(std::panic::catch_unwind(|| angle(0.7, actual, "self-test", "angle")).is_err());
|
||||
assert!(std::panic::catch_unwind(|| roundoff(0.7, actual, "self-test", "angle")).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -375,7 +375,27 @@ fn layer_states() {
|
||||
}
|
||||
#[test]
|
||||
fn layouts_and_paperspace() {
|
||||
collection(collections::layouts(), collections::assert_layouts);
|
||||
let case = collections::layouts();
|
||||
for version in Version::ALL {
|
||||
let mut expected = case.drawing.clone();
|
||||
if version >= Version::R2007 {
|
||||
// DWG stores effective viewport lighting from R2007 onward. Preserve it for DXF export.
|
||||
for layout in expected.layouts.iter_mut() {
|
||||
let handles: Vec<_> = layout.entities.iter().map(|e| e.handle).collect();
|
||||
for handle in handles {
|
||||
layout.entities.modify(handle, |e| {
|
||||
if let cadcraft_doc::EntityKind::Viewport(v) = &mut e.kind {
|
||||
v.extra = [(292, "1"), (282, "1"), (141, "0.0"), (142, "0.0")]
|
||||
.into_iter()
|
||||
.map(|(code, value)| cadcraft_doc::RawTag { code, value: value.into() })
|
||||
.collect();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
super::check_version_with(&case.name, &case.drawing, &expected, version, collections::assert_layouts);
|
||||
}
|
||||
}
|
||||
|
||||
fn with_dimension_styles(cases: Vec<Case>) {
|
||||
|
||||
@@ -395,9 +395,69 @@ fn hostile_viewport_ucs_groups_do_not_panic() {
|
||||
assert_eq!((u.x_axis, u.y_axis), (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_viewport_keeps_its_nondefault_style_sheet_and_ucs_icon_origin() {
|
||||
let (d, h) = base();
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
let groups = [(1, "monochrome.ctb".into()), (74, "1".into())];
|
||||
let back = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
|
||||
let (_, viewport) = the_viewport(&back);
|
||||
assert!(viewport.extra.iter().any(|t| t.code == 1 && t.value == "monochrome.ctb"));
|
||||
assert!(viewport.extra.iter().any(|t| t.code == 74 && t.value == "1"));
|
||||
}
|
||||
|
||||
/// An explicit 282=1 selects two lights. A DXF consumer can interpret an omitted 282
|
||||
/// as one light; keep the authored groups even when they match DWG-generated values.
|
||||
#[test]
|
||||
fn explicit_dxf_lighting_survives_save_and_reopen() {
|
||||
let (d, h) = base();
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
for (enabled, brightness, ambient) in [("1", "0.0", false), ("0", "0.0", false), ("1", "0.25", false), ("1", "0.0", true)] {
|
||||
let mut groups = vec![(292, enabled.into()), (282, "1".into()), (141, brightness.into()), (142, "0.0".into())];
|
||||
if ambient {
|
||||
groups.push((63, "250".into()));
|
||||
}
|
||||
let drawing = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
|
||||
let saved = cadcraft_io::write_dxf(&drawing);
|
||||
let native = viewport_record(&saved, h);
|
||||
for (code, value) in &groups {
|
||||
assert_eq!(group(&native, &code.to_string()).and_then(num), num(value), "native DXF viewport group {code}");
|
||||
}
|
||||
let back = cadcraft_io::read_dxf(saved.as_bytes()).unwrap();
|
||||
let (_, viewport) = the_viewport(&back);
|
||||
for (code, value) in &groups {
|
||||
assert!(viewport.extra.iter().any(|t| t.code == *code && num(&t.value) == num(value)), "{code}: {:?}", viewport.extra);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn dwg_preserves_explicit_viewport_lighting() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let (d, h) = base();
|
||||
let text = cadcraft_io::write_dxf(&d);
|
||||
for (enabled, brightness) in [("1", "0.0"), ("0", "0.0"), ("1", "0.25")] {
|
||||
let groups = [(292, enabled.into()), (282, "1".into()), (141, brightness.into()), (142, "0.0".into())];
|
||||
let drawing = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
|
||||
let bytes = cadcraft_io::write_with(
|
||||
&drawing,
|
||||
"lighting.dwg",
|
||||
&cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2010), binary: false },
|
||||
)
|
||||
.unwrap();
|
||||
let back = cadcraft_io::read(&bytes, "lighting.dwg").unwrap();
|
||||
let (_, viewport) = the_viewport(&back);
|
||||
for (code, value) in &groups {
|
||||
let want = num(value).unwrap();
|
||||
assert!(viewport.extra.iter().any(|t| t.code == *code && num(&t.value) == Some(want)), "{code}: {:?}", viewport.extra);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_default_viewport_reads_back_without_ucs_or_extras() {
|
||||
fn a_default_dwg_viewport_exports_its_effective_lighting() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
for version in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] {
|
||||
let (d, _) = base();
|
||||
@@ -406,7 +466,17 @@ fn a_default_viewport_reads_back_without_ucs_or_extras() {
|
||||
let (_, viewport) = the_viewport(&back);
|
||||
assert!(viewport.ucs.is_none(), "{version}: {:?}", viewport.ucs);
|
||||
assert!(!viewport.ucs_per_viewport, "{version}");
|
||||
assert!(viewport.extra.is_empty(), "{version}: {:?}", viewport.extra);
|
||||
let native = viewport_record(&cadcraft_io::write_dxf(&back), the_viewport(&back).0);
|
||||
let lighting = [(292, "1"), (282, "1"), (141, "0.0"), (142, "0.0")];
|
||||
if version >= cadcraft_io::Version::R2007 {
|
||||
assert_eq!(viewport.extra.len(), lighting.len());
|
||||
for (code, value) in lighting {
|
||||
assert_eq!(group(&native, &code.to_string()).and_then(num), num(value), "exported DWG lighting {code}");
|
||||
}
|
||||
} else {
|
||||
assert!(viewport.extra.is_empty(), "{version}: {:?}", viewport.extra);
|
||||
assert!(group(&native, "282").is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -427,6 +497,11 @@ fn a_viewport_with_non_default_snap_keeps_it() {
|
||||
for code in [14, 24] {
|
||||
assert_eq!(viewport.extra.iter().find(|t| t.code == code).and_then(|t| num(&t.value)), Some(2.0), "{version}");
|
||||
}
|
||||
assert_eq!(viewport.extra.len(), 2, "only the non-default snap spacing remains: {version}: {:?}", viewport.extra);
|
||||
let extras = viewport.extra.iter().map(|t| t.code).collect::<Vec<_>>();
|
||||
let mut expected = vec![14, 24];
|
||||
if version >= cadcraft_io::Version::R2007 {
|
||||
expected.extend([292, 282, 141, 142]);
|
||||
}
|
||||
assert_eq!(extras, expected, "{version}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +65,16 @@ fn check(bytes: &[u8], name: &str) -> cadcraft_doc::Drawing {
|
||||
assert_eq!(proxy.payload.bit_count, 9);
|
||||
assert_eq!(proxy.payload.data(), [0xA5, 0x80]);
|
||||
assert_eq!(proxy.graphics.data(), [0x12, 0x34, 0x56]);
|
||||
let class = classes.get(usize::try_from(proxy.class_id - 500).unwrap()).unwrap();
|
||||
// The DXF refers to the CLASSES section by ordinal, while the decoder renumbers
|
||||
// that same proxy against its document class table.
|
||||
let entities = sections.iter().find(|s| s.name == "ENTITIES").unwrap();
|
||||
let records = craft_dxf::records(&entities.tags);
|
||||
let (_, record) = records.iter().find(|(kind, _)| kind == "ACAD_PROXY_ENTITY").unwrap();
|
||||
let file_id = record.iter().skip_while(|t| t.code != 100 || t.str() != "AcDbProxyEntity").find(|t| t.code == 91).unwrap().i64();
|
||||
let class = classes.get(usize::try_from(file_id - 500).unwrap()).unwrap();
|
||||
let decoded_class = decoded.classes.iter().find(|c| i32::from(c.class_number) == proxy.class_id).unwrap();
|
||||
assert_eq!(decoded_class.dxf_name, "SPDSNOTEPOSITION");
|
||||
assert_eq!(decoded_class.cpp_class_name, "mcsDbObjectNotePosition");
|
||||
assert!(class.1.iter().any(|t| t.code == 1 && t.str() == "SPDSNOTEPOSITION"));
|
||||
assert!(class.1.iter().any(|t| t.code == 2 && t.str() == "mcsDbObjectNotePosition"));
|
||||
drawing
|
||||
@@ -121,7 +130,7 @@ fn duplicate_names_keep_distinct_classes_for_entities_and_dictionary_objects() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let source = duplicate_class_dxf();
|
||||
for binary in [false, true] {
|
||||
let input = if binary { craft_dxf::write_binary(&craft_dxf::parse(&source).unwrap(), true) } else { source.clone() };
|
||||
let input = if binary { craft_dxf::write_binary(&craft_dxf::parse(&source).unwrap(), true).unwrap() } else { source.clone() };
|
||||
let mut drawing = cadcraft_io::read(&input, "source.dxf").unwrap();
|
||||
for _ in 0..3 {
|
||||
for name in ["copy.dxf", "copy.dwg"] {
|
||||
|
||||
@@ -11,6 +11,10 @@ workspace = true
|
||||
[dependencies]
|
||||
craft-mcp = { workspace = true }
|
||||
craft-jsonrpc = { workspace = true }
|
||||
# The live client: tool calls go to the open window while the ArtCraft Launcher's switch allows it.
|
||||
craft-control = { workspace = true, features = ["agents"] }
|
||||
# The challenge handshake of the window's agent server (`craft_automation::security`; no egui without `ui`).
|
||||
craft-automation = { workspace = true }
|
||||
cadcraft-engine = { workspace = true }
|
||||
cadcraft-render = { workspace = true }
|
||||
cadcraft-io = { workspace = true }
|
||||
|
||||
+107
-4
@@ -2,6 +2,7 @@
|
||||
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpStream, ToSocketAddrs};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -18,6 +19,9 @@ pub trait Backend {
|
||||
fn has_ui(&self) -> bool;
|
||||
/// Describe the backend connection for client-facing status.
|
||||
fn describe(&self) -> String;
|
||||
/// The `agent_folders` tool's answer: the folders this session may open from and save to, and
|
||||
/// whether files outside them are refused ([`crate::live::folders_reply`]).
|
||||
fn agent_folders(&mut self) -> Result<Value, String>;
|
||||
}
|
||||
|
||||
/// A running CADCraft app reached through its loopback control port.
|
||||
@@ -35,6 +39,10 @@ pub struct Remote {
|
||||
authed: bool,
|
||||
/// Longest reply line accepted (`MAX_REPLY_LINE`; smaller in tests).
|
||||
max_reply: usize,
|
||||
/// The open window's agent server ([`Remote::signed_in`]): each connection signs in once with
|
||||
/// the challenge handshake and this token, which never crosses the wire. `None`: the `--control`
|
||||
/// server, which takes the token from its token file on every request.
|
||||
handshake: Option<String>,
|
||||
}
|
||||
|
||||
/// The port component of a `HOST:PORT` address, for locating the token file.
|
||||
@@ -42,6 +50,15 @@ fn port_of(addr: &str) -> Option<u16> {
|
||||
addr.rsplit(':').next().and_then(|p| p.parse::<u16>().ok())
|
||||
}
|
||||
|
||||
/// How long a reply may take; the app answers a request within its own 60 s deadline.
|
||||
const REPLY_WAIT: Duration = Duration::from_secs(90);
|
||||
|
||||
/// How long each sign-in reply of the agent server may take.
|
||||
const SIGN_IN_WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Longest sign-in reply read (two nonces and a proof).
|
||||
const SIGN_IN_REPLY: usize = 64 * 1024;
|
||||
|
||||
/// How long a launched app has to open its control port.
|
||||
const LAUNCH_WAIT: Duration = Duration::from_secs(30);
|
||||
|
||||
@@ -67,7 +84,17 @@ fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) ->
|
||||
impl Remote {
|
||||
/// Connect to a running control server; its session token is read lazily when the first request is sent.
|
||||
pub fn connect(addr: &str) -> std::io::Result<Self> {
|
||||
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None, authed: false, max_reply: MAX_REPLY_LINE };
|
||||
let mut r = Self::lazy(addr, false);
|
||||
r.reconnect()?;
|
||||
Ok(r)
|
||||
}
|
||||
/// The open window's agent server at `addr` (`127.0.0.1:<port>` from the connection file the
|
||||
/// app publishes while the ArtCraft Launcher's switch lets agents in), signed in with the
|
||||
/// challenge handshake and `token` from the token file it names: the app proves it holds the
|
||||
/// token before anything derived from it is sent, so a program that took the port of an app
|
||||
/// that quit learns nothing.
|
||||
pub fn signed_in(addr: &str, token: String) -> std::io::Result<Self> {
|
||||
let mut r = Self { handshake: Some(token), ..Self::lazy(addr, false) };
|
||||
r.reconnect()?;
|
||||
Ok(r)
|
||||
}
|
||||
@@ -75,7 +102,7 @@ impl Remote {
|
||||
/// the server before the app is open. With `launch`, a call that finds nothing at `addr`
|
||||
/// opens the app with that control port first (macOS) and waits for it.
|
||||
pub fn lazy(addr: &str, launch: bool) -> Self {
|
||||
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE }
|
||||
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE, handshake: None }
|
||||
}
|
||||
|
||||
/// The per-session token for this port, read (and cached) from the owner-only token file. A
|
||||
@@ -86,6 +113,10 @@ impl Remote {
|
||||
/// peer: a name that also resolves elsewhere (`localhost` → `::1`, where another local account
|
||||
/// may listen on the same port) must not be handed the desktop's credential (CWE-522).
|
||||
fn token(&mut self) -> Option<&str> {
|
||||
// The agent server took the handshake: no request carries the token.
|
||||
if self.handshake.is_some() {
|
||||
return None;
|
||||
}
|
||||
let port = port_of(&self.addr)?;
|
||||
let peer = self.conn.as_ref().and_then(|(_, s)| s.peer_addr().ok());
|
||||
if peer != Some(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) {
|
||||
@@ -131,9 +162,12 @@ impl Remote {
|
||||
match TcpStream::connect_timeout(&sa, Duration::from_millis(800)) {
|
||||
Ok(s) => {
|
||||
s.set_nodelay(true).ok();
|
||||
s.set_read_timeout(Some(Duration::from_secs(90))).ok();
|
||||
s.set_read_timeout(Some(REPLY_WAIT)).ok();
|
||||
let read = s.try_clone()?;
|
||||
self.conn = Some((BufReader::new(read), s));
|
||||
if let Some(token) = self.handshake.clone() {
|
||||
return self.sign_in(&token).inspect_err(|_| self.conn = None);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => last = e,
|
||||
@@ -141,6 +175,52 @@ impl Remote {
|
||||
}
|
||||
Err(last)
|
||||
}
|
||||
/// The challenge handshake of the agent server (`craft_automation::security`) on the new
|
||||
/// connection: send a nonce, check the app's proof that it holds the token, then send this
|
||||
/// side's proof.
|
||||
fn sign_in(&mut self, token: &str) -> std::io::Result<()> {
|
||||
use craft_automation::security::{AUTH_METHOD, CHALLENGE_METHOD, ProofRole, generate_nonce, handshake_proof, proof_matches};
|
||||
let addr = self.addr.clone();
|
||||
let refused =
|
||||
|why: &str| std::io::Error::new(std::io::ErrorKind::PermissionDenied, format!("CADCraft at {addr} refused the agent connection: {why}"));
|
||||
let client_nonce = generate_nonce().map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
let challenge = self.sign_in_frame(CHALLENGE_METHOD, json!({"clientNonce": client_nonce}))?;
|
||||
if challenge.get("ok") != Some(&Value::Bool(true)) {
|
||||
return Err(refused(challenge.get("error").and_then(Value::as_str).unwrap_or("no challenge")));
|
||||
}
|
||||
let field = |key: &str| challenge.pointer(&format!("/result/{key}")).and_then(Value::as_str).unwrap_or_default().to_string();
|
||||
let (server_nonce, server_proof) = (field("serverNonce"), field("serverProof"));
|
||||
if !proof_matches(token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
format!("the program on {addr} did not prove it is the CADCraft that published the agent connection; start CADCraft again"),
|
||||
));
|
||||
}
|
||||
let proof = handshake_proof(token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
let signed = self.sign_in_frame(AUTH_METHOD, json!({"proof": proof}))?;
|
||||
if signed.get("ok") != Some(&Value::Bool(true)) {
|
||||
return Err(refused(signed.get("error").and_then(Value::as_str).unwrap_or("authentication failed")));
|
||||
}
|
||||
self.authed = true;
|
||||
Ok(())
|
||||
}
|
||||
/// One sign-in frame (id 0; requests count from 1) and its reply, within [`SIGN_IN_WAIT`].
|
||||
fn sign_in_frame(&mut self, method: &str, params: Value) -> std::io::Result<Value> {
|
||||
let addr = self.addr.clone();
|
||||
let Some((reader, writer)) = self.conn.as_mut() else { return Err(std::io::Error::other("not connected")) };
|
||||
writer.set_read_timeout(Some(SIGN_IN_WAIT)).ok();
|
||||
writeln!(writer, "{}", json!({"id": 0, "method": method, "params": params}))?;
|
||||
writer.flush()?;
|
||||
let mut reply = String::new();
|
||||
let n = read_reply_line(reader, &mut reply, SIGN_IN_REPLY)?;
|
||||
writer.set_read_timeout(Some(REPLY_WAIT)).ok();
|
||||
if n == 0 {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, format!("{addr} closed the connection during the sign-in")));
|
||||
}
|
||||
serde_json::from_str(&reply).map_err(|_| {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, format!("{addr} did not answer the sign-in; is that CADCraft's agent connection?"))
|
||||
})
|
||||
}
|
||||
/// On failure the flag says whether the request may already have reached the server.
|
||||
fn roundtrip(&mut self, line: &str) -> Result<String, (std::io::Error, bool)> {
|
||||
if self.conn.is_none() {
|
||||
@@ -230,6 +310,11 @@ impl Remote {
|
||||
}
|
||||
self.set_token(req);
|
||||
let line = req.to_string();
|
||||
// The agent server refuses a longer line and closes the connection; nothing was sent.
|
||||
if self.handshake.is_some() && line.len() > craft_automation::security::MAX_REQUEST_BYTES {
|
||||
let why = format!("the request is longer than the {} bytes the agent connection takes", craft_automation::security::MAX_REQUEST_BYTES);
|
||||
return Err((std::io::Error::new(std::io::ErrorKind::InvalidInput, why), false));
|
||||
}
|
||||
if !self.authed && line.len() > crate::control_token::MAX_UNAUTHENTICATED_LINE {
|
||||
let mut ping = json!({"id": req.get("id").cloned().unwrap_or(Value::Null), "method": "ping"});
|
||||
self.set_token(&mut ping);
|
||||
@@ -333,7 +418,18 @@ impl Backend for Remote {
|
||||
}
|
||||
/// What this backend talks to, for messages.
|
||||
fn describe(&self) -> String {
|
||||
format!("connected to CADCraft at {}", self.addr)
|
||||
if self.handshake.is_some() {
|
||||
format!("the open CADCraft window at {}", self.addr)
|
||||
} else {
|
||||
format!("connected to CADCraft at {}", self.addr)
|
||||
}
|
||||
}
|
||||
/// The window's agent server holds requests to Options › AI Agents' folders; `--control` to none.
|
||||
fn agent_folders(&mut self) -> Result<Value, String> {
|
||||
if self.handshake.is_some() {
|
||||
return Err("the window holds agents to the folders of Options › AI Agents; `cadcraft-cli mcp` answers `agent_folders` for it".into());
|
||||
}
|
||||
Ok(crate::live::folders_reply(&craft_control::agents::AgentFolders::default(), false))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -525,6 +621,13 @@ impl Backend for Headless {
|
||||
fn describe(&self) -> String {
|
||||
"headless CADCraft session".into()
|
||||
}
|
||||
/// The automation roots it runs in, if any.
|
||||
fn agent_folders(&mut self) -> Result<Value, String> {
|
||||
let mut folders = craft_control::agents::AgentFolders::default();
|
||||
folders.read = self.roots.as_ref().and_then(|r| r.read_root().map(Path::to_path_buf));
|
||||
folders.write = self.roots.as_ref().and_then(|r| r.write_root().map(Path::to_path_buf));
|
||||
Ok(crate::live::folders_reply(&folders, self.roots.is_some()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -11,10 +11,12 @@
|
||||
pub mod args;
|
||||
mod backend;
|
||||
pub mod control_token;
|
||||
pub mod live;
|
||||
mod server;
|
||||
mod tools;
|
||||
|
||||
pub use backend::{Backend, Headless, Remote};
|
||||
pub use live::{Live, LiveConfig};
|
||||
pub use server::{PROTOCOL_VERSION, Server};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Plain `cadcraft-cli mcp` with the suite's `AI-MCP` flag: tools go to the open CADCraft window
|
||||
//! while the ArtCraft Launcher's switch lets agents use it, found through the connection file the
|
||||
//! app publishes in its settings folder, and otherwise to a session without a window, as `mcp`
|
||||
//! always did (`--headless` forces that). The file is read again on every tool call, so the app may
|
||||
//! start, quit or move to another port while the MCP client stays connected; the client's
|
||||
//! configuration holds no port and no token.
|
||||
//!
|
||||
//! While agents may use the app but it is closed, Options › AI Agents › When CADCraft is closed (or
|
||||
//! `--when-closed`) decides: start the app and wait for it, work without a window, or an error that
|
||||
//! says what to do. A session that went headless stays headless for the rest of the MCP session, so
|
||||
//! the drawing doesn't move under the agent.
|
||||
//!
|
||||
//! The lookup is the framework's, shared by every Craft app ([`craft_control::agents::Live`]); this
|
||||
//! module supplies CADCraft's parts: where its settings are, its window client
|
||||
//! ([`Remote::signed_in`]) and its headless session ([`Headless`]).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use cadcraft_engine::agent_settings;
|
||||
use cadcraft_engine::file_access::AutomationRoots;
|
||||
use craft_control::agents::{self, AgentFolders, Consent, HeadlessFolders, Route, Window};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub use craft_control::agents::{LAUNCH_TIMEOUT, LaunchFn, WhenAppClosed, mcp_flag};
|
||||
|
||||
use crate::backend::{Backend, Headless, Remote};
|
||||
|
||||
/// The id the ArtCraft Launcher's app list names CADCraft by (its catalog id).
|
||||
pub const LAUNCHER_APP_ID: &str = "cadcraft";
|
||||
/// The app's name in the lookup's messages and in its default agent folder,
|
||||
/// `Documents/ArtCraft/Agents/CADCraft`.
|
||||
pub const APP_NAME: &str = "CADCraft";
|
||||
/// The desktop app's file name beside the CLI (without `.exe`).
|
||||
const APP_EXE: &str = "cadcraft";
|
||||
|
||||
/// Whether agents may use the open window now: with the suite's `AI-MCP` flag, the ArtCraft
|
||||
/// Launcher's switch. CADCraft had no agent consent of its own before the switch (`--control` is a
|
||||
/// launch option, not a consent), so without the flag agents get no window this way.
|
||||
pub fn agents_allowed_now() -> bool {
|
||||
agents::agents_allowed(agents::mcp_flag(), agents::launcher_allows(LAUNCHER_APP_ID), false)
|
||||
}
|
||||
|
||||
/// The default agent folder, `Documents/ArtCraft/Agents/CADCraft`.
|
||||
pub fn default_folder() -> Option<PathBuf> {
|
||||
agents::default_folder(APP_NAME)
|
||||
}
|
||||
|
||||
/// The folders the open window holds agent requests to: Options › AI Agents' folders, the default
|
||||
/// agent folder for an empty one (made when used). The app uses the same.
|
||||
pub fn window_folders(settings: &agent_settings::AgentSettings, default: Option<&Path>) -> AgentFolders {
|
||||
settings.folders_with(default)
|
||||
}
|
||||
|
||||
/// The `agent_folders` tool's answer: the folders, and whether files outside them are refused.
|
||||
pub fn folders_reply(folders: &AgentFolders, confined: bool) -> Value {
|
||||
let mut answer = agents::folders_answer(folders);
|
||||
answer["confined"] = json!(confined);
|
||||
if !confined {
|
||||
answer["note"] = json!("This session is not held to folders: keep to the files the person gave you.");
|
||||
}
|
||||
answer
|
||||
}
|
||||
|
||||
/// What [`Live`] needs from the CLI.
|
||||
pub struct LiveConfig {
|
||||
/// The app's settings folder: its connection file, token file and agent settings.
|
||||
pub config_dir: PathBuf,
|
||||
/// Overrides the app's closed-app choice (`--when-closed`).
|
||||
pub when_closed: Option<WhenAppClosed>,
|
||||
/// The CLI's `--automation-read-root` and `--automation-write-root`.
|
||||
pub read_root: Option<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
/// Starts the app; `None` when this install can't (no app beside the CLI).
|
||||
pub launch: Option<LaunchFn>,
|
||||
pub launch_timeout: Duration,
|
||||
/// Whether the person lets agents use the open app ([`agents_allowed_now`]); tests replace it.
|
||||
pub allowed: fn() -> bool,
|
||||
/// The default agent folder for an empty folder setting ([`default_folder`]); tests replace it.
|
||||
pub default_folder: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl LiveConfig {
|
||||
/// The lookup for the app with its settings in `config_dir`.
|
||||
pub fn new(config_dir: PathBuf) -> Self {
|
||||
LiveConfig {
|
||||
config_dir,
|
||||
when_closed: None,
|
||||
read_root: None,
|
||||
write_root: None,
|
||||
launch: None,
|
||||
launch_timeout: LAUNCH_TIMEOUT,
|
||||
allowed: agents_allowed_now,
|
||||
default_folder: default_folder(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A session without a window and the folders it is held to.
|
||||
struct HeadlessSession {
|
||||
backend: Headless,
|
||||
folders: AgentFolders,
|
||||
confined: bool,
|
||||
}
|
||||
|
||||
type Shared = agents::Live<Arc<Mutex<Remote>>, Arc<Mutex<HeadlessSession>>>;
|
||||
|
||||
/// The backend of plain `cadcraft-cli mcp` with the `AI-MCP` flag: each call goes where
|
||||
/// [`craft_control::agents::Live::resolve`] says.
|
||||
pub struct Live {
|
||||
shared: Shared,
|
||||
config_dir: PathBuf,
|
||||
default_folder: Option<PathBuf>,
|
||||
allowed: fn() -> bool,
|
||||
}
|
||||
|
||||
impl Live {
|
||||
/// The lookup with `cfg`; nothing is looked up until the first call.
|
||||
pub fn new(cfg: LiveConfig) -> Self {
|
||||
let LiveConfig { config_dir, when_closed, read_root, write_root, launch, launch_timeout, allowed, default_folder } = cfg;
|
||||
let consent = move |dir: &Path| Consent::new(allowed(), agent_settings::load(dir));
|
||||
let connect = |w: &Window| Remote::signed_in(&w.addr(), w.token.clone()).map(|r| Arc::new(Mutex::new(r))).map_err(|e| e.to_string());
|
||||
let headless = move |folders: &HeadlessFolders| headless_session(folders, allowed()).map(|h| Arc::new(Mutex::new(h)));
|
||||
let mut shared = agents::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, headless);
|
||||
shared.when_closed = when_closed;
|
||||
shared.read_roots = read_root.into_iter().collect();
|
||||
shared.write_root = write_root;
|
||||
shared.launch = launch;
|
||||
shared.launch_timeout = launch_timeout;
|
||||
shared.default_folder = default_folder.clone();
|
||||
Live { shared: agents::Live::new(shared), config_dir, default_folder, allowed }
|
||||
}
|
||||
}
|
||||
|
||||
/// The headless session for `folders`. Without folders it is held to none, as `mcp` always was,
|
||||
/// unless agents are `allowed`: then the folders are the app's agent folders, and having none
|
||||
/// (the default folder couldn't be made) refuses every file rather than none.
|
||||
fn headless_session(folders: &HeadlessFolders, allowed: bool) -> Result<HeadlessSession, String> {
|
||||
// The CLI takes one read root, and the agent settings name one read folder.
|
||||
let read = folders.read.first().map(PathBuf::as_path);
|
||||
let write = folders.write.as_deref();
|
||||
let roots = match AutomationRoots::new(read, write)? {
|
||||
Some(roots) => Some(roots),
|
||||
None if allowed => Some(AutomationRoots::none()),
|
||||
None => None,
|
||||
};
|
||||
let mut shown = AgentFolders::default();
|
||||
shown.read = read.map(Path::to_path_buf);
|
||||
shown.write = write.map(Path::to_path_buf);
|
||||
Ok(HeadlessSession { confined: roots.is_some(), backend: Headless::default().with_automation_roots(roots), folders: shown })
|
||||
}
|
||||
|
||||
impl Backend for Live {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
match self.shared.resolve()? {
|
||||
Route::Window(window) => window.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
|
||||
Route::Headless(session) => session.lock().unwrap_or_else(PoisonError::into_inner).backend.call(method, params),
|
||||
}
|
||||
}
|
||||
/// A window may answer while agents are allowed and the session hasn't gone headless.
|
||||
fn has_ui(&self) -> bool {
|
||||
match self.shared.current() {
|
||||
Some(Route::Window(_)) => true,
|
||||
Some(Route::Headless(_)) => false,
|
||||
None => (self.allowed)(),
|
||||
}
|
||||
}
|
||||
fn describe(&self) -> String {
|
||||
match self.shared.current() {
|
||||
Some(Route::Window(window)) => window.lock().unwrap_or_else(PoisonError::into_inner).describe(),
|
||||
Some(Route::Headless(session)) => session.lock().unwrap_or_else(PoisonError::into_inner).backend.describe(),
|
||||
None => "the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it, otherwise a headless session".into(),
|
||||
}
|
||||
}
|
||||
fn agent_folders(&mut self) -> Result<Value, String> {
|
||||
match self.shared.resolve()? {
|
||||
Route::Window(_) => {
|
||||
let settings = agent_settings::load(&self.config_dir);
|
||||
Ok(folders_reply(&window_folders(&settings, self.default_folder.as_deref()), true))
|
||||
}
|
||||
Route::Headless(session) => {
|
||||
let session = session.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
Ok(folders_reply(&session.folders, session.confined))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How to start the desktop app that ships with the CLI at `cli` (detached, with no standard
|
||||
/// streams: the CLI's carry the MCP protocol, and the app must outlive the MCP client).
|
||||
pub fn launcher(cli: &Path) -> Option<LaunchFn> {
|
||||
agents::launcher(cli, APP_EXE)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use craft_automation::security::{AuthStep, ServerHandshake};
|
||||
use craft_control::agents::{Connection, TOKEN_FILE, write_connection};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
const OTHER: &str = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210";
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-live-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A stand-in for the window's agent server (`craft_automation::server`): the challenge
|
||||
/// handshake with `token`, then every request answered `{"window": true}`. Returns the port and
|
||||
/// every line it read.
|
||||
fn agent_server(token: &'static str) -> (u16, Arc<Mutex<Vec<Value>>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let log = Arc::clone(&seen);
|
||||
std::thread::spawn(move || {
|
||||
for conn in listener.incoming() {
|
||||
let Ok(conn) = conn else { continue };
|
||||
let log = Arc::clone(&log);
|
||||
std::thread::spawn(move || {
|
||||
let mut out = conn.try_clone().unwrap();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
let mut signed_in = false;
|
||||
for line in BufReader::new(conn).lines() {
|
||||
let Ok(line) = line else { return };
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
log.lock().unwrap().push(req.clone());
|
||||
let reply = if signed_in {
|
||||
json!({"id": req["id"], "ok": true, "result": {"window": true}})
|
||||
} else {
|
||||
let (reply, step) = handshake.reply(&line, token);
|
||||
signed_in = step == AuthStep::Authenticated;
|
||||
if step == AuthStep::Rejected {
|
||||
let _ = writeln!(out, "{reply}");
|
||||
return;
|
||||
}
|
||||
reply
|
||||
};
|
||||
if writeln!(out, "{reply}").is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
(port, seen)
|
||||
}
|
||||
|
||||
/// Publish a window on `port` in `dir` with `token` in its token file, as the app's link does.
|
||||
fn publish(dir: &Path, port: u16, token: &str) {
|
||||
let token_file = dir.join(TOKEN_FILE);
|
||||
std::fs::write(&token_file, token).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&token_file, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
write_connection(dir, &Connection::new(port, token_file, "CADCraft test")).unwrap();
|
||||
}
|
||||
|
||||
fn live(dir: &Path, allowed: fn() -> bool, when_closed: Option<WhenAppClosed>) -> Live {
|
||||
let mut cfg = LiveConfig::new(dir.to_path_buf());
|
||||
cfg.allowed = allowed;
|
||||
cfg.when_closed = when_closed;
|
||||
cfg.default_folder = Some(dir.join("Agents"));
|
||||
Live::new(cfg)
|
||||
}
|
||||
|
||||
/// With the window published, calls go to it after the challenge handshake, and nothing sent
|
||||
/// carries the token.
|
||||
#[test]
|
||||
fn live_calls_go_to_the_open_window_while_the_switch_allows() {
|
||||
let dir = temp("window");
|
||||
let (port, seen) = agent_server(TOKEN);
|
||||
publish(&dir, port, TOKEN);
|
||||
let mut live = live(&dir, || true, None);
|
||||
assert_eq!(live.call("ping", json!({})), Ok(json!({"window": true})));
|
||||
assert_eq!(live.call("drawing.inspect", json!({})), Ok(json!({"window": true})));
|
||||
assert!(live.has_ui());
|
||||
let seen = seen.lock().unwrap();
|
||||
assert!(seen.iter().any(|req| req["method"] == "drawing.inspect"), "{seen:?}");
|
||||
assert!(!serde_json::to_string(&*seen).unwrap().contains(TOKEN), "the token crossed the wire: {seen:?}");
|
||||
drop(seen);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// While the launcher's switch doesn't let agents in and no window is published, calls work
|
||||
/// without a window, as plain `mcp` always did, held to no folders the command didn't give.
|
||||
#[test]
|
||||
fn live_without_the_switch_works_without_a_window() {
|
||||
let dir = temp("no-switch");
|
||||
let mut live = live(&dir, || false, None);
|
||||
assert_eq!(live.call("ping", json!({})), Ok(json!("pong")));
|
||||
assert!(!live.has_ui());
|
||||
assert_eq!(live.agent_folders().unwrap()["confined"], json!(false));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A connection file a crashed app left behind (nothing listens on its port) is not a window:
|
||||
/// the closed-app choice decides, and a headless session is held to the agent folders.
|
||||
#[test]
|
||||
fn live_with_the_app_closed_follows_the_closed_app_choice() {
|
||||
let dir = temp("closed");
|
||||
let gone = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = gone.local_addr().unwrap().port();
|
||||
drop(gone);
|
||||
publish(&dir, port, TOKEN);
|
||||
|
||||
let err = live(&dir, || true, Some(WhenAppClosed::Error)).call("ping", json!({})).unwrap_err();
|
||||
assert!(err.contains("isn't running"), "{err}");
|
||||
|
||||
let mut headless = live(&dir, || true, Some(WhenAppClosed::Headless));
|
||||
assert_eq!(headless.call("ping", json!({})), Ok(json!("pong")));
|
||||
let folders = headless.agent_folders().unwrap();
|
||||
assert_eq!(folders["confined"], json!(true));
|
||||
assert_eq!(folders["write_folder"], json!(dir.join("Agents").to_string_lossy()));
|
||||
let outside = dir.parent().unwrap().join("outside.png");
|
||||
let err = headless.call("ui.render", json!({"path": outside.to_string_lossy()})).unwrap_err();
|
||||
assert!(err.contains("outside the write root"), "a file outside the agent folder is refused: {err}");
|
||||
let inside = dir.join("Agents").join("plan.png");
|
||||
assert!(headless.call("ui.render", json!({"path": inside.to_string_lossy()})).is_ok(), "one inside it is written");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A program on the published port that doesn't hold the token gets nothing from the client:
|
||||
/// it can't prove itself, so no request is sent.
|
||||
#[test]
|
||||
fn a_window_without_the_token_is_refused() {
|
||||
let dir = temp("bad-token");
|
||||
let (port, seen) = agent_server(OTHER);
|
||||
publish(&dir, port, TOKEN);
|
||||
let err = live(&dir, || true, Some(WhenAppClosed::Error)).call("drawing.inspect", json!({})).unwrap_err();
|
||||
assert!(err.contains("did not prove"), "{err}");
|
||||
assert!(seen.lock().unwrap().iter().all(|req| req["method"] != "drawing.inspect"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ pub fn tool_definitions(has_ui: bool) -> Value {
|
||||
json!({"name": "open", "description": "Open a DXF or DWG file.", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}),
|
||||
json!({"name": "save", "description": "Save the drawing (DXF or DWG by extension). A .svg, .png or .pdf path exports instead: the drawing keeps its name and unsaved changes.", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}}),
|
||||
json!({"name": "cancel", "description": "Press Escape: cancel the running command (or clear the selection).", "inputSchema": {"type": "object", "properties": {}}}),
|
||||
craft_control::agents::folders_tool(),
|
||||
];
|
||||
if has_ui {
|
||||
tools.push(json!({"name": "screenshot", "description": "Screenshot the CADCraft window (PNG).", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}}));
|
||||
@@ -137,6 +138,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Result<Value,
|
||||
"open" => b.call("app.open", a),
|
||||
"save" => b.call("app.save", a),
|
||||
"cancel" => b.call("cmdline.key", json!({"key": "escape"})),
|
||||
craft_control::agents::FOLDERS_TOOL => b.agent_folders(),
|
||||
"screenshot" => b.call("ui.screenshot", a),
|
||||
"ui_inspect" => b.call("ui.inspect", json!({})),
|
||||
"ui_click" => b.call("ui.pointer", a),
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! The contents of a dimension's anonymous `*D` block: the dimension's graphics as plain objects.
|
||||
|
||||
use cadcraft_doc::{Common, Dimension, Line, MText, Solid};
|
||||
|
||||
use super::{Color, DimGeometry, Drawing, Entity, EntityKind, Handle, LineRole, Vec2, dimension_in};
|
||||
|
||||
/// Anonymous dimension blocks (`*D1`…) with the rendered geometry, as consumers expect.
|
||||
///
|
||||
/// The entities of the block of dimension `dm` on layer `layer`, with handle 0. The DXF/DWG
|
||||
/// writer makes the blocks of a saved file with it.
|
||||
pub fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Vec<Entity> {
|
||||
// The dimension as drawn: its overrides, DIMSCALE (0 = the drawing's) and text font.
|
||||
let style = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
|
||||
let g = dimension_in(d, dm);
|
||||
let mut out = Vec::new();
|
||||
// Each part in its style colour (DIMCLRD, DIMCLRE, DIMCLRT), ByBlock when the style says so,
|
||||
// as AutoCAD writes them: readers that draw the block drew every part ByBlock, i.e. in the
|
||||
// dimension's own colour (#1052).
|
||||
let in_color = |color: Color| Common { layer: layer.into(), color, ..Common::default() };
|
||||
let (dim_c, ext_c, text_c) = (in_color(style.dim_line_color), in_color(style.ext_line_color), in_color(style.text_color));
|
||||
let line_entities = |i: usize, l: &[Vec2]| -> Vec<Entity> {
|
||||
let c = match g.line_roles.get(i) {
|
||||
Some(LineRole::Ext) => &ext_c,
|
||||
_ => &dim_c,
|
||||
};
|
||||
l.windows(2)
|
||||
.filter_map(|seg| match seg {
|
||||
[a, b] => Some(Entity { handle: Handle(0), common: c.clone(), kind: EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) }) }),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// The text's marks (arc length symbol, DIMINSPECT frame) go after the text background.
|
||||
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| !g.text_marks.contains(i)) {
|
||||
out.extend(line_entities(i, l));
|
||||
}
|
||||
for t in &g.fills {
|
||||
if let [a, b, cc] = t.as_slice() {
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: dim_c.clone(),
|
||||
kind: EntityKind::Solid(Solid { corners: [a.to3(0.0), b.to3(0.0), cc.to3(0.0), cc.to3(0.0)] }),
|
||||
});
|
||||
}
|
||||
}
|
||||
// DIMTFILL 2: the text background in DIMTFILLCLR, under the text and its marks (SOLID
|
||||
// corners go 1, 2, 4, 3).
|
||||
if style.text_fill == 2
|
||||
&& let [p0, p1, p2, p3] = g.text_fill.as_slice()
|
||||
{
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: in_color(style.text_fill_color),
|
||||
kind: EntityKind::Solid(Solid { corners: [p0.to3(0.0), p1.to3(0.0), p3.to3(0.0), p2.to3(0.0)] }),
|
||||
});
|
||||
}
|
||||
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| g.text_marks.contains(i)) {
|
||||
out.extend(line_entities(i, l));
|
||||
}
|
||||
// The text, and the part after `\X` below the dimension line as a second MTEXT, as AutoCAD
|
||||
// writes it (#1055).
|
||||
let texts = std::iter::once((g.value.clone(), g.text_pos)).chain(g.below.clone());
|
||||
for (contents, at) in texts.filter(|(t, _)| !t.is_empty()) {
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: text_c.clone(),
|
||||
kind: EntityKind::MText(MText {
|
||||
insert: at.to3(0.0),
|
||||
height: g.text_height,
|
||||
width: 0.0,
|
||||
attach: 5,
|
||||
rotation: g.text_angle,
|
||||
style: style.text_style.clone(),
|
||||
contents: DimGeometry::mtext_code(&contents),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -82,8 +82,8 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
|
||||
};
|
||||
match mode {
|
||||
cadcraft_doc::AnnoDraw::Hidden => return,
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) => {
|
||||
let mut scaled = cadcraft_doc::anno_scaled(e, f);
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } => {
|
||||
let mut scaled = cadcraft_doc::anno_placed(e, factor, by);
|
||||
scaled.common.anno_scales.clear();
|
||||
return entity_parts(b, ctx, &scaled);
|
||||
}
|
||||
|
||||
@@ -590,6 +590,7 @@ pub use table::{
|
||||
};
|
||||
|
||||
mod blocks;
|
||||
mod dim_block;
|
||||
mod dim_draw;
|
||||
mod display;
|
||||
mod draw;
|
||||
@@ -598,6 +599,7 @@ mod props;
|
||||
mod text_entity;
|
||||
mod viewports;
|
||||
|
||||
pub use dim_block::dim_block_entities;
|
||||
pub use dim_draw::{dim_text, dimension_in};
|
||||
pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha};
|
||||
pub use pipeline::{Options, build, build_entities, build_entities_in_viewport, build_plot};
|
||||
|
||||
@@ -37,6 +37,9 @@ web-time = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
# Agents in the open window: the agent link host and the Agents page of Options.
|
||||
craft-automation = { workspace = true, features = ["ui", "agents"] }
|
||||
craft-control = { workspace = true, features = ["agents"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# `Updater::ready_for_tests`.
|
||||
@@ -44,8 +47,8 @@ craft-update = { workspace = true, features = ["screen-testing"] }
|
||||
# The workspace `egui` dependency enables `default_fonts` and `monochrome_emoji_fonts` in
|
||||
# production too; the tests exercise the same installed chain as the app.
|
||||
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
|
||||
# Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) translation in tests (same naga wgpu uses).
|
||||
naga = { version = "30", features = ["wgsl-in", "glsl-out"] }
|
||||
# Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) and Metal translations in tests (same naga wgpu uses).
|
||||
naga = { version = "30", features = ["wgsl-in", "glsl-out", "msl-out"] }
|
||||
|
||||
[build-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user