mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-03 11:18:30 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
384d41d6ff | ||
|
|
6681531546 | ||
|
|
97fed2970c | ||
|
|
44fa197bcc | ||
|
|
36e8c31f0d | ||
|
|
17fb7a3c43 | ||
|
|
5ab5e6f343 | ||
|
|
5a7182240e | ||
|
|
8698649da1 | ||
|
|
4610454c58 | ||
|
|
a6add77c5a | ||
|
|
e90f00dcf3 | ||
|
|
e7d05e1b42 | ||
|
|
4f0abbefdf | ||
|
|
0f3d445d1f | ||
|
|
d55ac7ba7a | ||
|
|
7afe6b3b78 | ||
|
|
616a7c0b52 | ||
|
|
0623c42d10 | ||
|
|
738230f7ea | ||
|
|
17e0c81967 | ||
|
|
1ba557615e | ||
|
|
01d5fae93f | ||
|
|
c974978fce | ||
|
|
adca169651 | ||
|
|
77973774d0 | ||
|
|
7a8ba5545e | ||
|
|
27b3e8727d | ||
|
|
456926ff70 | ||
|
|
6295b6093f | ||
|
|
15b2085dfe | ||
|
|
f894be9117 | ||
|
|
7843840bf0 | ||
|
|
d049a1cf7f | ||
|
|
adac927d7d | ||
|
|
db08e0b293 | ||
|
|
46845744a9 | ||
|
|
60ac9ac001 | ||
|
|
bc6277da45 | ||
|
|
96c348ff8e | ||
|
|
336126a95c | ||
|
|
2d351ff5a7 | ||
|
|
2a281c8d4c | ||
|
|
82f8b17348 | ||
|
|
ce7b234161 | ||
|
|
40f2274065 | ||
|
|
8a483b4804 | ||
|
|
8d0c97e57e | ||
|
|
6f7a827f41 | ||
|
|
53d515a0d3 | ||
|
|
51ea12b976 | ||
|
|
d45a216319 | ||
|
|
deb156e09b | ||
|
|
51d89dea17 | ||
|
|
c09ab353f0 | ||
|
|
4ecd4aed42 | ||
|
|
636dd26f07 | ||
|
|
0d70d25f07 | ||
|
|
15c8926c97 | ||
|
|
300a64f711 | ||
|
|
d0747f768a | ||
|
|
7cdd052b83 | ||
|
|
9d2d4085d3 | ||
|
|
b87838fbef | ||
|
|
8e329e42b9 | ||
|
|
a9ba2b5210 | ||
|
|
f4b2112da9 | ||
|
|
f243082d64 | ||
|
|
ccdbb4207a | ||
|
|
bc37092d35 | ||
|
|
8f82887924 | ||
|
|
d643981cea | ||
|
|
46ebd11c11 | ||
|
|
27a9b91f3c | ||
|
|
e48f8805a5 | ||
|
|
0c18fdd8f8 | ||
|
|
e064c97a3d | ||
|
|
9ddc83e676 | ||
|
|
5ef8b342de | ||
|
|
9bbe7b69a3 | ||
|
|
8cde239e64 | ||
|
|
8e4bf3cd9f | ||
|
|
26c9cef4d5 | ||
|
|
931c2c799d | ||
|
|
0a43052c1f | ||
|
|
7c09b2bc14 | ||
|
|
79ba6cf891 | ||
|
|
15c3c9564a | ||
|
|
f8578a4020 | ||
|
|
ed7b601123 | ||
|
|
f288082ff3 | ||
|
|
fb07eaab7e | ||
|
|
865285ca46 | ||
|
|
5f751ee30d | ||
|
|
0fd046c4c1 | ||
|
|
7bd33b7ff1 | ||
|
|
9ce7cde286 | ||
|
|
0cf540495f | ||
|
|
6050f3c396 | ||
|
|
e37f18166d | ||
|
|
3371028cdf | ||
|
|
6cf44e32ff | ||
|
|
206d40bc0d | ||
|
|
f796d5c8fc | ||
|
|
03bf451124 | ||
|
|
2659b44569 | ||
|
|
030f8c5c88 | ||
|
|
c6402fa9a5 | ||
|
|
e5f62c9546 | ||
|
|
7364032102 | ||
|
|
9e8b027f7b | ||
|
|
2d52623dd6 | ||
|
|
f5a70b0e98 | ||
|
|
0f7940a986 | ||
|
|
13aa3a5cc6 | ||
|
|
3fe6d7e954 | ||
|
|
5950cbce24 | ||
|
|
8028efba49 | ||
|
|
76a1ece890 | ||
|
|
04dc8bc2b0 | ||
|
|
e9fa62f141 | ||
|
|
88a3069ea2 | ||
|
|
8ca0152d62 | ||
|
|
4b2dd11f64 | ||
|
|
114a3fe4e7 | ||
|
|
f760e79be9 | ||
|
|
6d0da01e75 | ||
|
|
b837e9c1e4 | ||
|
|
20e2efebf7 | ||
|
|
a193f64e04 | ||
|
|
54afe41115 | ||
|
|
4741c4a737 | ||
|
|
494dbd965b | ||
|
|
de4f74d43d | ||
|
|
14603dcf9d | ||
|
|
bea1843497 | ||
|
|
ad63f0144f | ||
|
|
911e4dd3be | ||
|
|
a6889461be | ||
|
|
f9284510ea | ||
|
|
723997489a | ||
|
|
0bc5f721fb | ||
|
|
b163dd3245 | ||
|
|
10f42e323f | ||
|
|
75ea55d956 | ||
|
|
7aaee29277 | ||
|
|
e9f1699bea | ||
|
|
334bcc3dc0 | ||
|
|
3944964adf | ||
|
|
ba2887bad0 | ||
|
|
400c5889ab | ||
|
|
2f22fdca41 | ||
|
|
bf77ffdbba | ||
|
|
98a5f5c352 | ||
|
|
74f2f29958 | ||
|
|
1b40e9ca4e | ||
|
|
566e137483 | ||
|
|
81ca3d0cc5 | ||
|
|
24f1290377 | ||
|
|
8cbc4e4ef7 | ||
|
|
e9ac879b83 | ||
|
|
ffde4b3bbe | ||
|
|
0db2d73e02 | ||
|
|
fcb2188143 | ||
|
|
ab183249f9 | ||
|
|
cd4912b003 | ||
|
|
71671af789 | ||
|
|
900bac863d | ||
|
|
9b9b9d1efc | ||
|
|
1ed527ec16 | ||
|
|
61d1f267cf | ||
|
|
b9c9162b14 | ||
|
|
a8cc7e4a5c | ||
|
|
7edd1168f6 | ||
|
|
bbf613e944 | ||
|
|
91acccc36a | ||
|
|
dec54a9ded | ||
|
|
38a239b1e9 | ||
|
|
60ac79d4b5 | ||
|
|
a65a9b36b5 | ||
|
|
808ae34499 | ||
|
|
2d9b9d1512 | ||
|
|
3504edbcdb | ||
|
|
f8769d9650 | ||
|
|
0b2cfae274 | ||
|
|
c647cb4eb9 | ||
|
|
0314c8bf2a | ||
|
|
71f4879f9c | ||
|
|
472d3661ce | ||
|
|
ca90388ff3 | ||
|
|
ded4122de0 | ||
|
|
fe3b20a37a | ||
|
|
9746b6999a | ||
|
|
0ca0af9026 | ||
|
|
6971715295 | ||
|
|
5bfba91aa8 | ||
|
|
080c96aa06 | ||
|
|
a2f732118f | ||
|
|
c2af11dfa7 | ||
|
|
b1dcb46e08 | ||
|
|
c00bc59949 | ||
|
|
1b577e9eed | ||
|
|
29bf02b6ce | ||
|
|
1998da2643 | ||
|
|
28ed9c58a7 | ||
|
|
a3560a1442 | ||
|
|
87fc77ee7d | ||
|
|
013fddd927 | ||
|
|
af412d767c | ||
|
|
6139f12b3f | ||
|
|
c40ff9603e | ||
|
|
1cae514a0d | ||
|
|
2604fa0326 | ||
|
|
595ccf2b06 | ||
|
|
e05636a26a | ||
|
|
452cac8f0c | ||
|
|
7623ee2e91 | ||
|
|
f036f6ce07 | ||
|
|
d06393f33a | ||
|
|
8acdceeb61 | ||
|
|
4ce72c668a | ||
|
|
ebeee968b5 | ||
|
|
2eaf90df4b | ||
|
|
d8cf5fbb62 | ||
|
|
bf3e607bd6 | ||
|
|
6042310fc7 | ||
|
|
1ec5d20c84 | ||
|
|
723810f768 | ||
|
|
60e22f38c4 | ||
|
|
ba63055fd3 | ||
|
|
cec2e0c04a | ||
|
|
8fb5e95f15 | ||
|
|
5f4a17cb7c | ||
|
|
1c02f239c3 | ||
|
|
ea0d0e9595 | ||
|
|
5c24bc3dcf | ||
|
|
5689203791 | ||
|
|
b99ea8905e | ||
|
|
c1c97ed00e | ||
|
|
a551f206e8 | ||
|
|
b70c8609c9 | ||
|
|
27fb887f38 | ||
|
|
906395b4d2 | ||
|
|
4a3243e70a | ||
|
|
a41ab8e249 | ||
|
|
cc560bde49 | ||
|
|
b10856b14e | ||
|
|
687e30afa2 | ||
|
|
629d56689f | ||
|
|
a6665d4040 | ||
|
|
d93c513d2a | ||
|
|
170ebd3ee4 | ||
|
|
d61ad720d7 | ||
|
|
df3b0a865c | ||
|
|
eb719cd766 | ||
|
|
3523324084 | ||
|
|
fc99200d73 | ||
|
|
bbfcd27d6c | ||
|
|
a3243c96be | ||
|
|
55ec024e31 | ||
|
|
d23c4726de | ||
|
|
f60b174711 | ||
|
|
4e58f46423 | ||
|
|
5daebac3b5 | ||
|
|
ea87dafb99 | ||
|
|
53b8a64871 | ||
|
|
64cb95d8ec | ||
|
|
4a0063f5f6 | ||
|
|
cf9a63c92f | ||
|
|
d8c2c4cb4c | ||
|
|
939fec385c | ||
|
|
36c14239cc | ||
|
|
7eaf0c3104 | ||
|
|
77bc4dba9e | ||
|
|
f2c849273c | ||
|
|
f4f0702d08 | ||
|
|
98401d6de2 | ||
|
|
97fbaf7da4 | ||
|
|
90a239b410 | ||
|
|
26fe7656af | ||
|
|
0056d148fe | ||
|
|
ca87d3acd1 | ||
|
|
cc50a8c3c5 | ||
|
|
1811abc66b | ||
|
|
5b26e817d8 | ||
|
|
15b99d94ba | ||
|
|
50a7e7a3da | ||
|
|
324e3f4e97 | ||
|
|
d28ba1ce33 | ||
|
|
f6124ce296 | ||
|
|
f197952a9c | ||
|
|
fbee9d6f5e | ||
|
|
246f13b5a7 | ||
|
|
fd11cc7c6a | ||
|
|
2ca02bf87d | ||
|
|
ab61236574 | ||
|
|
17b5b06a78 | ||
|
|
876f6ccef9 | ||
|
|
9ae49fe1df |
@@ -0,0 +1,34 @@
|
||||
name: Cache prune
|
||||
|
||||
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
|
||||
# budget, where GitHub evicts entries a run still needs. Each main CI attempt's `cache warm` leg
|
||||
# saves a new rolling entry; this deletes the entry it replaced once the attempt ends. It runs once
|
||||
# after every attempt, re-runs of failed jobs and canceled runs included (craft-common-actions
|
||||
# actions/cache-prune).
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
# A fork's pull request from a branch named main also matches `branches`.
|
||||
if: github.event.workflow_run.event == 'push' && github.event.workflow_run.head_branch == 'main' && github.event.workflow_run.head_repository.full_name == github.repository
|
||||
timeout-minutes: 10
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
# A failed pass warns; the next run's prune deletes what it missed.
|
||||
- name: Prune replaced cache entries
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@b2726eb1defb6eccdfad920cc6988e1e3ec1c3c9 # main
|
||||
continue-on-error: true
|
||||
+9
-1
@@ -22,11 +22,18 @@ Generated-in-code assets are original and have no file to list:
|
||||
- the sample drawings (`crates/engine/src/sample.rs`);
|
||||
- the synthetic two-hexagon hatch logo (`crates/io/tests/it/hatch_loop_flags.rs`, `logo`):
|
||||
original contributor geometry, generated in code from invented points, under MIT OR Apache-2.0.
|
||||
- the self-contained line drawings/DXF bytes generated by provider regressions in
|
||||
`crates/ui-egui/src/file_provider_app/tests.rs` and
|
||||
`apps/cadcraft-web/src/file_providers/browser_tests.rs` (CADCraft contributors, original test
|
||||
code/data, MIT OR Apache-2.0; no vendor drawing, external image, font or other asset is added).
|
||||
|
||||
| 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. |
|
||||
| `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`. |
|
||||
@@ -84,13 +91,14 @@ Generated-in-code assets are original and have no file to list:
|
||||
| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker |
|
||||
| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted); terminology corrections: Andrea Brandi (@starise) with OpenAI Codex (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; targeted Chamfer terminology review by a native speaker |
|
||||
| `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added |
|
||||
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif; missing rows and the Find and Replace dialog: Saleh Hassan Alnemari (@salehnemari-max) with Claude Code (AI-assisted) | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the added rows reviewed line by line by the translator, a native speaker |
|
||||
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted); 870 later rows: @HolyZephyros (AI-assisted) | Original Turkish translations of CADCraft English strings (original catalog by @ogzhnklvz; 870 later rows written from CADCraft's English strings in #3291) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app for the original catalog was reviewed by a native speaker; the 870 rows added in #3291 have not yet been reviewed by a native speaker |
|
||||
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
|
||||
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the craft-i18n#401 phase 1 changes reviewed by a native Vietnamese speaker; older rows not yet proofread in full |
|
||||
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
|
||||
| `crates/ui-egui/src/i18n/ta.tsv` | @newsbaba24x7 (AI-assisted) | Original Tamil translations of CADCraft English strings, shared with storytold/craft-i18n `locales/ta/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings; the 1,289 rows from craft-i18n reviewed there for language and terminology by native speakers, and the whole Tamil interface reviewed in the running app by native speakers Radhika and Mohan Raj (2026-11-14); no font assets added (Tamil comes from an installed font or the craft-fonts face) |
|
||||
| `crates/ui-egui/src/i18n/he.tsv` | Hagai Baram (@hrb9), AI-assisted; shared `craft-i18n#42` rows include contributions by @nocturney with ChatGPT (AI-assisted) | Original Hebrew translations of CADCraft English strings (1,444 rows shared with [storytold/craft-i18n#42](https://github.com/storytold/craft-i18n/pull/42) at `fdff86e3`, `locales/he/common.tsv` and `locales/he/cadcraft.tsv`, plus 443 additional CADCraft UI strings) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | Clean-room translations written from the plain meaning of CADCraft's English strings; no proprietary localization resources copied; terminology and the running app reviewed by @hrb9 (a native Hebrew speaker), while independent line-by-line proofreading by a second native speaker remains pending; no font assets added (Hebrew uses an installed system font or the optional `craft-fonts` face) |
|
||||
|
||||
|
||||
## PDF import
|
||||
|
||||
Generated
+221
-75
@@ -26,6 +26,29 @@ dependencies = [
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "acadrust"
|
||||
version = "0.6.6"
|
||||
source = "git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436#5d5c482b3fcb3dc77e8281474461760f32959436"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags 2.13.2",
|
||||
"byteorder",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"foldhash 0.2.0",
|
||||
"indexmap",
|
||||
"itoa",
|
||||
"memmap2",
|
||||
"nom 7.1.3",
|
||||
"oem_cp",
|
||||
"once_cell",
|
||||
"rayon",
|
||||
"ryu",
|
||||
"thiserror 2.0.21",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "accesskit"
|
||||
version = "0.25.2"
|
||||
@@ -445,7 +468,7 @@ checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -480,7 +503,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -705,7 +728,7 @@ checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -744,10 +767,10 @@ dependencies = [
|
||||
"fmv-macos-events",
|
||||
"hidapi",
|
||||
"log",
|
||||
"muda",
|
||||
"muda 0.22.0",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"pollster 1.0.1",
|
||||
"rfd",
|
||||
"pollster",
|
||||
"rfd 0.18.0",
|
||||
"ron",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -758,6 +781,8 @@ dependencies = [
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"x11-dl",
|
||||
"xkbcommon-dl",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
@@ -838,9 +863,9 @@ dependencies = [
|
||||
"craft-font-catalog",
|
||||
"craft-shx",
|
||||
"encoding_rs",
|
||||
"harfrust 0.14.0",
|
||||
"harfrust 0.16.2",
|
||||
"icu_segmenter",
|
||||
"skrifa 0.48.0",
|
||||
"skrifa 0.50.0",
|
||||
"unicode-bidi",
|
||||
]
|
||||
|
||||
@@ -855,7 +880,7 @@ dependencies = [
|
||||
name = "cadcraft-io"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"acadrust 0.6.6 (git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436)",
|
||||
"cadcraft-color",
|
||||
"cadcraft-doc",
|
||||
"cadcraft-fonts",
|
||||
@@ -959,6 +984,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-bindgen-test",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
@@ -1022,6 +1048,12 @@ dependencies = [
|
||||
"wayland-client",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cast"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.10.0"
|
||||
@@ -1111,9 +1143,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.7"
|
||||
version = "4.6.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
|
||||
checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
@@ -1121,9 +1153,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.7"
|
||||
version = "4.6.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -1133,23 +1165,23 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_complete"
|
||||
version = "4.6.11"
|
||||
version = "4.6.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f"
|
||||
checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848"
|
||||
dependencies = [
|
||||
"clap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.7"
|
||||
version = "4.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
|
||||
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1160,9 +1192,9 @@ checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
|
||||
|
||||
[[package]]
|
||||
name = "clap_mangen"
|
||||
version = "0.3.3"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "211d617eaa4b735c96c9e0228fcbdb5120ef623f2b8cb67ffb84c3e02dbc28a4"
|
||||
checksum = "a3b6a8907b1723f211693e27b9af5899b86a9512ef5b08bd4a15b6bceb30da6d"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"roff",
|
||||
@@ -1427,7 +1459,7 @@ name = "craft-dwg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"acadrust 0.6.6 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"log",
|
||||
]
|
||||
|
||||
@@ -1631,7 +1663,7 @@ dependencies = [
|
||||
"js-sys",
|
||||
"log",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"rfd",
|
||||
"rfd 0.17.2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
@@ -1955,7 +1987,7 @@ dependencies = [
|
||||
"craft-settings",
|
||||
"craft-win32",
|
||||
"egui",
|
||||
"muda",
|
||||
"muda 0.21.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
@@ -2124,7 +2156,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2250,7 +2282,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"pollster 1.0.1",
|
||||
"pollster",
|
||||
"profiling",
|
||||
"raw-window-handle",
|
||||
"ron",
|
||||
@@ -2371,7 +2403,7 @@ dependencies = [
|
||||
"kittest",
|
||||
"log",
|
||||
"open",
|
||||
"pollster 1.0.1",
|
||||
"pollster",
|
||||
"serde",
|
||||
"tempfile",
|
||||
"toml",
|
||||
@@ -2407,9 +2439,9 @@ checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.42"
|
||||
version = "0.8.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679"
|
||||
checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"core_detect",
|
||||
@@ -2442,7 +2474,7 @@ checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2722,7 +2754,7 @@ checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2773,7 +2805,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3077,14 +3109,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "harfrust"
|
||||
version = "0.14.0"
|
||||
version = "0.16.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86aa776d6d32b072119e1f1650f4db843ff4382a4aaa6a2c9c4e35703cd377cb"
|
||||
checksum = "d29463af2039b1bd7ccf60cb9f11fafbfe14b18ab6fb1790dab57aba456e155f"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"read-fonts 0.45.1",
|
||||
"read-fonts 0.47.0",
|
||||
"smallvec",
|
||||
"yoke",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3199,9 +3232,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "heapless"
|
||||
version = "0.8.0"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
|
||||
checksum = "411fdef4df93751117bd9ef8caa0e7f99c65dafec5bd84313eb8e2fdd75e32f2"
|
||||
dependencies = [
|
||||
"hash32",
|
||||
"stable_deref_trait",
|
||||
@@ -4004,9 +4037,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "lyon_geom"
|
||||
@@ -4064,6 +4097,16 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minicov"
|
||||
version = "0.3.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
@@ -4118,6 +4161,24 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "muda"
|
||||
version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a775675be5389020a44c56efbdf3bbea8b97f47dfdd325e6c5c5213797a7e0aa"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"dpi",
|
||||
"keyboard-types",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"png",
|
||||
"thiserror 2.0.21",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion"
|
||||
version = "0.8.1"
|
||||
@@ -4148,9 +4209,9 @@ checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
|
||||
|
||||
[[package]]
|
||||
name = "naga"
|
||||
version = "30.0.1"
|
||||
version = "30.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"
|
||||
checksum = "fd0dd362bf26c0ffdd143df6da66a25d287e196eff482f117771010b207ad163"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"bit-set",
|
||||
@@ -4263,6 +4324,15 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
@@ -4361,6 +4431,7 @@ dependencies = [
|
||||
"objc2-core-video",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-quartz-core 0.3.2",
|
||||
"objc2-uniform-type-identifiers 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4737,7 +4808,7 @@ dependencies = [
|
||||
"objc2-link-presentation",
|
||||
"objc2-quartz-core 0.2.2",
|
||||
"objc2-symbols",
|
||||
"objc2-uniform-type-identifiers",
|
||||
"objc2-uniform-type-identifiers 0.2.2",
|
||||
"objc2-user-notifications",
|
||||
]
|
||||
|
||||
@@ -4764,6 +4835,16 @@ dependencies = [
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-uniform-type-identifiers"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7902ac02859fc1f7045f8b598c63f1ae0cc7efeaa06a9bc9f3d9a3c955974fa4"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-user-notifications"
|
||||
version = "0.2.2"
|
||||
@@ -4798,6 +4879,12 @@ version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "oorandom"
|
||||
version = "11.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
|
||||
|
||||
[[package]]
|
||||
name = "open"
|
||||
version = "5.4.5"
|
||||
@@ -5155,15 +5242,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pollster"
|
||||
version = "0.4.0"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
|
||||
|
||||
[[package]]
|
||||
name = "pollster"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336"
|
||||
checksum = "7e9b9cf600136f5b976fbc5727d58c26e1ecab8ee23088d44ef1c7af793550ab"
|
||||
|
||||
[[package]]
|
||||
name = "polycool"
|
||||
@@ -5414,14 +5495,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.45.1"
|
||||
version = "0.47.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4edc8db0d972de88e53a085b1f01fb3fbdae7bb0cb7a0ce2b2f8285a412fe3ef"
|
||||
checksum = "a39d2f8f681030a7bcbbcf3e8568775ac2393afd51401a2e2133ee89e3953897"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"foldhash 0.2.0",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
"smallvec",
|
||||
"yoke",
|
||||
]
|
||||
|
||||
@@ -5528,7 +5610,31 @@ dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"percent-encoding",
|
||||
"pollster 0.4.0",
|
||||
"raw-window-handle",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rfd"
|
||||
version = "0.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4b9d4857b10297ffb0f64cae711e983a7aeaee561848d56d429d3858bd8ed93"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"dispatch2",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"log",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-uniform-type-identifiers 0.3.2",
|
||||
"percent-encoding",
|
||||
"pollster",
|
||||
"raw-window-handle",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
@@ -5570,12 +5676,11 @@ checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
|
||||
|
||||
[[package]]
|
||||
name = "ron"
|
||||
version = "0.12.2"
|
||||
version = "0.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81116b9531d61eabc41aeb228e4b6b2435bcca3233b98cf3b3077d4e6e9debb3"
|
||||
checksum = "97b3fe97c18ff24299ea56f802c5693eb34266fb0bc8317f4e101debc8a3ceaf"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"typeid",
|
||||
@@ -5593,12 +5698,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rstar"
|
||||
version = "0.13.0"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5912b862fa5ffb462607bfd1e35036c458c537921f508c8235a83d5f3987edfe"
|
||||
checksum = "d95c33d01e9acee7be3363f99e9ef88b1a587186e81e03843fbe39d77d9a0c1f"
|
||||
dependencies = [
|
||||
"heapless",
|
||||
"num-traits",
|
||||
"ordered-float",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -5837,7 +5943,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5861,7 +5967,7 @@ checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5975,12 +6081,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.48.0"
|
||||
version = "0.50.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a5213b4825bac3587046330052d61bfac7bd3bd0d203c758d7c2ef726fcea034"
|
||||
checksum = "e85ba678a6023a063d0a78c8770f1c166674ef46af13523d05eff67430f79dfe"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.45.1",
|
||||
"once_cell",
|
||||
"read-fonts 0.47.0",
|
||||
"smallvec",
|
||||
"yoke",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6167,9 +6276,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -6184,7 +6293,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6293,7 +6402,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6811,7 +6920,7 @@ dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
@@ -6824,6 +6933,45 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test"
|
||||
version = "0.3.79"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"cast",
|
||||
"js-sys",
|
||||
"libm",
|
||||
"minicov",
|
||||
"nu-ansi-term",
|
||||
"num-traits",
|
||||
"oorandom",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-bindgen-test-macro",
|
||||
"wasm-bindgen-test-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test-macro"
|
||||
version = "0.3.79"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test-shared"
|
||||
version = "0.2.129"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe"
|
||||
|
||||
[[package]]
|
||||
name = "wayland-backend"
|
||||
version = "0.3.17"
|
||||
@@ -7129,8 +7277,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "wgpu-hal"
|
||||
version = "30.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"arrayvec",
|
||||
@@ -7710,7 +7856,7 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -7782,7 +7928,7 @@ dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
"zbus_names",
|
||||
"zvariant",
|
||||
"zvariant_utils",
|
||||
@@ -7857,7 +8003,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -7901,7 +8047,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7989,7 +8135,7 @@ dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
"zvariant_utils",
|
||||
]
|
||||
|
||||
@@ -8002,6 +8148,6 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.10",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
+10
-3
@@ -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]
|
||||
@@ -61,10 +63,10 @@ rayon = "1"
|
||||
# rendering / formats
|
||||
tiny-skia = { version = "0.12", default-features = false, features = ["std", "simd", "png-format"] }
|
||||
lyon_tessellation = "1.0.22"
|
||||
skrifa = "0.48"
|
||||
skrifa = "0.50"
|
||||
# Text shaping (OpenType GSUB/GPOS, HarfBuzz port on read-fonts; egui's epaint is still on 0.12,
|
||||
# so the graph has both) and the Unicode Bidirectional Algorithm for right-to-left drawing text.
|
||||
harfrust = "0.14"
|
||||
harfrust = "0.16"
|
||||
unicode-bidi = "0.3.18"
|
||||
# Line-break opportunities between Thai words for MTEXT word wrap (Thai writes no spaces between
|
||||
# words): UAX #14 with ICU4X's compiled-in LSTM word model (not its dictionaries).
|
||||
@@ -85,13 +87,14 @@ egui = { version = "0.37", default-features = false, features = ["default_fonts"
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
wasm-bindgen-test = "0.3.79"
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
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"] }
|
||||
rfd = "0.17"
|
||||
rfd = "0.18"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
[workspace.lints.rust]
|
||||
@@ -129,6 +132,10 @@ hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
|
||||
# wgpu-hal that picks a Metal language version the system compiler accepts, not the OS's alone
|
||||
# (#1631; upstream gfx-rs/wgpu#10687). See vendor/wgpu-hal/CADCRAFT.md for when to remove it.
|
||||
wgpu-hal = { path = "vendor/wgpu-hal" }
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
|
||||
@@ -10,9 +10,435 @@ 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) is licensed under the
|
||||
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.
|
||||
is available from crates.io and the repository above. The licence text and upstream third-party
|
||||
notices are retained in licenses/dwg/, copied verbatim from craft-libs at
|
||||
8fa4db64a9bb943520259ea95331a303ba788f21, the revision this repository pins.
|
||||
|
||||
acadrust's DWG reader and writer include code ported and adapted from ACadSharp
|
||||
(https://github.com/DomCR/ACadSharp), Copyright (c) 2021 Albert Domenech, under the MIT License.
|
||||
The Mozilla Public License 2.0 text and the upstream third-party notices follow.
|
||||
|
||||
The following text is reproduced verbatim from licenses/dwg/acadrust-MPL-2.0.txt:
|
||||
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under the name "LEGAL", and included in all Covered Software
|
||||
distributed in Source Code Form. Except to the extent prohibited by
|
||||
statute or regulation, such description must be sufficiently detailed
|
||||
for a recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
|
||||
The following text is reproduced verbatim from licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md:
|
||||
|
||||
# Third-Party Notices
|
||||
|
||||
## ACadSharp
|
||||
|
||||
The DWG reader and writer include code ported and adapted from ACadSharp. The repository
|
||||
history's initial DWG support commit identifies the source classes explicitly, including
|
||||
`DwgStreamReaderBase`, `DwgLZ77AC21Decompressor`, `DwgFileHeaderWriterAC18`, and
|
||||
`DwgObjectWriter`. Their current Rust implementations are in `src/io/dwg`.
|
||||
|
||||
Copyright (c) 2021 Albert Domenech
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
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.
|
||||
|
||||
|
||||
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
|
||||
|
||||
@@ -124,7 +124,7 @@ numbers):
|
||||
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
|
||||
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
|
||||
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
|
||||
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული) and Tamil (தமிழ், with an installed Tamil font), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
|
||||
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული), Tamil (தமிழ், with an installed Tamil font), Dutch (Nederlands) and European Portuguese (Português (Portugal)) (catalogs in `storytold/craft-i18n`; fall back to English until embedded), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
|
||||
| Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) |
|
||||
|
||||
## Quick start
|
||||
@@ -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 |
|
||||
|
||||
@@ -61,6 +61,8 @@ fn install_io() {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
//! An INSERT's ATTRIBs and SEQEND reached from AutoLISP through the CLI (`entnext`, `entget`,
|
||||
//! `entmod`, `entdel`): the walk, a value edit (one Undo step), names that stop holding (erase,
|
||||
//! ATTSYNC, Undo, a reinsert that reuses the parent handle), edits that are refused, and the
|
||||
//! name bounds.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A scratch directory, removed on drop also when an assertion fails.
|
||||
struct Dir(PathBuf);
|
||||
|
||||
impl Dir {
|
||||
fn new(tag: &str) -> Dir {
|
||||
let p = std::env::temp_dir().join(format!("cc-cli-attribs-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&p);
|
||||
std::fs::create_dir_all(&p).expect("create scratch dir");
|
||||
Dir(p)
|
||||
}
|
||||
|
||||
fn path(&self, name: &str) -> PathBuf {
|
||||
self.0.join(name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// One `cadcraft-cli run`: a fresh profile, an optional drawing to open, and the steps to run.
|
||||
struct Run {
|
||||
args: Vec<String>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn new(dir: &Dir, file: Option<&Path>) -> Run {
|
||||
let mut args: Vec<String> = vec!["run".into(), "--config-dir".into(), dir.path("profile").to_string_lossy().into_owned()];
|
||||
match file {
|
||||
Some(f) => args.push(f.to_string_lossy().into_owned()),
|
||||
None => args.push("--metric".into()),
|
||||
}
|
||||
Run { args }
|
||||
}
|
||||
|
||||
fn cmd(&mut self, id: &str, params: Value) -> &mut Run {
|
||||
self.args.push("--cmd".into());
|
||||
self.args.push(format!("{id} {params}"));
|
||||
self
|
||||
}
|
||||
|
||||
fn lisp(&mut self, code: &str) -> &mut Run {
|
||||
self.cmd("lisp", json!({ "code": code }))
|
||||
}
|
||||
|
||||
fn save(&mut self, path: &Path) -> &mut Run {
|
||||
self.args.push("--save".into());
|
||||
self.args.push(path.to_string_lossy().into_owned());
|
||||
self
|
||||
}
|
||||
|
||||
fn output(&self) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&self.args).output().expect("run cadcraft-cli")
|
||||
}
|
||||
|
||||
/// Run it: the value each `lisp` step returned, in order (commands' own results are left out).
|
||||
fn out(&self) -> Vec<Value> {
|
||||
let out = self.output();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{}: {}", self.args.join(" "), err);
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
text.lines()
|
||||
.map(|l| serde_json::from_str::<Value>(l).unwrap_or_else(|e| panic!("not a result: {l}: {e}")))
|
||||
.filter(|v| v.get("value").is_some())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The value a `lisp` step returned, as AutoLISP's `prin1` shows it.
|
||||
fn value(results: &[Value], i: usize) -> String {
|
||||
match results.get(i).and_then(|r| r.get("value")) {
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
other => panic!("step {i}: no value: {other:?} in {results:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` without the quotes `prin1` puts round a string.
|
||||
fn text(results: &[Value], i: usize) -> String {
|
||||
value(results, i).trim_matches('"').to_string()
|
||||
}
|
||||
|
||||
/// TAGBLK.dxf: block TAGBLK with a circle and four attribute definitions (TAG1 D1, TAG2 D2
|
||||
/// verify, TAG3 P3 preset, TAG4 C4 constant). Opening the file again gives the drawing fresh
|
||||
/// names.
|
||||
const FIXTURE: &str = r#"(progn
|
||||
(entmake '((0 . "BLOCK") (2 . "TAGBLK") (70 . 2) (10 0.0 0.0 0.0)))
|
||||
(entmake '((0 . "CIRCLE") (10 -5.0 0.0 0.0) (40 . 2.0)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 0.0 0.0) (40 . 2.5) (1 . "D1") (3 . "P1") (2 . "TAG1") (70 . 0)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 5.0 0.0) (40 . 2.5) (1 . "D2") (3 . "P2") (2 . "TAG2") (70 . 4)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 10.0 0.0) (40 . 2.5) (1 . "P3") (3 . "P3") (2 . "TAG3") (70 . 8)))
|
||||
(entmake '((0 . "ATTDEF") (10 0.0 15.0 0.0) (40 . 2.5) (1 . "C4") (3 . "P4") (2 . "TAG4") (70 . 2)))
|
||||
(entmake '((0 . "ENDBLK"))))"#;
|
||||
|
||||
/// The first reference: INSERT TAGBLK at (10,10) with TAG1 "A1", TAG2 verified as "B1" and
|
||||
/// TAG3 preset ("P3"); TAG4 is constant, so it is not asked.
|
||||
const INSERT: &str = r#"(command "_.-INSERT" "TAGBLK" '(10 10) 1 1 0 "A1" "B1" "")"#;
|
||||
|
||||
fn fixture(dir: &Dir) -> PathBuf {
|
||||
let file = dir.path("TAGBLK.dxf");
|
||||
let mut run = Run::new(dir, None);
|
||||
let out = run.lisp(FIXTURE).save(&file).out();
|
||||
assert_eq!(text(&out, 0), "TAGBLK");
|
||||
file
|
||||
}
|
||||
|
||||
/// The walk from the entity named `i`: its records' tags and values, then the type of the record
|
||||
/// that ends the run.
|
||||
const WALK: &str = r#"(progn
|
||||
(setq e (entnext i) n 0 ts nil ed nil)
|
||||
(while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e))))))
|
||||
(setq ts (append ts (list (cdr (assoc 2 ed)) (cdr (assoc 1 ed)))) n (1+ n) e (entnext e)))
|
||||
(list n ts (cdr (assoc 0 ed))))"#;
|
||||
|
||||
#[test]
|
||||
fn the_walk_reaches_each_attrib_and_ends_at_the_seqend() {
|
||||
let dir = Dir::new("walk");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(
|
||||
r#"(progn
|
||||
{INSERT}
|
||||
(setq i (entlast))
|
||||
(setvar "ATTREQ" 0)
|
||||
(command "_.-INSERT" "TAGBLK" '(60 10) 1 1 0)
|
||||
(setvar "ATTREQ" 1)
|
||||
(setq second (entlast))
|
||||
"inserted")"#
|
||||
))
|
||||
// Three attributes, then the SEQEND owned by the reference, then the next main entity.
|
||||
.lisp(&format!(
|
||||
r#"(progn {WALK}
|
||||
(list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (equal (entnext e) second) (cdr (assoc 0 (entget (entnext e))))))"#
|
||||
))
|
||||
// The second reference (no attribute answers, ATTREQ 0) took the definitions' values; its
|
||||
// own run ends at its SEQEND, with nothing drawn after it.
|
||||
.lisp(&format!(
|
||||
r#"(progn (setq i second) {WALK}
|
||||
(list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (entnext e)))"#
|
||||
))
|
||||
.out();
|
||||
assert_eq!(text(&out, 0), "inserted");
|
||||
assert_eq!(value(&out, 1), "(3 (\"TAG1\" \"A1\" \"TAG2\" \"B1\" \"TAG3\" \"P3\") \"SEQEND\" T T \"INSERT\")");
|
||||
// Its record ends with its own SEQEND, and nothing is drawn after the reference.
|
||||
assert_eq!(value(&out, 2), "(3 (\"TAG1\" \"D1\" \"TAG2\" \"D2\" \"TAG3\" \"P3\") \"SEQEND\" T nil)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_edit_changes_group_one_only_and_is_one_undo_step() {
|
||||
let dir = Dir::new("value");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 2 (entget a))) (cdr (assoc 1 (entget a)))))"#))
|
||||
.lisp(
|
||||
r#"(progn
|
||||
(setq d (entget a) r (entmod (subst (cons 1 "A2") (assoc 1 d) d)))
|
||||
(list (cdr (assoc 0 r)) (cdr (assoc 1 r)) (cdr (assoc 1 (entget a))) (cdr (assoc 2 (entget a)))
|
||||
(cdr (assoc 40 (entget a))) (cdr (assoc 8 (entget a))) (equal (cdr (assoc -2 (entget a))) i)))"#,
|
||||
)
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
// The edit is one Undo step: the value is back, and the name given before it holds no
|
||||
// longer (the drawing it was given in was restored from another state).
|
||||
.lisp(
|
||||
r#"(list (entget a) (progn (setq e (entnext (entlast)))
|
||||
(list (cdr (assoc 2 (entget e))) (cdr (assoc 1 (entget e))))))"#,
|
||||
)
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(\"TAG1\" \"A1\")");
|
||||
assert_eq!(value(&out, 1), "(\"ATTRIB\" \"A2\" \"A2\" \"TAG1\" 2.5 \"0\" T)");
|
||||
assert_eq!(value(&out, 2), "(nil (\"TAG1\" \"A1\"))");
|
||||
// Redo brings the edit back; the name given before the Undo still names nothing.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i) d (entget a)) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#))
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
.cmd("redo", json!({ "count": 1 }))
|
||||
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(value(&out, 1), "(nil \"A2\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_stops_holding_after_erase_attsync_and_undo() {
|
||||
let dir = Dir::new("stale");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run.lisp(&format!(r#"(progn {INSERT} (setq i (entlast)) (cdr (assoc 5 (entget i))))"#)).out();
|
||||
let handle = text(&out, 0);
|
||||
|
||||
// Erased: the reference's records are gone with it, and the name names nothing.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (cdr (assoc 2 (entget a))))"#))
|
||||
.cmd("erase", json!({ "handles": [handle] }))
|
||||
.lisp("(list (entget a) (entnext a))")
|
||||
// Undone: the reference is back, but a name given before the Undo does not come back with
|
||||
// it: a walk gives its records new ones.
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
// ATTSYNC rebuilds the reference's attributes: the name given before names nothing, and
|
||||
// the rebuilt attribute keeps the value.
|
||||
.lisp("(progn (setq b (entnext (entlast))) (cdr (assoc 2 (entget b))))")
|
||||
.cmd("attsync", json!({ "name": "TAGBLK" }))
|
||||
.lisp("(list (entget b) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "\"TAG1\"");
|
||||
assert_eq!(value(&out, 1), "(nil nil)");
|
||||
assert_eq!(value(&out, 2), "(nil \"A1\")");
|
||||
assert_eq!(value(&out, 3), "\"TAG1\"");
|
||||
assert_eq!(value(&out, 4), "(nil \"A1\")");
|
||||
|
||||
// A reinsert after an Undo takes the parent handle back: the old name must not name its
|
||||
// attribute.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 5 (entget i))) (cdr (assoc 2 (entget a)))))"#))
|
||||
.cmd("undo", json!({ "count": 1 }))
|
||||
.lisp(&format!(r#"(progn {INSERT} (list (cdr (assoc 5 (entget (entlast)))) (entget a)))"#))
|
||||
.lisp("(list (cdr (assoc 2 (entget (entnext (entlast))))) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(text(&out, 0), format!("(\"{handle}\" \"TAG1\")"));
|
||||
// The same handle, and the old name names nothing in the new reference.
|
||||
assert_eq!(value(&out, 1), format!("(\"{handle}\" nil)"));
|
||||
assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_of_anything_but_the_value_is_refused() {
|
||||
let dir = Dir::new("refused");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(
|
||||
r#"(progn {INSERT} (setq i (entlast) a (entnext i) s (entnext (entnext (entnext a))) p0 (cdr (assoc 10 (entget a)))) "named")"#
|
||||
))
|
||||
.lisp(
|
||||
r#"(progn
|
||||
(setq d (entget a))
|
||||
(list
|
||||
(entmod (subst (cons 2 "TAGX") (assoc 2 d) d))
|
||||
(entmod (subst (cons 40 9.0) (assoc 40 d) d))
|
||||
(entmod (subst (cons 0 "SEQEND") (assoc 0 d) d))
|
||||
(entmod (entget s))
|
||||
(entmod (subst (cons 410 "Layout2") (assoc 410 d) d))
|
||||
(entmod (subst (cons 1 "A2") (assoc 1 d) (subst (cons 410 "Layout2") (assoc 410 d) d)))
|
||||
(entdel a) (entdel s)))"#,
|
||||
)
|
||||
// Nothing changed: the same tag, value, height and place, and the name still holds.
|
||||
.lisp(
|
||||
r#"(progn (setq e (entnext (entlast)) d (entget e))
|
||||
(list (cdr (assoc 2 d)) (cdr (assoc 1 d)) (cdr (assoc 40 d)) (equal p0 (cdr (assoc 10 d))) (equal (entget a) d)))"#,
|
||||
)
|
||||
.out();
|
||||
assert_eq!(text(&out, 0), "named");
|
||||
assert_eq!(value(&out, 1), "(nil nil nil nil nil nil nil nil)");
|
||||
assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\" 2.5 T T)");
|
||||
}
|
||||
|
||||
/// A minimal drawing: `before` (records written as they are), then an INSERT with `attribs`
|
||||
/// ATTRIBs (each tag T, value V) and its SEQEND, last in the file. A header `$HANDSEED` is
|
||||
/// written when `handseed` is given (a hostile file can name any next handle).
|
||||
fn insert_dxf_seed(attribs: usize, before: &str, handseed: Option<&str>) -> String {
|
||||
let mut s = String::with_capacity(before.len().saturating_add(attribs.saturating_mul(96)));
|
||||
if let Some(seed) = handseed {
|
||||
s.push_str("0\nSECTION\n2\nHEADER\n9\n$HANDSEED\n5\n");
|
||||
s.push_str(seed);
|
||||
s.push('\n');
|
||||
s.push_str("0\nENDSEC\n");
|
||||
}
|
||||
s.push_str("0\nSECTION\n2\nENTITIES\n");
|
||||
s.push_str(before);
|
||||
s.push_str("0\nINSERT\n5\n20\n8\n0\n66\n1\n2\nTAGBLK\n10\n0\n20\n0\n30\n0\n");
|
||||
for _ in 0..attribs {
|
||||
s.push_str("0\nATTRIB\n5\n21\n8\n0\n10\n0\n20\n0\n30\n0\n40\n1\n1\nV\n2\nT\n70\n0\n");
|
||||
}
|
||||
s.push_str("0\nSEQEND\n5\n22\n0\nENDSEC\n0\nEOF\n");
|
||||
s
|
||||
}
|
||||
|
||||
fn insert_dxf(attribs: usize, before: &str) -> String {
|
||||
insert_dxf_seed(attribs, before, None)
|
||||
}
|
||||
|
||||
/// The number of records a walk from `i` reaches, counting each `entnext`.
|
||||
const COUNT: &str = r#"(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)"#;
|
||||
|
||||
#[test]
|
||||
fn a_walk_is_stable_and_its_names_are_no_handles() {
|
||||
let dir = Dir::new("stable");
|
||||
// A file's line one below the top of the handle range: it keeps its handle, and the
|
||||
// records' names, which are no handles, never name it.
|
||||
let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n";
|
||||
let file = dir.path("hostile.dxf");
|
||||
std::fs::write(&file, insert_dxf(2, before)).expect("write the DXF");
|
||||
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(
|
||||
r#"(progn
|
||||
(setq i (handent "20") line (handent "FFFFFFFFFFFFFFFE") a (entnext i) b (entnext i))
|
||||
(list (cdr (assoc 5 (entget line))) (equal (handent "FFFFFFFFFFFFFFFE") line)
|
||||
(not (equal a line)) (cdr (assoc 0 (entget a))) (equal a b) (equal (entnext a) (entnext b))))"#,
|
||||
)
|
||||
.lisp(&format!(r#"(progn (setq i (handent "20")) {COUNT})"#))
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(\"FFFFFFFFFFFFFFFE\" T T \"ATTRIB\" T T)");
|
||||
// Two ATTRIBs and the SEQEND, then the line (it sorts last by its handle), then the end.
|
||||
assert_eq!(value(&out, 1), "4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_reference_does_not_revive_an_old_name() {
|
||||
let dir = Dir::new("restored");
|
||||
let file = fixture(&dir);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(
|
||||
r#"(progn {INSERT} (setq i (entlast) a (entnext i))
|
||||
(entdel i)
|
||||
(setq gone (entget a))
|
||||
(entdel i)
|
||||
(list gone (entget a) (cdr (assoc 1 (entget (entnext i))))))"#
|
||||
))
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(nil nil \"A1\")", "the reference comes back, the old name does not");
|
||||
|
||||
// ERASE, then OOPS: the same. The old name never comes back with the reference.
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let handle = text(&run.lisp(&format!(r#"(progn {INSERT} (cdr (assoc 5 (entget (entlast)))))"#)).out(), 0);
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(&format!(r#"(progn {INSERT} (setq a (entnext (entlast))) "named")"#))
|
||||
.cmd("erase", json!({ "handles": [handle] }))
|
||||
.cmd("oops", json!({}))
|
||||
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
|
||||
.out();
|
||||
assert_eq!(value(&out, 1), "(nil \"A1\")", "OOPS restores the reference, not the old name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_line_is_never_a_record() {
|
||||
let dir = Dir::new("handseed");
|
||||
let file = dir.path("hostile.dxf");
|
||||
// A file's $HANDSEED in the reserved band is the file's own handle and is not followed (#913),
|
||||
// so the line made after the walk gets the drawing's seed. The record's name is no handle:
|
||||
// the line is the line, and the name still names the attribute. The engine's
|
||||
// `a_new_object_at_any_handle_is_never_a_record` puts the seed at the top of the range.
|
||||
std::fs::write(&file, insert_dxf_seed(1, "", Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF");
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(r#"(progn (setq i (handent "20") a (entnext i)) (list (cdr (assoc 0 (entget a))) (cdr (assoc 5 (entget (entlast))))))"#)
|
||||
.lisp(r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#)
|
||||
.lisp(r#"(list (cdr (assoc 0 (entget a))) (entdel a))"#)
|
||||
.out();
|
||||
assert_eq!(value(&out, 0), "(\"ATTRIB\" \"20\")");
|
||||
assert_eq!(value(&out, 1), "\"100\"");
|
||||
assert_eq!(value(&out, 2), "(\"ATTRIB\" nil)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_at_the_top_of_the_handle_range_walk_as_lines() {
|
||||
let dir = Dir::new("walkrange");
|
||||
let file = dir.path("hostile.dxf");
|
||||
let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n\
|
||||
0\nLINE\n5\nFFFFFFFFFFFFFFFF\n8\n0\n10\n0\n20\n0\n30\n0\n11\n6\n21\n6\n31\n0\n";
|
||||
std::fs::write(&file, insert_dxf_seed(1, before, Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF");
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run
|
||||
.lisp(r#"(progn (setq i (handent "20")) (entnext i))"#)
|
||||
// The line at the top of the range is in the drawing. Without it, the walk from the line
|
||||
// below would end in nil, and nil equals the nil `handent` gives for a handle not there.
|
||||
.lisp(r#"(progn (setq top (handent "FFFFFFFFFFFFFFFF")) (list (cdr (assoc 0 (entget top))) (cdr (assoc 5 (entget top)))))"#)
|
||||
.lisp(r#"(equal (entnext (handent "FFFFFFFFFFFFFFFE")) top)"#)
|
||||
.lisp("(entnext top)")
|
||||
.out();
|
||||
assert_eq!(value(&out, 1), "(\"LINE\" \"FFFFFFFFFFFFFFFF\")");
|
||||
assert_eq!(value(&out, 2), "T");
|
||||
assert_eq!(value(&out, 3), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_session_names_at_most_65536_records() {
|
||||
let dir = Dir::new("names");
|
||||
let file = dir.path("many.dxf");
|
||||
// One more attribute than the limit of names: the walk stops at the limit, and nothing in the
|
||||
// drawing changed.
|
||||
std::fs::write(&file, insert_dxf(65_537, "")).expect("write the DXF");
|
||||
let mut run = Run::new(&dir, Some(&file));
|
||||
let out = run.lisp(&format!("(progn (setq i (entlast)) {COUNT})")).lisp(&format!("(progn (setq i (entlast)) {COUNT})")).out();
|
||||
assert_eq!(value(&out, 0), "65536");
|
||||
// The names given by the first walk hold: the second walk is the same.
|
||||
assert_eq!(value(&out, 1), "65536");
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
mod block_resources;
|
||||
mod cli;
|
||||
mod dash_limit_note;
|
||||
mod drafting_spacing;
|
||||
|
||||
@@ -37,3 +37,6 @@ wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url", "MessageEvent", "UrlSearchParams", "MediaQueryList", "Event", "EventTarget", "CustomEvent", "CustomEventInit"] }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
|
||||
wasm-bindgen-test = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Same-origin file-provider bridge. Persistence belongs to the registered provider, not WASM.
|
||||
//!
|
||||
//! Callbacks enqueue commands for a later egui frame. Exporting bytes never acknowledges them.
|
||||
|
||||
use cadcraft_ui_egui::file_providers::{Host, Resource};
|
||||
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure, prelude::wasm_bindgen};
|
||||
|
||||
thread_local! {
|
||||
static CURRENT_CONTEXT: std::cell::RefCell<Option<egui::Context>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
const API: &str = "cadcraftFileProviders";
|
||||
const EVENT: &str = "cadcraft-file-provider";
|
||||
const MAX_BYTES: u32 = 80 * 1024 * 1024;
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(catch, js_namespace = Uint8Array, js_name = from)]
|
||||
fn copy_event_bytes(bytes: &[u8]) -> Result<Uint8Array, JsValue>;
|
||||
}
|
||||
|
||||
fn error(message: impl ToString) -> JsValue {
|
||||
JsValue::from_str(&message.to_string())
|
||||
}
|
||||
|
||||
fn object(value: &serde_json::Value) -> Result<JsValue, JsValue> {
|
||||
js_sys::JSON::parse(&value.to_string())
|
||||
}
|
||||
|
||||
fn set(target: &JsValue, key: &str, value: &JsValue) -> Result<(), JsValue> {
|
||||
if Reflect::set(target, &key.into(), value)? { Ok(()) } else { Err(error("file-provider API is not writable")) }
|
||||
}
|
||||
|
||||
// Inspect UTF-16 length before copying a host string into WASM memory.
|
||||
fn bounded_string(value: JsValue, max_units: u32) -> Result<String, JsValue> {
|
||||
let text = value.dyn_into::<js_sys::JsString>().map_err(|_| error("resource fields must be strings"))?;
|
||||
if text.length() > max_units {
|
||||
return Err(error("resource field is too large"));
|
||||
}
|
||||
text.as_string().ok_or_else(|| error("invalid resource field"))
|
||||
}
|
||||
|
||||
fn resource(value: JsValue) -> Result<Resource, JsValue> {
|
||||
if value.is_null() || !value.is_object() || Array::is_array(&value) {
|
||||
return Err(error("resource entries must be objects"));
|
||||
}
|
||||
let entry = value.dyn_into::<Object>()?;
|
||||
let id = bounded_string(Reflect::get(&entry, &"id".into())?, 160)?;
|
||||
let name = bounded_string(Reflect::get(&entry, &"name".into())?, 255)?;
|
||||
let updated = Reflect::get(&entry, &"updatedAt".into())?;
|
||||
let updated_at = if updated.is_undefined() { String::new() } else { bounded_string(updated, 100)? };
|
||||
Ok(Resource { id, name, updated_at })
|
||||
}
|
||||
|
||||
fn wake_later(ctx: &egui::Context) {
|
||||
let fallback = ctx.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
CURRENT_CONTEXT.with(|current| current.borrow().as_ref().unwrap_or(&fallback).request_repaint());
|
||||
});
|
||||
}
|
||||
|
||||
/// Makes the capability discoverable without enabling it or changing the browser's writer.
|
||||
pub fn install(host: Host, ctx: egui::Context) -> Result<(), JsValue> {
|
||||
let window = web_sys::window().ok_or_else(|| error("no window"))?;
|
||||
CURRENT_CONTEXT.with(|current| *current.borrow_mut() = Some(ctx.clone()));
|
||||
if Reflect::has(&window, &API.into())? {
|
||||
// A graphics restart keeps the page capability and pending requests, and renews its wake target.
|
||||
return Ok(());
|
||||
}
|
||||
// A delayed result from an earlier page must never address a new document's request.
|
||||
let crypto = Reflect::get(&window, &"crypto".into())?;
|
||||
let random = Reflect::get(&crypto, &"getRandomValues".into())?.dyn_into::<Function>()?;
|
||||
let nonce = Uint8Array::new_with_length(16);
|
||||
random.call1(&crypto, &nonce)?;
|
||||
host.set_session(nonce.to_vec().iter().map(|byte| format!("{byte:02x}")).collect()).map_err(error)?;
|
||||
|
||||
let api = Object::new();
|
||||
set(&api, "protocolVersion", &1.into())?;
|
||||
set(&api, "app", &"cadcraft".into())?;
|
||||
set(&api, "capabilities", &object(&serde_json::json!(["revisionAck", "externalRecents", "saveDestination", "openBytes"]))?)?;
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let register = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<String, JsValue>>::new(move |id, label, namespace| {
|
||||
let id = bounded_string(id, 160)?;
|
||||
let label = bounded_string(label, 100)?;
|
||||
let namespace = bounded_string(namespace, 160)?;
|
||||
let connection = h.connect(id, label, namespace).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(connection)
|
||||
});
|
||||
set(&api, "registerProvider", register.as_ref())?;
|
||||
register.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let unregister = Closure::<dyn FnMut() -> Result<bool, JsValue>>::new(move || {
|
||||
h.disconnect().map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(true)
|
||||
});
|
||||
set(&api, "unregisterProvider", unregister.as_ref())?;
|
||||
unregister.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let enabled = Closure::<dyn FnMut(JsValue) -> Result<bool, JsValue>>::new(move |value: JsValue| {
|
||||
let value = value.as_bool().ok_or_else(|| error("enabled must be a boolean"))?;
|
||||
h.set_enabled(value).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(true)
|
||||
});
|
||||
set(&api, "setEnabled", enabled.as_ref())?;
|
||||
enabled.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let resources = Closure::<dyn FnMut(JsValue, JsValue) -> Result<(), JsValue>>::new(move |connection, value: JsValue| {
|
||||
let connection = bounded_string(connection, 160)?;
|
||||
if !Array::is_array(&value) {
|
||||
return Err(error("resources must be an array of at most 100 entries"));
|
||||
}
|
||||
let entries = value.dyn_into::<Array>()?;
|
||||
if entries.length() > 100 {
|
||||
return Err(error("resources must be an array of at most 100 entries"));
|
||||
}
|
||||
// Read only bounded metadata; do not copy or serialize arbitrary host properties.
|
||||
let resources = entries.iter().map(resource).collect::<Result<Vec<_>, _>>()?;
|
||||
h.set_resources(&connection, resources).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "setResources", resources.as_ref())?;
|
||||
resources.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let request_open = Closure::<dyn FnMut(JsValue) -> Result<String, JsValue>>::new(move |resource| {
|
||||
let resource = bounded_string(resource, 160)?;
|
||||
let request = h.request_open(&resource).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(request)
|
||||
});
|
||||
set(&api, "requestOpen", request_open.as_ref())?;
|
||||
request_open.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let open = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, name, value: JsValue| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let name = bounded_string(name, 255)?;
|
||||
let bytes = value.dyn_into::<Uint8Array>().map_err(|_| error("bytes must be a Uint8Array"))?;
|
||||
if bytes.length() > MAX_BYTES {
|
||||
return Err(error("file exceeds the provider limit"));
|
||||
}
|
||||
h.open(request, name, bytes.to_vec()).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "openResource", open.as_ref())?;
|
||||
open.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let cancel_open = Closure::<dyn FnMut(JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, message| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let message = bounded_string(message, 1024)?;
|
||||
h.cancel_open(request, message).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "cancelOpen", cancel_open.as_ref())?;
|
||||
cancel_open.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let result = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, status, resource| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let status = bounded_string(status, 8)?;
|
||||
let resource = bounded_string(resource, 160)?;
|
||||
h.result(request, status, resource).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "saveResult", result.as_ref())?;
|
||||
result.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let dialog = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, destination, name| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let destination = bounded_string(destination, 8)?;
|
||||
let name = bounded_string(name, 255)?;
|
||||
h.resolve_dialog(&request, &destination, &name).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "resolveSaveDialog", dialog.as_ref())?;
|
||||
dialog.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let snapshot = Closure::<dyn FnMut() -> Result<JsValue, JsValue>>::new(move || object(&h.snapshot()));
|
||||
set(&api, "snapshot", snapshot.as_ref())?;
|
||||
snapshot.forget();
|
||||
set(&window, API, &Object::freeze(&api))?;
|
||||
dispatch(&serde_json::json!({"type": "ready", "protocolVersion": 1}), None)
|
||||
}
|
||||
|
||||
fn dispatch(metadata: &serde_json::Value, bytes: Option<Vec<u8>>) -> Result<(), JsValue> {
|
||||
let detail = object(metadata)?;
|
||||
if let Some(bytes) = bytes {
|
||||
set(&detail, "bytes", ©_event_bytes(&bytes)?.into())?;
|
||||
}
|
||||
let init = web_sys::CustomEventInit::new();
|
||||
init.set_detail(&detail);
|
||||
let event = web_sys::CustomEvent::new_with_event_init_dict(EVENT, &init)?;
|
||||
web_sys::window().ok_or_else(|| error("no window"))?.dispatch_event(&event)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn publish(host: &Host) {
|
||||
if host.publish_events_with(dispatch, |error| log::error!("file-provider event delivery failed: {error:?}")) {
|
||||
CURRENT_CONTEXT.with(|current| {
|
||||
if let Some(ctx) = current.borrow().as_ref() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod browser_tests;
|
||||
@@ -0,0 +1,271 @@
|
||||
//! Original, self-contained DXF fixture. Rust closures create genuine JS exceptions; no JS source.
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_engine::{Session, cmd::file};
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
|
||||
use serde_json::json;
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
|
||||
use wasm_bindgen_test::*;
|
||||
|
||||
wasm_bindgen_test_configure!(run_in_browser);
|
||||
|
||||
fn error(message: impl ToString) -> JsValue {
|
||||
JsValue::from_str(&message.to_string())
|
||||
}
|
||||
fn field(object: &JsValue, name: &str) -> Result<JsValue, JsValue> {
|
||||
Reflect::get(object, &name.into())
|
||||
}
|
||||
fn text(object: &JsValue, name: &str) -> Result<String, JsValue> {
|
||||
field(object, name)?.as_string().ok_or_else(|| error(format!("missing string field {name}")))
|
||||
}
|
||||
fn call(object: &JsValue, name: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
|
||||
let function = field(object, name)?.dyn_into::<Function>()?;
|
||||
let array = Array::new();
|
||||
for argument in arguments {
|
||||
array.push(argument);
|
||||
}
|
||||
function.apply(object, &array)
|
||||
}
|
||||
|
||||
struct Page {
|
||||
window: web_sys::Window,
|
||||
api: JsValue,
|
||||
host: cadcraft_ui_egui::file_providers::Host,
|
||||
ctx: egui::Context,
|
||||
events: Rc<RefCell<Vec<JsValue>>>,
|
||||
listener: Closure<dyn FnMut(web_sys::Event)>,
|
||||
}
|
||||
impl Page {
|
||||
fn install(app: &CadApp) -> Result<Self, JsValue> {
|
||||
let window = web_sys::window().ok_or_else(|| error("no browser window"))?;
|
||||
if Reflect::has(&window, &super::API.into())? {
|
||||
return Err(error("fixture requires a fresh owned page"));
|
||||
}
|
||||
let host = app.file_providers.clone();
|
||||
let ctx = egui::Context::default();
|
||||
let events = Rc::new(RefCell::new(Vec::new()));
|
||||
let seen = events.clone();
|
||||
let listener = Closure::<dyn FnMut(web_sys::Event)>::new(move |event: web_sys::Event| {
|
||||
if let Ok(event) = event.dyn_into::<web_sys::CustomEvent>() {
|
||||
seen.borrow_mut().push(event.detail());
|
||||
}
|
||||
});
|
||||
window.add_event_listener_with_callback(super::EVENT, listener.as_ref().unchecked_ref())?;
|
||||
let mut page = Self { window, api: JsValue::UNDEFINED, host, ctx, events, listener };
|
||||
super::install(page.host.clone(), page.ctx.clone())?;
|
||||
page.api = field(&page.window, super::API)?;
|
||||
Ok(page)
|
||||
}
|
||||
fn api(&self, method: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
|
||||
call(&self.api, method, arguments)
|
||||
}
|
||||
fn latest(&self, kind: &str) -> Result<JsValue, JsValue> {
|
||||
self.events
|
||||
.borrow()
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|event| text(event, "type").is_ok_and(|name| name == kind))
|
||||
.cloned()
|
||||
.ok_or_else(|| error(format!("missing real window event {kind}")))
|
||||
}
|
||||
fn tick(&self, app: &mut CadApp) {
|
||||
self.ctx.run_ui(Default::default(), |ui| app.logic(ui.ctx())).drop_without_applying_deltas();
|
||||
}
|
||||
fn choose(&self, app: &mut CadApp) -> Result<String, JsValue> {
|
||||
let value = app.run("qsave", serde_json::Value::Null).map_err(error)?;
|
||||
value
|
||||
.get("requestId")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| error("qsave did not create a real provider choice"))
|
||||
}
|
||||
fn captured_save(&self, app: &mut CadApp) -> Result<String, JsValue> {
|
||||
let request = self.choose(app)?;
|
||||
super::publish(&self.host);
|
||||
assert_eq!(text(&self.latest("saveDialog")?, "requestId")?, request);
|
||||
self.api("resolveSaveDialog", &[request.clone().into(), "provider".into(), "Fixture.dxf".into()])?;
|
||||
Ok(request)
|
||||
}
|
||||
// Both the injected callback and production publisher are entered through catch-enabled
|
||||
// Function::call0. Restore the exact own descriptor (or remove our inherited-method shadow)
|
||||
// BEFORE assertions, even when an uncaught production exception returns Err from call0.
|
||||
fn with_replacement(&self, target: &JsValue, key: &str, replacement: &JsValue) -> Result<Result<JsValue, JsValue>, JsValue> {
|
||||
let object = field(&js_sys::global(), "Object")?;
|
||||
let descriptor = call(&object, "getOwnPropertyDescriptor", &[target.clone(), key.into()])?;
|
||||
let original = field(target, key)?;
|
||||
let host = self.host.clone();
|
||||
let operation = Closure::<dyn FnMut()>::new(move || super::publish(&host));
|
||||
let outcome = match Reflect::set(target, &key.into(), replacement) {
|
||||
Ok(true) => operation.as_ref().unchecked_ref::<Function>().call0(&JsValue::UNDEFINED),
|
||||
Ok(false) => Err(error("injected method is not writable")),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
if descriptor.is_undefined() {
|
||||
if !Reflect::delete_property(target.unchecked_ref::<Object>(), &key.into())? {
|
||||
return Err(error("could not remove injected method"));
|
||||
}
|
||||
} else {
|
||||
call(&object, "defineProperty", &[target.clone(), key.into(), descriptor.clone()])?;
|
||||
}
|
||||
let restored = call(&object, "getOwnPropertyDescriptor", &[target.clone(), key.into()])?;
|
||||
if field(target, key)? != original || restored.is_undefined() != descriptor.is_undefined() {
|
||||
return Err(error("injected property was not restored exactly"));
|
||||
}
|
||||
if !descriptor.is_undefined() {
|
||||
for attribute in ["value", "get", "set", "writable", "enumerable", "configurable"] {
|
||||
if field(&restored, attribute)? != field(&descriptor, attribute)? {
|
||||
return Err(error("injected property descriptor changed"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
fn fail_copy(&self) -> Result<u32, JsValue> {
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
let seen = calls.clone();
|
||||
let fault = Closure::<dyn FnMut(JsValue) -> Result<JsValue, JsValue>>::new(move |_| {
|
||||
seen.set(seen.get() + 1);
|
||||
Err(js_sys::RangeError::new("synthetic CAD byte-copy failure").into())
|
||||
});
|
||||
let array = field(&js_sys::global(), "Uint8Array")?;
|
||||
self.with_replacement(&array, "from", fault.as_ref())??;
|
||||
Ok(calls.get())
|
||||
}
|
||||
fn fail_dispatch(&self, kind: &str) -> Result<u32, JsValue> {
|
||||
let original = field(&self.window, "dispatchEvent")?.dyn_into::<Function>()?;
|
||||
let window: JsValue = self.window.clone().into();
|
||||
let wanted = kind.to_string();
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
let seen = calls.clone();
|
||||
let fault = Closure::<dyn FnMut(JsValue) -> Result<JsValue, JsValue>>::new(move |event: JsValue| {
|
||||
if text(&field(&event, "detail")?, "type")? == wanted {
|
||||
seen.set(seen.get() + 1);
|
||||
Err(js_sys::RangeError::new("synthetic CAD metadata dispatch failure").into())
|
||||
} else {
|
||||
original.call1(&window, &event)
|
||||
}
|
||||
});
|
||||
self.with_replacement(&self.window, "dispatchEvent", fault.as_ref())??;
|
||||
Ok(calls.get())
|
||||
}
|
||||
}
|
||||
impl Drop for Page {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.window.remove_event_listener_with_callback(super::EVENT, self.listener.as_ref().unchecked_ref());
|
||||
let _ = Reflect::delete_property(self.window.unchecked_ref::<Object>(), &super::API.into());
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn real_window_delivery_recovery_preserves_dxf_and_consumes_actual_cad_actions() -> Result<(), JsValue> {
|
||||
// Production codec hooks, on this fixture's fresh browser page only. Native app fixtures
|
||||
// use cadcraft_io directly and never replace their process-global test hooks.
|
||||
file::set_io(file::IoHooks {
|
||||
read: |bytes, name| cadcraft_io::read(bytes, name).map_err(|error| error.to_string()),
|
||||
write: |drawing, name| cadcraft_io::write(drawing, name).map_err(|error| error.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
file::set_write_as(|drawing, name, options| {
|
||||
cadcraft_io::write_with(drawing, name, &cadcraft_io::SaveOptions { version: options.version, binary: options.binary })
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
let mut app = CadApp::new(Session::new(), Services { no_file_system: true, ..Default::default() });
|
||||
app.run("line", json!({"points":[[0,0],[10,10]]})).map_err(error)?;
|
||||
let page = Page::install(&app)?;
|
||||
let connection = page.api("registerProvider", &["fixture".into(), "Fixture storage".into(), "account-one".into()])?;
|
||||
let resources = Array::new();
|
||||
for id in ["file-1", "file-2"] {
|
||||
let resource = Object::new();
|
||||
Reflect::set(&resource, &"id".into(), &id.into())?;
|
||||
Reflect::set(&resource, &"name".into(), &"Fixture.dxf".into())?;
|
||||
Reflect::set(&resource, &"updatedAt".into(), &"".into())?;
|
||||
resources.push(&resource);
|
||||
}
|
||||
page.api("setResources", &[connection.clone(), resources.into()])?;
|
||||
let uid = app.session.state().map_err(error)?.uid;
|
||||
let checkpoint = app.session.state().map_err(error)?.saved.clone();
|
||||
let chooser = page.choose(&mut app)?;
|
||||
assert_eq!(page.fail_dispatch("saveDialog")?, 1);
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
assert_eq!(text(&page.latest("saveFailed")?, "requestId")?, chooser);
|
||||
assert!(page.api("resolveSaveDialog", &[chooser.into(), "provider".into(), "Late.dxf".into()]).is_err());
|
||||
assert!(!page.host.busy());
|
||||
assert!(Arc::ptr_eq(&app.session.state().map_err(error)?.saved, &checkpoint));
|
||||
|
||||
let read = page.api("requestOpen", &["file-2".into()])?;
|
||||
assert_eq!(page.fail_dispatch("openRequested")?, 1);
|
||||
let failed_read = page.latest("openFailed")?;
|
||||
assert_eq!(field(&failed_read, "requestId")?, read);
|
||||
assert_eq!(text(&failed_read, "resourceId")?, "file-2");
|
||||
assert_eq!(field(&failed_read, "connectionId")?, connection);
|
||||
assert!(!page.host.busy());
|
||||
|
||||
let failed = page.captured_save(&mut app)?;
|
||||
let later_read = page.api("requestOpen", &["file-2".into()])?;
|
||||
app.set_status("Awaiting the synthetic byte-copy failure");
|
||||
assert_eq!(page.fail_copy()?, 1, "actual catch-enabled production copy must throw exactly once");
|
||||
assert!(!page.events.borrow().iter().any(|event| text(event, "type").is_ok_and(|kind| kind == "save")));
|
||||
assert_eq!(field(&page.latest("openRequested")?, "requestId")?, later_read);
|
||||
assert!(page.api("saveResult", &[failed.clone().into(), "saved".into(), "file-1".into()]).is_err());
|
||||
page.api("cancelOpen", &[later_read, "".into()])?;
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
assert_eq!(text(&page.latest("saveFailed")?, "requestId")?, failed);
|
||||
let state = app.session.state().map_err(error)?;
|
||||
assert_eq!(state.uid, uid);
|
||||
assert!(state.is_dirty() && Arc::ptr_eq(&state.saved, &checkpoint));
|
||||
assert!(!page.host.busy() && page.host.bound_document("file-1").is_none());
|
||||
assert!(app.status.as_ref().is_some_and(|(message, _)| message.contains("File provider save failed")));
|
||||
|
||||
let retry = page.captured_save(&mut app)?;
|
||||
assert_ne!(retry, failed);
|
||||
super::publish(&page.host);
|
||||
let saved = page.latest("save")?;
|
||||
assert_eq!(text(&saved, "requestId")?, retry);
|
||||
assert_eq!(text(&saved, "filename")?, "Fixture.dxf");
|
||||
assert_eq!(text(&saved, "documentId")?, uid.to_string());
|
||||
assert_eq!(field(&saved, "connectionId")?, connection);
|
||||
let bytes = field(&saved, "bytes")?.dyn_into::<Uint8Array>()?;
|
||||
assert!(bytes.length() > 0);
|
||||
let drawing = cadcraft_io::read(&bytes.to_vec(), "Fixture.dxf").map_err(error)?;
|
||||
assert_eq!(drawing.model.len(), app.session.state().map_err(error)?.doc.model.len());
|
||||
assert!(!drawing.model.is_empty());
|
||||
assert!(page.host.pending_for(uid) && app.session.state().map_err(error)?.is_dirty());
|
||||
let captured = app.session.state().map_err(error)?.doc.clone();
|
||||
let captured_revision = app.session.state().map_err(error)?.revision;
|
||||
app.run("line", json!({"points":[[20,20],[30,30]]})).map_err(error)?;
|
||||
page.api("saveResult", &[retry.clone().into(), "saved".into(), "file-1".into()])?;
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
let terminal = page.latest("saved")?;
|
||||
assert_eq!(text(&terminal, "requestId")?, retry);
|
||||
assert_eq!(text(&terminal, "resourceId")?, "file-1");
|
||||
assert_eq!(text(&terminal, "revision")?, captured_revision.to_string());
|
||||
let state = app.session.state().map_err(error)?;
|
||||
assert!(state.is_dirty() && Arc::ptr_eq(&state.saved, &captured), "ACK owns its snapshot, never later edits");
|
||||
assert_eq!(page.host.bound_document("file-1"), Some(uid));
|
||||
assert!(!page.host.busy());
|
||||
|
||||
let open = page.api("requestOpen", &["file-2".into()])?;
|
||||
super::publish(&page.host);
|
||||
page.api("openResource", &[open.clone(), "Fixture.dxf".into(), bytes.into()])?;
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
let opened = page.latest("opened")?;
|
||||
assert_eq!(field(&opened, "requestId")?, open);
|
||||
assert_eq!(text(&opened, "resourceId")?, "file-2");
|
||||
assert_eq!(field(&opened, "connectionId")?, connection);
|
||||
assert_eq!(text(&opened, "namespace")?, "account-one");
|
||||
let imported = app.session.state().map_err(error)?;
|
||||
assert_ne!(imported.uid, uid);
|
||||
assert_eq!(imported.doc.model.len(), drawing.model.len());
|
||||
let original = app.session.docs.iter().find(|doc| doc.uid == uid).ok_or_else(|| error("original drawing was lost on provider open"))?;
|
||||
assert!(original.is_dirty() && Arc::ptr_eq(&original.saved, &captured));
|
||||
assert!(!page.host.busy());
|
||||
page.api("unregisterProvider", &[])?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -15,6 +15,8 @@ mod api;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod download;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod file_providers;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod host;
|
||||
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
@@ -47,6 +49,7 @@ mod web {
|
||||
self.1.drain(&mut self.0);
|
||||
self.0.system_animations = self.3.as_ref().map(|reduced| !reduced.matches());
|
||||
self.0.logic(ctx);
|
||||
crate::file_providers::publish(&self.0.file_providers);
|
||||
let drawing = self.0.session.state().ok();
|
||||
crate::push_title(&mut self.4, drawing.map(|d| d.title.as_str()), drawing.is_some_and(|d| d.is_dirty()), set_page_title);
|
||||
// The crate suppresses duplicates, so reporting after every logic callback
|
||||
@@ -82,6 +85,7 @@ mod web {
|
||||
self.1.take_dropped(ui.ctx());
|
||||
}
|
||||
self.0.ui(ui);
|
||||
crate::file_providers::publish(&self.0.file_providers);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +140,8 @@ mod web {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
@@ -179,6 +185,13 @@ mod web {
|
||||
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
|
||||
let control = crate::api::install(cc.egui_ctx.clone());
|
||||
let mut app = CadApp::new(session, services()).with_control(control);
|
||||
// The provider capability is independent of the parent and same-document host modes.
|
||||
// Avoid two hosts competing for the same Save command.
|
||||
if app_bridge.is_none() {
|
||||
if let Err(error) = crate::file_providers::install(app.file_providers.clone(), cc.egui_ctx.clone()) {
|
||||
log::error!("file provider capability could not be installed: {error:?}");
|
||||
}
|
||||
}
|
||||
app.system_languages =
|
||||
web_sys::window().map(|w| w.navigator().languages().iter().filter_map(|v| v.as_string()).collect()).unwrap_or_default();
|
||||
if let Some(profile) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::options::PROFILE_KEY)) {
|
||||
|
||||
@@ -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.
|
||||
@@ -51,7 +57,7 @@ rfd = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
muda = { version = "0.21", default-features = false }
|
||||
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"] }
|
||||
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
|
||||
|
||||
@@ -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]
|
||||
|
||||
+106
-7
@@ -199,6 +199,8 @@ pub fn install_io() {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
@@ -219,11 +221,34 @@ fn services() -> Services {
|
||||
pick_pgp: Some(Box::new(|dir: Option<&str>| {
|
||||
file_dialog(&Pick::Pgp(dir.unwrap_or_default().into())).pick_file().map(|p| p.to_string_lossy().to_string())
|
||||
})),
|
||||
open_folder: Some(Box::new(|dir: &str| open_folder(dir).map_err(Into::into))),
|
||||
// Set in `main` once the Nightly session record exists.
|
||||
at_exit: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Why [`open_folder`] could not show a folder.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum OpenFolderError {
|
||||
#[error("{dir}: {source}")]
|
||||
Create { dir: String, source: std::io::Error },
|
||||
#[error("{program}: {source}")]
|
||||
Launch { program: &'static str, source: std::io::Error },
|
||||
}
|
||||
|
||||
/// Show `dir` in the system's file manager (Finder, Explorer or the desktop's own), creating it
|
||||
/// first so a folder nothing was saved in yet still opens.
|
||||
fn open_folder(dir: &str) -> Result<(), OpenFolderError> {
|
||||
std::fs::create_dir_all(dir).map_err(|source| OpenFolderError::Create { dir: dir.to_string(), source })?;
|
||||
#[cfg(target_os = "macos")]
|
||||
let program = "open";
|
||||
#[cfg(target_os = "windows")]
|
||||
let program = "explorer";
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
let program = "xdg-open";
|
||||
std::process::Command::new(program).arg(dir).spawn().map(|_| ()).map_err(|source| OpenFolderError::Launch { program, source })
|
||||
}
|
||||
|
||||
/// The file types `pick` offers: (label, extensions). Shared by the blocking dialogs and the
|
||||
/// macOS sheets.
|
||||
fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> {
|
||||
@@ -473,6 +498,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
|
||||
@@ -564,9 +621,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()
|
||||
@@ -595,9 +664,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| {
|
||||
@@ -641,7 +707,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;
|
||||
}
|
||||
@@ -691,6 +756,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));
|
||||
}
|
||||
@@ -756,6 +824,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;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::str::FromStr;
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Arc, mpsc};
|
||||
|
||||
use cadcraft_ui_egui::menus::{self, Entry};
|
||||
use cadcraft_ui_egui::{CadApp, i18n};
|
||||
@@ -44,10 +44,10 @@ impl NativeMenu {
|
||||
// wake the app for it: the handler does, and the choice runs in the next frame.
|
||||
let (sender, events) = mpsc::channel();
|
||||
let wake = ctx.clone();
|
||||
MenuEvent::set_event_handler(Some(move |event| {
|
||||
MenuEvent::set_event_handler(Some(Arc::new(move |event| {
|
||||
let _ = sender.send(event);
|
||||
wake.request_repaint();
|
||||
}));
|
||||
})));
|
||||
let menu = Menu::new();
|
||||
let mut items = HashMap::new();
|
||||
let language = app.language();
|
||||
|
||||
@@ -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,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -213,21 +214,21 @@ mod tests {
|
||||
let path = directory.join("workspace.json");
|
||||
let (mut first, restored, error) = Workspace::at(Some(path.clone()));
|
||||
assert!(restored.is_none() && error.is_none());
|
||||
let ui = UiState {
|
||||
show_palettes: false,
|
||||
show_command_line: false,
|
||||
toolset_tab: "Modeling".into(),
|
||||
collapsed_groups: vec!["Solid".into()],
|
||||
history_lines: 5,
|
||||
dialog: Some("layers".into()),
|
||||
start_tab: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut ui = UiState::default();
|
||||
ui.show_palettes = false;
|
||||
ui.show_command_line = false;
|
||||
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();
|
||||
let bytes = fs::read(&path).unwrap();
|
||||
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();
|
||||
@@ -313,7 +314,9 @@ mod tests {
|
||||
let (mut store, ui, error) = Workspace::at(Some(path.clone()));
|
||||
assert!(ui.is_none());
|
||||
assert!(error.as_deref().is_some_and(|error| error.contains("left unchanged")));
|
||||
store.save_if_changed(&UiState { show_palettes: false, ..Default::default() }, Instant::now()).unwrap();
|
||||
let mut ui = UiState::default();
|
||||
ui.show_palettes = false;
|
||||
store.save_if_changed(&ui, Instant::now()).unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), bytes);
|
||||
}
|
||||
fs::remove_dir_all(directory).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();
|
||||
@@ -351,7 +355,8 @@ mod tests {
|
||||
let path = directory.join("workspace.json");
|
||||
let (mut store, _, _) = Workspace::at(Some(path.clone()));
|
||||
let start = Instant::now();
|
||||
let mut ui = UiState { history_lines: 1, ..Default::default() };
|
||||
let mut ui = UiState::default();
|
||||
ui.history_lines = 1;
|
||||
assert_eq!(store.save_if_changed(&ui, start).unwrap(), None);
|
||||
// A drag: a new state every frame, none of them written until the interval ends.
|
||||
for (frame, lines) in (2..=5).enumerate() {
|
||||
@@ -375,7 +380,8 @@ mod tests {
|
||||
let directory = temp_dir();
|
||||
let path = directory.join("workspace.json");
|
||||
let (mut store, _, _) = Workspace::at(Some(path.clone()));
|
||||
let mut ui = UiState { show_palettes: false, ..Default::default() };
|
||||
let mut ui = UiState::default();
|
||||
ui.show_palettes = false;
|
||||
store.save_if_changed(&ui, Instant::now()).unwrap();
|
||||
let good = fs::read(&path).unwrap();
|
||||
ui.collapsed_groups = vec!["x".repeat(257)];
|
||||
@@ -391,7 +397,8 @@ mod tests {
|
||||
let (mut store, _, _) = Workspace::at(Some(path.clone()));
|
||||
// Simulate a destination becoming unavailable after startup.
|
||||
fs::create_dir(&path).unwrap();
|
||||
let ui = UiState { show_palettes: false, ..Default::default() };
|
||||
let mut ui = UiState::default();
|
||||
ui.show_palettes = false;
|
||||
let first_error = store.save_if_changed(&ui, Instant::now()).unwrap_err();
|
||||
fs::remove_dir(&path).unwrap();
|
||||
assert_eq!(store.save_if_changed(&ui, Instant::now()).unwrap_err(), first_error);
|
||||
|
||||
+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
|
||||
|
||||
@@ -104,6 +104,48 @@ enum Val {
|
||||
Flip(Vec3, Vec3, bool),
|
||||
/// A flip grip's state: its value record's last group 70.
|
||||
State(bool),
|
||||
/// Where a visibility or lookup parameter is, when an action carries it, with its state or
|
||||
/// value (unchanged; its record holds both).
|
||||
At(Vec3, String),
|
||||
}
|
||||
|
||||
/// What an action carries of parameter `node`: the value this change has given it so far, else
|
||||
/// its current one; of a visibility or lookup parameter, its position (its state or value stays).
|
||||
/// None for a parameter whose state this change sets (it stays where it is).
|
||||
fn carried(m: &DynamicBlock, values: &BTreeMap<i32, Value>, new: &BTreeMap<i32, Val>, node: i32) -> Option<Val> {
|
||||
match new.get(&node) {
|
||||
Some(Val::Text(_)) => None,
|
||||
Some(v) => Some(v.clone()),
|
||||
None => match current(m, values, node)? {
|
||||
Val::Text(t) => located(m, values, node).map(|p| Val::At(p, t)),
|
||||
v => Some(v),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameter value `v` with each of its points moved by `f` (a visibility or lookup parameter's
|
||||
/// carried position too); `None` for a value without points (a state or a value alone).
|
||||
fn moved(v: Val, f: impl Fn(Vec3) -> Vec3) -> Option<Val> {
|
||||
Some(match v {
|
||||
Val::Point(q) => Val::Point(f(q)),
|
||||
Val::At(q, t) => Val::At(f(q), t),
|
||||
Val::Points(b, e) => Val::Points(f(b), f(e)),
|
||||
Val::Flip(b, e, s) => Val::Flip(f(b), f(e), s),
|
||||
Val::Text(_) | Val::State(_) => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a visibility or lookup parameter is on a reference: as its record has it, else as the
|
||||
/// dynamic block has it.
|
||||
fn located(m: &DynamicBlock, values: &BTreeMap<i32, Value>, node: i32) -> Option<Vec3> {
|
||||
let home = m.parameters.iter().find(|p| p.node == node).and_then(|p| match &p.kind {
|
||||
ParameterKind::Visibility { at, .. } | ParameterKind::Lookup { at, .. } => Some(*at),
|
||||
_ => None,
|
||||
})?;
|
||||
Some(match values.get(&node) {
|
||||
Some(Value::Text { at: Some(q), .. }) => *q,
|
||||
_ => home,
|
||||
})
|
||||
}
|
||||
|
||||
/// A rotation parameter's angle (radians, 0 to 2π): its end's direction from its base, from the
|
||||
@@ -173,7 +215,7 @@ fn current(m: &DynamicBlock, values: &BTreeMap<i32, Value>, node: i32) -> Option
|
||||
let p = m.parameters.iter().find(|p| p.node == node)?;
|
||||
let given = values.get(&node);
|
||||
Some(match (&p.kind, given) {
|
||||
(_, Some(Value::Text { value })) => Val::Text(value.clone()),
|
||||
(_, Some(Value::Text { value, .. })) => Val::Text(value.clone()),
|
||||
(_, Some(Value::Point { at })) => Val::Point(*at),
|
||||
(_, Some(Value::Points { base, end })) => Val::Points(*base, *end),
|
||||
(_, Some(Value::Flip { base, end, flipped })) => Val::Flip(*base, *end, *flipped),
|
||||
@@ -954,7 +996,7 @@ impl ActionRun<'_> {
|
||||
/// The value of parameter `node` so far: carried along by an action already, else the
|
||||
/// reference's.
|
||||
fn value_of(&self, node: i32) -> Option<Val> {
|
||||
self.new.get(&node).cloned().or_else(|| current(self.m, self.values, node))
|
||||
carried(self.m, self.values, &self.new, node)
|
||||
}
|
||||
|
||||
/// Action `a`, when one of its connections follows a parameter the change sets.
|
||||
@@ -1022,13 +1064,9 @@ impl ActionRun<'_> {
|
||||
}
|
||||
let back = |q: Vec3| q - rebase.to3(0.0);
|
||||
for p in self.m.parameters.iter().filter(|p| !matches!(p.kind, ParameterKind::BasePoint { .. })) {
|
||||
let moved = match self.value_of(p.node) {
|
||||
Some(Val::Point(q)) => Val::Point(back(q)),
|
||||
Some(Val::Points(b, e)) => Val::Points(back(b), back(e)),
|
||||
Some(Val::Flip(b, e, f)) => Val::Flip(back(b), back(e), f),
|
||||
_ => continue,
|
||||
};
|
||||
self.new.insert(p.node, moved);
|
||||
// A visibility or lookup grip goes back too (its carried position).
|
||||
let Some(now) = self.value_of(p.node).and_then(|v| moved(v, back)) else { continue };
|
||||
self.new.insert(p.node, now);
|
||||
}
|
||||
rebase
|
||||
}
|
||||
@@ -1047,14 +1085,8 @@ impl ActionRun<'_> {
|
||||
continue;
|
||||
}
|
||||
let Some(cur) = self.value_of(node) else { continue };
|
||||
let p = |q: Vec3| t.apply(q.xy()).to3(q.z);
|
||||
let moved = match cur {
|
||||
Val::Point(q) => Val::Point(p(q)),
|
||||
Val::Points(b, e) => Val::Points(p(b), p(e)),
|
||||
Val::Flip(b, e, f) => Val::Flip(p(b), p(e), f),
|
||||
other => other,
|
||||
};
|
||||
self.new.insert(node, moved);
|
||||
let now = moved(cur.clone(), |q| t.apply(q.xy()).to3(q.z)).unwrap_or(cur);
|
||||
self.new.insert(node, now);
|
||||
} else if let Some(c) = self.copy_of(h) {
|
||||
self.moves.entry(c).or_default().push(Op::Transform(t));
|
||||
}
|
||||
@@ -1082,7 +1114,8 @@ impl ActionRun<'_> {
|
||||
}
|
||||
let Some(cur) = self.value_of(node) else { continue };
|
||||
let home = current(self.m, &BTreeMap::new(), node);
|
||||
self.new.insert(node, turned_and_shifted(cur, home, frame, (turn, v)));
|
||||
let at = located(self.m, &BTreeMap::new(), node);
|
||||
self.new.insert(node, turned_and_shifted(cur, (home, at), frame, (turn, v)));
|
||||
continue;
|
||||
}
|
||||
let Some(c) = self.copy_of(h) else { continue };
|
||||
@@ -1148,7 +1181,8 @@ impl ActionRun<'_> {
|
||||
}
|
||||
let Some(cur) = self.value_of(node) else { continue };
|
||||
let home = current(self.m, &BTreeMap::new(), node);
|
||||
self.new.insert(node, shifted(cur, home, frame, v));
|
||||
let at = located(self.m, &BTreeMap::new(), node);
|
||||
self.new.insert(node, shifted(cur, (home, at), frame, v));
|
||||
continue;
|
||||
}
|
||||
let Some(c) = self.copy_of(h) else { continue };
|
||||
@@ -1204,7 +1238,7 @@ fn earlier_copies(src: &Block, src_tag: &HashMap<Handle, i64>, arrays: &HashMap<
|
||||
|
||||
/// A parameter value `cur` turned by `turn`, and carried by `v` where its points are in `frame`
|
||||
/// (judged where the dynamic block has them, `home`), after a polar stretch.
|
||||
fn turned_and_shifted(cur: Val, home: Option<Val>, frame: &[Vec2], (turn, v): (Mat3, Vec2)) -> Val {
|
||||
fn turned_and_shifted(cur: Val, (home, located): (Option<Val>, Option<Vec3>), frame: &[Vec2], (turn, v): (Mat3, Vec2)) -> Val {
|
||||
let carry = |p: Vec3, at: Vec3| {
|
||||
let q = turn.apply(p.xy()).to3(p.z);
|
||||
if in_frame(frame, at.xy()) { q + v.to3(0.0) } else { q }
|
||||
@@ -1212,6 +1246,8 @@ fn turned_and_shifted(cur: Val, home: Option<Val>, frame: &[Vec2], (turn, v): (M
|
||||
match (cur, home) {
|
||||
(Val::Point(p), Some(Val::Point(h))) => Val::Point(carry(p, h)),
|
||||
(Val::Point(p), _) => Val::Point(carry(p, p)),
|
||||
// A carried visibility or lookup grip: in the frame where the dynamic block has it.
|
||||
(Val::At(p, t), _) => Val::At(carry(p, located.unwrap_or(p)), t),
|
||||
(Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(carry(b, hb), carry(e, he)),
|
||||
(Val::Points(b, e), _) => Val::Points(carry(b, b), carry(e, e)),
|
||||
(Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(carry(b, hb), carry(e, he), f),
|
||||
@@ -1222,11 +1258,12 @@ fn turned_and_shifted(cur: Val, home: Option<Val>, frame: &[Vec2], (turn, v): (M
|
||||
|
||||
/// Parameter value `cur` carried by `v`: the points in `frame` (empty: all of them), judged where
|
||||
/// the dynamic block has them (`home`), move.
|
||||
fn shifted(cur: Val, home: Option<Val>, frame: &[Vec2], v: Vec2) -> Val {
|
||||
fn shifted(cur: Val, (home, located): (Option<Val>, Option<Vec3>), frame: &[Vec2], v: Vec2) -> Val {
|
||||
let shift = |p: Vec3, at: Option<Vec3>| if frame.is_empty() || in_frame(frame, at.unwrap_or(p).xy()) { p + v.to3(0.0) } else { p };
|
||||
match (cur, home) {
|
||||
(Val::Point(p), Some(Val::Point(h))) => Val::Point(shift(p, Some(h))),
|
||||
(Val::Point(p), _) => Val::Point(shift(p, None)),
|
||||
(Val::At(p, t), _) => Val::At(shift(p, located), t),
|
||||
(Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(shift(b, Some(hb)), shift(e, Some(he))),
|
||||
(Val::Points(b, e), _) => Val::Points(shift(b, None), shift(e, None)),
|
||||
(Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(shift(b, Some(hb)), shift(e, Some(he)), f),
|
||||
@@ -2030,6 +2067,10 @@ fn write_value(tags: &mut Vec<RawTag>, v: &Val) {
|
||||
return;
|
||||
}
|
||||
Val::Point(p) => vec![*p],
|
||||
Val::At(p, t) => {
|
||||
write_value(tags, &Val::Text(t.clone()));
|
||||
vec![*p]
|
||||
}
|
||||
Val::Points(b, e) | Val::Flip(b, e, _) => vec![*b, *e],
|
||||
Val::State(f) => {
|
||||
set_state(tags, *f);
|
||||
@@ -2244,6 +2285,29 @@ mod tests {
|
||||
assert_eq!(total, 23);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_carried_visibility_grip_moves_with_the_points() {
|
||||
let up = |q: Vec3| q + Vec3::new(0.0, 1.0, 0.0);
|
||||
let at = Val::At(Vec3::new(2.0, 0.0, 0.0), "Open".into());
|
||||
assert_eq!(moved(at, up), Some(Val::At(Vec3::new(2.0, 1.0, 0.0), "Open".into())));
|
||||
assert_eq!(moved(Val::Text("Open".into()), up), None);
|
||||
assert_eq!(moved(Val::State(true), up), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polar_stretch_carries_a_visibility_grip() {
|
||||
let turn = Mat3::rotate_about(Vec2::ZERO, std::f64::consts::FRAC_PI_2);
|
||||
let frame = [Vec2::new(1.0, -1.0), Vec2::new(3.0, 1.0)];
|
||||
let at = |x: f64, y: f64| Val::At(Vec3::new(x, y, 0.0), "Open".into());
|
||||
let near = |v: Val, x: f64, y: f64| matches!(v, Val::At(p, _) if (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9);
|
||||
// In the frame where the dynamic block has it: turned, then moved.
|
||||
let v = turned_and_shifted(at(2.0, 0.0), (None, Some(Vec3::new(2.0, 0.0, 0.0))), &frame, (turn, Vec2::new(0.0, 1.0)));
|
||||
assert!(near(v, 0.0, 3.0));
|
||||
// Outside it: only turned.
|
||||
let v = turned_and_shifted(at(5.0, 0.0), (None, Some(Vec3::new(5.0, 0.0, 0.0))), &frame, (turn, Vec2::new(0.0, 1.0)));
|
||||
assert!(near(v, 0.0, 5.0));
|
||||
}
|
||||
|
||||
fn tagged(h: u64, tag_value: Option<&str>) -> Entity {
|
||||
let mut e = Entity::new(Handle(h), EntityKind::Line(crate::Line { a: Vec3::ZERO, b: Vec3::ZERO }));
|
||||
if let Some(v) = tag_value {
|
||||
|
||||
@@ -172,7 +172,7 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
|
||||
for p in &m.parameters {
|
||||
if let ParameterKind::Visibility { states, .. } = &p.kind {
|
||||
let current = match r.values.get(&p.node) {
|
||||
Some(Value::Text { value }) => states.iter().find(|s| s.name.eq_ignore_ascii_case(value)),
|
||||
Some(Value::Text { value, .. }) => states.iter().find(|s| s.name.eq_ignore_ascii_case(value)),
|
||||
_ => states.first(),
|
||||
};
|
||||
if let Some(s) = current {
|
||||
@@ -340,7 +340,11 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
|
||||
ParameterKind::Visibility { at, label, .. } | ParameterKind::Lookup { at, label, .. } => {
|
||||
let Some(list) = choices.get(&label.to_ascii_uppercase()).filter(|c| !c.is_empty()) else { continue };
|
||||
if shown(p.node, grip(0)) {
|
||||
let at = world(*at);
|
||||
// Where the reference's record has it (an action may have carried it).
|
||||
let at = match r.values.get(&p.node) {
|
||||
Some(Value::Text { at: Some(q), .. }) => world(*q),
|
||||
_ => world(*at),
|
||||
};
|
||||
out.push(DynGrip {
|
||||
node: p.node,
|
||||
part: GripPart::At,
|
||||
|
||||
@@ -23,8 +23,13 @@ const MAX_VALUES: usize = 10_000;
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum Value {
|
||||
/// A visibility state's name or a lookup value.
|
||||
Text { value: String },
|
||||
/// A visibility state's name or a lookup value, and where the parameter is when the record
|
||||
/// says (an action may have carried it from where the dynamic block has it).
|
||||
Text {
|
||||
value: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
at: Option<Vec3>,
|
||||
},
|
||||
/// A point parameter's position.
|
||||
Point { at: Vec3 },
|
||||
/// A two-point parameter's points.
|
||||
@@ -93,17 +98,18 @@ fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(Stri
|
||||
out
|
||||
}
|
||||
|
||||
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip
|
||||
/// A value XRECORD: its text (group 1) when it has one, with the parameter's position (a
|
||||
/// visibility or lookup grip's, 10/20/30) when it has that too; else its points; a flip
|
||||
/// parameter's also has its state, a group 70 after its points (the header's `70 25`, `70 104`
|
||||
/// come before them).
|
||||
fn value(o: &ForeignObject) -> Option<Value> {
|
||||
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
|
||||
return Some(Value::Text { value: t.value.clone() });
|
||||
}
|
||||
let num = |code: i32, i: usize| {
|
||||
o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
|
||||
};
|
||||
let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0)));
|
||||
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
|
||||
return Some(Value::Text { value: t.value.clone(), at: point(0) });
|
||||
}
|
||||
let first_point = o.tags.iter().position(|t| t.code == 10).unwrap_or(o.tags.len());
|
||||
let state = o.tags.get(first_point..).unwrap_or_default().iter().rev().find(|t| t.code == 70).map(|t| t.value.trim() == "1");
|
||||
match (point(0), point(1)) {
|
||||
|
||||
@@ -50,7 +50,7 @@ mod xdata;
|
||||
|
||||
pub use xdata::{
|
||||
MAX_XDATA_APP_NAME, MAX_XDATA_CHUNK, MAX_XDATA_GROUPS, MAX_XDATA_STRING, RESERVED_XDATA_APPS, XdataError, check_xdata_app_name,
|
||||
check_xdata_groups, is_model_xdata_app, is_reserved_xdata_app, is_xdata_group, set_xdata_app, xdata_apps, xdata_of,
|
||||
check_xdata_groups, is_model_xdata, is_model_xdata_app, is_reserved_xdata_app, is_xdata_group, set_xdata_app, xdata_apps, xdata_of,
|
||||
};
|
||||
|
||||
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
|
||||
|
||||
@@ -154,7 +154,43 @@ impl AttribProps {
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TagKey<'a>(pub &'a str);
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static TAG_CROSS_PROBE: std::cell::Cell<Option<(usize, [usize; 2])>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn record_tag_cross_probe(left: &str, right: &str) {
|
||||
TAG_CROSS_PROBE.with(|probe| {
|
||||
let Some((position, mut counts)) = probe.get() else { return };
|
||||
match (left.as_bytes().get(position), right.as_bytes().get(position)) {
|
||||
(Some(b'A'), Some(b'D')) => counts[0] += 1,
|
||||
(Some(b'D'), Some(b'A')) => counts[1] += 1,
|
||||
_ => return,
|
||||
}
|
||||
probe.set(Some((position, counts)));
|
||||
});
|
||||
}
|
||||
|
||||
impl TagKey<'_> {
|
||||
/// Count comparisons in both directions between the A and D fixture tag sets.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_cross_probes<T>(position: usize, f: impl FnOnce() -> T) -> (T, [usize; 2]) {
|
||||
struct Restore(Option<(usize, [usize; 2])>);
|
||||
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
TAG_CROSS_PROBE.with(|probe| probe.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
TAG_CROSS_PROBE.with(|probe| {
|
||||
let _restore = Restore(probe.replace(Some((position, [0; 2]))));
|
||||
let value = f();
|
||||
(value, probe.get().map_or([0; 2], |(_, counts)| counts))
|
||||
})
|
||||
}
|
||||
|
||||
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
|
||||
/// finds equal.
|
||||
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
|
||||
@@ -164,6 +200,8 @@ impl TagKey<'_> {
|
||||
|
||||
impl PartialEq for TagKey<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
record_tag_cross_probe(self.0, other.0);
|
||||
self.0.eq_ignore_ascii_case(other.0)
|
||||
}
|
||||
}
|
||||
@@ -172,6 +210,8 @@ impl Eq for TagKey<'_> {}
|
||||
|
||||
impl Ord for TagKey<'_> {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
#[cfg(test)]
|
||||
record_tag_cross_probe(self.0, other.0);
|
||||
self.folded().cmp(other.folded())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +197,11 @@ pub struct Leader {
|
||||
pub spline: bool,
|
||||
#[serde(default = "standard")]
|
||||
pub style: String,
|
||||
/// Per-leader style overrides (the `ACAD` DSTYLE xdata of a LEADER): DimStyle field names
|
||||
/// (camelCase) → values, merged over the named style as a dimension's are. A leader draws
|
||||
/// with its arrow size, overall scale, leader arrowhead and dimension line colour.
|
||||
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
|
||||
pub overrides: serde_json::Map<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -31,10 +31,34 @@ pub fn is_reserved_xdata_app(name: &str) -> bool {
|
||||
/// than kept raw: the [`RESERVED_XDATA_APPS`] on any entity, and `ACAD` on a dimension, whose
|
||||
/// `ACAD` run (`DSTYLE`) holds its dimension-style overrides. The reader models those too, so
|
||||
/// raw groups set under such a name would be dropped on save; they are refused instead.
|
||||
/// [`is_model_xdata`] also knows the one list of a leader's `ACAD` run that is modelled.
|
||||
pub fn is_model_xdata_app(name: &str, kind: &super::EntityKind) -> bool {
|
||||
is_reserved_xdata_app(name) || (name.trim().eq_ignore_ascii_case("ACAD") && matches!(kind, super::EntityKind::Dimension(_)))
|
||||
}
|
||||
|
||||
/// The list in a dimension's or a leader's `ACAD` xdata that holds its dimension-style overrides.
|
||||
const DSTYLE_LIST: &str = "DSTYLE";
|
||||
|
||||
/// Whether `groups` (one application's xdata, its `1001` left out) hold a list named `name`
|
||||
/// (any case): a `1000 <name>` group followed by `1002 {`. A string that only reads `<name>`
|
||||
/// starts no list.
|
||||
fn has_xdata_list(groups: &[RawTag], name: &str) -> bool {
|
||||
groups.windows(2).any(
|
||||
|w| matches!(w, [n, open] if n.code == 1000 && n.value.trim().eq_ignore_ascii_case(name) && open.code == 1002 && open.value.trim() == "{"),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether `groups`, given as raw xdata of application `name` for an entity of `kind`, hold
|
||||
/// what is written from the model: all data of an application [`is_model_xdata_app`] names,
|
||||
/// and on a leader an `ACAD` run with a `DSTYLE` list. A leader's `DSTYLE` list is its
|
||||
/// dimension-style overrides, read into the leader and written from it; raw groups with one
|
||||
/// would be dropped on save or contradict the overrides, so they are refused instead. The rest
|
||||
/// of a leader's `ACAD` data is kept raw and may be set.
|
||||
pub fn is_model_xdata(name: &str, groups: &[RawTag], kind: &super::EntityKind) -> bool {
|
||||
is_model_xdata_app(name, kind)
|
||||
|| (name.trim().eq_ignore_ascii_case("ACAD") && matches!(kind, super::EntityKind::Leader(_)) && has_xdata_list(groups, DSTYLE_LIST))
|
||||
}
|
||||
|
||||
/// Why an application name or a run of xdata groups was refused.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct XdataError(pub String);
|
||||
@@ -214,6 +238,30 @@ mod tests {
|
||||
RawTag { code, value: value.into() }
|
||||
}
|
||||
|
||||
/// `ACAD` xdata is modelled as a DSTYLE list on a leader (a name followed by an opening
|
||||
/// brace, anywhere in the run, any case), and not on another entity or under another name.
|
||||
#[test]
|
||||
fn a_leaders_dstyle_list_is_model_data_and_its_other_acad_data_is_not() {
|
||||
use super::super::{EntityKind, Leader, Line};
|
||||
use cadcraft_geom::Vec3;
|
||||
let leader = EntityKind::Leader(Leader {
|
||||
vertices: vec![Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0)],
|
||||
arrow: true,
|
||||
spline: false,
|
||||
style: "Standard".into(),
|
||||
overrides: serde_json::Map::new(),
|
||||
});
|
||||
let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) });
|
||||
let list = [t(1000, "MINE"), t(1000, " dstyle "), t(1002, "{"), t(1070, "41"), t(1040, "9.0"), t(1002, "}")];
|
||||
let loose = [t(1000, "DSTYLE"), t(1070, "41"), t(1000, "OTHER"), t(1002, "{"), t(1002, "}")];
|
||||
assert!(is_model_xdata("acad", &list, &leader));
|
||||
assert!(!is_model_xdata("ACAD", &loose, &leader), "a string that only reads DSTYLE starts no list");
|
||||
assert!(!is_model_xdata("ACAD", &[], &leader));
|
||||
assert!(!is_model_xdata("ACME", &list, &leader), "another application's list is its own");
|
||||
assert!(!is_model_xdata("ACAD", &list, &line));
|
||||
assert!(is_model_xdata("CADCRAFT", &[], &leader) && is_model_xdata("CADCRAFT", &[], &line));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apps_are_split_at_their_names() {
|
||||
let x = vec![t(1001, "A"), t(1000, "one"), t(1070, "1"), t(1001, "b"), t(1000, "two")];
|
||||
|
||||
+52
-24
@@ -242,15 +242,29 @@ pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool {
|
||||
m.b.abs() < t && m.c.abs() < t && m.a > 0.0 && (m.a - m.d).abs() <= t
|
||||
}
|
||||
|
||||
/// How many characters a single-line text value draws, as the fonts read it: a `%%` code is the
|
||||
/// one character it stands for (`%%d`, `%%p`, `%%c`, `%%%`, `%%nnn`) or none (the underline and
|
||||
/// overline toggles `%%u` and `%%o`), `\U+XXXX` is one character, and invisible formatting
|
||||
/// characters (joiners, directional marks) take no room.
|
||||
fn drawn_chars(value: &str) -> usize {
|
||||
/// What a single-line text value draws, as the fonts read it.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Drawn {
|
||||
/// How many characters take room.
|
||||
chars: usize,
|
||||
/// Whether any of them is underlined, and whether any is overlined.
|
||||
underlined: bool,
|
||||
overlined: bool,
|
||||
}
|
||||
|
||||
/// What a single-line text value draws, as the fonts read it: a `%%` code is the one character
|
||||
/// it stands for (`%%d`, `%%p`, `%%c`, `%%%`, `%%nnn`) or none (`%%u` and `%%o`, which turn the
|
||||
/// underline and the overline on and off for the characters after them), `\U+XXXX` is one
|
||||
/// character, and invisible formatting characters (joiners, directional marks) take no room.
|
||||
fn drawn_text(value: &str) -> Drawn {
|
||||
let invisible = |c: char| matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{2069}' | '\u{FEFF}' | '\u{061C}');
|
||||
let chars: Vec<char> = value.chars().collect();
|
||||
let (mut i, mut drawn) = (0usize, 0usize);
|
||||
// The toggles as they stand, and what the characters drawn so far have had.
|
||||
let (mut under, mut over) = (false, false);
|
||||
let mut out = Drawn::default();
|
||||
while let Some(&c) = chars.get(i) {
|
||||
let before = drawn;
|
||||
let escaped = (c == '\\' && matches!(chars.get(i + 1), Some('U' | 'u')) && chars.get(i + 2) == Some(&'+'))
|
||||
.then(|| chars.get(i + 3..i + 7))
|
||||
.flatten()
|
||||
@@ -262,7 +276,8 @@ fn drawn_chars(value: &str) -> usize {
|
||||
i += 7;
|
||||
} else if c == '%' && chars.get(i + 1) == Some(&'%') {
|
||||
match chars.get(i + 2).map_or(' ', char::to_ascii_lowercase) {
|
||||
'u' | 'o' => i += 3,
|
||||
'u' => (under, i) = (!under, i + 3),
|
||||
'o' => (over, i) = (!over, i + 3),
|
||||
'd' | 'p' | 'c' | '%' => (drawn, i) = (drawn + 1, i + 3),
|
||||
digit if digit.is_ascii_digit() => {
|
||||
let digits = chars.iter().skip(i + 2).take(3).take_while(|d| d.is_ascii_digit()).count();
|
||||
@@ -275,15 +290,19 @@ fn drawn_chars(value: &str) -> usize {
|
||||
drawn += usize::from(!invisible(c));
|
||||
i += 1;
|
||||
}
|
||||
if drawn > before {
|
||||
(out.underlined, out.overlined) = (out.underlined || under, out.overlined || over);
|
||||
}
|
||||
}
|
||||
drawn
|
||||
Drawn { chars: drawn, ..out }
|
||||
}
|
||||
|
||||
/// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` drawn characters, following its
|
||||
/// Bounds of a single-line TEXT / ATTDEF / ATTRIB that draws `drawn`, following its
|
||||
/// justification the same way the renderer places it (the stroke font is about 0.88 of the height
|
||||
/// per character). Empty when nothing is drawn.
|
||||
fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
|
||||
/// per character), its underline and overline included. Empty when nothing is drawn.
|
||||
fn text_box(t: &crate::Text, drawn: Drawn) -> Bounds2 {
|
||||
use crate::{HAlign, VAlign};
|
||||
let len = drawn.chars;
|
||||
if len == 0 {
|
||||
return Bounds2::EMPTY;
|
||||
}
|
||||
@@ -340,15 +359,22 @@ fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
|
||||
HAlign::Center | HAlign::Middle => -w / 2.0,
|
||||
HAlign::Right => -w,
|
||||
};
|
||||
// The box from its bottom to its top. Bottom justification lifts the line by a third of the
|
||||
// height it is drawn at: the box starts where the shortest line would and ends where the
|
||||
// tallest would.
|
||||
let (y0, y1) = match (t.halign, t.valign) {
|
||||
(HAlign::Middle, _) | (_, VAlign::Middle) => (-h / 2.0, h / 2.0),
|
||||
(_, VAlign::Baseline) => (0.0, h),
|
||||
(_, VAlign::Bottom) => (low / 3.0, h / 3.0 + h),
|
||||
(_, VAlign::Top) => (-h, 0.0),
|
||||
// Where the baseline of a line drawn `drawn_h` high lies. Bottom justification lifts the line
|
||||
// by a third of the height it is drawn at.
|
||||
let baseline = |drawn_h: f64| match (t.halign, t.valign) {
|
||||
(HAlign::Middle, _) | (_, VAlign::Middle) => -drawn_h / 2.0,
|
||||
(_, VAlign::Baseline) => 0.0,
|
||||
(_, VAlign::Bottom) => drawn_h / 3.0,
|
||||
(_, VAlign::Top) => -drawn_h,
|
||||
};
|
||||
// The fonts draw an underline a fifth of the drawn height below the baseline and an overline
|
||||
// a fifth of it above the line's top.
|
||||
let below = if drawn.underlined { 0.2 } else { 0.0 };
|
||||
let above = if drawn.overlined { 1.2 } else { 1.0 };
|
||||
// The box from its bottom to its top: it starts where the lowest of the shortest and the
|
||||
// tallest possible line would and ends where the highest of the two would.
|
||||
let [(b0, t0), (b1, t1)] = [low, h].map(|drawn_h| (baseline(drawn_h) - below * drawn_h, baseline(drawn_h) + above * drawn_h));
|
||||
let (y0, y1) = (b0.min(b1), t0.max(t1));
|
||||
let local = [Vec2::new(dx, y0), Vec2::new(dx + w, y0), Vec2::new(dx + w, y1), Vec2::new(dx, y1)];
|
||||
// Backwards and upside-down text is mirrored about the point it is placed by.
|
||||
let (mx, my) = (if t.backwards { -1.0 } else { 1.0 }, if t.upside_down { -1.0 } else { 1.0 });
|
||||
@@ -484,7 +510,7 @@ fn constant_box(a: &crate::Attrib, upright: bool) -> Bounds2 {
|
||||
let turn = |r: f64| if upright { 0.0 } else { r };
|
||||
match a.multiline_text() {
|
||||
Some(m) if !blank(&m.contents) => mtext_box(&crate::MText { rotation: turn(m.rotation), ..m }),
|
||||
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, drawn_chars(&a.text.value)),
|
||||
None if !blank(&a.text.value) => text_box(&crate::Text { rotation: turn(a.text.rotation), ..a.text.clone() }, drawn_text(&a.text.value)),
|
||||
_ => Bounds2::EMPTY,
|
||||
}
|
||||
}
|
||||
@@ -619,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)
|
||||
@@ -675,10 +703,10 @@ fn bounds_in<'a>(
|
||||
EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY,
|
||||
EntityKind::MText(t) if blank(&t.contents) => Bounds2::EMPTY,
|
||||
// Text that matches the layout's orientation is drawn upright (#2498).
|
||||
EntityKind::Text(t) if e.common.matches_layout_orientation() => text_box(&crate::Text { rotation: 0.0, ..t.clone() }, drawn_chars(&t.value)),
|
||||
EntityKind::Text(t) if e.common.matches_layout_orientation() => text_box(&crate::Text { rotation: 0.0, ..t.clone() }, drawn_text(&t.value)),
|
||||
EntityKind::MText(t) if e.common.matches_layout_orientation() => mtext_box(&crate::MText { rotation: 0.0, ..t.clone() }),
|
||||
EntityKind::Text(t) => text_box(t, drawn_chars(&t.value)),
|
||||
EntityKind::AttDef(a) => text_box(&a.text, drawn_chars(&a.tag)),
|
||||
EntityKind::Text(t) => text_box(t, drawn_text(&t.value)),
|
||||
EntityKind::AttDef(a) => text_box(&a.text, drawn_text(&a.tag)),
|
||||
EntityKind::MText(t) => mtext_box(t),
|
||||
EntityKind::Insert(ins) => {
|
||||
if depth >= MAX_BLOCK_DEPTH {
|
||||
@@ -727,7 +755,7 @@ fn bounds_in<'a>(
|
||||
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts, frozen) {
|
||||
b = b.union(&match a.multiline_text() {
|
||||
Some(m) => mtext_box(&m),
|
||||
None => text_box(&a.text, drawn_chars(&a.text.value)),
|
||||
None => text_box(&a.text, drawn_text(&a.text.value)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -261,6 +261,11 @@ pub fn is_user_pattern(name: &str) -> bool {
|
||||
name.eq_ignore_ascii_case(USER_PATTERN)
|
||||
}
|
||||
|
||||
/// Names owned by the standard library or the native user-defined hatch form.
|
||||
pub fn is_reserved_pattern_name(name: &str) -> bool {
|
||||
is_user_pattern(name) || pattern(name).is_some()
|
||||
}
|
||||
|
||||
/// Hatch pattern scales must be greater than this limit. For a user-defined hatch, the scale is its line spacing.
|
||||
pub const MIN_HATCH_PATTERN_SCALE: f64 = 1e-9;
|
||||
|
||||
|
||||
+50
-11
@@ -186,7 +186,11 @@ impl PlotStyle {
|
||||
/// The printed colour of an object drawn in `rgb`: the style's colour (else `rgb`), turned
|
||||
/// grey when asked, then screened toward white.
|
||||
pub fn apply_color(&self, rgb: Rgb) -> Rgb {
|
||||
let c = self.color.unwrap_or(rgb);
|
||||
self.shade(self.color.unwrap_or(rgb))
|
||||
}
|
||||
/// `c` turned grey when the style asks for it, then screened toward white: what the style
|
||||
/// does to a colour it does not replace.
|
||||
pub fn shade(&self, c: Rgb) -> Rgb {
|
||||
let c = if self.grayscale {
|
||||
let g = (c.luma().clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
Rgb(g, g, g)
|
||||
@@ -372,30 +376,65 @@ impl PlotStyleTable {
|
||||
}
|
||||
}
|
||||
|
||||
/// The tables of the user's plot style folder, as the host last read them (see
|
||||
/// [`set_plot_style_folder`]). Empty until a host reads a folder.
|
||||
static FOLDER: std::sync::RwLock<Option<std::sync::Arc<Vec<PlotStyleTable>>>> = std::sync::RwLock::new(None);
|
||||
|
||||
/// Replace the tables of the user's plot style folder that every drawing can use. The host reads
|
||||
/// the folder (this crate does no file I/O) and calls this again after each change.
|
||||
pub fn set_plot_style_folder(tables: Vec<PlotStyleTable>) {
|
||||
if let Ok(mut f) = FOLDER.write() {
|
||||
*f = Some(std::sync::Arc::new(tables));
|
||||
}
|
||||
}
|
||||
|
||||
/// The tables of the user's plot style folder (empty when the host has read none).
|
||||
pub fn plot_style_folder() -> std::sync::Arc<Vec<PlotStyleTable>> {
|
||||
FOLDER.read().ok().and_then(|f| f.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The folder's table called `name` (case-insensitive).
|
||||
pub fn plot_style_folder_table(name: &str) -> Option<PlotStyleTable> {
|
||||
let n = name.trim();
|
||||
plot_style_folder().iter().find(|t| t.name.eq_ignore_ascii_case(n)).cloned()
|
||||
}
|
||||
|
||||
/// Whether a page setup's table name means "no plot style table".
|
||||
pub fn no_plot_style_table(name: &str) -> bool {
|
||||
let n = name.trim();
|
||||
n.is_empty() || n.eq_ignore_ascii_case("none")
|
||||
}
|
||||
|
||||
/// The plot style table a page setup names, if it is one we know: the drawing's own tables
|
||||
/// first, then the built-in ones. `None` for no table (empty or "None") and for tables we don't
|
||||
/// have.
|
||||
/// The plot style table a page setup names, if it is one we know: the drawing's own tables first
|
||||
/// (a folder table a layout chose is copied into the drawing, and the drawing then plots with its
|
||||
/// copy whatever happens to the file), then the user's plot style folder, then the built-in ones. `None` for no table (empty or "None") and for tables we don't have.
|
||||
pub fn plot_style_table(d: &crate::Drawing, name: &str) -> Option<PlotStyleTable> {
|
||||
if no_plot_style_table(name) {
|
||||
return None;
|
||||
}
|
||||
let n = name.trim();
|
||||
d.plot_style_tables.iter().find(|t| t.name.eq_ignore_ascii_case(n)).cloned().or_else(|| PlotStyleTable::builtin(n))
|
||||
d.plot_style_tables
|
||||
.iter()
|
||||
.find(|t| t.name.eq_ignore_ascii_case(n))
|
||||
.cloned()
|
||||
.or_else(|| plot_style_folder_table(n))
|
||||
.or_else(|| PlotStyleTable::builtin(n))
|
||||
}
|
||||
|
||||
/// The names of every table a drawing can use: its own, then the built-in ones it doesn't
|
||||
/// shadow.
|
||||
/// The names of every table a drawing can use: the drawing's own, the folder's, then the built-in
|
||||
/// ones, each name once.
|
||||
pub fn plot_style_table_names(d: &crate::Drawing) -> Vec<String> {
|
||||
let mut v: Vec<String> = d.plot_style_tables.iter().map(|t| t.name.clone()).collect();
|
||||
for b in BUILTIN_PLOT_STYLE_TABLES {
|
||||
if !v.iter().any(|n| n.eq_ignore_ascii_case(b)) {
|
||||
v.push((*b).to_string());
|
||||
let mut v: Vec<String> = Vec::new();
|
||||
let folder = plot_style_folder();
|
||||
let all = d
|
||||
.plot_style_tables
|
||||
.iter()
|
||||
.map(|t| t.name.as_str())
|
||||
.chain(folder.iter().map(|t| t.name.as_str()))
|
||||
.chain(BUILTIN_PLOT_STYLE_TABLES.iter().copied());
|
||||
for n in all {
|
||||
if !v.iter().any(|x| x.eq_ignore_ascii_case(n)) {
|
||||
v.push(n.to_string());
|
||||
}
|
||||
}
|
||||
v
|
||||
|
||||
+74
-1
@@ -6,12 +6,19 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::{Entity, Handle};
|
||||
|
||||
const CHUNK_MAX: usize = 1024;
|
||||
const SHARDS: usize = 64;
|
||||
|
||||
/// A content token no store has had: one count for the process (a `u64` does not run out).
|
||||
fn next_token() -> u64 {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Chunk {
|
||||
id: u32,
|
||||
@@ -24,11 +31,19 @@ pub struct EntityStore {
|
||||
shards: Vec<Arc<HashMap<Handle, u32>>>,
|
||||
len: usize,
|
||||
next_chunk: u32,
|
||||
/// This state of the entities ([`EntityStore::content_token`]). Not part of [`PartialEq`].
|
||||
token: u64,
|
||||
}
|
||||
|
||||
impl Default for EntityStore {
|
||||
fn default() -> Self {
|
||||
EntityStore { chunks: Vec::new(), shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(), len: 0, next_chunk: 0 }
|
||||
EntityStore {
|
||||
chunks: Vec::new(),
|
||||
shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(),
|
||||
len: 0,
|
||||
next_chunk: 0,
|
||||
token: next_token(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +62,17 @@ impl EntityStore {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
/// A number for this state of the entities: a clone has it too, and every edit gives the
|
||||
/// store a number no store has had, so two stores with one token hold the same entities in
|
||||
/// the same order. What is derived from the entities (a block's ATTDEFs by tag) can be kept
|
||||
/// under it. Not part of [`PartialEq`]: equal stores can have different tokens.
|
||||
pub fn content_token(&self) -> u64 {
|
||||
self.token
|
||||
}
|
||||
/// The entities are about to change: a new token.
|
||||
fn edited(&mut self) {
|
||||
self.token = next_token();
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
@@ -101,6 +127,7 @@ impl EntityStore {
|
||||
self.replace(e);
|
||||
return;
|
||||
}
|
||||
self.edited();
|
||||
let needs_new = self.chunks.last().is_none_or(|c| c.items.len() >= CHUNK_MAX);
|
||||
if needs_new {
|
||||
let c = self.new_chunk();
|
||||
@@ -120,6 +147,7 @@ impl EntityStore {
|
||||
self.replace(e);
|
||||
return;
|
||||
}
|
||||
self.edited();
|
||||
let needs_new = self.chunks.first().is_none_or(|c| c.items.len() >= CHUNK_MAX);
|
||||
if needs_new {
|
||||
let c = self.new_chunk();
|
||||
@@ -137,6 +165,7 @@ impl EntityStore {
|
||||
pub fn replace(&mut self, e: Entity) -> bool {
|
||||
let Some(id) = self.chunk_id(e.handle) else { return false };
|
||||
let Some(pos) = self.chunk_pos(id) else { return false };
|
||||
self.edited();
|
||||
let Some(c) = self.chunks.get_mut(pos) else { return false };
|
||||
let chunk = Arc::make_mut(c);
|
||||
if let Some(slot) = chunk.items.iter_mut().find(|x| x.handle == e.handle) {
|
||||
@@ -149,6 +178,7 @@ impl EntityStore {
|
||||
pub fn remove(&mut self, h: Handle) -> Option<Arc<Entity>> {
|
||||
let id = self.chunk_id(h)?;
|
||||
let pos = self.chunk_pos(id)?;
|
||||
self.edited();
|
||||
let c = self.chunks.get_mut(pos)?;
|
||||
let chunk = Arc::make_mut(c);
|
||||
let i = chunk.items.iter().position(|x| x.handle == h)?;
|
||||
@@ -165,6 +195,7 @@ impl EntityStore {
|
||||
pub fn modify<F: FnOnce(&mut Entity)>(&mut self, h: Handle, f: F) -> bool {
|
||||
let Some(id) = self.chunk_id(h) else { return false };
|
||||
let Some(pos) = self.chunk_pos(id) else { return false };
|
||||
self.edited();
|
||||
let Some(c) = self.chunks.get_mut(pos) else { return false };
|
||||
let chunk = Arc::make_mut(c);
|
||||
match chunk.items.iter_mut().find(|x| x.handle == h) {
|
||||
@@ -219,6 +250,7 @@ impl EntityStore {
|
||||
self.push(Arc::unwrap_or_clone(e));
|
||||
return false;
|
||||
};
|
||||
self.edited();
|
||||
let Some(c) = self.chunks.get_mut(pos) else {
|
||||
// Unreachable in practice too; never lose the object.
|
||||
self.push(Arc::unwrap_or_clone(e));
|
||||
@@ -297,6 +329,47 @@ mod tests {
|
||||
Entity::new(Handle(h), EntityKind::Point(Point { p: Vec2::new(h as f64, 0.0).to3(0.0), angle: 0.0 }))
|
||||
}
|
||||
|
||||
/// One token per state of the entities: shared by clones, new after every kind of edit, and
|
||||
/// different for copies edited apart (#1660's ATTDEF index is kept by it).
|
||||
#[test]
|
||||
fn a_content_token_names_one_state_of_the_entities() {
|
||||
let mut a = EntityStore::new();
|
||||
for h in 1..=3 {
|
||||
a.push(ent(h));
|
||||
}
|
||||
assert_eq!(a.clone().content_token(), a.content_token(), "a clone holds the same entities");
|
||||
let (mut b, mut c) = (a.clone(), a.clone());
|
||||
assert!(b.modify(Handle(1), |e| e.common.layer = "B".into()));
|
||||
assert!(c.modify(Handle(1), |e| e.common.layer = "C".into()));
|
||||
assert_ne!(b.content_token(), c.content_token(), "copies edited apart");
|
||||
assert_ne!(b.content_token(), a.content_token());
|
||||
let edits: [fn(&mut EntityStore); 8] = [
|
||||
|s| s.push(ent(9)),
|
||||
|s| s.push_front(ent(8)),
|
||||
|s| {
|
||||
s.replace(ent(2));
|
||||
},
|
||||
|s| {
|
||||
s.remove(Handle(3));
|
||||
},
|
||||
|s| {
|
||||
s.bring_to_front(Handle(1));
|
||||
},
|
||||
|s| {
|
||||
s.send_to_back(Handle(2));
|
||||
},
|
||||
|s| {
|
||||
s.move_next_to(Handle(1), Handle(2), true);
|
||||
},
|
||||
|s| s.sort_by_key(|e| std::cmp::Reverse(e.handle.0)),
|
||||
];
|
||||
for (i, edit) in edits.iter().enumerate() {
|
||||
let mut s = a.clone();
|
||||
edit(&mut s);
|
||||
assert_ne!(s.content_token(), a.content_token(), "edit {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_get_remove() {
|
||||
let mut s = EntityStore::new();
|
||||
|
||||
@@ -1076,9 +1076,13 @@ fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
|
||||
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
|
||||
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
assert!(!d.extents(&Space::Model).is_empty());
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
|
||||
let (bounds, cross_probes) = crate::TagKey::with_cross_probes(1000, || d.extents(&Space::Model));
|
||||
assert!(!bounds.is_empty());
|
||||
// Layer inheritance and the constant-value filter each query the opposite set.
|
||||
// With no matches, an unindexed scan bypasses the probe (zero) or compares every pair.
|
||||
for probes in cross_probes {
|
||||
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {cross_probes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
|
||||
|
||||
@@ -24,7 +24,7 @@ serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# R-tree spatial index for picking, window selection and object snaps (MIT OR Apache-2.0).
|
||||
rstar = { version = "0.13", default-features = false }
|
||||
rstar = { version = "0.14", default-features = false }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
@@ -280,6 +280,9 @@ impl DocState {
|
||||
self.view_history.clear();
|
||||
self.block_edit = Some(be);
|
||||
self.revision += 1;
|
||||
// The editor's drawing is another drawing with the host's handles: a name given in the
|
||||
// host must not resolve in it (BCLOSE ends the editor's names the same way, #1660).
|
||||
self.expire_names();
|
||||
}
|
||||
|
||||
/// Save the Block Editor's objects into the block (BSAVE), or into a new block `as_name`
|
||||
@@ -346,6 +349,9 @@ impl DocState {
|
||||
self.views = host.views;
|
||||
self.view_history = host.view_history;
|
||||
self.revision += 1;
|
||||
// The editor's drawing shares the host's handles: a name given in it must never resolve
|
||||
// to a host record (or the other way round) after the drawing comes back.
|
||||
self.expire_names();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ mod griphot;
|
||||
pub(crate) mod groups;
|
||||
pub(crate) mod hatch;
|
||||
mod image;
|
||||
mod inquiry;
|
||||
pub(crate) mod inquiry;
|
||||
pub mod interface;
|
||||
mod layer;
|
||||
mod layout;
|
||||
@@ -35,6 +35,7 @@ mod modify2;
|
||||
mod mtext_opts;
|
||||
mod overkill;
|
||||
mod pline_opts;
|
||||
pub mod plotstyle_folder;
|
||||
pub mod plotters;
|
||||
mod props;
|
||||
pub use blocks::library::{clear_library_cache, list_library, read_library_file};
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -305,6 +305,9 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
|
||||
arrow,
|
||||
spline,
|
||||
style: style(s),
|
||||
// The drawing's DIM* overrides, as a new dimension takes them: the arrowhead is then drawn
|
||||
// with the DIMASZ the hook line above was sized from, and they are saved with the leader.
|
||||
overrides: s.doc().map(|d| d.dim_overrides()).unwrap_or_default(),
|
||||
}))?;
|
||||
let annotation = match ann {
|
||||
Annotation::Text(lines) => {
|
||||
|
||||
@@ -117,8 +117,10 @@ fn run_recover(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.state_mut()?;
|
||||
let report = crate::audit::fix(Arc::make_mut(&mut st.doc));
|
||||
if report.issues.is_empty() {
|
||||
// Nothing to fix: the drawing opens unchanged, like OPEN.
|
||||
st.doc = st.saved.clone();
|
||||
// Nothing to fix: the drawing opens unchanged, like OPEN. `fix` may already
|
||||
// have copied it, so put the saved one back; no record name exists yet.
|
||||
let saved = st.saved.clone();
|
||||
st.restore_drawing(saved);
|
||||
}
|
||||
if copy && !st.is_dirty() {
|
||||
// An unsaved copy (Drawing Recovery): closing it asks to save it under a name.
|
||||
|
||||
@@ -104,12 +104,17 @@ pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib>
|
||||
let m = ins.transform(blk.base.xy());
|
||||
// The reference's attributes by tag, gathered once for all the definitions (#1923).
|
||||
let carried = ins.attribs_by_tag();
|
||||
#[cfg(test)]
|
||||
let carried = carried.into_iter().map(|(tag, attrib)| (tests::MeasuredTag(tag), attrib)).collect::<std::collections::BTreeMap<_, _>>();
|
||||
defs.iter()
|
||||
.map(|ad| {
|
||||
let mut k = EntityKind::Text(ad.text.clone());
|
||||
k.transform(&m);
|
||||
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
|
||||
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
|
||||
let key = TagKey(&ad.tag);
|
||||
#[cfg(test)]
|
||||
let key = tests::MeasuredTag(key);
|
||||
t.value = carried.get(&key).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
|
||||
Attrib {
|
||||
tag: ad.tag.clone(),
|
||||
text: t,
|
||||
@@ -204,6 +209,8 @@ pub(super) fn sync(s: &mut Session, name: &str) -> Result<(String, usize)> {
|
||||
let defs = attdefs(&blk);
|
||||
let d = s.doc_mut()?;
|
||||
let n = update_references(d, &blk.name, |ins| ins.attribs = synced(&blk, &defs, ins));
|
||||
// The references have new ATTRIBs: names given to the old ones hold no longer (#1660).
|
||||
s.state_mut()?.expire_names();
|
||||
Ok((blk.name.clone(), n))
|
||||
}
|
||||
|
||||
@@ -359,6 +366,74 @@ impl Interactive for AttsyncM {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
std::thread_local! {
|
||||
static SYNC_CROSS_PROBES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// Use the actual tag ordering and count only probes between different fixture sets.
|
||||
pub(super) struct MeasuredTag<'a>(pub(super) TagKey<'a>);
|
||||
|
||||
impl MeasuredTag<'_> {
|
||||
fn record(&self, other: &Self) {
|
||||
let TagKey(left) = self.0;
|
||||
let TagKey(right) = other.0;
|
||||
let sides = (left.as_bytes().first(), right.as_bytes().first());
|
||||
if matches!(sides, (Some(b'A'), Some(b'D')) | (Some(b'D'), Some(b'A'))) {
|
||||
SYNC_CROSS_PROBES.with(|count| count.set(count.get().map(|n| n + 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for MeasuredTag<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.record(other);
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for MeasuredTag<'_> {}
|
||||
|
||||
impl PartialOrd for MeasuredTag<'_> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for MeasuredTag<'_> {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.record(other);
|
||||
self.0.cmp(&other.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_uses_indexed_cross_set_tag_matching() {
|
||||
const N: usize = 512;
|
||||
let mut s = Session::new();
|
||||
s.execute("attdef", &json!({"tag":"T", "default":"d", "at":[0, 1], "height":1.0})).unwrap();
|
||||
s.execute("line", &json!({"points":[[0, 0], [10, 0]]})).unwrap();
|
||||
let ids: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
|
||||
s.execute("block", &json!({"name":"B", "base":[0, 0], "keep":"delete", "handles":ids})).unwrap();
|
||||
let added = s.execute("insert", &json!({"name":"B", "at":[0, 0], "attribs":{"T":"v"}})).unwrap();
|
||||
let handle = Handle::parse_hex(added["handle"].as_str().unwrap()).unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
let blk = doc.block("B").unwrap();
|
||||
let base = (*attdefs(blk)[0]).clone();
|
||||
let EntityKind::Insert(mut ins) = doc.entity(handle).unwrap().kind.clone() else { panic!("insert expected") };
|
||||
let value = ins.attribs[0].clone();
|
||||
let defs: Vec<_> = (0..N).map(|i| Attrib { tag: format!("D{i:05}"), ..base.clone() }).collect();
|
||||
let defs: Vec<_> = defs.iter().collect();
|
||||
ins.attribs = (0..N).map(|i| Attrib { tag: format!("A{i:05}"), ..value.clone() }).collect();
|
||||
|
||||
SYNC_CROSS_PROBES.with(|count| count.set(Some(0)));
|
||||
let result = synced(blk, &defs, &ins);
|
||||
let probes = SYNC_CROSS_PROBES.with(|count| count.replace(None).unwrap());
|
||||
assert_eq!(result.len(), N);
|
||||
assert!(result.iter().all(|a| a.text.value == "d"));
|
||||
// No cross-set comparisons means this lookup was bypassed, whereas a scan does N*N.
|
||||
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {probes}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attdisp_keywords_map_to_attmode() {
|
||||
assert_eq!([attmode("Normal"), attmode("on"), attmode("OFF"), attmode("x")], [Some(1), Some(2), Some(0), None]);
|
||||
|
||||
@@ -6,7 +6,7 @@ use cadcraft_doc::{Drawing, Entity, EntityKind};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::attribs::{attdefs, synced, update_reference_entities};
|
||||
use super::purge::{override_arrows, used_blocks};
|
||||
use super::purge::{leader_override_arrows, override_arrows, used_blocks};
|
||||
use super::references_block;
|
||||
use crate::cmd::curves::KW;
|
||||
use crate::cmd::machines::{SelOutcome, SelectPhase};
|
||||
@@ -81,6 +81,8 @@ fn replace(s: &mut Session, old: &str, new: &str, purge: bool) -> Result<(usize,
|
||||
});
|
||||
let key = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(&old)).cloned();
|
||||
let purged = purge && !referenced(d, &old) && key.is_some_and(|k| d.blocks.remove(&k).is_some());
|
||||
// Replaced references have new ATTRIBs: names given to the old ones hold no longer (#1660).
|
||||
s.state_mut()?.expire_names();
|
||||
Ok((n, purged))
|
||||
}
|
||||
|
||||
@@ -94,6 +96,7 @@ fn referenced(d: &Drawing, name: &str) -> bool {
|
||||
match &e.kind {
|
||||
EntityKind::Insert(i) => vec![i.block.clone()],
|
||||
EntityKind::Dimension(dm) => dm.block.iter().cloned().chain(override_arrows(dm)).collect(),
|
||||
EntityKind::Leader(l) => leader_override_arrows(l).collect(),
|
||||
EntityKind::MLeader(m) => m.block.iter().map(|b| b.block.clone()).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
|
||||
@@ -230,6 +230,9 @@ impl Session {
|
||||
/// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no
|
||||
/// drag: the UI offers the choices, or flips, with `blocks.reference.set`.
|
||||
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
|
||||
// The value of an expression the frames are working out answers its prompt before the
|
||||
// command it was typed in is cancelled for the grip.
|
||||
self.lisp_settle_answer();
|
||||
if self.running.is_some() {
|
||||
self.cancel();
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::super::file::io;
|
||||
use super::super::modify::explode_kind;
|
||||
use super::purge::{Kind, candidates, is_arrow_override, override_arrows, override_name, scan_reads_everything};
|
||||
use super::purge::{Kind, candidates, is_arrow_override, leader_override_arrows, override_arrows, override_name, scan_reads_everything};
|
||||
use super::{referenced_block, references_block, valid_block_name};
|
||||
use crate::cmd::{bad, str_param};
|
||||
use crate::{EngineError, Result, Session};
|
||||
@@ -200,8 +200,10 @@ fn reachable(d: &Drawing, roots: Vec<String>) -> BTreeSet<String> {
|
||||
let Some(b) = d.block(&n) else { continue };
|
||||
for e in b.entities.iter() {
|
||||
todo.extend(referenced_block(e));
|
||||
if let EntityKind::Dimension(dm) = &e.kind {
|
||||
todo.extend(override_arrows(dm));
|
||||
match &e.kind {
|
||||
EntityKind::Dimension(dm) => todo.extend(override_arrows(dm)),
|
||||
EntityKind::Leader(l) => todo.extend(leader_override_arrows(l)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -214,8 +216,10 @@ fn needed_blocks(src: &Drawing) -> BTreeSet<String> {
|
||||
let mut roots: Vec<String> = Vec::new();
|
||||
for e in src.model.iter() {
|
||||
roots.extend(referenced_block(e));
|
||||
if let EntityKind::Dimension(dm) = &e.kind {
|
||||
roots.extend(override_arrows(dm));
|
||||
match &e.kind {
|
||||
EntityKind::Dimension(dm) => roots.extend(override_arrows(dm)),
|
||||
EntityKind::Leader(l) => roots.extend(leader_override_arrows(l)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for st in &src.dim_styles {
|
||||
@@ -319,6 +323,20 @@ fn rename_style_arrows(d: &mut Drawing, own: &BTreeSet<String>, renames: &Rename
|
||||
}
|
||||
}
|
||||
|
||||
/// Point the arrowhead blocks a dimension's or a leader's `overrides` name at their renamed
|
||||
/// blocks. Only a block that was renamed changes the value: a number naming a block that kept
|
||||
/// its name stays as it was given.
|
||||
fn rename_override_arrows(overrides: &mut serde_json::Map<String, Value>, renames: &Renames) {
|
||||
for (key, value) in overrides.iter_mut() {
|
||||
if is_arrow_override(key)
|
||||
&& let Some(b) = override_name(value)
|
||||
&& let Some(n) = renames.get(&b).filter(|n| **n != b)
|
||||
{
|
||||
*value = json!(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy of a source entity for this drawing: a fresh handle, block references renamed, and
|
||||
/// links to other source objects (associative dimension points) dropped.
|
||||
fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &Renames) -> Entity {
|
||||
@@ -346,17 +364,9 @@ fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &Renames) -> Entit
|
||||
if let Some(n) = dm.block.as_ref().and_then(|b| renames.get(b)) {
|
||||
dm.block = Some(n.clone());
|
||||
}
|
||||
for (key, value) in dm.overrides.iter_mut() {
|
||||
// Only a block that was renamed changes the value: a number naming a block that
|
||||
// kept its name stays as it was given.
|
||||
if is_arrow_override(key)
|
||||
&& let Some(b) = override_name(value)
|
||||
&& let Some(n) = renames.get(&b).filter(|n| **n != b)
|
||||
{
|
||||
*value = json!(n);
|
||||
}
|
||||
}
|
||||
rename_override_arrows(&mut dm.overrides, renames);
|
||||
}
|
||||
EntityKind::Leader(l) => rename_override_arrows(&mut l.overrides, renames),
|
||||
EntityKind::MLeader(m) => {
|
||||
if let Some(b) = &mut m.block
|
||||
&& let Some(n) = renames.get(&b.block)
|
||||
|
||||
@@ -147,11 +147,22 @@ pub(in crate::cmd) fn override_name(v: &Value) -> Option<String> {
|
||||
|
||||
/// The arrowhead block names a dimension's overrides set.
|
||||
pub(in crate::cmd) fn override_arrows(dm: &cadcraft_doc::Dimension) -> impl Iterator<Item = String> + '_ {
|
||||
dm.overrides.iter().filter(|(k, _)| is_arrow_override(k)).filter_map(|(_, v)| override_name(v)).filter(|n| !n.is_empty())
|
||||
arrows_in(&dm.overrides)
|
||||
}
|
||||
|
||||
/// The arrowhead block names a leader's overrides set (its DIMLDRBLK), as [`override_arrows`]
|
||||
/// gives a dimension's.
|
||||
pub(in crate::cmd) fn leader_override_arrows(l: &cadcraft_doc::Leader) -> impl Iterator<Item = String> + '_ {
|
||||
arrows_in(&l.overrides)
|
||||
}
|
||||
|
||||
/// The arrowhead block names a set of dimension style overrides names.
|
||||
fn arrows_in(overrides: &serde_json::Map<String, Value>) -> impl Iterator<Item = String> + '_ {
|
||||
overrides.iter().filter(|(k, _)| is_arrow_override(k)).filter_map(|(_, v)| override_name(v)).filter(|n| !n.is_empty())
|
||||
}
|
||||
|
||||
/// Upper-case names of blocks reachable from model space, the layouts and dimensions, and the
|
||||
/// arrowhead blocks dimension styles and dimension overrides name.
|
||||
/// arrowhead blocks dimension styles and dimension or leader overrides name.
|
||||
pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
|
||||
let mut used = HashSet::new();
|
||||
let mut frontier: Vec<String> = Vec::new();
|
||||
@@ -170,6 +181,7 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
|
||||
frontier.extend(dm.block.clone());
|
||||
frontier.extend(override_arrows(dm));
|
||||
}
|
||||
EntityKind::Leader(l) => frontier.extend(leader_override_arrows(l)),
|
||||
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
|
||||
// A dimension kept as read draws, and is saved with, the block it names (#3438).
|
||||
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
|
||||
@@ -189,6 +201,7 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
|
||||
frontier.extend(dm.block.clone());
|
||||
frontier.extend(override_arrows(dm));
|
||||
}
|
||||
EntityKind::Leader(l) => frontier.extend(leader_override_arrows(l)),
|
||||
EntityKind::MLeader(m) => frontier.extend(m.block.as_ref().map(|b| b.block.clone())),
|
||||
EntityKind::Unknown(u) => frontier.extend(u.dimension_block().map(str::to_string)),
|
||||
_ => {}
|
||||
|
||||
@@ -1073,7 +1073,7 @@ pub(crate) fn after_command(s: &mut Session, before: &Arc<Drawing>, id: &str) ->
|
||||
.iter()
|
||||
.any(|store| store.iter().any(|e| !owned.contains(&e.handle) && !st.doc.entity(e.handle).is_some_and(|a| Arc::ptr_eq(a, e))));
|
||||
if touched {
|
||||
st.doc = before.clone();
|
||||
st.restore_drawing(before.clone());
|
||||
return Some("Only the working set can be edited during REFEDIT (REFSET adds objects, REFCLOSE ends the edit).".into());
|
||||
}
|
||||
let seed = before.handseed;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -70,9 +70,16 @@ pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ---------------- interactive ----------------
|
||||
|
||||
/// A LINE between two 3D points.
|
||||
fn line3(a: cadcraft_geom::Vec3, b: cadcraft_geom::Vec3) -> EntityKind {
|
||||
EntityKind::Line(cadcraft_doc::Line { a, b })
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct LineM {
|
||||
pts: Vec<Vec2>,
|
||||
/// The Z of each of `pts` ([`Session::point_z`]: typed, or from an object snap).
|
||||
zs: Vec<f64>,
|
||||
handles: Vec<cadcraft_doc::Handle>,
|
||||
/// A first point picked as a deferred tangent/perpendicular, resolved by the next point.
|
||||
first: Option<snap::Deferred>,
|
||||
@@ -85,8 +92,11 @@ impl LineM {
|
||||
let what = if first.mode == snap::mode::TAN { "tangent" } else { "perpendicular" };
|
||||
return Err(crate::EngineError::Other(format!("No {what} line through that point; pick another point.")));
|
||||
};
|
||||
self.handles.push(s.add_entity(line(a, b))?);
|
||||
// The deferred start lies on the curve at z = 0; the other end keeps its own Z.
|
||||
let z = s.point_z();
|
||||
self.handles.push(s.add_entity(line3(a.to3(0.0), b.to3(z)))?);
|
||||
self.pts = vec![a, b];
|
||||
self.zs = vec![0.0, z];
|
||||
self.first = None;
|
||||
s.last_point = b;
|
||||
Ok(Step::Continue)
|
||||
@@ -119,6 +129,7 @@ impl Interactive for LineM {
|
||||
let e = t + Vec2::new(ang.cos(), ang.sin()) * dist;
|
||||
self.handles.push(s.add_entity(line(t, e))?);
|
||||
self.pts = vec![t, e];
|
||||
self.zs = vec![0.0, 0.0];
|
||||
s.last_point = e;
|
||||
self.first = None;
|
||||
return Ok(Step::Continue);
|
||||
@@ -143,13 +154,15 @@ impl Interactive for LineM {
|
||||
None => Ok(Step::Continue),
|
||||
},
|
||||
Input::Point(p) => {
|
||||
if let Some(last) = self.pts.last().copied() {
|
||||
if last.near(p, 1e-12) {
|
||||
let z = s.point_z();
|
||||
if let (Some(last), Some(lz)) = (self.pts.last().copied(), self.zs.last().copied()) {
|
||||
if last.near(p, 1e-12) && (lz - z).abs() < 1e-12 {
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
self.handles.push(s.add_entity(line(last, p))?);
|
||||
self.handles.push(s.add_entity(line3(last.to3(lz), p.to3(z)))?);
|
||||
}
|
||||
self.pts.push(p);
|
||||
self.zs.push(z);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Keyword(k) if k == "Undo" => {
|
||||
@@ -160,11 +173,14 @@ impl Interactive for LineM {
|
||||
s.doc_mut()?.remove_entity(h);
|
||||
}
|
||||
self.pts.pop();
|
||||
self.zs.pop();
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Input::Keyword(k) if k == "Close" => {
|
||||
if let (Some(a), Some(b)) = (self.pts.last().copied(), self.pts.first().copied()) {
|
||||
s.add_entity(line(a, b))?;
|
||||
if let (Some(a), Some(b), Some(za), Some(zb)) =
|
||||
(self.pts.last().copied(), self.pts.first().copied(), self.zs.last().copied(), self.zs.first().copied())
|
||||
{
|
||||
s.add_entity(line3(a.to3(za), b.to3(zb)))?;
|
||||
}
|
||||
Ok(Step::Done)
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ impl Interactive for PointM {
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match i {
|
||||
Input::Point(p) => {
|
||||
s.add_entity(EntityKind::Point(Point { p: v3(p), angle: 0.0 }))?;
|
||||
s.add_entity(EntityKind::Point(Point { p: p.to3(s.point_z()), angle: 0.0 }))?;
|
||||
Ok(if self.multiple { Step::Continue } else { Step::Done })
|
||||
}
|
||||
Input::Enter => Ok(Step::Done),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Accept, EntityKind, Handle, Helix, HelixConstrain, Input, Interactive, MAX_GEN, Polyline3d, Prompt, Result, Session, Spline, Step, Value, Vec2,
|
||||
Vec3, added, bad, bool_or, circle, curves, f64_or, f64_req, line, number, other, point_req, points_param, v3,
|
||||
Vec3, added, bad, bool_or, circle, curves, f64_or, f64_req, line, number, other, point_req, points_param,
|
||||
};
|
||||
|
||||
// =====================================================================================
|
||||
@@ -26,13 +26,14 @@ pub(super) fn run_3dpoly(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Poly3dM {
|
||||
pts: Vec<Vec2>,
|
||||
/// The vertices: a typed point keeps its Z ([`Session::point_z`]), a picked one is at z = 0.
|
||||
pts: Vec<Vec3>,
|
||||
handle: Option<Handle>,
|
||||
}
|
||||
|
||||
impl Poly3dM {
|
||||
fn sync(&mut self, s: &mut Session, closed: bool) -> Result<()> {
|
||||
let k = EntityKind::Polyline3d(Polyline3d { points: self.pts.iter().map(|p| v3(*p)).collect(), closed });
|
||||
let k = EntityKind::Polyline3d(Polyline3d { points: self.pts.clone(), closed });
|
||||
match (self.handle, self.pts.len() >= 2) {
|
||||
(Some(h), true) => s.doc_mut()?.modify_entity(h, |e| e.kind = k)?,
|
||||
(None, true) => self.handle = Some(s.add_entity(k)?),
|
||||
@@ -53,14 +54,15 @@ impl Interactive for Poly3dM {
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
match self.pts.len() {
|
||||
0 => Prompt::new("Specify start point of polyline", Accept::POINT),
|
||||
1 | 2 => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Undo"]).base_opt(self.pts.last().copied()),
|
||||
_ => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Close", "Undo"]).base_opt(self.pts.last().copied()),
|
||||
1 | 2 => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Undo"]).base_opt(self.pts.last().map(|p| p.xy())),
|
||||
_ => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Close", "Undo"]).base_opt(self.pts.last().map(|p| p.xy())),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match i {
|
||||
Input::Point(p) => {
|
||||
if self.pts.last().is_none_or(|l| !l.near(p, 1e-12)) && self.pts.len() < MAX_GEN {
|
||||
let p = p.to3(s.point_z());
|
||||
if self.pts.last().is_none_or(|l| (*l - p).len() > 1e-12) && self.pts.len() < MAX_GEN {
|
||||
self.pts.push(p);
|
||||
self.sync(s, false)?;
|
||||
}
|
||||
@@ -80,7 +82,7 @@ impl Interactive for Poly3dM {
|
||||
}
|
||||
}
|
||||
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
self.pts.last().map(|l| vec![line(*l, c)]).unwrap_or_default()
|
||||
self.pts.last().map(|l| vec![line(l.xy(), c)]).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use cadcraft_doc::EntityKind;
|
||||
use cadcraft_geom::{Arc, Vec2};
|
||||
use cadcraft_geom::{Arc, Vec2, Vec3};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{Input, Session};
|
||||
@@ -1466,6 +1466,40 @@ fn poly3d_json_and_command_line() {
|
||||
assert_eq!(s.state().unwrap().undo.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poly3d_typed_points_keep_their_z() {
|
||||
// A typed third number reaches the polyline (#1409, #1410): absolute `x,y,z`, relative
|
||||
// `@dx,dy,dz`, and `@dx,dy`, which keeps the last point's Z, as in AutoCAD.
|
||||
let mut s = Session::new();
|
||||
s.cmdline("3dpoly 0,0,0 10,0,5 @0,10,-2 @5,0 #1,2,3").unwrap();
|
||||
// A picked point lies on the XY plane.
|
||||
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.running.is_none());
|
||||
let EntityKind::Polyline3d(p) = last(&s) else { panic!("{:?}", last(&s)) };
|
||||
let got: Vec<[f64; 3]> = p.points.iter().map(|v| [v.x, v.y, v.z]).collect();
|
||||
assert_eq!(got, vec![[0.0, 0.0, 0.0], [10.0, 0.0, 5.0], [10.0, 10.0, 3.0], [15.0, 10.0, 3.0], [1.0, 2.0, 3.0], [20.0, 20.0, 0.0]]);
|
||||
// LASTPOINT carries the Z of a typed point.
|
||||
s.cmdline("3dpoly 0,0,0 4,5,6").unwrap();
|
||||
assert_eq!(crate::sysvars::get(&s, "LASTPOINT"), Some(json!([4.0, 5.0, 6.0])));
|
||||
s.input(Input::Enter).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poly3d_flat_and_vertical_segments() {
|
||||
// Two numbers still give z = 0.
|
||||
let mut s = Session::new();
|
||||
s.cmdline("3dpoly 0,0 1,0 1,1 ").unwrap();
|
||||
assert!(matches!(last(&s), EntityKind::Polyline3d(p) if p.points.len() == 3 && p.points.iter().all(|v| v.z == 0.0)));
|
||||
// A point straight above the last one is a new vertex, not a repeat.
|
||||
s.cmdline("3dpoly 0,0,0 0,0,5 ").unwrap();
|
||||
assert!(matches!(last(&s), EntityKind::Polyline3d(p) if p.points.len() == 2 && p.points[1].z == 5.0));
|
||||
// Undo drops the Z with its point.
|
||||
s.cmdline("3dpoly 0,0,1 1,0,2 u 0,1,3 ").unwrap();
|
||||
let EntityKind::Polyline3d(p) = last(&s) else { panic!("{:?}", last(&s)) };
|
||||
assert_eq!(p.points, vec![Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, 1.0, 3.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mline_json_and_command_line() {
|
||||
// Element offsets from the vertex path, sorted.
|
||||
|
||||
@@ -73,7 +73,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// A programmatic undo/redo (`engine.execute`, MCP, control channel, scripts) first ends a running
|
||||
/// command the way Esc does, exactly as `Session::start` does for Cmd+Z, the menu or the command
|
||||
/// line. Otherwise it would swap the drawing under the command and pop the previous command's step.
|
||||
/// As there, the value of an expression the frames are working out answers its prompt first: the
|
||||
/// command it ends is the step to take back.
|
||||
fn end_running_command(s: &mut Session) {
|
||||
s.lisp_settle_answer();
|
||||
if s.running.is_some() {
|
||||
s.cancel();
|
||||
}
|
||||
|
||||
@@ -108,6 +108,47 @@ pub fn entity_codec() -> Option<&'static EntityCodec> {
|
||||
CODEC.get()
|
||||
}
|
||||
|
||||
/// One record written after an entity's own, at `index` (an INSERT's ATTRIB, then its SEQEND):
|
||||
/// its type name and the groups of its record, without its `0` group. AutoLISP's `entnext` and
|
||||
/// `entget` reach an INSERT's attributes through it, one record at a time (the attributes have no
|
||||
/// handle of their own in the drawing). Installed by the app with the DXF writer, a lower layer;
|
||||
/// optional, so a host without one simply has no such records ([`EntityCodec`] is unchanged).
|
||||
pub type EntitySubRecord = fn(&Drawing, &cadcraft_doc::Entity, usize) -> Option<(String, Vec<craft_dxf::Tag>)>;
|
||||
|
||||
static SUB_RECORD: OnceLock<EntitySubRecord> = OnceLock::new();
|
||||
|
||||
// This thread hid the optional provider ([`without_entity_sub_record`], tests only).
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static SUB_RECORD_HIDDEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
pub fn set_entity_sub_record(f: EntitySubRecord) {
|
||||
let _ = SUB_RECORD.set(f);
|
||||
}
|
||||
pub fn entity_sub_record() -> Option<EntitySubRecord> {
|
||||
#[cfg(test)]
|
||||
if SUB_RECORD_HIDDEN.with(std::cell::Cell::get) {
|
||||
return None;
|
||||
}
|
||||
SUB_RECORD.get().copied()
|
||||
}
|
||||
|
||||
/// Run `f` as a host that did not install [`EntitySubRecord`]: `entnext` must walk the drawing's
|
||||
/// entities as it did before the provider existed. Tests only.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn without_entity_sub_record<R>(f: impl FnOnce() -> R) -> R {
|
||||
struct Unhide;
|
||||
impl Drop for Unhide {
|
||||
fn drop(&mut self) {
|
||||
SUB_RECORD_HIDDEN.with(|h| h.set(false));
|
||||
}
|
||||
}
|
||||
SUB_RECORD_HIDDEN.with(|h| h.set(true));
|
||||
let _unhide = Unhide;
|
||||
f()
|
||||
}
|
||||
|
||||
/// The drawing's non-graphic records as written (tables, BLOCK records, objects): each one's
|
||||
/// type, groups after the type and role (see [`cadcraft_doc::foreign::ForeignKey`]). AutoLISP's
|
||||
/// `namedobjdict`, `tblobjname` and `handent` of non-graphic objects read them (installed by the
|
||||
@@ -341,6 +382,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
)
|
||||
.noundo(),
|
||||
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
|
||||
CommandSpec::new("document.next", "Next Drawing", |s, _| run_cycle(s, true))
|
||||
.menu(&["Window", "Next Drawing"])
|
||||
.key(if cfg!(target_os = "macos") { "Ctrl+Tab" } else { "Cmd+Tab" })
|
||||
.params("{} → {index}: the open drawing after this one, the first after the last")
|
||||
.enabled(always)
|
||||
.noundo(),
|
||||
CommandSpec::new("document.prev", "Previous Drawing", |s, _| run_cycle(s, false))
|
||||
.menu(&["Window", "Previous Drawing"])
|
||||
.key(if cfg!(target_os = "macos") { "Ctrl+Shift+Tab" } else { "Cmd+Shift+Tab" })
|
||||
.params("{} → {index}: the open drawing before this one, the last before the first")
|
||||
.enabled(always)
|
||||
.noundo(),
|
||||
CommandSpec::new("document.bytes", "Drawing as bytes", run_bytes)
|
||||
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64, warnings?: what an image draws short of the drawing}")
|
||||
.noundo(),
|
||||
@@ -628,6 +681,14 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usi
|
||||
if s.doc()?.refedit.is_some() {
|
||||
return Err(bad(cmd, "A block reference is being edited in place: finish with REFCLOSE (Save or Discard) before saving."));
|
||||
}
|
||||
// A saved drawing carries the folder's plot style tables its layouts use.
|
||||
if is_drawing_file(path) {
|
||||
let st = s.state_mut()?;
|
||||
let mut d = st.drawing().clone();
|
||||
if super::layout::keep_used_folder_copies(std::sync::Arc::make_mut(&mut d)) {
|
||||
*st.drawing_arc_mut() = d;
|
||||
}
|
||||
}
|
||||
let (bytes, notes) = write_bytes(s, cmd, path, opts)?;
|
||||
let n = commit_save(s, path, &bytes, store)?;
|
||||
if is_drawing_file(path) {
|
||||
@@ -987,6 +1048,17 @@ fn run_switch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// `document.next` and `document.prev`: switch to the neighbouring open drawing, wrapping round at either end. With one drawing open nothing changes.
|
||||
fn run_cycle(s: &mut Session, forward: bool) -> Result<Value> {
|
||||
let count = s.docs.len();
|
||||
if count < 2 {
|
||||
return Ok(json!({ "index": s.active }));
|
||||
}
|
||||
let i = if forward { (s.active + 1) % count } else { (s.active + count - 1) % count };
|
||||
run_switch(s, &json!({ "index": i }))?;
|
||||
Ok(json!({ "index": i }))
|
||||
}
|
||||
|
||||
fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fmt = str_param(p, "format").unwrap_or("dxf");
|
||||
let opts = save_options("document.bytes", p)?;
|
||||
@@ -1457,6 +1529,33 @@ mod tests {
|
||||
s.execute("close", &json!({"index": 2})).unwrap();
|
||||
assert_eq!(active_title(&s), "Drawing2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_and_previous_drawing_wrap_round_and_end_the_running_command() {
|
||||
let mut s = Session::new();
|
||||
s.execute("new", &json!({})).unwrap();
|
||||
s.execute("new", &json!({})).unwrap();
|
||||
assert_eq!((s.docs.len(), s.active), (3, 2));
|
||||
assert_eq!(s.execute("document.next", &json!({})).unwrap()["index"], 0, "after the last comes the first");
|
||||
assert_eq!(s.active, 0);
|
||||
assert_eq!(s.execute("document.prev", &json!({})).unwrap()["index"], 2, "before the first comes the last");
|
||||
s.execute("document.prev", &json!({})).unwrap();
|
||||
assert_eq!(s.active, 1);
|
||||
s.cmdline("line").unwrap();
|
||||
assert!(s.running.is_some());
|
||||
s.execute("document.next", &json!({})).unwrap();
|
||||
assert!(s.running.is_none(), "a command left running belongs to the drawing it started in");
|
||||
assert_eq!(s.active, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_drawing_with_one_drawing_open_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(s.docs.len(), 1);
|
||||
assert_eq!(s.execute("document.next", &json!({})).unwrap()["index"], 0);
|
||||
assert_eq!(s.execute("document.prev", &json!({})).unwrap()["index"], 0);
|
||||
assert_eq!(s.docs.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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()
|
||||
@@ -276,9 +278,10 @@ impl GripEdit {
|
||||
}
|
||||
"Undo" => match self.undo.pop() {
|
||||
Some(doc) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an earlier
|
||||
// one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
@@ -490,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
|
||||
@@ -519,6 +526,9 @@ impl Session {
|
||||
/// view being edited does not show are left out (the first grip left is the base grip), and it
|
||||
/// is an error when none is left.
|
||||
pub fn start_grip_edit(&mut self, hot: &[(Handle, usize)]) -> Result<()> {
|
||||
// The value of an expression the frames are working out answers its prompt before the
|
||||
// command it was typed in is cancelled for the grips.
|
||||
self.lisp_settle_answer();
|
||||
if self.running.is_some() {
|
||||
self.cancel();
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
|
||||
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
|
||||
|
||||
mod capture;
|
||||
mod patfile;
|
||||
pub(super) use edit::{set_pattern, takes_pattern};
|
||||
pub(super) use patfile::run_patterns;
|
||||
pub use patfile::{PatternChoice, pattern_choices};
|
||||
pub use patfile::{PatternChoice, pattern_choices, pattern_choices_in, register_drawing_patterns};
|
||||
pub(super) use patfile::{drawing_lines, run_patterns};
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale};
|
||||
@@ -56,6 +57,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
|
||||
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
|
||||
CommandSpec::new("hatch.capture", "Capture hatch tile", capture::run)
|
||||
.params("{first:[x,y], second:[x,y], name?:string} → {pattern, patternText}; capture line segments inside the tile in the active space")
|
||||
.enabled(has_doc)
|
||||
.noundo(),
|
||||
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
|
||||
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
|
||||
.enabled(has_doc)
|
||||
@@ -340,6 +345,7 @@ pub(crate) fn gradient_name(t: &str) -> Option<&'static str> {
|
||||
|
||||
#[derive(Clone)]
|
||||
struct HatchSettings {
|
||||
lines: Vec<cadcraft_doc::library::PatternLine>,
|
||||
pattern: String,
|
||||
scale: f64,
|
||||
/// HPSPACE for user-defined patterns. The entity stores it as its scale.
|
||||
@@ -372,8 +378,10 @@ impl HatchSettings {
|
||||
angle: f64_or(p, "angle", 0.0).to_radians(),
|
||||
centered: bool_or(p, "centered", true),
|
||||
});
|
||||
let lines = s.doc().ok().and_then(|d| drawing_lines(d, &pattern)).unwrap_or_else(|| patfile::lines_for(&pattern));
|
||||
let scale = f64_or(p, "scale", hdr.1).max(1e-9);
|
||||
HatchSettings {
|
||||
lines,
|
||||
pattern,
|
||||
scale,
|
||||
user_spacing: scale,
|
||||
@@ -417,12 +425,12 @@ impl HatchSettings {
|
||||
background: None,
|
||||
// A user-defined hatch's families come from its angle, spacing and double flag, not
|
||||
// from a pattern definition; any other hatch takes the loaded pattern's, if any.
|
||||
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { patfile::lines_for(&self.pattern) },
|
||||
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { self.lines.clone() },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn make(s: &mut Session, p: &Value, gradient: bool) -> Result<Value> {
|
||||
fn make(s: &mut Session, p: &Value, gradient: bool, loaded: &[String]) -> Result<Value> {
|
||||
// A zero or negative pattern scale would be clamped to a near-zero spacing.
|
||||
size_param(if gradient { "gradient" } else { "hatch" }, p, "scale", false)?;
|
||||
let cmd = if gradient { "gradient" } else { "hatch" };
|
||||
@@ -435,7 +443,10 @@ fn make(s: &mut Session, p: &Value, gradient: bool) -> Result<Value> {
|
||||
if gradient && str_param(p, "name").is_some_and(|t| gradient_name(t).is_none()) {
|
||||
return Err(bad(cmd, format!("unknown gradient `name`; use one of {}", GRADIENT_NAMES.join(", "))));
|
||||
}
|
||||
let st = HatchSettings::from(s, p, gradient);
|
||||
let mut st = HatchSettings::from(s, p, gradient);
|
||||
if loaded.iter().any(|n| n.eq_ignore_ascii_case(&st.pattern)) {
|
||||
st.lines = patfile::lines_for(&st.pattern);
|
||||
}
|
||||
// Loops by picked point or selected object: one hatch each when separate.
|
||||
let mut groups: Vec<Vec<HatchLoop>> = Vec::new();
|
||||
// Internal points and boundary objects can come together (the dialog's Pick points and
|
||||
@@ -534,18 +545,19 @@ fn add_hatches(s: &mut Session, st: &HatchSettings, groups: Vec<Vec<HatchLoop>>)
|
||||
}
|
||||
|
||||
fn run_hatch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
patfile::load_param(p)?;
|
||||
let loaded = patfile::load_param(p)?;
|
||||
// Like the prompt: a name without a definition would be drawn as ANSI31.
|
||||
if let Some(up) = str_param(p, "pattern").map(str::to_ascii_uppercase)
|
||||
&& cadcraft_doc::library::pattern(&up).is_none()
|
||||
&& patfile::user_pattern(&up).is_none()
|
||||
&& drawing_lines(s.doc()?, &up).is_none()
|
||||
{
|
||||
return Err(bad("hatch", format!("unknown pattern {up}: not built in; load it with patternFile or patternText (a .pat file)")));
|
||||
}
|
||||
make(s, p, false)
|
||||
make(s, p, false, &loaded)
|
||||
}
|
||||
fn run_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
make(s, p, true)
|
||||
make(s, p, true, &[])
|
||||
}
|
||||
|
||||
fn boundary_at(s: &mut Session, q: Vec2) -> Result<Vec<Handle>> {
|
||||
@@ -574,8 +586,9 @@ fn run_boundary(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for q in pts {
|
||||
out.extend(boundary_at(s, q)?.into_iter().map(|h| h.hex()));
|
||||
if out.len() > MAX_BOUNDARY_OUTPUT {
|
||||
// The refused call leaves no partial result behind.
|
||||
s.state_mut()?.doc = before;
|
||||
// The refused call leaves no partial result behind. Handles it gave out can
|
||||
// be given again, so names of INSERT records end.
|
||||
s.state_mut()?.restore_drawing(before);
|
||||
return Err(bad("boundary", format!("more than {MAX_BOUNDARY_OUTPUT} boundary polylines in one call; split the work")));
|
||||
}
|
||||
}
|
||||
@@ -705,13 +718,17 @@ impl HatchM {
|
||||
self.settings.double = s.last_used.hatch_double;
|
||||
return Ok(true);
|
||||
}
|
||||
let up = match patfile::typed_file(s, t) {
|
||||
let file = patfile::typed_file(s, t);
|
||||
let explicit = file.is_some();
|
||||
let up = match file {
|
||||
// Nothing loaded from it: the pattern is asked again.
|
||||
Some(n) if n.is_empty() => return Ok(false),
|
||||
Some(n) => n,
|
||||
None => t.to_ascii_uppercase(),
|
||||
};
|
||||
if pattern_exists(&up) {
|
||||
let local = if explicit { None } else { drawing_lines(s.doc()?, &up) };
|
||||
if local.is_some() || pattern_exists(&up) {
|
||||
self.settings.lines = local.unwrap_or_else(|| patfile::lines_for(&up));
|
||||
self.settings.pattern = up.clone();
|
||||
// A named pattern, SOLID included, is not the user-defined one.
|
||||
self.settings.double = false;
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
//! Capture a rectangular tile from the active drawing space as reusable PAT text.
|
||||
use cadcraft_doc::{Drawing, EntityKind, Space, library::PatternLine};
|
||||
use cadcraft_geom::Vec2;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::{bad, point_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const COMMAND: &str = "hatch.capture";
|
||||
|
||||
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let corner = |key| point_param(p, key).filter(|q| q.is_finite()).ok_or_else(|| bad(COMMAND, format!("give a finite {key} point [x,y]")));
|
||||
let a = corner("first")?;
|
||||
let b = corner("second")?;
|
||||
let name = match p.get("name") {
|
||||
None => "CAPTURED_TILE",
|
||||
Some(v) => v.as_str().ok_or_else(|| bad(COMMAND, "name must be a string"))?,
|
||||
}
|
||||
.trim()
|
||||
.to_ascii_uppercase();
|
||||
if name.is_empty()
|
||||
|| name.len() > 31
|
||||
|| !name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
|
||||
|| cadcraft_doc::library::is_reserved_pattern_name(&name)
|
||||
{
|
||||
return Err(bad(COMMAND, "use a custom pattern name of 1 to 31 letters, digits or underscores"));
|
||||
}
|
||||
let lines = capture_lines(s.doc()?, &s.space(), a, b).map_err(|e| bad(COMMAND, e))?;
|
||||
let mut text = format!("*{name}, Custom pattern\n");
|
||||
for line in lines {
|
||||
text.push_str(&format!("{},{},{},{},{}", line.angle, line.origin.0, line.origin.1, line.delta.0, line.delta.1));
|
||||
for dash in line.dashes {
|
||||
text.push_str(&format!(",{dash}"));
|
||||
}
|
||||
text.push('\n');
|
||||
}
|
||||
Ok(json!({"pattern": name, "patternText": text}))
|
||||
}
|
||||
|
||||
/// A PAT family repeats along an integer combination of the two tile edges.
|
||||
/// The perpendicular neighbour is a second combination with determinant one.
|
||||
fn captured_family(start: Vec2, end: Vec2, u: Vec2, v: Vec2, m: i32, n: i32) -> PatternLine {
|
||||
let along = u * f64::from(m) + v * f64::from(n);
|
||||
let period = along.len();
|
||||
let dir = along / period;
|
||||
// Extended Euclid: a*m + b*n = 1, so the neighbour is -b*u + a*v.
|
||||
let (mut r, mut t) = (m, n);
|
||||
let (mut a, mut b, mut c, mut d) = (1, 0, 0, 1);
|
||||
while t != 0 {
|
||||
let k = r / t;
|
||||
(r, t) = (t, r % t);
|
||||
(a, c) = (c, a - k * c);
|
||||
(b, d) = (d, b - k * d);
|
||||
}
|
||||
let neighbour = (v * f64::from(a) - u * f64::from(b)) / f64::from(r);
|
||||
let len = start.dist(end);
|
||||
PatternLine {
|
||||
origin: (start.x, start.y),
|
||||
angle: dir.y.atan2(dir.x).to_degrees(),
|
||||
delta: (neighbour.dot(dir), u.cross(v) / period),
|
||||
dashes: if len >= period { Vec::new() } else { vec![len, len - period] },
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_lines(d: &Drawing, space: &Space, a: Vec2, b: Vec2) -> std::result::Result<Vec<PatternLine>, &'static str> {
|
||||
let low = Vec2::new(a.x.min(b.x), a.y.min(b.y));
|
||||
let w = (a.x - b.x).abs();
|
||||
let h = (a.y - b.y).abs();
|
||||
if !w.is_finite() || !h.is_finite() || w < 1e-9 || h < 1e-9 {
|
||||
return Err("Pick two opposite corners for the tile");
|
||||
}
|
||||
let entities = || d.space(space).into_iter().flat_map(|store| store.iter()).filter(|entity| d.is_visible(entity));
|
||||
let (mut origin, mut u, mut v) = (low, Vec2::new(w, 0.), Vec2::new(0., h));
|
||||
let mut guides = Vec::new();
|
||||
for entity in entities() {
|
||||
let EntityKind::LwPolyline(p) = &entity.kind else { continue };
|
||||
if !p.closed || p.vertices.len() != 4 || p.vertices.iter().any(|q| q.bulge != 0.) {
|
||||
continue;
|
||||
}
|
||||
let mut corners = [None; 4];
|
||||
let mut order = [0usize; 4];
|
||||
for (index, vertex) in p.vertices.iter().enumerate() {
|
||||
let q = vertex.p;
|
||||
let right = q.x > low.x + w / 2.;
|
||||
let top = q.y > low.y + h / 2.;
|
||||
let target = low + Vec2::new(if right { w } else { 0. }, if top { h } else { 0. });
|
||||
if (q.x - target.x).abs() <= w * 0.002 && (q.y - target.y).abs() <= h * 0.002 {
|
||||
order[index] = usize::from(right) + 2 * usize::from(top);
|
||||
corners[order[index]] = Some(q);
|
||||
}
|
||||
}
|
||||
if let [Some(bl), Some(br), Some(tl), Some(tr)] = corners
|
||||
&& order.iter().zip(order.iter().cycle().skip(1)).all(|(a, b)| (a ^ b).count_ones() == 1)
|
||||
&& (bl + (br - bl) + (tl - bl)).dist(tr) < w.min(h) * 1e-8
|
||||
{
|
||||
(origin, u, v) = (bl, br - bl, tl - bl);
|
||||
guides.push(entity.handle);
|
||||
}
|
||||
}
|
||||
let area = u.cross(v);
|
||||
let coords = |p: Vec2| Vec2::new(p.cross(v) / area, u.cross(p) / area);
|
||||
let world = |p: Vec2| u * p.x + v * p.y;
|
||||
let mut families = Vec::new();
|
||||
let mut add = |a: Vec2, b: Vec2, grid: bool| -> std::result::Result<(), &'static str> {
|
||||
let (mut start, mut end) = (a - origin, b - origin);
|
||||
let (s, e) = (coords(start), coords(end));
|
||||
let inside = |q: Vec2| (-1e-8..=1.00000001).contains(&q.x) && (-1e-8..=1.00000001).contains(&q.y);
|
||||
if !inside(s) || !inside(e) || start == end {
|
||||
return Ok(());
|
||||
}
|
||||
let delta = e - s;
|
||||
// Simple LINE geometry retains its original coordinates and short dash period.
|
||||
let simple = if delta.x.abs() < 1e-14 {
|
||||
Some((0, delta.y.signum() as i32))
|
||||
} else {
|
||||
(1..=128).find_map(|m| {
|
||||
let m = m * delta.x.signum() as i32;
|
||||
let n = f64::from(m) * delta.y / delta.x;
|
||||
(n.abs() <= 128. && (n - n.round()).abs() < 1e-10).then_some((m, n.round() as i32))
|
||||
})
|
||||
};
|
||||
let (mut m, mut n) = if let Some(dir) = simple.filter(|_| !grid) {
|
||||
dir
|
||||
} else {
|
||||
// Shared vertices round identically, including on neighbouring tiles.
|
||||
let snap = |p: Vec2| Vec2::new((p.x * 2048.).round(), (p.y * 2048.).round());
|
||||
let (s, e) = (snap(s), snap(e));
|
||||
if s == e {
|
||||
return Err("A segment is too small for the tile capture precision.");
|
||||
}
|
||||
start = world(s / 2048.);
|
||||
end = world(e / 2048.);
|
||||
((e.x - s.x) as i32, (e.y - s.y) as i32)
|
||||
};
|
||||
if m < 0 || (m == 0 && n < 0) {
|
||||
std::mem::swap(&mut start, &mut end);
|
||||
(m, n) = (-m, -n);
|
||||
}
|
||||
let (mut gcd, mut k) = (m.abs(), n.abs());
|
||||
while k != 0 {
|
||||
(gcd, k) = (k, gcd % k);
|
||||
}
|
||||
if gcd != 0 {
|
||||
families.push(captured_family(start, end, u, v, m / gcd, n / gcd));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
for entity in entities() {
|
||||
match &entity.kind {
|
||||
EntityKind::Line(l) => add(l.a.xy(), l.b.xy(), false)?,
|
||||
EntityKind::LwPolyline(p) if !guides.contains(&entity.handle) => {
|
||||
for (i, vertex) in p.vertices.iter().enumerate() {
|
||||
let next = p.vertices.get(i + 1).or_else(|| if p.closed { p.vertices.first() } else { None });
|
||||
if let Some(next) = next
|
||||
&& vertex.bulge == 0.
|
||||
{
|
||||
add(vertex.p, next.p, true)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if families.is_empty() {
|
||||
return Err("No complete line segments in the selected tile.");
|
||||
}
|
||||
Ok(families)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn capture_l_from_drawing_without_a_dialog() {
|
||||
let mut s = Session::new();
|
||||
s.execute("rectang", &json!({"p1":[30,40], "p2":[40,50]})).unwrap();
|
||||
for (a, b) in [([32, 42], [35, 42]), ([32, 42], [32, 46]), ([50, 60], [57, 60])] {
|
||||
s.execute("line", &json!({"points":[a,b]})).unwrap();
|
||||
}
|
||||
// An almost coincident hidden guide would shift the origin if it were used.
|
||||
let guide = s.execute("rectang", &json!({"p1":[30.01,40.01],"p2":[40.01,50.01]})).unwrap();
|
||||
s.execute("hideobjects", &json!({"handles":[guide["handle"]]})).unwrap();
|
||||
s.execute("layer.new", &json!({"name":"Hidden detail","current":true})).unwrap();
|
||||
s.execute("line", &json!({"points":[[33,43],[36,43]]})).unwrap();
|
||||
let detail = s.doc().unwrap().model.iter().last().unwrap().handle.hex();
|
||||
s.execute("layer.current", &json!({"name":"0"})).unwrap();
|
||||
s.execute("layoff", &json!({"handles":[detail]})).unwrap();
|
||||
let result = s.execute(COMMAND, &json!({"first":[40,50],"second":[30,40],"name":"HEADLESS_L"})).unwrap();
|
||||
let dest = s.execute("rectang", &json!({"p1":[0,0],"p2":[30,20]})).unwrap();
|
||||
let mut apply = result;
|
||||
apply["handles"] = json!([dest["handle"]]);
|
||||
s.execute("hatch", &apply).unwrap();
|
||||
let drawing = s.doc().unwrap();
|
||||
let hatch = drawing.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h) } else { None }).unwrap();
|
||||
assert_eq!(hatch.pattern, "HEADLESS_L");
|
||||
assert_eq!(hatch.pattern_lines.len(), 2, "frame and exterior segment excluded");
|
||||
for (angle, ink) in [(0., 3.), (90., 4.)] {
|
||||
let line = hatch.pattern_lines.iter().find(|l| (l.angle - angle).abs() < 1e-8).unwrap();
|
||||
assert_eq!(line.origin, (2., 2.));
|
||||
assert_eq!(line.dashes, vec![ink, ink - 10.]);
|
||||
assert!((line.delta.1 - 10.).abs() < 1e-8);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,9 +195,9 @@ fn separate(s: &mut Session, handle: Handle) -> Result<Vec<Handle>> {
|
||||
}
|
||||
|
||||
/// Pattern, scale and angle (degrees) from the parameters.
|
||||
fn properties(h: &mut Hatch, p: &Value) {
|
||||
fn properties(h: &mut Hatch, p: &Value, local: Option<&[cadcraft_doc::library::PatternLine]>) {
|
||||
if let Some(v) = str_param(p, "pattern") {
|
||||
set_pattern(h, v);
|
||||
set_pattern(h, v, local);
|
||||
}
|
||||
if let Some(x) = p.get("scale").and_then(Value::as_f64).filter(|x| x.is_finite() && *x > 0.0) {
|
||||
h.scale = x;
|
||||
@@ -222,11 +222,12 @@ pub(crate) fn takes_pattern(h: &Hatch, name: &str) -> bool {
|
||||
|
||||
/// Give `h` the pattern called `name` (HATCHEDIT's and Properties' pattern edit); false, and
|
||||
/// nothing changes, for a blank name or one the hatch can't take ([`takes_pattern`]).
|
||||
pub(crate) fn set_pattern(h: &mut Hatch, name: &str) -> bool {
|
||||
pub(crate) fn set_pattern(h: &mut Hatch, name: &str, local: Option<&[cadcraft_doc::library::PatternLine]>) -> bool {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || !takes_pattern(h, name) {
|
||||
if name.is_empty() || (local.is_none() && !takes_pattern(h, name)) {
|
||||
return false;
|
||||
}
|
||||
let keep_lines = h.pattern.eq_ignore_ascii_case(name) && !h.pattern_lines.is_empty();
|
||||
h.pattern = name.to_ascii_uppercase();
|
||||
h.solid = h.pattern == "SOLID";
|
||||
// A named pattern, SOLID included, replaces the gradient fill; the renderer draws the
|
||||
@@ -237,6 +238,10 @@ pub(crate) fn set_pattern(h: &mut Hatch, name: &str) -> bool {
|
||||
// any other name is the hatch's own and keeps its definition.
|
||||
if cadcraft_doc::library::pattern(&h.pattern).is_some() {
|
||||
h.pattern_lines.clear();
|
||||
} else if keep_lines {
|
||||
return true;
|
||||
} else if let Some(lines) = local {
|
||||
h.pattern_lines = lines.to_vec();
|
||||
} else if let Some(user) = super::patfile::user_pattern(&h.pattern) {
|
||||
h.pattern_lines = user.lines;
|
||||
}
|
||||
@@ -479,7 +484,9 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Like the prompt: a pattern must be one CADCraft defines, SOLID, or the hatches' own (a
|
||||
// pattern read from a file keeps its definition).
|
||||
let local = str_param(p, "pattern").and_then(|n| super::drawing_lines(s.doc().ok()?, n.trim()));
|
||||
if let Some(up) = str_param(p, "pattern").map(|v| v.trim().to_ascii_uppercase()).filter(|v| !v.is_empty())
|
||||
&& local.is_none()
|
||||
&& !defined_pattern(&up)
|
||||
{
|
||||
let d = s.doc()?;
|
||||
@@ -507,7 +514,7 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
notes.push(format!("Hatch {}: {missing} new boundary loop(s) could not be linked; it is now non-associative.", handle.hex()));
|
||||
}
|
||||
}
|
||||
properties(&mut h, p);
|
||||
properties(&mut h, p, local.as_deref());
|
||||
if let Some(g) = &grad {
|
||||
g.apply(&mut h);
|
||||
}
|
||||
@@ -720,7 +727,10 @@ impl Interactive for HatchEditM {
|
||||
(Ask::Pattern, _) => {
|
||||
if let Some(t) = text.filter(|t| !t.is_empty()) {
|
||||
let up = t.to_ascii_uppercase();
|
||||
if cadcraft_doc::library::pattern(&up).is_none() && super::patfile::user_pattern(&up).is_none() {
|
||||
if cadcraft_doc::library::pattern(&up).is_none()
|
||||
&& super::patfile::user_pattern(&up).is_none()
|
||||
&& super::drawing_lines(s.doc()?, &up).is_none()
|
||||
{
|
||||
s.echo(format!("Unknown pattern {up}."));
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
|
||||
|
||||
use cadcraft_doc::library::files::{UserPattern, parse_pat};
|
||||
use cadcraft_doc::library::{PatternLine, pattern, standard_patterns};
|
||||
use cadcraft_doc::library::{PatternLine, is_reserved_pattern_name, standard_patterns};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::helpers::support_text;
|
||||
@@ -38,7 +38,7 @@ pub(crate) fn user_pattern_name(name: &str) -> Option<String> {
|
||||
/// The line families a new hatch of pattern `name` carries: a user pattern's, else none (the
|
||||
/// library's patterns are drawn and saved from the library).
|
||||
pub(crate) fn lines_for(name: &str) -> Vec<PatternLine> {
|
||||
if pattern(name).is_some() {
|
||||
if is_reserved_pattern_name(name) {
|
||||
return Vec::new();
|
||||
}
|
||||
user_pattern(name).map(|p| p.lines).unwrap_or_default()
|
||||
@@ -70,6 +70,54 @@ pub fn pattern_choices() -> Vec<PatternChoice> {
|
||||
v
|
||||
}
|
||||
|
||||
fn embedded(d: &cadcraft_doc::Drawing) -> impl Iterator<Item = &cadcraft_doc::Hatch> {
|
||||
let stores = std::iter::once(&d.model)
|
||||
.chain(d.layouts.iter().map(|l| &l.entities))
|
||||
.chain(d.blocks.values().filter(|b| b.xref_path.is_none()).map(|b| &b.entities));
|
||||
stores.flat_map(|s| s.iter()).filter_map(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Hatch(h) if !h.pattern_lines.is_empty() => Some(h),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn drawing_lines(d: &cadcraft_doc::Drawing, name: &str) -> Option<Vec<PatternLine>> {
|
||||
if is_reserved_pattern_name(name) {
|
||||
return None;
|
||||
}
|
||||
embedded(d).find(|h| h.pattern.eq_ignore_ascii_case(name)).map(|h| h.pattern_lines.clone())
|
||||
}
|
||||
|
||||
/// An embedded definition takes precedence over the session library in its own drawing.
|
||||
pub fn pattern_choices_in(d: &cadcraft_doc::Drawing) -> Vec<PatternChoice> {
|
||||
let mut choices = pattern_choices();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for h in embedded(d) {
|
||||
if !seen.insert(h.pattern.to_ascii_uppercase()) || is_reserved_pattern_name(&h.pattern) {
|
||||
continue;
|
||||
}
|
||||
if let Some(c) = choices.iter_mut().find(|c| c.name.eq_ignore_ascii_case(&h.pattern)) {
|
||||
c.lines.clone_from(&h.pattern_lines);
|
||||
} else {
|
||||
choices.push(PatternChoice { name: h.pattern.clone(), description: String::new(), lines: h.pattern_lines.clone() });
|
||||
}
|
||||
}
|
||||
choices
|
||||
}
|
||||
|
||||
/// Make embedded custom definitions available when opening the hatch manager in an older drawing.
|
||||
pub fn register_drawing_patterns(d: &cadcraft_doc::Drawing) {
|
||||
let mut user = store();
|
||||
let mut known: std::collections::HashSet<_> = user.iter().map(|p| p.name.to_ascii_uppercase()).collect();
|
||||
for h in embedded(d) {
|
||||
if user.len() >= MAX_USER_PATTERNS {
|
||||
break;
|
||||
}
|
||||
if !h.pattern_lines.is_empty() && known.insert(h.pattern.to_ascii_uppercase()) && !is_reserved_pattern_name(&h.pattern) {
|
||||
user.push(UserPattern { name: h.pattern.clone(), description: String::new(), lines: h.pattern_lines.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add the patterns of a `.pat` file's text (a pattern loaded before under the same name is
|
||||
/// replaced). Returns the names added and the file's problems.
|
||||
pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
|
||||
@@ -78,7 +126,7 @@ pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
|
||||
let mut added = Vec::new();
|
||||
let mut user = store();
|
||||
for p in parsed.items {
|
||||
if pattern(&p.name).is_some() {
|
||||
if is_reserved_pattern_name(&p.name) {
|
||||
warnings.push(format!("{} is a built-in pattern; the built-in definition is kept", p.name));
|
||||
continue;
|
||||
}
|
||||
@@ -97,14 +145,15 @@ pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
|
||||
}
|
||||
|
||||
/// Load the pattern file a HATCH call names (`patternFile` path or `patternText` contents).
|
||||
pub(super) fn load_param(p: &Value) -> Result<()> {
|
||||
pub(super) fn load_param(p: &Value) -> Result<Vec<String>> {
|
||||
if let Some((text, source)) = support_text("hatch", p, "patternFile", "patternText")? {
|
||||
let (added, warnings) = load(&text);
|
||||
if added.is_empty() {
|
||||
return Err(bad("hatch", format!("no hatch pattern could be read from {source}: {}", warnings.join("; "))));
|
||||
}
|
||||
return Ok(added);
|
||||
}
|
||||
Ok(())
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// A `.pat` file typed at HATCH's pattern prompt: load it and return the pattern to use (the
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
|
||||
pub(crate) const MAX_PICKS: usize = 1000;
|
||||
|
||||
/// The first prompt's keywords: what to pick.
|
||||
const MODES: [&str; 4] = ["Points", "Objects", "oRigin", "Hatch"];
|
||||
const MODES: [&str; 5] = ["Points", "Objects", "oRigin", "Hatch", "TileRect"];
|
||||
|
||||
/// What HATCHPICK picks.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -22,6 +22,8 @@ pub enum PickMode {
|
||||
/// Internal points, each inside a closed boundary.
|
||||
#[default]
|
||||
Points,
|
||||
/// Two opposite corners of a rectangular custom-pattern tile.
|
||||
TileRect,
|
||||
/// Closed boundary objects.
|
||||
Objects,
|
||||
/// One point: the pattern origin.
|
||||
@@ -44,6 +46,7 @@ pub struct HatchPicks {
|
||||
fn mode_named(t: &str) -> Option<PickMode> {
|
||||
Some(match t.trim().to_ascii_lowercase().as_str() {
|
||||
"points" | "p" => PickMode::Points,
|
||||
"tilerect" | "tile" => PickMode::TileRect,
|
||||
"objects" | "o" => PickMode::Objects,
|
||||
"origin" | "r" => PickMode::Origin,
|
||||
"hatch" | "h" => PickMode::Hatch,
|
||||
@@ -134,6 +137,10 @@ impl Interactive for HatchPickM {
|
||||
match self.mode {
|
||||
None => Prompt::new("Enter what to pick", Accept::TEXT).kw(&MODES),
|
||||
Some(PickMode::Points) => Prompt::new("Pick internal point", Accept::POINT).kw(&["Undo"]),
|
||||
Some(PickMode::TileRect) => {
|
||||
Prompt::new(if self.picks.is_empty() { "Pick first corner of tile" } else { "Pick opposite corner of tile" }, Accept::POINT)
|
||||
.kw(&["Undo"])
|
||||
}
|
||||
Some(PickMode::Objects) => Prompt::new("Select objects", Accept::SELECT).kw(&["Undo"]),
|
||||
Some(PickMode::Origin) => Prompt::new("Specify the pattern origin", Accept::POINT),
|
||||
Some(PickMode::Hatch) => Prompt::new("Select hatch object", Accept::SELECT),
|
||||
@@ -150,12 +157,13 @@ impl Interactive for HatchPickM {
|
||||
};
|
||||
match (mode, i) {
|
||||
(_, Input::Cancel) => Ok(Step::Cancel),
|
||||
(PickMode::Points | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => {
|
||||
(PickMode::Points | PickMode::TileRect | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => {
|
||||
if self.picks.pop().is_none() {
|
||||
s.echo("Nothing to undo.");
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(PickMode::TileRect, Input::Enter) => Ok(Step::Continue),
|
||||
(PickMode::Points | PickMode::Objects, Input::Enter) => {
|
||||
self.keep(s, mode);
|
||||
Ok(Step::Done)
|
||||
@@ -174,6 +182,17 @@ impl Interactive for HatchPickM {
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(PickMode::TileRect, Input::Point(q)) => {
|
||||
if self.count() < 2 {
|
||||
self.picks.push(Pick::Point(q, Vec::new()));
|
||||
}
|
||||
if self.count() >= 2 {
|
||||
self.keep(s, mode);
|
||||
Ok(Step::Done)
|
||||
} else {
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
}
|
||||
(PickMode::Objects, Input::Pick(hs)) => {
|
||||
let room = MAX_PICKS.saturating_sub(self.count());
|
||||
let closed: Vec<Handle> = {
|
||||
|
||||
@@ -281,7 +281,7 @@ pub(crate) fn z_at(s: &Session, p: Vec2) -> f64 {
|
||||
}
|
||||
|
||||
/// The Z of `e` at the point of it nearest `p` (seen from above), when it has one there.
|
||||
fn entity_z(e: &Entity, p: Vec2) -> Option<f64> {
|
||||
pub(crate) fn entity_z(e: &Entity, p: Vec2) -> Option<f64> {
|
||||
let on_segment = |a: Vec3, b: Vec3| {
|
||||
let d = b.xy() - a.xy();
|
||||
let l2 = d.dot(d);
|
||||
@@ -308,6 +308,7 @@ fn entity_z(e: &Entity, p: Vec2) -> Option<f64> {
|
||||
// Read in world coordinates already.
|
||||
EntityKind::Circle(c) => Some(c.center.z),
|
||||
EntityKind::Arc(a) => Some(a.center.z),
|
||||
EntityKind::Ellipse(el) => Some(el.center.z),
|
||||
EntityKind::Text(t) | EntityKind::AttDef(cadcraft_doc::Attrib { text: t, .. }) => Some(t.insert.z),
|
||||
EntityKind::MText(t) => Some(t.insert.z),
|
||||
EntityKind::Insert(i) => Some(i.insert.z),
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
|
||||
use viewports::MviewM;
|
||||
|
||||
mod plotstyle;
|
||||
pub(crate) use plotstyle::keep_used_folder_copies;
|
||||
mod prompts;
|
||||
mod viewports;
|
||||
|
||||
@@ -82,18 +83,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("pagesetup", "Page Setup Manager...", run_pagesetup)
|
||||
.menu(&["File", "Page Setup Manager..."])
|
||||
.params(
|
||||
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
|
||||
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}; layout \"Model\" keeps only plotStyleTable",
|
||||
),
|
||||
// PLOT and EXPORTPDF are undoable for what a plot keeps in the drawing (a folder table's
|
||||
// copy, Model's table); a plot that changes nothing leaves no undo step.
|
||||
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
|
||||
.menu(&["File", "Print..."])
|
||||
.key("Cmd+P")
|
||||
.alias(&["print"])
|
||||
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)")
|
||||
.noundo(),
|
||||
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)"),
|
||||
CommandSpec::new("exportpdf", "Export to PDF...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "exportpdf")?, "exportpdf"))
|
||||
.menu(&["File", "Export to PDF..."])
|
||||
.params("{path? (else returns base64 `data`), layout?, device? (its papers; the output stays PDF), paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)")
|
||||
.noundo(),
|
||||
.params("{path? (else returns base64 `data`), layout?, device? (its papers; the output stays PDF), paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)"),
|
||||
CommandSpec::new("mspace", "Model Space (in viewport)", run_mspace)
|
||||
.alias(&["ms"])
|
||||
.params("{handle?: viewport, at?: [x,y] paper point inside a viewport} (default: the last active or first viewport)")
|
||||
@@ -812,13 +813,27 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"plotTransparency",
|
||||
];
|
||||
let changes = keys.iter().any(|k| p.get(k).is_some());
|
||||
// Model keeps only its plot style table (the rest of its plot settings are chosen per plot).
|
||||
if str_param(p, "layout").is_some_and(|n| n.eq_ignore_ascii_case("model")) {
|
||||
if let Some(k) = keys.iter().find(|k| **k != "plotStyleTable" && p.get(**k).is_some()) {
|
||||
return Err(bad(cmd, format!("Model keeps only `plotStyleTable`; `{k}` is chosen for each plot")));
|
||||
}
|
||||
if let Some(v) = str_param(p, "plotStyleTable")
|
||||
&& plotstyle::table_choice_changes(s.doc()?, v, true)
|
||||
&& plotstyle::set_model_table(s.doc_mut()?, v)
|
||||
{
|
||||
s.touch();
|
||||
}
|
||||
let table = s.doc()?.model_page.as_ref().map(|m| m.plot_style_table.clone()).unwrap_or_default();
|
||||
return Ok(json!({ "layout": "Model", "page": { "plotStyleTable": table } }));
|
||||
}
|
||||
let name = match str_param(p, "layout") {
|
||||
Some(n) => Some(layout_name(cmd, s.doc()?, n)?),
|
||||
None => s.space().layout().map(str::to_string),
|
||||
};
|
||||
let Some(name) = name else {
|
||||
if changes {
|
||||
return Err(bad(cmd, "pass `layout` (model-space page setups are not stored yet)"));
|
||||
return Err(bad(cmd, "pass `layout` (Model keeps only its `plotStyleTable`, with `layout: \"Model\"`)"));
|
||||
}
|
||||
// Report every layout's page setup.
|
||||
let d = s.doc()?;
|
||||
@@ -927,6 +942,8 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
if let Some(v) = str_param(p, "plotStyleTable") {
|
||||
page.plot_style_table = v.chars().take(260).collect();
|
||||
// A table from the user's plot style folder travels with the drawing.
|
||||
plotstyle::keep_folder_copy(s.doc_mut()?, &page.plot_style_table);
|
||||
}
|
||||
if let Some(v) = p.get("displayPlotStyles").and_then(Value::as_bool) {
|
||||
page.show_plot_styles = v;
|
||||
@@ -1057,7 +1074,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
};
|
||||
let pages = sheets.as_ref().map_or(1, Vec::len);
|
||||
let format = opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).unwrap_or_else(|| "pdf".into());
|
||||
match str_param(p, "path") {
|
||||
let r = match str_param(p, "path") {
|
||||
Some(_path) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
@@ -1070,22 +1087,44 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
|
||||
super::file::report_new_folder(s, &mut r, folder);
|
||||
super::file::report_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
r
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
super::exchange::deliver_file(cmd, _path, &bytes, super::file::deliver())?;
|
||||
let mut r = json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
|
||||
super::file::report_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
r
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
|
||||
super::file::report_notes(s, &mut r, notes);
|
||||
Ok(r)
|
||||
r
|
||||
}
|
||||
};
|
||||
// A table from the user's plot style folder that a plot used travels with the drawing, as
|
||||
// one chosen in a page setup does, and Model, which has no page setup dialog of its own,
|
||||
// remembers the table it last plotted with. A preview (an image with no file) changes nothing,
|
||||
// and so does a plot whose output was refused or failed: this runs only once it is written.
|
||||
if let Some(table) = str_param(p, "plotStyleTable")
|
||||
&& (str_param(p, "path").is_some() || !is_image)
|
||||
{
|
||||
// Model is the sheet plotted when `layouts` names it alone, whatever tab is showing.
|
||||
let model = match sheets.as_deref() {
|
||||
Some(names) => matches!(names, [only] if only.eq_ignore_ascii_case("model")),
|
||||
None => matches!(space, Space::Model),
|
||||
};
|
||||
// Checked first: `doc_mut` copies the drawing, which records an undo step even for no change.
|
||||
if plotstyle::table_choice_changes(s.doc()?, table, model) {
|
||||
let d = s.doc_mut()?;
|
||||
let changed = if model { plotstyle::set_model_table(d, table) } else { plotstyle::keep_folder_copy(d, table) };
|
||||
if changed {
|
||||
s.touch();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The model-space rectangle a plot of `plotArea` covers: `extents` (default) plots everything,
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
//! Plot styles: PLOTSTYLE (an object's or the current named plot style) and STYLESMANAGER (the
|
||||
//! plot style tables: list, view, create, edit, delete, load and save in our own file format).
|
||||
//! plot style tables: list, view, create, edit, rename, delete, load and save in our own file
|
||||
//! format).
|
||||
//!
|
||||
//! Tables the drawing keeps live in `Drawing::plot_style_tables` and are saved with it; they
|
||||
//! shadow built-in tables of the same name. Editing a built-in table stores an edited copy in
|
||||
//! the drawing.
|
||||
//! A table lives in the user's plot style folder ([`super::super::plotstyle_folder`]), which
|
||||
//! every drawing can use, or in the drawing (`Drawing::plot_style_tables`, saved with it). The
|
||||
//! drawing's table wins over a folder's of the same name, and both over a built-in one. A page
|
||||
//! setup (a layout's or Model's) or a plot that uses a folder table takes a copy of it into the
|
||||
//! drawing, which from then on plots with its copy whatever happens to the file. Editing a
|
||||
//! built-in table stores an edited copy in the drawing.
|
||||
//!
|
||||
//! Changes to the folder's files are written at once: UNDO takes back the drawing's copy, not the
|
||||
//! file.
|
||||
|
||||
use cadcraft_doc::{Drawing, PlotStyle, PlotStyleKind, PlotStyleTable};
|
||||
use serde_json::{Value, json};
|
||||
@@ -21,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("stylesmanager", "Plot Style Manager...", run_stylesmanager)
|
||||
.menu(&["File", "Plot Styles..."])
|
||||
.params(
|
||||
"{action?: list (default)|get|new|set|delete|load|save, name?: table (\"x.ctb\"/\"x.stb\"), kind?: colorDependent|named (new), from?: table to copy (new), description?, style?: {name, color?: \"#rrggbb\"|null, grayscale?, screening?: 0-100, linetype?: name|null, lineweight?: mm|null, end?, join?, fill?, description?} (set), removeStyle?: name (set, named tables), path? (load/save; save without one returns `text`), text? (load)}",
|
||||
"{action?: list (default)|get|new|set|rename|delete|load|save|reload, name?: table (\"x.ctb\"/\"x.stb\"), where?: folder|drawing (new, load: default drawing; get, set, rename, delete: default the drawing's table, else the folder's), kind?: colorDependent|named (new), from?: table to copy (new), fromWhere?: folder|drawing (new: where `from` is; default the drawing's table, else the folder's, else built-in), description?, style?: {name, color?: \"#rrggbb\"|null, grayscale?, screening?: 0-100, linetype?: name|null, lineweight?: mm|null, end?, join?, fill?, description?} (set), removeStyle?: name (set, named tables), to?: new name (rename), path? (load/save; save without one returns `text`), text? (load)} (folder tables are files in the settings folder's `plotstyles` folder; list reports it in `folder`)",
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -93,18 +100,165 @@ fn run_plotstyle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ---------- STYLESMANAGER ----------
|
||||
|
||||
fn in_drawing(d: &Drawing, name: &str) -> bool {
|
||||
d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(name.trim()))
|
||||
}
|
||||
|
||||
fn in_folder(name: &str) -> bool {
|
||||
cadcraft_doc::plot_style_folder_table(name).is_some()
|
||||
}
|
||||
|
||||
fn table_summary(d: &Drawing, t: &PlotStyleTable) -> Value {
|
||||
let in_drawing = d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(&t.name));
|
||||
let drawing = in_drawing(d, &t.name);
|
||||
let folder = in_folder(&t.name);
|
||||
json!({
|
||||
"name": t.name,
|
||||
"description": t.description,
|
||||
"kind": if t.is_color_dependent() { "colorDependent" } else { "named" },
|
||||
"styles": t.styles.len(),
|
||||
"inDrawing": in_drawing,
|
||||
"builtin": PlotStyleTable::builtin(&t.name).is_some() && !in_drawing,
|
||||
"source": if drawing { "drawing" } else if folder { "folder" } else { "builtin" },
|
||||
"inFolder": folder,
|
||||
"inDrawing": drawing,
|
||||
"builtin": PlotStyleTable::builtin(&t.name).is_some() && !drawing && !folder,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a table goes or comes from.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Where {
|
||||
Folder,
|
||||
Drawing,
|
||||
}
|
||||
|
||||
fn where_param(cmd: &str, p: &Value) -> Result<Option<Where>> {
|
||||
place_param(cmd, p, "where")
|
||||
}
|
||||
|
||||
/// A place parameter (`where`, or `fromWhere` for `new`'s `from`): folder or drawing.
|
||||
fn place_param(cmd: &str, p: &Value, key: &str) -> Result<Option<Where>> {
|
||||
match str_param(p, key).map(str::to_ascii_lowercase).as_deref() {
|
||||
None => Ok(None),
|
||||
Some("folder") => Ok(Some(Where::Folder)),
|
||||
Some("drawing") => Ok(Some(Where::Drawing)),
|
||||
Some(_) => Err(bad(cmd, format!("`{key}` must be folder or drawing"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` with the ending a table of `t`'s kind needs (added when it has none), at most 255
|
||||
/// characters with it: the length every action that looks a table up reads (`table_name`).
|
||||
fn with_ending(cmd: &str, t: &PlotStyleTable, name: &str) -> Result<String> {
|
||||
let ext = if t.is_color_dependent() { ".ctb" } else { ".stb" };
|
||||
let lower = name.to_ascii_lowercase();
|
||||
if !lower.ends_with(ext) && (lower.ends_with(".ctb") || lower.ends_with(".stb")) {
|
||||
return Err(bad(cmd, format!("a {} table's name ends in {ext}", if ext == ".ctb" { "colour-dependent" } else { "named" })));
|
||||
}
|
||||
let full = if lower.ends_with(ext) { name.to_string() } else { format!("{name}{ext}") };
|
||||
if full.chars().count() > 255 {
|
||||
return Err(bad(cmd, "a plot style table's name is at most 255 characters, with its ending"));
|
||||
}
|
||||
Ok(full)
|
||||
}
|
||||
|
||||
/// Write `t` to the plot style folder.
|
||||
fn write_folder(cmd: &str, t: &PlotStyleTable) -> Result<()> {
|
||||
super::super::plotstyle_folder::write(t).map_err(|e| bad(cmd, e))
|
||||
}
|
||||
|
||||
/// Copy the folder's table `name` into `d` when `d` has no table of that name: a layout that
|
||||
/// chooses a folder table takes it into the drawing, and the drawing then plots with its copy
|
||||
/// whatever later happens to the file. A table the drawing already has is left as it is.
|
||||
/// Returns whether a copy was taken.
|
||||
pub(super) fn keep_folder_copy(d: &mut Drawing, name: &str) -> bool {
|
||||
let name = name.trim();
|
||||
if !needs_folder_copy(d, name) {
|
||||
return false;
|
||||
}
|
||||
match cadcraft_doc::plot_style_folder_table(name) {
|
||||
Some(t) => {
|
||||
store(d, t);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the drawing lacks the folder table `name`, which `keep_folder_copy` would copy in.
|
||||
fn needs_folder_copy(d: &Drawing, name: &str) -> bool {
|
||||
let name = name.trim();
|
||||
!cadcraft_doc::no_plot_style_table(name) && !in_drawing(d, name) && cadcraft_doc::plot_style_folder_table(name).is_some()
|
||||
}
|
||||
|
||||
/// `name` as Model's page setup keeps it: empty for no table.
|
||||
fn model_name(name: &str) -> String {
|
||||
let name: String = name.trim().chars().take(260).collect();
|
||||
if cadcraft_doc::no_plot_style_table(&name) { String::new() } else { name }
|
||||
}
|
||||
|
||||
/// Whether Model's table is something other than `name` (as `model_name` keeps it).
|
||||
fn model_differs(d: &Drawing, name: &str) -> bool {
|
||||
let current = d.model_page.as_ref().map(|p| p.plot_style_table.trim()).unwrap_or_default();
|
||||
!current.eq_ignore_ascii_case(name)
|
||||
}
|
||||
|
||||
/// Whether choosing `name` would change `d`: Model's table (`model`), or a folder copy the
|
||||
/// drawing lacks. Read first, as changing the drawing copies it and records an undo step.
|
||||
pub(crate) fn table_choice_changes(d: &Drawing, name: &str, model: bool) -> bool {
|
||||
(model && model_differs(d, &model_name(name))) || needs_folder_copy(d, name)
|
||||
}
|
||||
|
||||
/// Remember `name` as Model's plot style table. Model keeps no other page settings here, so its
|
||||
/// page setup is the one the DXF writer gives it otherwise, with this table; `"None"` or an empty
|
||||
/// name clears it. A folder table is copied into the drawing. Returns whether anything changed.
|
||||
pub(crate) fn set_model_table(d: &mut Drawing, name: &str) -> bool {
|
||||
let name = model_name(name);
|
||||
let changed = model_differs(d, &name);
|
||||
if changed {
|
||||
d.model_page
|
||||
.get_or_insert_with(|| cadcraft_doc::PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..Default::default() })
|
||||
.plot_style_table = name.clone();
|
||||
}
|
||||
keep_folder_copy(d, &name) || changed
|
||||
}
|
||||
|
||||
/// Copy into `d` every folder table its page setups (each layout's and Model's) use that it
|
||||
/// doesn't have yet, so a saved drawing carries all its plot style tables (like the built-in
|
||||
/// ones, it then plots the same on a computer without the files). Returns whether anything was
|
||||
/// copied.
|
||||
pub(crate) fn keep_used_folder_copies(d: &mut Drawing) -> bool {
|
||||
let used: Vec<String> = d.layouts.iter().map(|l| &l.page).chain(d.model_page.as_ref()).map(|page| page.plot_style_table.clone()).collect();
|
||||
let mut copied = false;
|
||||
for name in used {
|
||||
copied |= keep_folder_copy(d, &name);
|
||||
}
|
||||
copied
|
||||
}
|
||||
|
||||
/// Which table `name` an action works on: `where` when given, else the drawing's (the one its
|
||||
/// layouts plot with), else the folder's. `None` for a table in neither (a built-in one).
|
||||
fn place_of(cmd: &str, s: &Session, p: &Value, name: &str) -> Result<Option<Where>> {
|
||||
Ok(match where_param(cmd, p)? {
|
||||
Some(w) => Some(w),
|
||||
None if in_drawing(s.doc()?, name) => Some(Where::Drawing),
|
||||
None if in_folder(name) => Some(Where::Folder),
|
||||
None => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Table `name` from `place`, or as the drawing sees it when `place` is `None`.
|
||||
fn table_at(cmd: &str, d: &Drawing, name: &str, place: Option<Where>) -> Result<PlotStyleTable> {
|
||||
let found = match place {
|
||||
Some(Where::Drawing) => d.plot_style_tables.iter().find(|t| t.name.eq_ignore_ascii_case(name.trim())).cloned(),
|
||||
Some(Where::Folder) => cadcraft_doc::plot_style_folder_table(name.trim()),
|
||||
None => cadcraft_doc::plot_style_table(d, name),
|
||||
};
|
||||
let here = match place {
|
||||
Some(Where::Drawing) => " in the drawing",
|
||||
Some(Where::Folder) => " in the plot style folder",
|
||||
None => "",
|
||||
};
|
||||
found.ok_or_else(|| bad(cmd, format!("no plot style table `{name}`{here}")))
|
||||
}
|
||||
|
||||
fn table_name(cmd: &str, p: &Value) -> Result<String> {
|
||||
let n = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`name` (the table) is required"))?;
|
||||
Ok(n.chars().take(255).collect())
|
||||
@@ -192,18 +346,30 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "stylesmanager";
|
||||
let action = str_param(p, "action").unwrap_or("list").to_ascii_lowercase();
|
||||
match action.as_str() {
|
||||
"list" => {
|
||||
"list" | "reload" => {
|
||||
if action == "reload" {
|
||||
super::super::plotstyle_folder::reload();
|
||||
for st in &mut s.docs {
|
||||
st.revision += 1;
|
||||
}
|
||||
}
|
||||
let d = s.doc()?;
|
||||
let tables: Vec<Value> = cadcraft_doc::plot_style_table_names(d)
|
||||
.iter()
|
||||
.filter_map(|n| cadcraft_doc::plot_style_table(d, n))
|
||||
.map(|t| table_summary(d, &t))
|
||||
.collect();
|
||||
Ok(json!({ "tables": tables }))
|
||||
Ok(json!({
|
||||
"tables": tables,
|
||||
"folder": super::super::plotstyle_folder::location(),
|
||||
"warnings": super::super::plotstyle_folder::warnings(),
|
||||
}))
|
||||
}
|
||||
"get" => {
|
||||
let name = table_name(cmd, p)?;
|
||||
let place = where_param(cmd, p)?;
|
||||
let d = s.doc()?;
|
||||
let t = find_table(cmd, d, &table_name(cmd, p)?)?;
|
||||
let t = table_at(cmd, d, &name, place)?;
|
||||
let mut v = serde_json::to_value(&t).unwrap_or(Value::Null);
|
||||
if let (Some(o), Value::Object(sum)) = (v.as_object_mut(), table_summary(d, &t)) {
|
||||
o.insert("inDrawing".into(), sum.get("inDrawing").cloned().unwrap_or(Value::Null));
|
||||
@@ -215,7 +381,8 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut name = table_name(cmd, p)?;
|
||||
let d = s.doc()?;
|
||||
let mut t = match str_param(p, "from") {
|
||||
Some(from) => find_table(cmd, d, from)?,
|
||||
// A name both the drawing and the folder hold: `fromWhere` says which to copy.
|
||||
Some(from) => table_at(cmd, d, from, place_param(cmd, p, "fromWhere")?)?,
|
||||
None => {
|
||||
let named = match str_param(p, "kind").map(str::to_ascii_lowercase).as_deref() {
|
||||
None if name.to_ascii_lowercase().ends_with(".stb") => true,
|
||||
@@ -226,15 +393,13 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if named { PlotStyleTable::named("", "", Vec::new()) } else { PlotStyleTable::color_dependent("", "", |_| None) }
|
||||
}
|
||||
};
|
||||
let ext = if t.is_color_dependent() { ".ctb" } else { ".stb" };
|
||||
let lower = name.to_ascii_lowercase();
|
||||
if !lower.ends_with(ext) {
|
||||
if lower.ends_with(".ctb") || lower.ends_with(".stb") {
|
||||
return Err(bad(cmd, format!("a {} table's name ends in {ext}", if ext == ".ctb" { "colour-dependent" } else { "named" })));
|
||||
}
|
||||
name.push_str(ext);
|
||||
}
|
||||
if d.plot_style_tables.iter().any(|x| x.name.eq_ignore_ascii_case(&name)) {
|
||||
name = with_ending(cmd, &t, &name)?;
|
||||
let place = where_param(cmd, p)?.unwrap_or(Where::Drawing);
|
||||
let taken = match place {
|
||||
Where::Folder => in_folder(&name),
|
||||
Where::Drawing => in_drawing(d, &name),
|
||||
};
|
||||
if taken {
|
||||
return Err(bad(cmd, format!("plot style table `{name}` already exists")));
|
||||
}
|
||||
t.name = name;
|
||||
@@ -242,13 +407,19 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
t.description = desc.chars().take(255).collect();
|
||||
}
|
||||
let t = t.sanitized();
|
||||
let out = table_summary(d, &t);
|
||||
store(s.doc_mut()?, t);
|
||||
Ok(out)
|
||||
match place {
|
||||
Where::Folder => {
|
||||
write_folder(cmd, &t)?;
|
||||
s.touch();
|
||||
}
|
||||
Where::Drawing => store(s.doc_mut()?, t.clone()),
|
||||
}
|
||||
Ok(table_summary(s.doc()?, &t))
|
||||
}
|
||||
"set" => {
|
||||
let name = table_name(cmd, p)?;
|
||||
let mut t = find_table(cmd, s.doc()?, &name)?;
|
||||
let place = place_of(cmd, s, p, &name)?;
|
||||
let mut t = table_at(cmd, s.doc()?, &name, place)?;
|
||||
if let Some(desc) = str_param(p, "description") {
|
||||
t.description = desc.chars().take(255).collect();
|
||||
}
|
||||
@@ -306,19 +477,18 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o.insert("removedStyle".into(), json!(r.trim()));
|
||||
}
|
||||
}
|
||||
store(s.doc_mut()?, t);
|
||||
// The folder's file is written, and the drawings that keep a copy of it keep their copy;
|
||||
// a built-in table edited keeps an edited copy in the drawing.
|
||||
if place == Some(Where::Folder) {
|
||||
write_folder(cmd, &t)?;
|
||||
s.touch();
|
||||
} else {
|
||||
store(s.doc_mut()?, t);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
"delete" => {
|
||||
let name = table_name(cmd, p)?;
|
||||
let d = s.doc_mut()?;
|
||||
let before = d.plot_style_tables.len();
|
||||
d.plot_style_tables.retain(|t| !t.name.eq_ignore_ascii_case(&name));
|
||||
if d.plot_style_tables.len() == before {
|
||||
return Err(bad(cmd, format!("the drawing keeps no plot style table `{name}` (built-in tables can't be deleted)")));
|
||||
}
|
||||
Ok(json!({ "deleted": name }))
|
||||
}
|
||||
"rename" => run_rename(s, p, cmd),
|
||||
"delete" => run_delete(s, p, cmd),
|
||||
"load" => {
|
||||
let text = match (str_param(p, "text"), str_param(p, "path")) {
|
||||
(Some(t), _) => t.to_string(),
|
||||
@@ -342,9 +512,15 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if t.name.is_empty() {
|
||||
return Err(bad(cmd, "the table has no name: pass `name`"));
|
||||
}
|
||||
let out = table_summary(s.doc()?, &t);
|
||||
store(s.doc_mut()?, t);
|
||||
Ok(out)
|
||||
t.name = with_ending(cmd, &t, &t.name.clone())?;
|
||||
match where_param(cmd, p)?.unwrap_or(Where::Drawing) {
|
||||
Where::Folder => {
|
||||
write_folder(cmd, &t)?;
|
||||
s.touch();
|
||||
}
|
||||
Where::Drawing => store(s.doc_mut()?, t.clone()),
|
||||
}
|
||||
Ok(table_summary(s.doc()?, &t))
|
||||
}
|
||||
"save" => {
|
||||
let name = table_name(cmd, p)?;
|
||||
@@ -364,6 +540,86 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, delete, load, save)"))),
|
||||
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, rename, delete, load, save, reload)"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// STYLESMANAGER rename: the folder's file, or the drawing's table and the layouts (and Model)
|
||||
/// of this drawing that use it. Renaming the file leaves the drawings' copies as they are.
|
||||
fn run_rename(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
let name = table_name(cmd, p)?;
|
||||
let to = str_param(p, "to").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`to` (the new name) is required"))?;
|
||||
let Some(place) = place_of(cmd, s, p, &name)? else {
|
||||
return Err(bad(
|
||||
cmd,
|
||||
format!("no plot style table `{name}` in the folder or the drawing (built-in tables can't be renamed: copy one with `new` and `from`)"),
|
||||
));
|
||||
};
|
||||
let mut t = table_at(cmd, s.doc()?, &name, Some(place))?;
|
||||
let old = t.name.clone();
|
||||
let to = with_ending(cmd, &t, to)?;
|
||||
let same = to.eq_ignore_ascii_case(&old);
|
||||
let taken = match place {
|
||||
Where::Folder => in_folder(&to),
|
||||
Where::Drawing => in_drawing(s.doc()?, &to),
|
||||
};
|
||||
if !same && taken {
|
||||
return Err(bad(cmd, format!("plot style table `{to}` already exists")));
|
||||
}
|
||||
t.name = to.clone();
|
||||
let mut layouts = 0usize;
|
||||
match place {
|
||||
Where::Folder => {
|
||||
write_folder(cmd, &t)?;
|
||||
if !same && let Err(e) = super::super::plotstyle_folder::delete(&old) {
|
||||
// Take the new file back, so the table isn't held twice and the rename can be tried again.
|
||||
let undone = super::super::plotstyle_folder::delete(&to);
|
||||
let left = if undone.is_ok() { "the table keeps its old name" } else { "both files now hold the table" };
|
||||
return Err(bad(cmd, format!("can't remove `{old}` from the plot style folder ({e}); {left}")));
|
||||
}
|
||||
s.touch();
|
||||
}
|
||||
Where::Drawing => {
|
||||
let d = s.doc_mut()?;
|
||||
for x in d.plot_style_tables.iter_mut().filter(|x| x.name.eq_ignore_ascii_case(&old)) {
|
||||
x.name = to.clone();
|
||||
}
|
||||
for l in d.layouts.iter_mut().filter(|l| l.page.plot_style_table.trim().eq_ignore_ascii_case(&old)) {
|
||||
l.page.plot_style_table = to.clone();
|
||||
layouts += 1;
|
||||
}
|
||||
if let Some(m) = d.model_page.as_mut().filter(|m| m.plot_style_table.trim().eq_ignore_ascii_case(&old)) {
|
||||
m.plot_style_table = to.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({ "name": to, "renamed": old, "layouts": layouts, "where": if place == Where::Folder { "folder" } else { "drawing" } }))
|
||||
}
|
||||
|
||||
/// STYLESMANAGER delete: the drawing's table or the folder's file.
|
||||
fn run_delete(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
|
||||
let name = table_name(cmd, p)?;
|
||||
let place = match where_param(cmd, p)? {
|
||||
Some(w) => w,
|
||||
None if in_drawing(s.doc()?, &name) => Where::Drawing,
|
||||
None if in_folder(&name) => Where::Folder,
|
||||
None => {
|
||||
return Err(bad(cmd, format!("no plot style table `{name}` in the folder or the drawing (built-in tables can't be deleted)")));
|
||||
}
|
||||
};
|
||||
match place {
|
||||
Where::Folder => {
|
||||
super::super::plotstyle_folder::delete(&name).map_err(|e| bad(cmd, e))?;
|
||||
s.touch();
|
||||
}
|
||||
Where::Drawing => {
|
||||
let d = s.doc_mut()?;
|
||||
let before = d.plot_style_tables.len();
|
||||
d.plot_style_tables.retain(|t| !t.name.eq_ignore_ascii_case(&name));
|
||||
if d.plot_style_tables.len() == before {
|
||||
return Err(bad(cmd, format!("the drawing keeps no plot style table `{name}` (built-in tables can't be deleted)")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({ "deleted": name, "where": if place == Where::Folder { "folder" } else { "drawing" } }))
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -267,7 +268,7 @@ pub(crate) fn explode_with(
|
||||
// pieces are copies of the block's objects and keep theirs.
|
||||
let own_pieces = !matches!(e.kind, EntityKind::Insert(_));
|
||||
let d = s.doc_mut()?;
|
||||
d.remove_entity(*h);
|
||||
let Some(removed) = d.remove_entity(*h) else { continue };
|
||||
for mut p in parts {
|
||||
if own_pieces {
|
||||
p.common.xdata.clear();
|
||||
@@ -278,6 +279,9 @@ pub(crate) fn explode_with(
|
||||
st.push(p);
|
||||
}
|
||||
}
|
||||
if !own_pieces && let Some(names) = s.record_names() {
|
||||
names.erased(&removed);
|
||||
}
|
||||
}
|
||||
s.set_selection(Vec::new());
|
||||
Ok(out)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use crate::cmd::helpers::v3;
|
||||
|
||||
use super::{
|
||||
Accept, Arc, EngineError, Entity, EntityKind, Handle, Input, Interactive, Line, PolyVertex, Prompt, Result, Session, Step, Value, Vec2, arc, bad,
|
||||
bool_or, ccw_sweep, f64_or, json, line, line_line_infinite, number, point_param,
|
||||
@@ -7,15 +9,43 @@ use super::{
|
||||
|
||||
/// What CHAMFER takes (as in AutoCAD, not arcs, circles, ellipses or splines).
|
||||
const CHAMFER_LINES_ONLY: &str =
|
||||
"CHAMFER works on lines (and polylines with the Polyline option); it cannot chamfer arcs, circles, ellipses or splines.";
|
||||
"CHAMFER works on lines, rays and xlines (and polylines with the Polyline option); it cannot chamfer arcs, circles, ellipses or splines.";
|
||||
|
||||
fn as_line(e: &Entity) -> Option<Line> {
|
||||
match &e.kind {
|
||||
EntityKind::Line(l) => Some(Line::new(l.a.xy(), l.b.xy())),
|
||||
EntityKind::Ray(r) | EntityKind::XLine(r) => Some(half_line(r, Some(true))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Both objects as lines for FILLET and CHAMFER, an xline as the half-line from its base towards
|
||||
/// the side picked of the corner: a line starting 1e8 away puts the corner ~1e-8 off.
|
||||
fn fillet_pair(e1: &Entity, p1: Vec2, e2: &Entity, p2: Vec2) -> Option<(Line, Line)> {
|
||||
let (l1, l2) = (as_line(e1)?, as_line(e2)?);
|
||||
let Some((x, _, _)) = line_line_infinite(l1.a, l1.b, l2.a, l2.b) else { return Some((l1, l2)) };
|
||||
let side = |e: &Entity, l: Line, p: Vec2| match &e.kind {
|
||||
EntityKind::XLine(r) => {
|
||||
let t = r.dir.xy().dot(p - x);
|
||||
half_line(r, (t != 0.0).then_some(t > 0.0))
|
||||
}
|
||||
_ => l,
|
||||
};
|
||||
Some((side(e1, l1, p1), side(e2, l2, p2)))
|
||||
}
|
||||
|
||||
/// A ray or xline as a line from its base whose far end lies beyond any corner, so that FILLET
|
||||
/// and CHAMFER keep the picked side; `unbounded_after_fillet` makes the unbounded ends rays
|
||||
/// again. With no side (a pick on the corner itself), both far ends.
|
||||
fn half_line(r: &cadcraft_doc::RayLine, forward: Option<bool>) -> Line {
|
||||
let (base, dir) = (r.base.xy(), r.dir.xy().normalized());
|
||||
match forward {
|
||||
Some(true) => Line::new(base, base + dir * 1e8),
|
||||
Some(false) => Line::new(base, base - dir * 1e8),
|
||||
None => Line::new(base - dir * 1e8, base + dir * 1e8),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fillet (or chamfer) two lines. `p1`/`p2` mark the kept side of each line.
|
||||
pub(crate) fn fillet_lines(
|
||||
s: &mut Session,
|
||||
@@ -32,7 +62,7 @@ pub(crate) fn fillet_lines(
|
||||
let d = s.doc()?;
|
||||
let e1 = d.entity(h1).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
|
||||
let e2 = d.entity(h2).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
|
||||
let (Some(l1), Some(l2)) = (as_line(&e1), as_line(&e2)) else {
|
||||
let Some((l1, l2)) = fillet_pair(&e1, p1, &e2, p2) else {
|
||||
if chamfer.is_none() {
|
||||
return crate::cmd::modify2::fillet_curves(s, h1, p1, h2, p2, radius);
|
||||
}
|
||||
@@ -328,9 +358,10 @@ impl Interactive for FilletM {
|
||||
Input::Keyword(k) if k == "Undo" => {
|
||||
match self.undo.pop() {
|
||||
Some(doc) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an earlier
|
||||
// one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
}
|
||||
None => s.echo("Nothing to undo."),
|
||||
@@ -486,17 +517,18 @@ fn fillet_corner(s: &mut Session, h1: Handle, p1: Vec2, h2: Handle, p2: Vec2, r:
|
||||
let d = s.doc()?;
|
||||
let k1 = d.entity(h1).map(|e| e.kind.clone());
|
||||
let k2 = d.entity(h2).map(|e| e.kind.clone());
|
||||
let pair = || fillet_pair(d.entity(h1)?, p1, d.entity(h2)?, p2);
|
||||
let chamfer = match cut {
|
||||
None => None,
|
||||
Some(c) => {
|
||||
let l = |h| d.entity(h).and_then(|e| as_line(e)).ok_or_else(|| EngineError::Other(CHAMFER_LINES_ONLY.into()));
|
||||
let (l1, l2) = (l(h1)?, l(h2)?);
|
||||
let (l1, l2) = pair().ok_or_else(|| EngineError::Other(CHAMFER_LINES_ONLY.into()))?;
|
||||
let (x, _, _) = line_line_infinite(l1.a, l1.b, l2.a, l2.b).ok_or_else(|| EngineError::Other("Lines are parallel.".into()))?;
|
||||
// The direction along each line towards its picked side.
|
||||
let dir = |l: &Line, p: Vec2| if (l.a - x).dot(p - x) >= (l.b - x).dot(p - x) { (l.a - x).normalized() } else { (l.b - x).normalized() };
|
||||
Some(c.distances(dir(&l1, p1), dir(&l2, p2))?)
|
||||
}
|
||||
};
|
||||
let lines = pair().is_some();
|
||||
let made = fillet_lines(s, h1, p1, h2, p2, r, chamfer)?;
|
||||
if !trim {
|
||||
let doc = s.doc_mut()?;
|
||||
@@ -505,10 +537,34 @@ fn fillet_corner(s: &mut Session, h1: Handle, p1: Vec2, h2: Handle, p2: Vec2, r:
|
||||
doc.modify_entity(h, |e| e.kind = k)?;
|
||||
}
|
||||
}
|
||||
} else if lines {
|
||||
for (h, k) in [(h1, &k1), (h2, &k2)] {
|
||||
if let Some(k) = k {
|
||||
unbounded_after_fillet(s, h, k)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(made)
|
||||
}
|
||||
|
||||
/// What FILLET or CHAMFER leaves of a ray or xline `was`, trimmed by `fillet_lines` as a line to
|
||||
/// the corner: a ray where the picked side is unbounded, as in AutoCAD (#1235).
|
||||
fn unbounded_after_fillet(s: &mut Session, h: Handle, was: &EntityKind) -> Result<()> {
|
||||
let (EntityKind::Ray(r) | EntityKind::XLine(r)) = was else { return Ok(()) };
|
||||
// The far end `half_line` gave it, if `fillet_lines` kept one; a ray never has the backward one.
|
||||
let far = [half_line(r, Some(true)).b, half_line(r, Some(false)).b];
|
||||
let doc = s.doc_mut()?;
|
||||
let Some(EntityKind::Line(l)) = doc.entity(h).map(|e| e.kind.clone()) else { return Ok(()) };
|
||||
let (kept, t) = match (l.a.xy(), l.b.xy()) {
|
||||
(a, b) if far.contains(&a) => (a, b),
|
||||
(a, b) if far.contains(&b) => (b, a),
|
||||
_ => return Ok(()),
|
||||
};
|
||||
let ray = cadcraft_doc::RayLine { base: v3(t), dir: v3((kept - t).normalized()) };
|
||||
doc.modify_entity(h, |e| e.kind = EntityKind::Ray(ray))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// CHAMFER Polyline: cut every corner between two straight segments of a 2D polyline. Returns
|
||||
/// how many corners were chamfered.
|
||||
fn chamfer_polyline(s: &mut Session, h: Handle, cut: ChamferCut) -> Result<usize> {
|
||||
|
||||
@@ -491,9 +491,10 @@ impl Interactive for OffsetM {
|
||||
(_, Input::Keyword(k)) if k == "Undo" => {
|
||||
match self.undo.pop() {
|
||||
Some((doc, picked)) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an earlier
|
||||
// one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
self.picked = if self.multiple { picked } else { None };
|
||||
if self.picked.is_none() {
|
||||
|
||||
@@ -55,6 +55,13 @@ pub(crate) fn erase_kept(s: &mut Session, hs: &[Handle]) -> Result<usize> {
|
||||
// (`refedit::after_command`), so what OOPS had stays.
|
||||
let refused = taken.iter().any(|t| crate::cmd::blocks::refedit::locked(d, t.entity.handle));
|
||||
if n > 0 && !refused {
|
||||
// The names of the erased references' records went with them: OOPS bringing them back
|
||||
// brings none back. Other references' names keep holding (#1660).
|
||||
if let Some(names) = s.record_names() {
|
||||
for t in &taken {
|
||||
names.erased(&t.entity);
|
||||
}
|
||||
}
|
||||
s.state_mut()?.erased = Erased(taken);
|
||||
}
|
||||
Ok(n)
|
||||
|
||||
@@ -116,7 +116,10 @@ impl SelectThen {
|
||||
Some((f, from)) => (Mat3::scale_about(base, f), from),
|
||||
None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(),
|
||||
},
|
||||
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
|
||||
Op::Mirror => match self.mirror_end(c) {
|
||||
Some(end) => (Mat3::mirror(base, end), base),
|
||||
None => return Vec::new(),
|
||||
},
|
||||
_ => return Vec::new(),
|
||||
};
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
@@ -135,7 +138,9 @@ impl SelectThen {
|
||||
k
|
||||
})
|
||||
.collect();
|
||||
out.push(line(rubber_from, c));
|
||||
if !self.ask_erase {
|
||||
out.push(line(rubber_from, c));
|
||||
}
|
||||
out
|
||||
}
|
||||
/// The drag with the cursor at `c` and the base point at `base`.
|
||||
@@ -148,10 +153,10 @@ impl SelectThen {
|
||||
let (f, from) = self.scale_reference_factor(base, c)?;
|
||||
(Mat3::scale_about(base, f), from)
|
||||
}
|
||||
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
|
||||
Op::Mirror => (Mat3::mirror(base, self.mirror_end(c)?), base),
|
||||
_ => return None,
|
||||
};
|
||||
let mut extra = vec![line(rubber_from, c)];
|
||||
let mut extra = if self.ask_erase { Vec::new() } else { vec![line(rubber_from, c)] };
|
||||
if self.op != Op::Mirror {
|
||||
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
|
||||
}
|
||||
@@ -489,6 +494,12 @@ impl SelectThen {
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
|
||||
/// The second point of MIRROR's line: the cursor while it is picked, then the picked point,
|
||||
/// so the mirrored copy stays on screen at "Erase source objects?" (#2667).
|
||||
fn mirror_end(&self, cursor: Vec2) -> Option<Vec2> {
|
||||
if self.ask_erase { self.pts.get(1).copied() } else { Some(cursor) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Objects MIRROR must preview individually: readable text and hatches retaining fill direction.
|
||||
|
||||
@@ -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;
|
||||
})
|
||||
|
||||
@@ -117,7 +117,10 @@ fn prim_to_segments(p: &Prim) -> Vec<Segment> {
|
||||
match p {
|
||||
Prim::Seg(s) => vec![*s],
|
||||
Prim::Circle(c) => vec![Segment::Arc { arc: Arc { center: c.center, radius: c.radius, start: 0.0, end: TAU - 1e-12 }, ccw: true }],
|
||||
Prim::Infinite { base, dir, .. } => vec![Segment::Line(Line::new(*base - *dir * 1e8, *base + *dir * 1e8))],
|
||||
Prim::Infinite { base, dir, ray } => {
|
||||
let start = if *ray { *base } else { *base - *dir * 1e8 };
|
||||
vec![Segment::Line(Line::new(start, *base + *dir * 1e8))]
|
||||
}
|
||||
Prim::Ellipse(e) => {
|
||||
let mut pts = Vec::new();
|
||||
e.tessellate(e.major.len() * 1e-4, &mut pts);
|
||||
|
||||
@@ -178,9 +178,10 @@ impl MocoroM {
|
||||
fn undo(&mut self, s: &mut Session) -> Result<Step> {
|
||||
match self.history.pop() {
|
||||
Some((doc, base)) => {
|
||||
// Settings changed meanwhile (a transparent command) stay.
|
||||
// Settings changed meanwhile (a transparent command) stay. The drawing put
|
||||
// back is an earlier one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
if s.doc()?.header != header {
|
||||
s.doc_mut()?.header = header;
|
||||
}
|
||||
|
||||
@@ -126,7 +126,8 @@ impl PeditM {
|
||||
"reverse" | "r" => self.apply_all(s, "reverse", &json!({}))?,
|
||||
"undo" | "u" => match self.mundo.pop() {
|
||||
Some((d, multi, morig)) => {
|
||||
*s.doc_mut()? = d;
|
||||
// The saved drawing includes its handle seed.
|
||||
s.state_mut()?.restore_drawing(std::sync::Arc::new(d));
|
||||
self.multi = multi;
|
||||
self.morig = morig;
|
||||
s.set_selection(self.multi.clone());
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{Ellipse, EntityKind, Line, Result, Segment, TAU, Vec2, ccw_sweep, curve_edits, curves, intersect_ext, norm_angle, other, v3};
|
||||
use super::{Ellipse, EntityKind, Line, Result, Segment, TAU, Vec2, ccw_sweep, curve_edits, curves, intersect_ext, line, norm_angle, other, v3};
|
||||
|
||||
// =====================================================================================
|
||||
// TRIM / EXTEND for ellipses and splines
|
||||
// TRIM / EXTEND for ellipses, splines and unbounded lines
|
||||
// =====================================================================================
|
||||
|
||||
pub(super) fn ellipse_of(e: &cadcraft_doc::Ellipse) -> Ellipse {
|
||||
@@ -63,7 +63,7 @@ fn ellipse_samples(ge: &Ellipse) -> Vec<f64> {
|
||||
(0..=n).map(|i| ge.start + sw * i as f64 / n as f64).collect()
|
||||
}
|
||||
|
||||
/// Trim objects that modify.rs does not handle itself (ellipses and splines).
|
||||
/// Trim objects that modify.rs does not handle itself (ellipses, splines, rays and xlines).
|
||||
pub(crate) fn trim_other(k: &EntityKind, cut: &[Segment], pick: Vec2) -> Result<Vec<EntityKind>> {
|
||||
let none = || other("Object does not intersect a cutting edge.");
|
||||
match k {
|
||||
@@ -142,11 +142,49 @@ pub(crate) fn trim_other(k: &EntityKind, cut: &[Segment], pick: Vec2) -> Result<
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
EntityKind::Ray(rl) | EntityKind::XLine(rl) => {
|
||||
// As in AutoCAD, a piece with two ends is a line and an unbounded one a ray (#1235).
|
||||
let xline = matches!(k, EntityKind::XLine(_));
|
||||
let (base, dir) = (rl.base.xy(), rl.dir.xy().normalized());
|
||||
// An xline is cut as two half-lines from its base: a segment starting 1e8 away puts
|
||||
// the cut points ~1e-8 off, enough for a later TRIM to see the edge again.
|
||||
let sides: &[f64] = if xline { &[1e8, -1e8] } else { &[1e8] };
|
||||
let mut ts: Vec<f64> = sides
|
||||
.iter()
|
||||
.map(|far| Segment::Line(Line::new(base, base + dir * *far)))
|
||||
.flat_map(|half| cut.iter().flat_map(move |c| intersect_ext(&half, c, false)))
|
||||
.map(|x| (x - base).dot(dir))
|
||||
.filter(|t| xline || *t > 1e-9)
|
||||
.collect();
|
||||
ts.sort_by(f64::total_cmp);
|
||||
let tp = (pick - base).dot(dir);
|
||||
let found = ts.len();
|
||||
ts.retain(|t| (t - tp).abs() > 5e-7);
|
||||
if found > 0 && ts.is_empty() {
|
||||
return Err(other("The pick is on the cut: nothing to trim."));
|
||||
}
|
||||
let lo = ts.iter().copied().rfind(|t| *t < tp);
|
||||
let hi = ts.iter().copied().find(|t| *t > tp);
|
||||
if lo.is_none() && hi.is_none() {
|
||||
return Err(none());
|
||||
}
|
||||
let ray = |p: Vec2, d: Vec2| EntityKind::Ray(cadcraft_doc::RayLine { base: v3(p), dir: v3(d) });
|
||||
let mut v = Vec::new();
|
||||
match lo {
|
||||
Some(t) if xline => v.push(ray(base + dir * t, -dir)),
|
||||
Some(t) => v.push(line(base, base + dir * t)),
|
||||
None => {}
|
||||
}
|
||||
if let Some(t) = hi {
|
||||
v.push(ray(base + dir * t, dir));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
_ => Err(other("Cannot trim that object.")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Extend objects that modify.rs does not handle itself (elliptical arcs and open splines).
|
||||
/// Extend objects that modify.rs does not handle itself (elliptical arcs, open splines and rays).
|
||||
pub(crate) fn extend_other(k: &EntityKind, cut: &[Segment], pick: Vec2) -> Result<EntityKind> {
|
||||
match k {
|
||||
EntityKind::Ellipse(e) => {
|
||||
@@ -171,6 +209,18 @@ pub(crate) fn extend_other(k: &EntityKind, cut: &[Segment], pick: Vec2) -> Resul
|
||||
Ok(ellipse_kind(&if from_end { Ellipse { end: t, ..ge } } else { Ellipse { start: t, ..ge } }))
|
||||
}
|
||||
EntityKind::Spline(sp) => curve_edits::extend_spline(sp, cut, pick),
|
||||
EntityKind::Ray(rl) => {
|
||||
// A ray's one end is its base: EXTEND moves it back to the nearest edge (#1236).
|
||||
let (base, dir) = (rl.base.xy(), rl.dir.xy().normalized());
|
||||
let back = Segment::Line(Line::new(base, base - dir * 1e8));
|
||||
let np = cut
|
||||
.iter()
|
||||
.flat_map(|c| intersect_ext(&back, c, false))
|
||||
.filter(|x| (*x - base).dot(dir) < -1e-9)
|
||||
.min_by(|x, y| x.dist(base).total_cmp(&y.dist(base)))
|
||||
.ok_or_else(|| other("Object does not intersect an edge."))?;
|
||||
Ok(EntityKind::Ray(cadcraft_doc::RayLine { base: v3(np), dir: rl.dir }))
|
||||
}
|
||||
_ => Err(other("Cannot extend that object.")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
//! The user's plot style folder: plot style tables kept as files on the computer, which every
|
||||
//! drawing can use (STYLESMANAGER `where: "folder"`, `docs/plot-styles.md`).
|
||||
//!
|
||||
//! Each table is one file in our own format ([`cadcraft_doc::PlotStyleTable::to_file_text`]),
|
||||
//! named after the table plus `.json`: `studio.ctb.json` holds `studio.ctb`. Native builds use
|
||||
//! the `plotstyles` folder of the CADCraft settings directory ([`crate::settings_dir::current`]);
|
||||
//! the web keeps the tables for the session. A host can install another store with
|
||||
//! [`set_plot_style_store`] (first call wins).
|
||||
//!
|
||||
//! The tables read are handed to `cadcraft_doc` ([`cadcraft_doc::set_plot_style_folder`]), so
|
||||
//! layouts, plots and the screen find them by name like the drawing's own tables.
|
||||
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use cadcraft_doc::PlotStyleTable;
|
||||
|
||||
/// Ending of a table file.
|
||||
pub const FILE_EXT: &str = ".json";
|
||||
/// Most table files read from the folder.
|
||||
pub const MAX_FILES: usize = 1000;
|
||||
|
||||
/// Where table files live. Names are file names ending in [`FILE_EXT`]; the engine never passes paths.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct PlotStyleStore {
|
||||
/// The folder as the user would look for it, if it is a place on disk.
|
||||
pub location: fn() -> Option<String>,
|
||||
/// File names in the folder.
|
||||
pub list: fn() -> std::result::Result<Vec<String>, String>,
|
||||
pub read: fn(&str) -> std::result::Result<String, String>,
|
||||
pub write: fn(&str, &str) -> std::result::Result<(), String>,
|
||||
pub delete: fn(&str) -> std::result::Result<(), String>,
|
||||
}
|
||||
|
||||
static STORE: OnceLock<PlotStyleStore> = OnceLock::new();
|
||||
static MEMORY: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
|
||||
/// Files skipped by the last read, with the reason.
|
||||
static WARNINGS: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
/// Which file holds each table the last read found: (table name, file name). A file need not be
|
||||
/// named after its table (`studio.json` holds `studio.ctb`), and edits go back to that file.
|
||||
static SOURCES: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
|
||||
static READ_ONCE: OnceLock<()> = OnceLock::new();
|
||||
/// Held through a whole read, so a read that started before a change can't hand `cadcraft_doc`
|
||||
/// its older list after the read that follows the change.
|
||||
static READING: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Install the host's plot style folder (first call wins).
|
||||
pub fn set_plot_style_store(s: PlotStyleStore) {
|
||||
let _ = STORE.set(s);
|
||||
}
|
||||
|
||||
/// Whether `name` can be a table file's name: no path separators, no leading dot, no characters
|
||||
/// a file system refuses, at most 200 characters (the file name adds its ending).
|
||||
pub fn valid_table_name(name: &str) -> bool {
|
||||
let n = name.trim();
|
||||
!n.is_empty()
|
||||
&& n == name
|
||||
&& n.chars().count() <= 200
|
||||
&& !n.starts_with('.')
|
||||
&& !n.ends_with('.')
|
||||
&& !n.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*'))
|
||||
}
|
||||
|
||||
/// The file that holds table `name`.
|
||||
pub fn file_name(name: &str) -> String {
|
||||
format!("{name}{FILE_EXT}")
|
||||
}
|
||||
|
||||
impl PlotStyleStore {
|
||||
/// A folder kept in memory for the life of the process.
|
||||
pub fn memory() -> PlotStyleStore {
|
||||
fn lock() -> std::result::Result<std::sync::MutexGuard<'static, Vec<(String, String)>>, String> {
|
||||
MEMORY.lock().map_err(|_| "the plot style folder is unavailable".to_string())
|
||||
}
|
||||
PlotStyleStore {
|
||||
location: || None,
|
||||
list: || Ok(lock()?.iter().map(|(n, _)| n.clone()).collect()),
|
||||
read: |n| lock()?.iter().find(|(f, _)| f == n).map(|(_, t)| t.clone()).ok_or_else(|| format!("{n}: no such file")),
|
||||
write: |n, t| {
|
||||
let mut m = lock()?;
|
||||
m.retain(|(f, _)| f != n);
|
||||
m.push((n.to_string(), t.to_string()));
|
||||
Ok(())
|
||||
},
|
||||
delete: |n| {
|
||||
let mut m = lock()?;
|
||||
let before = m.len();
|
||||
m.retain(|(f, _)| f != n);
|
||||
if m.len() == before { Err(format!("{n}: no such file")) } else { Ok(()) }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The `plotstyles` folder of the CADCraft settings directory.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn settings_folder() -> PlotStyleStore {
|
||||
fn dir() -> std::result::Result<std::path::PathBuf, String> {
|
||||
crate::settings_dir::current()
|
||||
.map(|r| r.join("plotstyles"))
|
||||
.ok_or_else(|| "there is no settings folder for plot style tables".to_string())
|
||||
}
|
||||
fn file(n: &str) -> std::result::Result<std::path::PathBuf, String> {
|
||||
let ok = n.strip_suffix(FILE_EXT).is_some_and(valid_table_name);
|
||||
if !ok {
|
||||
return Err(format!("`{n}` is not a plot style table file name"));
|
||||
}
|
||||
Ok(dir()?.join(n))
|
||||
}
|
||||
PlotStyleStore {
|
||||
location: || dir().ok().map(|d| d.display().to_string()),
|
||||
list: || {
|
||||
let d = dir()?;
|
||||
crate::file_access::check_read(&d)?;
|
||||
let rd = match std::fs::read_dir(d) {
|
||||
Ok(rd) => rd,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(e) => return Err(e.to_string()),
|
||||
};
|
||||
// All of them: `reload` keeps the first [`MAX_FILES`] in name order and says so.
|
||||
Ok(rd.filter_map(|e| e.ok()?.file_name().into_string().ok()).filter(|n| n.ends_with(FILE_EXT) && !n.starts_with('.')).collect())
|
||||
},
|
||||
read: |n| {
|
||||
let p = file(n)?;
|
||||
crate::file_access::check_read(&p)?;
|
||||
let bytes = crate::capped_read::read_capped(&p, cadcraft_doc::MAX_TABLE_FILE).map_err(|e| format!("{n}: {e}"))?;
|
||||
String::from_utf8(bytes).map_err(|e| format!("{n}: {e}"))
|
||||
},
|
||||
write: |n, t| {
|
||||
let p = file(n)?;
|
||||
crate::file_access::check_write(&p)?;
|
||||
std::fs::create_dir_all(dir()?).map_err(|e| e.to_string())?;
|
||||
crate::atomic_write::write_atomic(&p, t.as_bytes()).map_err(|e| format!("{n}: {e}"))
|
||||
},
|
||||
delete: |n| {
|
||||
let p = file(n)?;
|
||||
crate::file_access::check_write(&p)?;
|
||||
std::fs::remove_file(p).map_err(|e| format!("{n}: {e}"))
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn store() -> PlotStyleStore {
|
||||
*STORE.get_or_init(|| {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
PlotStyleStore::settings_folder()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
PlotStyleStore::memory()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The folder as the user would look for it (`None` on the web or without a settings folder).
|
||||
pub fn location() -> Option<String> {
|
||||
(store().location)()
|
||||
}
|
||||
|
||||
/// Files the last read skipped, and why.
|
||||
pub fn warnings() -> Vec<String> {
|
||||
WARNINGS.lock().map(|w| w.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The table a file holds: named after the file (so renaming the file renames the table), with
|
||||
/// the `.ctb`/`.stb` ending its kind asks for.
|
||||
fn table_from_file(file: &str, text: &str) -> std::result::Result<PlotStyleTable, String> {
|
||||
let mut t = PlotStyleTable::from_file_text(text)?;
|
||||
let stem = file.strip_suffix(FILE_EXT).unwrap_or(file);
|
||||
let ext = if t.is_color_dependent() { ".ctb" } else { ".stb" };
|
||||
let lower = stem.to_ascii_lowercase();
|
||||
t.name = if lower.ends_with(ext) {
|
||||
stem.to_string()
|
||||
} else if lower.ends_with(".ctb") || lower.ends_with(".stb") {
|
||||
return Err(format!("the file name ends in {} but the table is {}", &stem[stem.len() - 4..], kind_words(&t)));
|
||||
} else {
|
||||
format!("{stem}{ext}")
|
||||
};
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
fn kind_words(t: &PlotStyleTable) -> &'static str {
|
||||
if t.is_color_dependent() { "colour-dependent (.ctb)" } else { "named (.stb)" }
|
||||
}
|
||||
|
||||
/// Read the folder again and hand its tables to `cadcraft_doc`. Unreadable files are skipped and
|
||||
/// listed in [`warnings`]; a folder that can't be listed counts as empty.
|
||||
pub fn reload() -> Vec<PlotStyleTable> {
|
||||
let _reading = READING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let st = store();
|
||||
let mut warn = Vec::new();
|
||||
let mut tables: Vec<PlotStyleTable> = Vec::new();
|
||||
let mut sources = Vec::new();
|
||||
match (st.list)() {
|
||||
Ok(mut files) => {
|
||||
files.sort();
|
||||
if files.len() > MAX_FILES {
|
||||
warn.push(format!("only the first {MAX_FILES} files by name are read; {} more were left out", files.len() - MAX_FILES));
|
||||
}
|
||||
for f in files.iter().take(MAX_FILES) {
|
||||
match (st.read)(f).and_then(|text| table_from_file(f, &text)) {
|
||||
Ok(t) if tables.iter().any(|x| x.name.eq_ignore_ascii_case(&t.name)) => {
|
||||
warn.push(format!("{f}: another file already holds `{}`", t.name));
|
||||
}
|
||||
Ok(t) => {
|
||||
sources.push((t.name.clone(), f.clone()));
|
||||
tables.push(t);
|
||||
}
|
||||
Err(e) => warn.push(format!("{f}: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => warn.push(e),
|
||||
}
|
||||
tables.sort_by_key(|t| t.name.to_lowercase());
|
||||
if let Ok(mut w) = WARNINGS.lock() {
|
||||
*w = warn;
|
||||
}
|
||||
if let Ok(mut x) = SOURCES.lock() {
|
||||
*x = sources;
|
||||
}
|
||||
cadcraft_doc::set_plot_style_folder(tables.clone());
|
||||
let _ = READ_ONCE.set(());
|
||||
tables
|
||||
}
|
||||
|
||||
/// Read the folder the first time a session starts; later calls do nothing.
|
||||
pub fn read_once() {
|
||||
if READ_ONCE.get().is_none() {
|
||||
reload();
|
||||
}
|
||||
}
|
||||
|
||||
/// The file that holds table `name`: the one the last read found it in, else one named after it
|
||||
/// in any case.
|
||||
fn held_by(st: &PlotStyleStore, name: &str) -> Option<String> {
|
||||
let known = SOURCES.lock().ok().and_then(|x| x.iter().find(|(t, _)| t.eq_ignore_ascii_case(name)).map(|(_, f)| f.clone()));
|
||||
known.or_else(|| {
|
||||
let file = file_name(name);
|
||||
(st.list)().unwrap_or_default().into_iter().find(|f| f.eq_ignore_ascii_case(&file))
|
||||
})
|
||||
}
|
||||
|
||||
/// Write `t` to the folder and read it again. The file that held a table of the same name (under
|
||||
/// another file name, or another case of it) is replaced, not doubled.
|
||||
pub fn write(t: &PlotStyleTable) -> std::result::Result<(), String> {
|
||||
if !valid_table_name(&t.name) {
|
||||
return Err(format!("`{}` can't be a file name in the plot style folder (no / \\ : < > \" | ? * or leading dot)", t.name));
|
||||
}
|
||||
let st = store();
|
||||
let file = file_name(&t.name);
|
||||
let text = t.to_file_text();
|
||||
let old = held_by(&st, &t.name).filter(|f| *f != file);
|
||||
(st.write)(&file, &text)?;
|
||||
let result = match old {
|
||||
None => Ok(()),
|
||||
Some(old) => {
|
||||
let files = (st.list)().unwrap_or_default();
|
||||
if files.contains(&old) && files.contains(&file) {
|
||||
// Two files: the old one would still win the next read.
|
||||
(st.delete)(&old).map_err(|e| format!("{file} was written, but {old} still holds the old `{}`: {e}", t.name))
|
||||
} else {
|
||||
// One file under two spellings (a disk that ignores case): the write went to the
|
||||
// old file. Remove it and write again, so the file takes the new spelling; if
|
||||
// that fails, put the table back under the old one.
|
||||
(st.delete)(&old).and_then(|()| match (st.write)(&file, &text) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
let _ = (st.write)(&old, &text);
|
||||
Err(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
reload();
|
||||
result
|
||||
}
|
||||
|
||||
/// Remove table `name` from the folder and read it again.
|
||||
pub fn delete(name: &str) -> std::result::Result<(), String> {
|
||||
let st = store();
|
||||
let found = held_by(&st, name.trim()).ok_or_else(|| format!("the plot style folder has no table `{name}`"))?;
|
||||
let result = (st.delete)(&found);
|
||||
reload();
|
||||
result
|
||||
}
|
||||
@@ -170,7 +170,10 @@ fn copy_props(src: &Entity, dst: &mut Entity, m: &MatchProps) {
|
||||
b.overrides.clone_from(&a.overrides);
|
||||
b.block = None;
|
||||
}
|
||||
(EntityKind::Leader(a), EntityKind::Leader(b)) if m.dimension => b.style.clone_from(&a.style),
|
||||
(EntityKind::Leader(a), EntityKind::Leader(b)) if m.dimension => {
|
||||
b.style.clone_from(&a.style);
|
||||
b.overrides.clone_from(&a.overrides);
|
||||
}
|
||||
(EntityKind::Text(a), EntityKind::Text(b)) if m.text => {
|
||||
b.style.clone_from(&a.style);
|
||||
b.height = a.height;
|
||||
|
||||
@@ -204,6 +204,7 @@ fn set_override(dm: &mut cadcraft_doc::Dimension, field: &'static str, v: Value)
|
||||
/// A `properties.set` call, checked before any object changes: the values every object takes,
|
||||
/// and what the edits need to know beforehand.
|
||||
struct Call<'a> {
|
||||
hatch_lines: Option<Vec<cadcraft_doc::library::PatternLine>>,
|
||||
p: &'a Value,
|
||||
color: Option<Color>,
|
||||
transparency: Option<Transparency>,
|
||||
@@ -344,6 +345,20 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
),
|
||||
));
|
||||
}
|
||||
// On a leader that holds for the DSTYLE list of its `ACAD` run (its overrides); the
|
||||
// rest of the run is kept raw and may be set.
|
||||
if let Some((app, _)) =
|
||||
changes.iter().find(|(app, groups)| cadcraft_doc::is_model_xdata(app, groups.as_deref().unwrap_or_default(), &e.kind))
|
||||
{
|
||||
return Err(bad(
|
||||
"properties.set",
|
||||
format!(
|
||||
"{}: the DSTYLE list in xdata application {app} of a {} holds its dimension-style overrides, written from its own properties, and can't be set as raw data",
|
||||
h.hex(),
|
||||
e.kind.dxf_name()
|
||||
),
|
||||
));
|
||||
}
|
||||
let mut after = e.common.xdata.clone();
|
||||
super::xdata::apply(&mut after, changes);
|
||||
if after.len() > cadcraft_doc::MAX_XDATA_GROUPS {
|
||||
@@ -351,8 +366,10 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let hatch_lines = str_param(p, "pattern").and_then(|n| crate::cmd::hatch::drawing_lines(d, n.trim()));
|
||||
// A pattern must be one each hatch can take, as HATCHEDIT refuses others.
|
||||
if let Some(v) = str_param(p, "pattern").filter(|v| !v.trim().is_empty())
|
||||
&& hatch_lines.is_none()
|
||||
&& hs.iter().any(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if !crate::cmd::hatch::takes_pattern(x, v)))
|
||||
{
|
||||
return Err(bad("properties.set", format!("unknown pattern {}", v.trim().to_ascii_uppercase())));
|
||||
@@ -363,7 +380,7 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let prep = Prepared::new(d, p, &hs);
|
||||
let anno_scale = d.current_anno_scale();
|
||||
let c = Call { p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale };
|
||||
let c = Call { hatch_lines, p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale };
|
||||
// A failed call changes nothing (a command's error doesn't undo what it did), so the drawing
|
||||
// is taken for writing, and the layer made, only after every check.
|
||||
let d = s.doc_mut()?;
|
||||
@@ -805,7 +822,7 @@ fn dimension_posts(dm: &mut Dimension, c: &Call<'_>, used: &mut Used<'_>) {
|
||||
fn hatch(ha: &mut Hatch, c: &Call<'_>, used: &mut Used<'_>) {
|
||||
// HATCHEDIT's pattern edit (a blank name changes nothing, so it's ignored).
|
||||
if let Some(v) = str_param(c.p, "pattern")
|
||||
&& crate::cmd::hatch::set_pattern(ha, v)
|
||||
&& crate::cmd::hatch::set_pattern(ha, v, c.hatch_lines.as_deref())
|
||||
{
|
||||
used.insert("pattern");
|
||||
}
|
||||
@@ -818,3 +835,41 @@ fn hatch(ha: &mut Hatch, c: &Call<'_>, used: &mut Used<'_>) {
|
||||
used.insert("angle");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The hatch of a drawing, by handle.
|
||||
fn hatch_of(s: &Session, h: Handle) -> Hatch {
|
||||
match &s.doc().unwrap().entity(h).unwrap().kind {
|
||||
EntityKind::Hatch(ha) => ha.clone(),
|
||||
other => panic!("{h:?} is a {}", other.type_name()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_the_same_pattern_keeps_the_lines_the_hatch_carries() {
|
||||
// The loaded patterns are session-wide: HATCH.PATTERNS can clear them, and a drawing
|
||||
// reopened without its .pat file leaves the hatch's own families as the only copy.
|
||||
// Setting the name the hatch already carries must keep them (#1232).
|
||||
let mut s = Session::new();
|
||||
let kind = EntityKind::Hatch(
|
||||
serde_json::from_value(json!({
|
||||
"pattern": "MYGRID",
|
||||
"solid": false,
|
||||
"loops": [],
|
||||
"patternLines": [{"angle": 0.0, "origin": [0.0, 0.0], "delta": [0.0, 0.5], "dashes": []}],
|
||||
}))
|
||||
.unwrap(),
|
||||
);
|
||||
let h = s.add_entity(kind).unwrap();
|
||||
s.execute("properties.set", &json!({ "handles": [h.hex()], "pattern": "mygrid" })).unwrap();
|
||||
let ha = hatch_of(&s, h);
|
||||
assert_eq!(ha.pattern, "MYGRID");
|
||||
assert_eq!(ha.pattern_lines.len(), 1, "the definition the hatch carries was dropped");
|
||||
// A library pattern is drawn from the library: it has no lines of its own.
|
||||
s.execute("properties.set", &json!({ "handles": [h.hex()], "pattern": "ANSI31" })).unwrap();
|
||||
assert!(hatch_of(&s, h).pattern_lines.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -397,7 +397,7 @@ impl TrimM {
|
||||
let e = d.entity(h)?;
|
||||
// Half a pixel: finer than the eye can tell apart, coarse enough to stay quick.
|
||||
let tol = (s.pixel_size() / 2.0).max(1e-9);
|
||||
let extending = self.extend ^ s.shift_down;
|
||||
let extending = self.extend ^ (s.shift_down && s.person_input());
|
||||
let part = if extending {
|
||||
let grown = Entity { kind: extended(s, h, cursor, cut).ok()?, ..(**e).clone() };
|
||||
uncovered(d, &grown, std::slice::from_ref(&e.kind), tol)
|
||||
@@ -415,7 +415,7 @@ impl TrimM {
|
||||
Edges { only: self.edges.as_deref(), implied: !quick && implied }
|
||||
}
|
||||
fn select_edges(&mut self, s: &mut Session) {
|
||||
let extending = self.extend ^ s.shift_down;
|
||||
let extending = self.extend ^ (s.shift_down && s.person_input());
|
||||
s.echo(if extending { "Select boundary edges ..." } else { "Select cutting edges ..." });
|
||||
s.set_selection(Vec::new());
|
||||
self.stage = Stage::Edges(Vec::new());
|
||||
@@ -485,6 +485,7 @@ impl Interactive for TrimM {
|
||||
if self.extend { "EXTEND" } else { "TRIM" }
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
let preselected = if s.settings.pickfirst { s.selection() } else { Vec::new() };
|
||||
s.set_selection(Vec::new());
|
||||
let quick = quick_mode(s);
|
||||
let proj = match proj_mode(s) {
|
||||
@@ -497,7 +498,9 @@ impl Interactive for TrimM {
|
||||
if edge_mode(s) { "Extend" } else { "None" },
|
||||
if quick { "Quick" } else { "Standard" }
|
||||
));
|
||||
if !quick {
|
||||
if !preselected.is_empty() {
|
||||
self.edges = Some(preselected);
|
||||
} else if !quick {
|
||||
self.select_edges(s);
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
@@ -505,20 +508,15 @@ impl Interactive for TrimM {
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
match &self.stage {
|
||||
Stage::Pick => {
|
||||
let extending = self.extend ^ s.shift_down;
|
||||
let shift = s.shift_down && s.person_input();
|
||||
let extending = self.extend ^ shift;
|
||||
let (msg, first) = if extending {
|
||||
let msg = if s.shift_down {
|
||||
"Select object to extend or release Shift to trim"
|
||||
} else {
|
||||
"Select object to extend or shift-select to trim"
|
||||
};
|
||||
let msg =
|
||||
if shift { "Select object to extend or release Shift to trim" } else { "Select object to extend or shift-select to trim" };
|
||||
(msg, "Boundary edges")
|
||||
} else {
|
||||
let msg = if s.shift_down {
|
||||
"Select object to trim or release Shift to extend"
|
||||
} else {
|
||||
"Select object to trim or shift-select to extend"
|
||||
};
|
||||
let msg =
|
||||
if shift { "Select object to trim or release Shift to extend" } else { "Select object to trim or shift-select to extend" };
|
||||
(msg, "cuTting edges")
|
||||
};
|
||||
let mut kw = vec![first, "Fence", "Crossing", "mOde", "Project"];
|
||||
@@ -541,7 +539,7 @@ impl Interactive for TrimM {
|
||||
Stage::Crossing(None) => Prompt::new("Specify first corner", Accept::POINT),
|
||||
Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT),
|
||||
Stage::Mode => {
|
||||
let extending = self.extend ^ s.shift_down;
|
||||
let extending = self.extend ^ (s.shift_down && s.person_input());
|
||||
let msg = if extending { "Enter an extend mode option" } else { "Enter a trim mode option" };
|
||||
Prompt::new(msg, KW).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
|
||||
}
|
||||
@@ -565,7 +563,7 @@ impl Interactive for TrimM {
|
||||
self.cut.take();
|
||||
let quick = quick_mode(s);
|
||||
let implied = edge_mode(s);
|
||||
let extending = self.extend ^ s.shift_down;
|
||||
let extending = self.extend ^ (s.shift_down && s.person_input());
|
||||
match self.stage.clone() {
|
||||
Stage::Mode | Stage::Project | Stage::Edge => self.option(s, i),
|
||||
Stage::Edges(mut picked) => {
|
||||
@@ -696,9 +694,10 @@ impl Interactive for TrimM {
|
||||
}
|
||||
"Undo" => match self.undo.pop() {
|
||||
Some(doc) => {
|
||||
// Settings changed meanwhile stay.
|
||||
// Settings changed meanwhile stay. The drawing put back is an
|
||||
// earlier one: names of INSERT records end with it.
|
||||
let header = s.doc()?.header.clone();
|
||||
s.state_mut()?.doc = doc;
|
||||
s.state_mut()?.restore_drawing(doc);
|
||||
s.doc_mut()?.header = header;
|
||||
}
|
||||
None => s.echo("Nothing to undo."),
|
||||
@@ -733,7 +732,7 @@ impl Interactive for TrimM {
|
||||
return None;
|
||||
}
|
||||
let px = (s.pixel_size() / 2.0).max(1e-9);
|
||||
let extending = self.extend ^ s.shift_down;
|
||||
let extending = self.extend ^ (s.shift_down && s.person_input());
|
||||
Some(picks_preview(s, &work, extending, self.edges(quick, implied), quick, tol, px))
|
||||
}
|
||||
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
|
||||
@@ -302,7 +302,7 @@ fn run_view_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => 0.0,
|
||||
};
|
||||
if !s.state_mut()?.set_view(View { center: c, height: h, twist }) {
|
||||
s.state_mut()?.doc = before.0;
|
||||
s.state_mut()?.restore_drawing(before.0);
|
||||
return Err(bad("view.set", "the view is too large to show. Nothing was changed"));
|
||||
}
|
||||
if let Some(dview::Target::Viewport(h)) = target {
|
||||
|
||||
@@ -237,7 +237,7 @@ impl DviewM {
|
||||
set_twist(s, t, twist)?;
|
||||
}
|
||||
if !s.state_mut()?.set_view(View { twist, ..v }) {
|
||||
s.state_mut()?.doc = before;
|
||||
s.state_mut()?.restore_drawing(before);
|
||||
return Err(EngineError::Other("The view is too large to show.".into()));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -28,6 +28,13 @@ pub struct DocState {
|
||||
pub title: String,
|
||||
pub saved: Arc<Drawing>,
|
||||
pub revision: u64,
|
||||
/// How many times the names AutoLISP gave this drawing's INSERTs' ATTRIBs and SEQENDs ended all
|
||||
/// at once (#1660): another state of the drawing was shown (Undo, Redo, opening or closing the
|
||||
/// Block Editor, a change taken back, or a command putting an earlier drawing back through
|
||||
/// [`DocState::restore_drawing`]), or attribute sets were rebuilt in place (ATTSYNC,
|
||||
/// -BLOCKREPLACE). A name given before names nothing after one of these, never another
|
||||
/// record.
|
||||
pub(crate) names_epoch: u64,
|
||||
pub space: Space,
|
||||
/// Tiled model viewports (VPORTS).
|
||||
pub tiles: ModelTiles,
|
||||
@@ -71,6 +78,7 @@ impl DocState {
|
||||
path,
|
||||
title: title.into(),
|
||||
revision: 1,
|
||||
names_epoch: 0,
|
||||
space: Space::Model,
|
||||
tiles: ModelTiles::default(),
|
||||
mspace: None,
|
||||
@@ -97,8 +105,26 @@ impl DocState {
|
||||
self.follow_layout(&cur.doc);
|
||||
self.reconcile_untiled_twist();
|
||||
self.revision += 1;
|
||||
self.expire_names();
|
||||
cur
|
||||
}
|
||||
/// Names given to records without handles (an INSERT's ATTRIBs and SEQEND) stop holding: the
|
||||
/// records of the drawing they were given for may be gone or replaced. They are never given
|
||||
/// to another record, so a routine's stale name names nothing (`nil`) rather than something
|
||||
/// else.
|
||||
pub(crate) fn expire_names(&mut self) {
|
||||
self.names_epoch = self.names_epoch.wrapping_add(1);
|
||||
}
|
||||
/// Show `doc` again. It is a drawing this document already showed, so its handle seed can
|
||||
/// give the next object a handle a removed one had. Names of INSERT records end, as they do
|
||||
/// for Undo. The same drawing already on show is left as it is: nothing was given out again.
|
||||
pub(crate) fn restore_drawing(&mut self, doc: Arc<Drawing>) {
|
||||
if Arc::ptr_eq(&self.doc, &doc) {
|
||||
return;
|
||||
}
|
||||
self.doc = doc;
|
||||
self.expire_names();
|
||||
}
|
||||
/// After undo/redo replaced the drawing (`before` is the one shown until then): if the current
|
||||
/// layout no longer exists, follow it to its other name when it was renamed (same tab order,
|
||||
/// a name `before` did not have), else go to the Model tab.
|
||||
@@ -145,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.
|
||||
|
||||
@@ -93,6 +93,8 @@ pub const NO_FILES: &[&str] = &[
|
||||
"close",
|
||||
"closeall",
|
||||
"document.switch",
|
||||
"document.next",
|
||||
"document.prev",
|
||||
"document.bytes",
|
||||
"u",
|
||||
"undo",
|
||||
@@ -241,6 +243,7 @@ pub const NO_FILES: &[&str] = &[
|
||||
"gradient",
|
||||
"boundary",
|
||||
"region",
|
||||
"hatch.capture",
|
||||
"hatchedit",
|
||||
"hatchgenerateboundary",
|
||||
"hatchpick",
|
||||
|
||||
@@ -26,7 +26,7 @@ impl Session {
|
||||
};
|
||||
let Some(st) = st.filter(|st| !Arc::ptr_eq(before, &st.doc)) else { return Ok(()) };
|
||||
let Some(h) = first_non_finite(before, &st.doc) else { return Ok(()) };
|
||||
st.doc = before.clone();
|
||||
st.restore_drawing(before.clone());
|
||||
st.selection = selection.to_vec();
|
||||
Err(EngineError::BadParams {
|
||||
cmd: cmd.into(),
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -46,7 +46,7 @@ pub mod units;
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Space};
|
||||
use cadcraft_geom::{Bounds2, Vec2};
|
||||
use cadcraft_geom::{Bounds2, Vec2, Vec3};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -57,7 +57,7 @@ pub use cadcraft_geom as geom;
|
||||
pub use cadcraft_render as render;
|
||||
pub use cmd::blocks::WblockPicks;
|
||||
pub use cmd::blocks::attedit::{AttributeRow, attributes};
|
||||
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
|
||||
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices, pattern_choices_in, register_drawing_patterns};
|
||||
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
|
||||
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
|
||||
|
||||
@@ -138,6 +138,12 @@ pub struct Session {
|
||||
pub(crate) last_paste_table: Option<(String, Option<f64>)>,
|
||||
/// LASTPOINT.
|
||||
pub last_point: Vec2,
|
||||
/// LASTPOINT's Z, as `(last_point, z)`: it holds only while `last_point` is still that point
|
||||
/// (whatever sets `last_point` without a Z puts it back on z = 0). See [`Session::last_point3`].
|
||||
last_point_z: (Vec2, f64),
|
||||
/// The Z of the point being entered: the third number of a typed point
|
||||
/// ([`prompt::parse_point3_with`]), 0 for a picked one. See [`Session::point_z`].
|
||||
point_z: f64,
|
||||
/// AREA and PERIMETER: the last area AREA or MEASUREGEOM measured (in their Add and Subtract
|
||||
/// modes the running total) and that area's perimeter. Not saved, as in AutoCAD.
|
||||
pub area: f64,
|
||||
@@ -164,7 +170,8 @@ pub struct Session {
|
||||
/// this instead of receiving modifiers through `Input`, which stays free of UI state.
|
||||
pub ctrl_down: bool,
|
||||
/// Whether Shift is held right now (from the UI, overwritten every frame). TRIM/EXTEND read
|
||||
/// this to temporarily toggle the active mode, as in AutoCAD.
|
||||
/// this to temporarily toggle the active mode, as in AutoCAD; commands should gate it through
|
||||
/// [`Session::person_input`], which is false for program-fed input.
|
||||
pub shift_down: bool,
|
||||
/// Origin of the point currently being fed by `input_snapped`; never reused by typed points.
|
||||
picked_viewport: Option<snap::ViewportPoint>,
|
||||
@@ -223,6 +230,8 @@ impl Session {
|
||||
}
|
||||
/// A session with no open drawing (the Start tab).
|
||||
pub fn empty() -> Self {
|
||||
// The user's plot style folder, read once per process (STYLESMANAGER reads it again).
|
||||
cmd::plotstyle_folder::read_once();
|
||||
Session {
|
||||
docs: Vec::new(),
|
||||
active: 0,
|
||||
@@ -241,6 +250,8 @@ impl Session {
|
||||
last_command: None,
|
||||
last_paste_table: None,
|
||||
last_point: Vec2::ZERO,
|
||||
last_point_z: (Vec2::ZERO, 0.0),
|
||||
point_z: 0.0,
|
||||
area: 0.0,
|
||||
perimeter: 0.0,
|
||||
distance: 0.0,
|
||||
@@ -284,9 +295,12 @@ impl Session {
|
||||
pub fn doc(&self) -> Result<&Drawing> {
|
||||
Ok(&self.state()?.doc)
|
||||
}
|
||||
/// Copy-on-write access to the drawing.
|
||||
/// Copy-on-write access to the drawing. The revision changes too: a drawing nothing else holds
|
||||
/// is edited in place, so a cache keyed by the drawing's pointer alone would miss the edit.
|
||||
pub fn doc_mut(&mut self) -> Result<&mut Drawing> {
|
||||
Ok(Arc::make_mut(&mut self.state_mut()?.doc))
|
||||
let st = self.state_mut()?;
|
||||
st.revision += 1;
|
||||
Ok(Arc::make_mut(&mut st.doc))
|
||||
}
|
||||
/// Settings for the active drawing, without caching drawing variables in the profile.
|
||||
pub fn drafting_settings(&self) -> Settings {
|
||||
@@ -402,6 +416,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();
|
||||
|
||||
+106
-9
@@ -126,6 +126,11 @@ impl Env {
|
||||
#[derive(Default)]
|
||||
pub struct LispState {
|
||||
envs: HashMap<u64, Env>,
|
||||
/// The names given to records without a handle of their own (an INSERT's ATTRIBs and SEQEND,
|
||||
/// #1660), by drawing. They are the session's, not a snapshot's, so the drawing's undo states
|
||||
/// and the Block Editor's drawing share them; each use checks what a name stands for against
|
||||
/// the drawing.
|
||||
pub(crate) records: HashMap<u64, drawing::RecordNames>,
|
||||
run: Option<Box<Run>>,
|
||||
/// A routine runs, from its start to its end (also while its machine is out of `run`).
|
||||
active: bool,
|
||||
@@ -151,6 +156,8 @@ pub struct LispState {
|
||||
/// pass: the lowest of its own and its callers' allowances, and of what is left to an
|
||||
/// expression typed at a prompt.
|
||||
pub(crate) callback_ceiling: Option<u64>,
|
||||
/// The host draws frames and calls [`Session::lisp_tick`] in each ([`Session::lisp_by_frames`]).
|
||||
frames: bool,
|
||||
}
|
||||
|
||||
/// What U and REDO inside the running routine take back: the commands it ran, each as the drawing
|
||||
@@ -164,6 +171,10 @@ struct RoutineSteps {
|
||||
/// Where the routine's undo step starts, when U or REDO inside it went on to the drawing's
|
||||
/// own steps; else where the routine started.
|
||||
base: Option<(Arc<Drawing>, Vec<Handle>)>,
|
||||
/// The commands the routine was started in that still run: the one an expression was typed
|
||||
/// at the prompt of, and the one that command interrupted when it is transparent. What they
|
||||
/// did is their own undo step, not the routine's ([`Session::lisp_host_ends`]).
|
||||
hosts: u8,
|
||||
}
|
||||
|
||||
/// What a run may use (see [`value`]'s memory notes).
|
||||
@@ -211,6 +222,9 @@ struct Run {
|
||||
/// An expression typed at a command's prompt ([`Session::lisp_eval_answer`]): blocking, with
|
||||
/// [`ANSWER_CAP`] steps instead of [`BLOCKING_CAP`].
|
||||
answer: bool,
|
||||
/// An answer the frames carry on ([`Session::lisp_by_frames`]): its value goes to the prompt
|
||||
/// when it ends, since the call that started it has returned.
|
||||
deferred: bool,
|
||||
/// Steps taken, for the caps on blocking runs and on routines run on without frames.
|
||||
steps: u64,
|
||||
/// The `*error*` handler is the one running.
|
||||
@@ -226,9 +240,11 @@ struct Run {
|
||||
const SLICE: u64 = 400_000;
|
||||
/// Steps a blocking run (a programmatic call) may take before it is stopped.
|
||||
const BLOCKING_CAP: u64 = 500_000_000;
|
||||
/// Steps an expression typed at a command's prompt may take, the callbacks it runs included. It
|
||||
/// runs blocking, since its value is the prompt's answer, so the interface draws no frame and
|
||||
/// Esc doesn't reach it until it ends; a routine at `Command:` runs a slice per frame instead.
|
||||
/// Steps an expression typed at a command's prompt may take, the callbacks it runs included. Its
|
||||
/// value is the prompt's answer, so every input but Esc waits for it. Without frames it runs
|
||||
/// blocking; with them ([`Session::lisp_by_frames`]) it runs a slice per frame, as a routine at
|
||||
/// `Command:` does, so Esc stops it. A callback runs inside one step either way, so Esc doesn't
|
||||
/// reach it before it ends.
|
||||
const ANSWER_CAP: u64 = 20_000_000;
|
||||
|
||||
impl Session {
|
||||
@@ -251,6 +267,13 @@ impl Session {
|
||||
pub(crate) fn lisp_forget_closed(&mut self) {
|
||||
let docs = &self.docs;
|
||||
self.lisp.envs.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid));
|
||||
self.lisp.records.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid));
|
||||
}
|
||||
|
||||
/// The active drawing's names of an INSERT's records (#1660), made on first use.
|
||||
pub(crate) fn record_names(&mut self) -> Option<&mut drawing::RecordNames> {
|
||||
let uid = self.state().ok()?.uid;
|
||||
Some(self.lisp.records.entry(uid).or_default())
|
||||
}
|
||||
|
||||
/// A routine is running (possibly waiting for input).
|
||||
@@ -291,7 +314,9 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Evaluate an expression typed at a command's prompt, whose value is the answer: it runs to
|
||||
/// the end as a programmatic call does, within [`ANSWER_CAP`] steps.
|
||||
/// the end as a programmatic call does, within [`ANSWER_CAP`] steps. Where the host draws
|
||||
/// frames ([`Session::lisp_by_frames`]) and the first slice doesn't end it, this returns
|
||||
/// `None` and the frames carry it on; its value then answers the prompt by itself.
|
||||
pub(crate) fn lisp_eval_answer(&mut self, src: &str) -> crate::Result<Option<std::result::Result<Value, String>>> {
|
||||
let forms = read::read_all(src).map_err(|e| crate::EngineError::Other(format!("; error: {}", e.msg)))?;
|
||||
self.lisp_start(Machine::forms(forms), false, true, Vec::new(), "LISP".into(), true)
|
||||
@@ -318,7 +343,11 @@ impl Session {
|
||||
let st = self.state()?;
|
||||
let before = Some((st.doc.clone(), st.selection.clone()));
|
||||
let uid = st.uid;
|
||||
self.lisp.steps = RoutineSteps { uid, ..RoutineSteps::default() };
|
||||
let hosts = u8::from(self.running.is_some()) + u8::from(self.suspended.is_some());
|
||||
self.lisp.steps = RoutineSteps { uid, hosts, ..RoutineSteps::default() };
|
||||
// What an earlier routine left when it ended in a later frame or at a later input, where
|
||||
// no call was waiting for it, is not this one's.
|
||||
self.lisp_last = None;
|
||||
self.lisp.run = Some(Box::new(Run {
|
||||
machine,
|
||||
uid,
|
||||
@@ -329,6 +358,7 @@ impl Session {
|
||||
inputs: inputs.into(),
|
||||
blocking,
|
||||
answer,
|
||||
deferred: false,
|
||||
steps: 0,
|
||||
handler: false,
|
||||
string_bytes: 0,
|
||||
@@ -337,7 +367,8 @@ impl Session {
|
||||
self.lisp_drive();
|
||||
if blocking {
|
||||
// A blocking run that waits for a command's input (`pause`) can't get it: cancel.
|
||||
if self.lisp.run.is_some() {
|
||||
// An answer the frames carry on is not waiting for input.
|
||||
if self.lisp.run.as_ref().is_some_and(|r| !r.deferred) {
|
||||
self.lisp_abort("Function cancelled");
|
||||
}
|
||||
}
|
||||
@@ -365,6 +396,24 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Say whether the host draws frames and calls [`Session::lisp_tick`] in each. Where it does,
|
||||
/// an expression typed at a command's prompt runs a slice per frame, so Esc
|
||||
/// ([`Session::cancel`]) stops it; elsewhere it runs to its end before the call returns.
|
||||
pub fn lisp_by_frames(&mut self, on: bool) {
|
||||
self.lisp.frames = on;
|
||||
}
|
||||
|
||||
/// An input other than Esc comes after the answer the frames are working out, as it did when
|
||||
/// the answer ran blocking: run the expression to its end first, within its allowance. The
|
||||
/// input entry points call this themselves; a host calls it before it reads the command's
|
||||
/// state ([`Session::prompting`]) to choose where an input goes, so the choice is the one it
|
||||
/// would make with the answer in.
|
||||
pub fn lisp_settle_answer(&mut self) {
|
||||
if self.lisp.run.as_ref().is_some_and(|r| r.deferred && matches!(r.waiting, Some(Need::Yield))) {
|
||||
self.lisp_run_until_input();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the routine needs ticks ([`Session::lisp_tick`]) to go on.
|
||||
pub fn lisp_busy(&self) -> bool {
|
||||
self.lisp.run.as_ref().is_some_and(|r| matches!(r.waiting, Some(Need::Yield)))
|
||||
@@ -432,7 +481,7 @@ impl Session {
|
||||
if let Some((doc, sel)) = self.lisp.steps.base.as_ref().or(run.before.as_ref())
|
||||
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == run.uid)
|
||||
{
|
||||
st.doc = doc.clone();
|
||||
st.restore_drawing(doc.clone());
|
||||
st.selection = sel.clone();
|
||||
}
|
||||
run.handler = true;
|
||||
@@ -474,10 +523,14 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
Outcome::Wait(Need::Yield) => {
|
||||
if run.blocking {
|
||||
// An answer gives the interface a frame where there is one, so Esc reaches
|
||||
// it. A script's line is answered before its next one, so it runs on.
|
||||
let by_frames = run.answer && self.lisp.frames && !self.in_script;
|
||||
if run.blocking && !by_frames {
|
||||
self.lisp.run = Some(run);
|
||||
continue;
|
||||
}
|
||||
run.deferred |= by_frames;
|
||||
run.waiting = Some(Need::Yield);
|
||||
self.lisp.run = Some(run);
|
||||
return;
|
||||
@@ -498,7 +551,8 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
Outcome::Wait(Need::Get(req)) => {
|
||||
if let Some(v) = run.inputs.pop_front() {
|
||||
let (req, given) = self.lisp_supplied(&mut run.inputs, req);
|
||||
if let Some(v) = given {
|
||||
run.machine.resume(v);
|
||||
self.lisp.run = Some(run);
|
||||
continue;
|
||||
@@ -516,6 +570,25 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The value a `get…` call takes from the inputs given up front, `None` when they ran out, and
|
||||
/// the request as it then stands. `getangle` and `getorient` read each input as the prompt
|
||||
/// would ([`input::GetRequest::supplied`]): one the prompt refuses is echoed with the reason
|
||||
/// and the next one is taken, and the first of two points makes the request ask for the
|
||||
/// second. The other calls take the input as their value.
|
||||
fn lisp_supplied(&mut self, inputs: &mut std::collections::VecDeque<Value>, mut req: input::GetRequest) -> (input::GetRequest, Option<Value>) {
|
||||
if !req.reads_supplied() {
|
||||
return (req, inputs.pop_front());
|
||||
}
|
||||
while let Some(v) = inputs.pop_front() {
|
||||
match req.supplied(self, &v) {
|
||||
input::Answer::Value(v) => return (req, Some(v)),
|
||||
input::Answer::Again(msg) => self.echo(msg),
|
||||
input::Answer::Second(p) => req = input::with_first(&req, p),
|
||||
}
|
||||
}
|
||||
(req, None)
|
||||
}
|
||||
|
||||
/// Move printed text to the command history: complete lines, and with `all` the rest too.
|
||||
fn lisp_flush(&mut self, env: &mut Env, all: bool) {
|
||||
// One pass over the buffer, dropping the printed lines once at the end: draining each line
|
||||
@@ -544,6 +617,7 @@ impl Session {
|
||||
/// The routine finished: print its value (command-line expressions), record its undo step.
|
||||
fn lisp_end(&mut self, result: std::result::Result<Value, String>) {
|
||||
let Some(run) = self.lisp.run.take() else { return };
|
||||
let (deferred, handler) = (run.deferred, run.handler);
|
||||
self.lisp.active = false;
|
||||
let steps = std::mem::take(&mut self.lisp.steps);
|
||||
let mut env = self.lisp.envs.remove(&run.uid).unwrap_or_default();
|
||||
@@ -563,6 +637,16 @@ impl Session {
|
||||
st.revision += 1;
|
||||
}
|
||||
self.lisp_last = Some(result);
|
||||
// The call that started an answer the frames carried on has returned: nothing reads how
|
||||
// it ended, and its value answers the prompt here. A failed answer's `*error*` handler
|
||||
// returns no answer.
|
||||
if deferred
|
||||
&& let Some(Ok(v)) = self.lisp_last.take()
|
||||
&& !handler
|
||||
&& let Err(e) = self.lisp_answer(v)
|
||||
{
|
||||
self.echo(e.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// A LISP error: run `*error*` when the routine defined one, else print it.
|
||||
@@ -707,6 +791,19 @@ impl Session {
|
||||
self.lisp.active
|
||||
}
|
||||
|
||||
/// A command ends, `nested` when it ran inside another. Whether the running routine was
|
||||
/// started in it (an expression typed at its prompt, or at the prompt of a transparent command
|
||||
/// inside it) rather than having started it: such a command began before the routine, so its
|
||||
/// undo step is its own.
|
||||
pub(crate) fn lisp_host_ends(&mut self, nested: bool) -> bool {
|
||||
let depth = 1 + u8::from(nested);
|
||||
if !self.lisp.active || depth > self.lisp.steps.hosts {
|
||||
return false;
|
||||
}
|
||||
self.lisp.steps.hosts = depth - 1;
|
||||
true
|
||||
}
|
||||
|
||||
/// A command the running routine ran changed the drawing (`snap` holds it as it was): U inside
|
||||
/// the routine takes it back, as AutoCAD's does, while the routine stays one undo step. UNDO
|
||||
/// Control One keeps only the last, None none.
|
||||
|
||||
@@ -253,6 +253,7 @@ static BUILTINS: &[Builtin] = &[
|
||||
ctx!("ENTUPD", drawing::entupd),
|
||||
ctx!("HANDENT", drawing::handent),
|
||||
ctx!("REGAPP", drawing::regapp),
|
||||
ctx!("TEXTBOX", drawing::textbox),
|
||||
ctx!("SSGET", drawing::ssget),
|
||||
ctx!("SSADD", drawing::ssadd),
|
||||
ctx!("SSDEL", drawing::ssdel),
|
||||
|
||||
@@ -21,7 +21,7 @@ use craft_dxf::Tag;
|
||||
|
||||
use super::builtins::args_err;
|
||||
use super::eval::{Ctx, Flow, Need};
|
||||
use super::value::{PickSet, Value, to_text};
|
||||
use super::value::{PickSet, RecordName, Value, equal, to_text};
|
||||
use super::{BlockSlots, LispError};
|
||||
use crate::{Input, Session};
|
||||
|
||||
@@ -119,6 +119,8 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
}
|
||||
}
|
||||
Value::Ename(h) => named(ctx.s, *h, None),
|
||||
// An INSERT's record (#1660) is no object of the drawing: it picks nothing.
|
||||
Value::Record(_) => feed(ctx.s, Input::Pick(Vec::new())),
|
||||
Value::PickSet(p) => feed(ctx.s, Input::Pick(items(p))),
|
||||
Value::Cons(_) => {
|
||||
if let Some(p) = arg.as_point() {
|
||||
@@ -326,8 +328,8 @@ pub(super) fn groups_to_list(tags: &[Tag]) -> Vec<Value> {
|
||||
const MAX_GROUP_TEXT: usize = 32 << 20;
|
||||
|
||||
/// An association list back to DXF groups (points split into x, y, z groups). The type
|
||||
/// (`0`), the entity name (`-1`), the handle (`5`), the owner (`330`) and the layout (`410`) are
|
||||
/// left out: they aren't the entity's to set.
|
||||
/// (`0`), the entity name (`-1`), the owner of a record (`-2`) and of the entity (`330`), the
|
||||
/// handle (`5`) and the layout (`410`) are left out: they aren't the entity's to set.
|
||||
fn list_to_groups(list: &Value) -> Result<(String, Vec<Tag>), LispError> {
|
||||
let mut kind = None;
|
||||
let mut tags = Vec::new();
|
||||
@@ -343,7 +345,7 @@ fn list_to_groups(list: &Value) -> Result<(String, Vec<Tag>), LispError> {
|
||||
other => return Err(LispError::bad_arg("stringp", other)),
|
||||
})
|
||||
}
|
||||
-1 | -3 | 5 | 330 | 360 | 410 | 102 => {}
|
||||
-1 | -2 | -3 | 5 | 330 | 360 | 410 | 102 => {}
|
||||
_ if point_group(code) && matches!(v, Value::Cons(_)) => {
|
||||
let p = v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &v))?;
|
||||
tags.push(Tag::f(code, p[0]));
|
||||
@@ -374,8 +376,310 @@ fn space_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option<Space> {
|
||||
d.space_of(h)
|
||||
}
|
||||
|
||||
// ---------------- an INSERT's ATTRIBs and SEQEND ----------------
|
||||
|
||||
/// The most names one drawing's LISP holds for an INSERT's records at once: a routine can't fill
|
||||
/// memory by walking. At the limit `entnext` gives no *new* name (`nil`) until names end (an
|
||||
/// erased reference, Undo, ATTSYNC) and make room; the names already given still hold.
|
||||
const MAX_RECORD_NAMES: usize = 65_536;
|
||||
|
||||
/// What a name given to an INSERT's ATTRIB or SEQEND stands for, while it holds.
|
||||
struct Record {
|
||||
owner: Handle,
|
||||
/// The record's place after the INSERT's own: an ATTRIB's index, or `attribs.len()` for the
|
||||
/// SEQEND.
|
||||
slot: usize,
|
||||
/// The ATTRIB's tag, which can be empty. A SEQEND has no tag.
|
||||
tag: Option<String>,
|
||||
}
|
||||
|
||||
impl Record {
|
||||
/// Whether the reference still has the same kind of record in this slot, with the same tag.
|
||||
fn holds(&self, attribs: &[cadcraft_doc::Attrib]) -> bool {
|
||||
match (attribs.get(self.slot), self.tag.as_deref()) {
|
||||
(Some(a), Some(tag)) => a.tag.eq_ignore_ascii_case(tag),
|
||||
(None, None) => self.slot == attribs.len(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The names a drawing's LISP gave to INSERTs' ATTRIBs and SEQENDs (#1660). These records have no
|
||||
/// handle of their own in the drawing, and their names are not handles ([`RecordName`]): nothing
|
||||
/// a drawing, a copy of it or another session gives out can ever be one. A name holds while its
|
||||
/// reference keeps the record in that place with that tag, in the drawing's name epoch it was
|
||||
/// given in (`DocState::expire_names`); otherwise it names nothing (`nil`), never another record.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RecordNames {
|
||||
/// Names by INSERT and then by slot. Removing an INSERT ends all its names, even after a
|
||||
/// change to the length of its attribute run.
|
||||
by_owner: HashMap<Handle, HashMap<usize, RecordName>>,
|
||||
/// What each name that still holds stands for, by its number.
|
||||
by_name: HashMap<u64, Record>,
|
||||
/// The drawing's name epoch the names were given in.
|
||||
epoch: u64,
|
||||
}
|
||||
|
||||
impl RecordNames {
|
||||
/// Forget every name once the drawing's name epoch moved on: the records they named may be
|
||||
/// gone or rebuilt.
|
||||
fn expire(&mut self, epoch: u64) {
|
||||
if self.epoch != epoch {
|
||||
self.by_owner.clear();
|
||||
self.by_name.clear();
|
||||
self.epoch = epoch;
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop the name numbered `id`: it names nothing from now on.
|
||||
fn retire(&mut self, id: u64) {
|
||||
if let Some(r) = self.by_name.remove(&id)
|
||||
&& let Some(slots) = self.by_owner.get_mut(&r.owner)
|
||||
&& slots.get(&r.slot).is_some_and(|n| n.id == id)
|
||||
{
|
||||
slots.remove(&r.slot);
|
||||
if slots.is_empty() {
|
||||
self.by_owner.remove(&r.owner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// End the names of the removed reference. Restoring it does not revive any of its names.
|
||||
pub(crate) fn erased(&mut self, e: &Entity) {
|
||||
if let Some(slots) = self.by_owner.remove(&e.handle) {
|
||||
for n in slots.into_values() {
|
||||
self.by_name.remove(&n.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many names hold now (tests).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn count(&self) -> usize {
|
||||
self.by_name.len()
|
||||
}
|
||||
|
||||
/// The INSERT and place `name` stands for in `d` now. A name that no longer holds is dropped:
|
||||
/// it names nothing from then on, also if its record comes back.
|
||||
fn lookup(&mut self, epoch: u64, d: &cadcraft_doc::Drawing, name: RecordName) -> Option<(Handle, usize)> {
|
||||
self.expire(epoch);
|
||||
let r = self.by_name.get(&name.id)?;
|
||||
let at = insert_attribs(d, r.owner).filter(|attribs| r.holds(attribs)).map(|_| (r.owner, r.slot));
|
||||
if at.is_none() {
|
||||
self.retire(name.id);
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// The name of record `slot` after INSERT `owner`'s own (its attributes, then its SEQEND),
|
||||
/// given now if it has none that holds: the same one while the record holds, so a repeated
|
||||
/// walk is stable. None past the SEQEND, at the limit of names, or when the numbers run out.
|
||||
fn name(&mut self, epoch: u64, attribs: &[cadcraft_doc::Attrib], owner: Handle, slot: usize) -> Option<RecordName> {
|
||||
self.expire(epoch);
|
||||
if let Some(n) = self.by_owner.get(&owner).and_then(|slots| slots.get(&slot)).copied() {
|
||||
if self.by_name.get(&n.id).is_some_and(|r| r.holds(attribs)) {
|
||||
return Some(n);
|
||||
}
|
||||
self.retire(n.id);
|
||||
}
|
||||
let tag = match attribs.get(slot) {
|
||||
Some(a) => Some(a.tag.clone()),
|
||||
None if slot == attribs.len() => None,
|
||||
None => return None,
|
||||
};
|
||||
if self.by_name.len() >= MAX_RECORD_NAMES {
|
||||
return None;
|
||||
}
|
||||
let name = RecordName::fresh(owner)?;
|
||||
self.by_owner.entry(owner).or_default().insert(slot, name);
|
||||
self.by_name.insert(name.id, Record { owner, slot, tag });
|
||||
Some(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The attributes of the block reference `h` in `d` (none for anything else, and for a reference
|
||||
/// with no attributes: an empty run of records is not written).
|
||||
fn insert_attribs(d: &cadcraft_doc::Drawing, h: Handle) -> Option<&[cadcraft_doc::Attrib]> {
|
||||
match d.entity(h).map(|e| &e.kind) {
|
||||
Some(cadcraft_doc::EntityKind::Insert(i)) if !i.attribs.is_empty() => Some(&i.attribs),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawing and its name epoch, without holding a borrow of the session.
|
||||
fn doc_and_epoch(ctx: &Ctx<'_>) -> Option<(Arc<cadcraft_doc::Drawing>, u64)> {
|
||||
let st = ctx.s.state().ok()?;
|
||||
Some((st.doc.clone(), st.names_epoch))
|
||||
}
|
||||
|
||||
/// The INSERT and record the name `name` stands for now (none when it no longer holds).
|
||||
fn record_of(ctx: &mut Ctx<'_>, name: RecordName) -> Option<(Handle, usize)> {
|
||||
let (d, epoch) = doc_and_epoch(ctx)?;
|
||||
ctx.s.record_names()?.lookup(epoch, &d, name)
|
||||
}
|
||||
|
||||
/// The name of record `slot` after INSERT `owner`'s own (#1660): an ATTRIB, or its SEQEND (one
|
||||
/// past the last attribute). None when it has no such record, when the host has no record
|
||||
/// mapping, or when no name is left to give.
|
||||
fn name_record(ctx: &mut Ctx<'_>, owner: Handle, slot: usize) -> Option<RecordName> {
|
||||
crate::cmd::file::entity_sub_record()?;
|
||||
let (d, epoch) = doc_and_epoch(ctx)?;
|
||||
let attribs = insert_attribs(&d, owner)?;
|
||||
ctx.s.record_names()?.name(epoch, attribs, owner, slot)
|
||||
}
|
||||
|
||||
/// An entity list: `head` (its name, type and, for an INSERT's record, its owner), then the
|
||||
/// groups of its record with the layout name after the AcDbEntity marker, as AutoCAD lists it.
|
||||
/// The layout is the one object `at` is in; without a layout of its own (an entity of a block
|
||||
/// definition) it has none.
|
||||
fn entity_list(d: &cadcraft_doc::Drawing, mut items: Vec<Value>, at: Handle, tags: &[Tag], in_block: bool) -> Value {
|
||||
let layout = match space_of(d, at) {
|
||||
Some(Space::Paper(name)) => name,
|
||||
_ => "Model".into(),
|
||||
};
|
||||
let mut placed_layout = in_block;
|
||||
for v in groups_to_list(tags) {
|
||||
// The layout name follows the AcDbEntity marker, as AutoCAD lists it.
|
||||
let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity");
|
||||
items.push(v);
|
||||
if after_marker {
|
||||
items.push(Value::cons(Value::Int(410), Value::str(&layout)));
|
||||
placed_layout = true;
|
||||
}
|
||||
}
|
||||
Value::list(items)
|
||||
}
|
||||
|
||||
/// The list of record `slot` of the reference `owner` named `name`: the DXF writer's record,
|
||||
/// its name (`-1`), type (`0`) and reference (`-2`). None when the host has no record mapping.
|
||||
fn record_list(d: &cadcraft_doc::Drawing, name: RecordName, owner: Handle, slot: usize) -> Option<(Value, Vec<Tag>)> {
|
||||
let e = d.entity(owner)?;
|
||||
let (kind, mut tags) = (crate::cmd::file::entity_sub_record()?)(d, e, slot)?;
|
||||
convert_angles(&kind, &mut tags, f64::to_radians);
|
||||
let head = vec![
|
||||
Value::cons(Value::Int(-1), Value::Record(name)),
|
||||
Value::cons(Value::Int(0), Value::str(&kind)),
|
||||
Value::cons(Value::Int(-2), Value::Ename(owner)),
|
||||
];
|
||||
Some((entity_list(d, head, owner, &tags, false), tags))
|
||||
}
|
||||
|
||||
/// `entget` of an INSERT's ATTRIB or SEQEND (#1660), while `name` names one.
|
||||
fn record_entget(ctx: &mut Ctx<'_>, name: RecordName) -> Option<Value> {
|
||||
let (owner, slot) = record_of(ctx, name)?;
|
||||
let d = ctx.s.doc().ok()?;
|
||||
record_list(d, name, owner, slot).map(|(list, _)| list)
|
||||
}
|
||||
|
||||
/// What an ATTRIB's submitted list asks to change: `Some(None)` when it asks for nothing, and
|
||||
/// `Some(Some(value))` for its value (group 1). `None` when it asks for any other edit: a group
|
||||
/// added, dropped, moved or changed other than the attribute's own value.
|
||||
fn value_edit(now: &[Tag], asked: &[Tag]) -> Option<Option<String>> {
|
||||
if now.len() != asked.len() {
|
||||
return None;
|
||||
}
|
||||
let mut value = None;
|
||||
let mut seen = false;
|
||||
for (n, a) in now.iter().zip(asked) {
|
||||
if n.code != a.code {
|
||||
return None;
|
||||
}
|
||||
if n.code == 1 {
|
||||
// A multiline attribute's embedded text has a group 1 of its own, after its marker
|
||||
// (101): only the attribute's value, before it, may differ.
|
||||
match (&n.value, &a.value) {
|
||||
(craft_dxf::Value::Str(old), craft_dxf::Value::Str(new)) if !seen => {
|
||||
seen = true;
|
||||
if old != new {
|
||||
value = Some(new.clone());
|
||||
}
|
||||
}
|
||||
_ if n == a => {}
|
||||
_ => return None,
|
||||
}
|
||||
} else if n != a {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(value)
|
||||
}
|
||||
|
||||
/// The submitted list has the items `entget` would return, in order, except at group 1 (the
|
||||
/// value): `value_edit` checks which group 1 may differ. Every other group, including the ones
|
||||
/// an entity cannot set (`-2`, `5`, `330`, `360`, `410`, `102`), must be the same.
|
||||
fn only_value_diff(expected: &Value, asked: &Value) -> bool {
|
||||
let (mut expected, mut asked) = (expected.iter(), asked.iter());
|
||||
loop {
|
||||
match (expected.next(), asked.next()) {
|
||||
(None, None) => return true,
|
||||
(Some(x), Some(y)) => {
|
||||
let code = x.car().as_number();
|
||||
if code != y.car().as_number() {
|
||||
return false;
|
||||
}
|
||||
if code != Some(1.0) && !equal(&x, &y, 0.0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `entmod` of the INSERT's record `name` stands for (#1660): only an ATTRIB's value may change,
|
||||
/// the group 1 value; its tag, place, flags and properties are the reference's. A SEQEND holds
|
||||
/// nothing to change, and a name that no longer holds names nothing: both give `nil`, the drawing
|
||||
/// as it is.
|
||||
fn entmod_attrib(ctx: &mut Ctx<'_>, list: &Value, name: RecordName) -> Value {
|
||||
let Some((owner, slot)) = record_of(ctx, name) else { return Value::Nil };
|
||||
// An outer list with an atom tail is not the list `entget` returned: iterating it would drop
|
||||
// the tail and accept the malformed list. The group pairs inside are dotted, as DXF has them.
|
||||
if !list.is_list() {
|
||||
return Value::Nil;
|
||||
}
|
||||
let Ok((kind, asked)) = list_to_groups(list) else { return Value::Nil };
|
||||
if !kind.eq_ignore_ascii_case("ATTRIB") {
|
||||
return Value::Nil;
|
||||
}
|
||||
let Ok(d) = ctx.s.doc() else { return Value::Nil };
|
||||
if crate::cmd::blocks::refedit::locked(d, owner) {
|
||||
return Value::Nil;
|
||||
}
|
||||
let Some((expected, now)) = record_list(d, name, owner, slot) else { return Value::Nil };
|
||||
// The type, layout, owner, handle and any other group are not the attribute's to change: a
|
||||
// list that differs from `entget` anywhere but its group 1 value is refused (a SEQEND's
|
||||
// list too), the drawing untouched.
|
||||
if !only_value_diff(&expected, list) {
|
||||
return Value::Nil;
|
||||
}
|
||||
match value_edit(&now, &asked) {
|
||||
None => Value::Nil,
|
||||
Some(None) => list.clone(),
|
||||
Some(Some(value)) => {
|
||||
let ok = ctx.s.doc_mut().is_ok_and(|d| {
|
||||
d.modify_entity(owner, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind
|
||||
&& let Some(a) = i.attribs.get_mut(slot)
|
||||
{
|
||||
a.text.value = value.clone();
|
||||
}
|
||||
})
|
||||
.is_ok()
|
||||
});
|
||||
if ok {
|
||||
ctx.s.touch();
|
||||
}
|
||||
if ok { list.clone() } else { Value::Nil }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 2)?;
|
||||
// An INSERT's ATTRIB or SEQEND (#1660) is not an entity of the drawing: its name reaches it.
|
||||
if let Value::Record(r) = &a[0] {
|
||||
return Ok(Flow::Value(record_entget(ctx, *r).unwrap_or_default()));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
// The applications whose xdata to list: names or wildcard patterns ("*": every application).
|
||||
let apps: Option<Vec<String>> = match a.get(1) {
|
||||
@@ -396,21 +700,8 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
let (kind, mut tags) = (codec()?.groups)(d, e);
|
||||
let xdata = apps.map(|apps| xdata_to_list(&e.common.xdata, &apps)).filter(|v| !v.is_nil());
|
||||
convert_angles(&kind, &mut tags, f64::to_radians);
|
||||
let layout = match space_of(d, h) {
|
||||
Some(Space::Paper(name)) => name,
|
||||
_ => "Model".into(),
|
||||
};
|
||||
let mut items = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))];
|
||||
let mut placed_layout = in_block;
|
||||
for v in groups_to_list(&tags) {
|
||||
// The layout name follows the AcDbEntity marker, as AutoCAD lists it.
|
||||
let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity");
|
||||
items.push(v);
|
||||
if after_marker {
|
||||
items.push(Value::cons(Value::Int(410), Value::str(&layout)));
|
||||
placed_layout = true;
|
||||
}
|
||||
}
|
||||
let head = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))];
|
||||
let mut items = entity_list(d, head, h, &tags, in_block).to_vec();
|
||||
if let Some(x) = xdata {
|
||||
items.push(Value::cons(Value::Int(-3), x));
|
||||
}
|
||||
@@ -545,6 +836,73 @@ pub fn regapp(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
Ok(Flow::Value(Value::str(name.trim())))
|
||||
}
|
||||
|
||||
/// `(textbox elist)`: the smallest box around a TEXT that `elist` describes (an `entget` list, or
|
||||
/// a partial one with at least the string, group 1), as its lower-left and upper-right corners
|
||||
/// relative to the insertion point, the text unrotated and left-justified. Groups the list
|
||||
/// leaves out take the current text style (TEXTSTYLE) and that style's height (TEXTSIZE when
|
||||
/// the style's is 0), width factor and obliquing. The text is shaped as it is drawn, so the box
|
||||
/// is that of the drawn glyphs (control codes such as `%%u` as drawn): its first corner is the
|
||||
/// insertion point unless letters reach below the baseline or lean left of it. A string that
|
||||
/// draws nothing (spaces) gives the line's advance by the text height. nil for a list that is
|
||||
/// not a TEXT.
|
||||
pub fn textbox(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
let list = &a[0];
|
||||
let nil = || Ok(Flow::Value(Value::Nil));
|
||||
if !matches!(list, Value::Cons(_)) {
|
||||
return nil();
|
||||
}
|
||||
let group = |code: i32| list.iter().find(|p| matches!(p.car(), Value::Int(c) if c == code)).map(|p| p.cdr());
|
||||
if group(1).is_none() || group(0).is_some_and(|k| !matches!(&k, Value::Str(s) if s.eq_ignore_ascii_case("TEXT"))) {
|
||||
return nil();
|
||||
}
|
||||
let Ok(d) = ctx.s.doc() else { return nil() };
|
||||
let style = match group(7) {
|
||||
Some(Value::Str(s)) => s.to_string(),
|
||||
_ => d.header.str("TEXTSTYLE", "Standard"),
|
||||
};
|
||||
let ts = d.text_style(&style).cloned().unwrap_or_default();
|
||||
let pair = |c: i32, v: Value| Value::cons(Value::Int(c), v);
|
||||
let mut items = vec![pair(0, Value::str("TEXT"))];
|
||||
if group(7).is_none() {
|
||||
items.push(pair(7, Value::str(&style)));
|
||||
}
|
||||
if group(40).is_none() {
|
||||
let h = if ts.height.is_finite() && ts.height > 0.0 { ts.height } else { d.header.f64("TEXTSIZE", 0.2) };
|
||||
items.push(pair(40, Value::Real(h)));
|
||||
}
|
||||
if group(41).is_none() {
|
||||
items.push(pair(41, Value::Real(ts.width_factor)));
|
||||
}
|
||||
if group(51).is_none() {
|
||||
items.push(pair(51, Value::Real(ts.oblique)));
|
||||
}
|
||||
items.extend(list.iter().filter(|p| !matches!(p.car(), Value::Int(0))));
|
||||
let Ok((_, _, cadcraft_doc::EntityKind::Text(t), _)) = entity_from_list(ctx, &Value::list(items)) else { return nil() };
|
||||
let t = cadcraft_doc::Text {
|
||||
insert: Default::default(),
|
||||
align_pt: None,
|
||||
rotation: 0.0,
|
||||
halign: cadcraft_doc::HAlign::Left,
|
||||
valign: cadcraft_doc::VAlign::Baseline,
|
||||
backwards: false,
|
||||
upside_down: false,
|
||||
..t
|
||||
};
|
||||
let Ok(d) = ctx.s.doc() else { return nil() };
|
||||
// The line's box runs from the font's descent to the text height over the advance; the
|
||||
// drawn points give the smallest box. With nothing drawn, the advance from the baseline up.
|
||||
let (sh, line) = cadcraft_render::place_text_entity(d, &t, &t.value);
|
||||
let mut b = cadcraft_geom::Bounds2::from_points(sh.strokes.iter().flatten().chain(sh.glyphs.iter().flatten().flatten()).copied());
|
||||
if b.is_empty() {
|
||||
b = cadcraft_geom::Bounds2::from_points([cadcraft_geom::Vec2::new(0.0, 0.0), line.max]);
|
||||
}
|
||||
if b.is_empty() || ![b.min.x, b.min.y, b.max.x, b.max.y].iter().all(|v| v.is_finite()) {
|
||||
return nil();
|
||||
}
|
||||
Ok(Flow::Value(Value::list([Value::point(&[b.min.x, b.min.y, 0.0]), Value::point(&[b.max.x, b.max.y, 0.0])])))
|
||||
}
|
||||
|
||||
/// The upper-case names of every application registered in the drawing or carrying xdata on an object.
|
||||
fn xdata_app_names(d: &cadcraft_doc::Drawing) -> std::collections::BTreeSet<String> {
|
||||
std::iter::once(&d.model)
|
||||
@@ -573,8 +931,9 @@ fn entity_from_list(ctx: &Ctx<'_>, list: &Value) -> Result<ListedEntity, LispErr
|
||||
Some((mut common, k)) => {
|
||||
if let Some(apps) = &xdata {
|
||||
for (app, groups) in apps {
|
||||
// `ACAD` on a dimension holds its overrides (DSTYLE), written from the model.
|
||||
if cadcraft_doc::is_model_xdata_app(app, &k) {
|
||||
// `ACAD` on a dimension holds its overrides (DSTYLE), written from the model; on
|
||||
// a leader its DSTYLE list does, and the rest of the run is kept.
|
||||
if cadcraft_doc::is_model_xdata(app, groups, &k) {
|
||||
return Err(LispError::new(format!("bad DXF group: xdata application {app} of a {kind} is written from its own properties")));
|
||||
}
|
||||
cadcraft_doc::set_xdata_app(&mut common.xdata, app, Some(groups));
|
||||
@@ -698,7 +1057,12 @@ fn end_block(ctx: &mut Ctx<'_>) -> Value {
|
||||
pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
let list = &a[0];
|
||||
let Some(Value::Ename(h)) = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr()) else {
|
||||
let name = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr());
|
||||
// An INSERT's record takes a value edit only (#1660); any other edit of one is refused.
|
||||
if let Some(Value::Record(r)) = name {
|
||||
return Ok(Flow::Value(entmod_attrib(ctx, list, r)));
|
||||
}
|
||||
let Some(Value::Ename(h)) = name else {
|
||||
return Err(LispError::bad_arg("lentityp", &Value::Nil));
|
||||
};
|
||||
let Some(old) = ctx.s.doc().ok().and_then(|d| d.entity(h)).cloned() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
@@ -728,6 +1092,12 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
{
|
||||
new.attribs = was.attribs.clone();
|
||||
}
|
||||
// A leader's style overrides are read from its `ACAD` DSTYLE xdata with the file's handle
|
||||
// tables, which a list has not: they are kept from the leader, and a list that gives a
|
||||
// DSTYLE list as raw xdata was refused above (`entity_from_list`).
|
||||
if let (cadcraft_doc::EntityKind::Leader(new), cadcraft_doc::EntityKind::Leader(was)) = (&mut kind, &old.kind) {
|
||||
new.overrides.clone_from(&was.overrides);
|
||||
}
|
||||
let Ok(d) = ctx.s.doc_mut() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
d.ensure_layer(&common.layer);
|
||||
let ok = d
|
||||
@@ -742,9 +1112,15 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
Ok(Flow::Value(if ok { list.clone() } else { Value::Nil }))
|
||||
}
|
||||
|
||||
/// `(entupd ename)`: redraw an entity (the canvas redraws on its own).
|
||||
/// `(entupd ename)`: redraw an entity (the canvas redraws on its own). For an INSERT's record
|
||||
/// (#1660) its reference: the record's name while it holds.
|
||||
pub fn entupd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
if let Value::Record(r) = &a[0] {
|
||||
let holds = record_of(ctx, *r).is_some();
|
||||
ctx.s.touch();
|
||||
return Ok(Flow::Value(if holds { a[0].clone() } else { Value::Nil }));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
ctx.s.touch();
|
||||
Ok(Flow::Value(if ctx.s.doc().is_ok_and(|d| d.entity(h).is_some()) { Value::Ename(h) } else { Value::Nil }))
|
||||
@@ -753,10 +1129,18 @@ pub fn entupd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
/// `(entdel ename)`: delete an entity, or bring back one this routine's drawing deleted.
|
||||
pub fn entdel(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
// An INSERT's ATTRIB or SEQEND is the reference's: it is not deleted on its own (#1660).
|
||||
if matches!(a[0], Value::Record(_)) {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
let Ok(d) = ctx.s.doc_mut() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
if let Some(space) = d.space_of(h) {
|
||||
if let Some(e) = d.remove_entity(h) {
|
||||
// The names of its records went with it: `entdel` bringing it back brings none back.
|
||||
if let Some(names) = ctx.s.record_names() {
|
||||
names.erased(&e);
|
||||
}
|
||||
ctx.env.deleted.insert(h, (space, e));
|
||||
ctx.s.touch();
|
||||
return Ok(Flow::Value(Value::Ename(h)));
|
||||
@@ -852,24 +1236,41 @@ pub fn entlast(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
|
||||
pub fn entnext(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 0, 1)?;
|
||||
// From an entity of a block definition: the next one in that block, nil after the last (#1700).
|
||||
if let Some(v) = a.first().filter(|v| !v.is_nil()) {
|
||||
let h = ename(v)?;
|
||||
if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none())
|
||||
&& let Some((_, next)) = block_slots(ctx).get(&h)
|
||||
{
|
||||
return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()));
|
||||
let after = match a.first() {
|
||||
None | Some(Value::Nil) => None,
|
||||
// From a record of an INSERT (#1660): the next record of its run, and after its SEQEND the
|
||||
// next main entity after the INSERT. A name that no longer holds names nothing.
|
||||
Some(Value::Record(r)) => {
|
||||
let Some((owner, slot)) = record_of(ctx, *r) else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let attribs = ctx.s.doc().ok().and_then(|d| insert_attribs(d, owner)).map_or(0, <[cadcraft_doc::Attrib]>::len);
|
||||
if slot < attribs {
|
||||
return Ok(Flow::Value(name_record(ctx, owner, slot.saturating_add(1)).map(Value::Record).unwrap_or_default()));
|
||||
}
|
||||
Some(owner)
|
||||
}
|
||||
}
|
||||
let order = handles_in_order(ctx);
|
||||
let next = match a.first() {
|
||||
None | Some(Value::Nil) => order.first().copied(),
|
||||
Some(v) => {
|
||||
let h = ename(v)?;
|
||||
let i = order.partition_point(|x| *x <= h);
|
||||
order.get(i).copied()
|
||||
// From an entity of a block definition: the next one in that block, nil after the last (#1700).
|
||||
if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none())
|
||||
&& let Some((_, next)) = block_slots(ctx).get(&h)
|
||||
{
|
||||
return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()));
|
||||
}
|
||||
// An INSERT with attributes is followed by its ATTRIBs and its SEQEND (#1660): its
|
||||
// first ATTRIB, or nil when no name is left to give (the walk stops rather than skip
|
||||
// records it can't name). A host without the optional record mapping has no such
|
||||
// records: the walk goes on to the next entity, as it always did.
|
||||
if crate::cmd::file::entity_sub_record().is_some() && ctx.s.doc().is_ok_and(|d| insert_attribs(d, h).is_some()) {
|
||||
return Ok(Flow::Value(name_record(ctx, h, 0).map(Value::Record).unwrap_or_default()));
|
||||
}
|
||||
Some(h)
|
||||
}
|
||||
};
|
||||
let order = handles_in_order(ctx);
|
||||
let next = match after {
|
||||
Some(h) => order.get(order.partition_point(|x| *x <= h)).copied(),
|
||||
None => order.first().copied(),
|
||||
};
|
||||
Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()))
|
||||
}
|
||||
|
||||
@@ -1151,6 +1552,13 @@ fn compare(h: f64, w: f64, op: &str) -> bool {
|
||||
|
||||
pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 0, 2)?;
|
||||
// A selection set holds objects of the drawing; an INSERT's record (#1660) is not one.
|
||||
if matches!(a.first(), Some(Value::Record(_))) {
|
||||
if let Some(ss) = a.get(1) {
|
||||
pickset(ss)?;
|
||||
}
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
match (a.first(), a.get(1)) {
|
||||
(None, _) => Ok(Flow::Value(new_pickset(ctx, Vec::new()))),
|
||||
(Some(e), None) => {
|
||||
@@ -1172,6 +1580,11 @@ pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
|
||||
pub fn ssdel(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
// Never in a selection set (#1660).
|
||||
if matches!(a[0], Value::Record(_)) {
|
||||
pickset(&a[1])?;
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
let p = pickset(&a[1])?;
|
||||
let removed = p.items.lock().map(|mut v| {
|
||||
@@ -1199,6 +1612,11 @@ pub fn ssname(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
|
||||
pub fn ssmemb(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
// Never in a selection set (#1660).
|
||||
if matches!(a[0], Value::Record(_)) {
|
||||
pickset(&a[1])?;
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
let h = ename(&a[0])?;
|
||||
Ok(Flow::Value(if items(&pickset(&a[1])?).contains(&h) { Value::Ename(h) } else { Value::Nil }))
|
||||
}
|
||||
@@ -1547,7 +1965,7 @@ pub fn load_source(s: &Session, name: &str) -> Option<String> {
|
||||
// startup files) a relative name is read as given.
|
||||
let dir = match s.lisp_support_dir() {
|
||||
Some(d) if !std::path::Path::new(name).is_absolute() => d,
|
||||
_ => return candidates.iter().find_map(super::builtins::read_text_file),
|
||||
_ => return read_module(candidates.iter().map(std::path::PathBuf::from)),
|
||||
};
|
||||
// A relative name stays inside the support folder: plain folder and file names only. `..` would
|
||||
// climb out of it, and on Windows a rooted name (`\tools`) or a drive-relative one (`C:tools`,
|
||||
@@ -1556,7 +1974,98 @@ pub fn load_source(s: &Session, name: &str) -> Option<String> {
|
||||
if !std::path::Path::new(name).components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) {
|
||||
return None;
|
||||
}
|
||||
candidates.iter().find_map(|c| super::builtins::read_text_file(dir.join(c)))
|
||||
read_module(candidates.iter().map(|c| dir.join(c)))
|
||||
}
|
||||
|
||||
/// Read the first candidate that exists, trying each exact name first. A module written on Windows
|
||||
/// names its include in one case and ships the file in another: Windows resolved that for free and
|
||||
/// a case-sensitive file system does not, so when no candidate matched, retry with the case of the
|
||||
/// name ignored. The folders in a candidate are used exactly as given.
|
||||
fn read_module(paths: impl Iterator<Item = std::path::PathBuf>) -> Option<String> {
|
||||
let paths: Vec<std::path::PathBuf> = paths.collect();
|
||||
if let Some(text) = paths.iter().find_map(super::builtins::read_text_file) {
|
||||
return Some(text);
|
||||
}
|
||||
paths.iter().find_map(|path| resolve_name_ignoring_case(path).and_then(|found| super::builtins::read_text_file(&found)))
|
||||
}
|
||||
|
||||
/// Find `path` when only the case of its last component differs from what is on disk.
|
||||
///
|
||||
/// Where a folder holds more than one spelling that matches, the smallest name wins, so the answer
|
||||
/// does not depend on directory order.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn resolve_name_ignoring_case(path: &std::path::Path) -> Option<std::path::PathBuf> {
|
||||
let wanted = path.file_name()?.to_str()?.to_lowercase();
|
||||
let dir = match path.parent() {
|
||||
Some(parent) if !parent.as_os_str().is_empty() => parent,
|
||||
_ => std::path::Path::new("."),
|
||||
};
|
||||
// Listing a folder opens it, and for a network path contacts its host: ask first.
|
||||
crate::file_access::check_read(dir).ok()?;
|
||||
let mut best: Option<std::path::PathBuf> = None;
|
||||
for entry in std::fs::read_dir(dir).ok()?.flatten() {
|
||||
let name = entry.file_name();
|
||||
let Some(candidate) = name.to_str() else { continue };
|
||||
if candidate.to_lowercase() != wanted {
|
||||
continue;
|
||||
}
|
||||
let full = dir.join(candidate);
|
||||
// A link counts as the file it leads to. Following it opens its target, so ask first.
|
||||
if crate::file_access::check_read(&full).is_err() || !std::fs::metadata(&full).is_ok_and(|meta| meta.is_file()) {
|
||||
continue;
|
||||
}
|
||||
if best.as_ref().is_none_or(|prev| full < *prev) {
|
||||
best = Some(full);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// The web has no file system for path lookup.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn resolve_name_ignoring_case(_path: &std::path::Path) -> Option<std::path::PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod case_lookup_tests {
|
||||
use super::resolve_name_ignoring_case;
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
/// Under automation roots the case fallback lists only a folder the roots let it read, and a
|
||||
/// link that leaves them is not a match.
|
||||
#[test]
|
||||
fn the_case_fallback_stays_inside_the_automation_roots() {
|
||||
let base = std::env::temp_dir().join(format!("cadcraft-case-roots-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let (inside, outside) = (base.join("in"), base.join("outside"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(inside.join("Tool.lsp"), "").unwrap();
|
||||
std::fs::write(outside.join("Tool.lsp"), "").unwrap();
|
||||
let roots = AutomationRoots::new(Some(&inside), None).unwrap();
|
||||
let find = |path: std::path::PathBuf| confine(roots.as_ref(), || resolve_name_ignoring_case(&path));
|
||||
|
||||
assert!(find(inside.join("tool.lsp")).is_some(), "found inside the read root");
|
||||
assert!(find(outside.join("tool.lsp")).is_none(), "nothing is found outside the roots");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
// A link's target is read from the link's own folder, so these hold even where the
|
||||
// temporary folder's path is relative.
|
||||
std::os::unix::fs::symlink("../outside/Tool.lsp", inside.join("Away.lsp")).unwrap();
|
||||
assert!(inside.join("Away.lsp").is_file(), "the link has a target");
|
||||
assert!(find(inside.join("away.lsp")).is_none(), "a link that leaves the roots");
|
||||
// This link may be read, since it leads back inside: only the check on the folder
|
||||
// itself keeps the fallback from listing that folder and finding it.
|
||||
std::os::unix::fs::symlink("../in/Tool.lsp", outside.join("Back.lsp")).unwrap();
|
||||
let back = confine(roots.as_ref(), || crate::file_access::check_read(outside.join("Back.lsp")));
|
||||
assert_eq!(back, Ok(()));
|
||||
assert!(find(outside.join("back.lsp")).is_none(), "a folder outside the roots is not listed");
|
||||
}
|
||||
// Without roots nothing is confined.
|
||||
assert!(resolve_name_ignoring_case(&outside.join("tool.lsp")).is_some());
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -86,6 +86,51 @@ impl GetRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an answer given up front (`lisp {code, inputs}`) is read as the prompt reads one
|
||||
/// ([`GetRequest::supplied`]) instead of being the value as it is: `getangle` and `getorient`
|
||||
/// return radians whatever the form of the answer.
|
||||
pub fn reads_supplied(&self) -> bool {
|
||||
matches!(self.kind, GetKind::Angle { .. })
|
||||
}
|
||||
|
||||
/// What an answer given up front gives, read as the same answer at the prompt: a number as
|
||||
/// that number typed (in AUNITS), a string as the text typed ([`GetRequest::typed`]), a point
|
||||
/// as a point picked, nil as Enter. The point is in the UCS, as the routine sees points.
|
||||
pub fn supplied(&self, s: &mut Session, v: &Value) -> Answer {
|
||||
let r = match v {
|
||||
Value::Nil => self.answer_value(s, Input::Enter),
|
||||
Value::Int(i) => self.text(s, &i.to_string()),
|
||||
Value::Real(x) => self.text(s, &x.to_string()),
|
||||
Value::Str(t) => self.typed(s, t),
|
||||
other => match other.as_point() {
|
||||
Some(p) => self.point(s, p),
|
||||
None => Err("Requires valid numeric angle or second point.".into()),
|
||||
},
|
||||
};
|
||||
match r {
|
||||
Ok(v) => Answer::Value(v),
|
||||
Err(Again::Second(p)) => Answer::Second(p),
|
||||
Err(Again::Msg(m)) => Answer::Again(m),
|
||||
}
|
||||
}
|
||||
|
||||
/// What text gives, read as the command line reads it typed at the prompt
|
||||
/// (`Session::typed_token`): empty or blank text is Enter, a keyword is that keyword,
|
||||
/// coordinates are a point (`1,1`, `@1,1`, `1<45`, `*1,1`: in the current UCS, the relative
|
||||
/// forms from the last point), and anything else is text (`45`, `45d`, `0.5r`, `50g`).
|
||||
fn typed(&self, s: &mut Session, t: &str) -> Result<Value, Again> {
|
||||
let t = t.trim();
|
||||
if t.is_empty() {
|
||||
return self.answer_value(s, Input::Enter);
|
||||
}
|
||||
if keyword(&self.initget.keywords, t).is_none()
|
||||
&& let Some(p) = s.parse_typed_point(t, s.last_point)
|
||||
{
|
||||
return self.answer_value(s, Input::Point(p));
|
||||
}
|
||||
self.text(s, t)
|
||||
}
|
||||
|
||||
fn answer_value(&self, s: &mut Session, input: Input) -> Result<Value, Again> {
|
||||
let ig = &self.initget;
|
||||
let no_null = ig.bits & 1 != 0;
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use cadcraft_doc::Handle;
|
||||
use serde_json::json;
|
||||
|
||||
use super::value::{Value, to_text};
|
||||
use crate::Session;
|
||||
use crate::cmd::file::{EntityCodec, set_entity_codec, set_object_records};
|
||||
use crate::cmd::file::{EntityCodec, set_entity_codec, set_entity_sub_record, set_object_records};
|
||||
|
||||
pub(super) fn session() -> Session {
|
||||
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
|
||||
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
|
||||
set_entity_sub_record(cadcraft_io::entity_sub_record);
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
set_object_records(cadcraft_io::object_records);
|
||||
Session::new()
|
||||
@@ -614,6 +619,91 @@ fn entmod_of_a_block_reference_keeps_its_attributes() {
|
||||
assert_eq!(insert(&s).1, want);
|
||||
}
|
||||
|
||||
/// entmod of a leader keeps its own dimension style overrides: they come from its DSTYLE xdata,
|
||||
/// read with the file's handle tables, and a list rebuilds the leader without them (#3721).
|
||||
#[test]
|
||||
fn entmod_of_a_leader_keeps_its_style_overrides() {
|
||||
let mut s = session();
|
||||
let overrides = serde_json::json!({ "arrowSize": 1.5, "leaderArrowBlock": "_ArchTick" });
|
||||
let overrides = overrides.as_object().cloned().unwrap();
|
||||
let leader = cadcraft_doc::Leader {
|
||||
vertices: vec![cadcraft_geom::Vec3::ZERO, cadcraft_geom::Vec3::new(10.0, 0.0, 0.0)],
|
||||
arrow: true,
|
||||
spline: false,
|
||||
style: "Standard".into(),
|
||||
overrides: overrides.clone(),
|
||||
};
|
||||
s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Leader(leader)).unwrap();
|
||||
let leader = |s: &Session| {
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Leader(l) => Some((e.common.layer.clone(), l.overrides.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
ok(&mut s, "(setq d (entget (entlast))) (entmod (subst (cons 8 \"UGO\") (assoc 8 d) d))");
|
||||
assert_eq!(leader(&s), ("UGO".to_string(), overrides));
|
||||
}
|
||||
|
||||
/// A session with one leader that has `overrides`.
|
||||
fn session_with_leader(overrides: serde_json::Value) -> Session {
|
||||
let mut s = session();
|
||||
let leader = cadcraft_doc::Leader {
|
||||
vertices: vec![cadcraft_geom::Vec3::ZERO, cadcraft_geom::Vec3::new(10.0, 0.0, 0.0)],
|
||||
arrow: true,
|
||||
spline: false,
|
||||
style: "Standard".into(),
|
||||
overrides: overrides.as_object().cloned().unwrap(),
|
||||
};
|
||||
s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Leader(leader)).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The overrides of the one leader of a drawing.
|
||||
fn leader_overrides(d: &cadcraft_doc::Drawing) -> serde_json::Map<String, serde_json::Value> {
|
||||
d.model
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Leader(l) => Some(l.overrides.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A leader's DSTYLE list is its style overrides, written from the model: `ACAD` xdata that
|
||||
/// holds one is refused by entmod and entmake (nil, nothing changes), with or without overrides
|
||||
/// on the leader. Other `ACAD` data on a leader is taken and survives a save beside them.
|
||||
#[test]
|
||||
fn a_dstyle_list_in_a_leaders_acad_xdata_is_refused_and_other_acad_data_kept() {
|
||||
const DSTYLE: &str = "(-3 (\"ACAD\" (1000 . \"DSTYLE\") (1002 . \"{\") (1070 . 41) (1040 . 9.0) (1002 . \"}\")))";
|
||||
for overrides in [serde_json::json!({}), serde_json::json!({ "arrowSize": 1.5 })] {
|
||||
let mut s = session_with_leader(overrides.clone());
|
||||
let want = overrides.as_object().cloned().unwrap();
|
||||
let count = s.doc().unwrap().model.len();
|
||||
assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '({DSTYLE})))")), "nil", "{overrides}");
|
||||
assert_eq!(ok(&mut s, "(assoc -3 (entget (entlast) '(\"*\")))"), "nil", "{overrides}");
|
||||
assert_eq!(leader_overrides(s.doc().unwrap()), want);
|
||||
// The same list after other groups of the run, and a new leader made with it.
|
||||
let later = DSTYLE.replace("(\"ACAD\" ", "(\"ACAD\" (1000 . \"MINE\") ");
|
||||
assert_eq!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '({later})))")), "nil", "{overrides}");
|
||||
assert_eq!(ok(&mut s, &format!("(entmake (append (entget (entlast)) '({DSTYLE})))")), "nil", "{overrides}");
|
||||
assert_eq!(s.doc().unwrap().model.len(), count, "nothing was made");
|
||||
// Other ACAD data, also a string that only reads DSTYLE, is foreign data and stays.
|
||||
let other = "(\"ACAD\" (1000 . \"DSTYLE\") (1000 . \"MINE\") (1070 . 42))";
|
||||
assert!(ok(&mut s, &format!("(entmod (append (entget (entlast)) '((-3 {other}))))")).contains("LEADER"));
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACAD\"))))"), format!("({other})"));
|
||||
assert_eq!(leader_overrides(s.doc().unwrap()), want);
|
||||
let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap();
|
||||
assert_eq!(leader_overrides(&back), want, "the overrides after a save and reopen");
|
||||
s.open_drawing(back, "back", None);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc -3 (entget (entlast) '(\"ACAD\"))))"), format!("({other})"), "{overrides}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An edit that leaves every handle where it was (a layer change) keeps entlast's cached order;
|
||||
/// one that adds an entity rebuilds it.
|
||||
#[test]
|
||||
@@ -1371,6 +1461,51 @@ fn a_leading_newline_ends_the_command_line_instead_of_adding_an_empty_one() {
|
||||
assert_eq!(&s.log[from..], ["Hello", "", "After a blank"]);
|
||||
}
|
||||
|
||||
/// A module written on Windows names its include in one case and ships the file in another.
|
||||
/// Windows resolved that for free; a case-sensitive file system does not.
|
||||
#[test]
|
||||
fn load_finds_a_support_file_named_in_another_case() {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-case-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("UpperCase.lsp"), "(setq case-test-loaded 1)").unwrap();
|
||||
|
||||
let mut s = session();
|
||||
s.set_lisp_support_dir(Some(dir.clone()));
|
||||
let _ = ok(&mut s, "(load \"uppercase\")");
|
||||
assert_eq!(to_text(&s.lisp_var("CASE-TEST-LOADED"), true), "1", "(load \"uppercase\") reads UpperCase.lsp");
|
||||
|
||||
// An exact name still wins when the folder also holds a spelling that differs only by case.
|
||||
// Where the folder ignores case (Windows and macOS by default) the two names are one file, so
|
||||
// there is nothing to choose between.
|
||||
std::fs::write(dir.join("case-probe"), "").unwrap();
|
||||
if !dir.join("CASE-PROBE").exists() {
|
||||
std::fs::write(dir.join("variant.lsp"), "(setq picked 1)").unwrap();
|
||||
std::fs::write(dir.join("Variant.lsp"), "(setq picked 2)").unwrap();
|
||||
let _ = ok(&mut s, "(load \"variant\")");
|
||||
assert_eq!(to_text(&s.lisp_var("PICKED"), true), "1", "the exact name wins");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A support file may be a link: it counts as the file it leads to.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn load_finds_a_linked_support_file_named_in_another_case() {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-case-link-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("kept")).unwrap();
|
||||
std::fs::write(dir.join("kept/real.lsp"), "(setq linked-loaded 1)").unwrap();
|
||||
// The target is read from the link's own folder, so it holds even where `dir` is relative.
|
||||
std::os::unix::fs::symlink("kept/real.lsp", dir.join("Linked.lsp")).unwrap();
|
||||
|
||||
let mut s = session();
|
||||
s.set_lisp_support_dir(Some(dir.clone()));
|
||||
let _ = ok(&mut s, "(load \"linked\")");
|
||||
assert_eq!(to_text(&s.lisp_var("LINKED-LOADED"), true), "1", "(load \"linked\") reads through Linked.lsp");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_files_load_from_the_support_folder() {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-startup-{}", std::process::id()));
|
||||
@@ -1966,3 +2101,704 @@ fn append_checks_the_cell_cap_before_building_its_result() {
|
||||
assert!(super::value::live_cells() < before + 50_000, "no oversized result was built");
|
||||
assert_eq!(ok(&mut s, "(setq l nil m nil) (length (append '(1) '(2 3)))"), "3");
|
||||
}
|
||||
|
||||
// ---------------- an INSERT's ATTRIBs and SEQEND (#1660) ----------------
|
||||
|
||||
/// A session with block K: a circle and attributes (tag, DXF flags, default value). `entmake`
|
||||
/// goes through the DXF codec, as in the app.
|
||||
fn with_attributes(defs: &[(&str, i32, &str)]) -> Session {
|
||||
let mut s = session();
|
||||
let mut code =
|
||||
String::from("(entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 3.0)))");
|
||||
for (i, (tag, flags, default)) in defs.iter().enumerate() {
|
||||
let y = 5.0 + 3.0 * i as f64;
|
||||
code += &format!(
|
||||
" (entmake '((0 . \"ATTDEF\") (10 0.0 {y:.1} 0.0) (40 . 2.5) (1 . \"{default}\") (3 . \"P{tag}\") (2 . \"{tag}\") (70 . {flags})))"
|
||||
);
|
||||
}
|
||||
code += " (entmake '((0 . \"ENDBLK\")))";
|
||||
s.cmdline(&format!("(progn {code})")).unwrap();
|
||||
s.log.clear();
|
||||
s
|
||||
}
|
||||
|
||||
/// `s` with one reference of K at (10,10), its values `attribs`, and the reference's handle; the
|
||||
/// LISP global `i` names it.
|
||||
fn inserted(s: &mut Session, attribs: serde_json::Value) -> Handle {
|
||||
s.execute("insert", &json!({ "name": "K", "at": [10, 10], "attribs": attribs })).unwrap();
|
||||
let h = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
ok(s, &format!("(setq i (handent \"{}\")) i", h.hex()));
|
||||
h
|
||||
}
|
||||
|
||||
/// Every reference's attributes (tag, value) from the model, in order.
|
||||
fn attribute_values(s: &Session) -> Vec<(String, String)> {
|
||||
let d = s.doc().unwrap();
|
||||
d.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect::<Vec<_>>()),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The records from `i` in order: (type, tag, value) and the SEQEND's owner.
|
||||
const WALK: &str = r#"(progn
|
||||
(setq e (entnext i) out nil)
|
||||
(while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e))))))
|
||||
(setq out (append out (list (list (cdr (assoc 0 ed)) (cdr (assoc 2 ed)) (cdr (assoc 1 ed))
|
||||
(if (equal (cdr (assoc -2 ed)) i) T nil))))
|
||||
e (entnext e)))
|
||||
(list out (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i)))"#;
|
||||
|
||||
#[test]
|
||||
fn entnext_walks_an_inserts_attribs_then_the_seqend_then_the_next_entity() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2"), ("T3", 0, "D3")]);
|
||||
inserted(&mut s, json!({ "T1": "A1", "T3": "A3" }));
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget i)))"), "\"INSERT\"");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 66 (entget i)))"), "1");
|
||||
assert_eq!(ok(&mut s, WALK), "(((\"ATTRIB\" \"T1\" \"A1\" T) (\"ATTRIB\" \"T2\" \"P2\" T) (\"ATTRIB\" \"T3\" \"A3\" T)) \"SEQEND\" T)");
|
||||
// After the SEQEND the main order goes on: a line made later is next, then nil.
|
||||
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entnext (entnext (entnext (entnext (entnext i))))))))"), "\"LINE\"");
|
||||
assert_eq!(ok(&mut s, "(entnext (entlast))"), "nil");
|
||||
// A reference of a block without attributes is followed by the next main entity, no SEQEND.
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
s.cmdline("(progn (entmake '((0 . \"BLOCK\") (2 . \"E\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (entmake '((0 . \"ENDBLK\"))))").unwrap();
|
||||
s.execute("insert", &json!({ "name": "E", "at": [0, 0] })).unwrap();
|
||||
let plain = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap();
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 0 (entget (entnext (handent \"{}\")))))", plain.hex())), "\"LINE\"");
|
||||
// The owner is group -2 in a record's list and not 330, and the reference's own list has
|
||||
// neither (as `entity_groups` keeps it).
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
assert_eq!(ok(&mut s, "(assoc 330 (entget (entnext i)))"), "nil");
|
||||
assert!(attribute_values(&s).iter().any(|(t, v)| t == "T1" && v == "A1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entmod_of_an_attrib_changes_only_its_value() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a) seq (entnext (entnext a)))");
|
||||
// The value (group 1) is the one edit an ATTRIB's list takes.
|
||||
let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
|
||||
assert!(r.contains("(1 . \"A2\")"), "{r}");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\"");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]);
|
||||
// A list asking for anything else, and any edit of the SEQEND, is refused and changes nothing.
|
||||
for code in [
|
||||
"(entmod (subst (cons 2 \"X\") (assoc 2 d) d))",
|
||||
"(entmod (subst (cons 40 9.0) (assoc 40 d) d))",
|
||||
"(entmod (subst (cons 8 \"L\") (assoc 8 d) d))",
|
||||
"(entmod (subst (cons 0 \"SEQEND\") (assoc 0 d) d))",
|
||||
"(entmod (entget seq))",
|
||||
// Groups `list_to_groups` does not keep are still the reference's: an edit (or an added
|
||||
// group) is refused, also when the same list changes group 1.
|
||||
"(entmod (subst (cons 410 \"Layout2\") (assoc 410 d) d))",
|
||||
"(entmod (subst (cons -2 a) (assoc -2 d) d))",
|
||||
"(entmod (append d (list (cons 5 \"FF\"))))",
|
||||
"(entmod (append d (list (cons 330 a))))",
|
||||
"(entmod (append d (list (cons 360 \"FF\"))))",
|
||||
"(entmod (append d (list (cons 102 \"{X\"))))",
|
||||
"(entmod (subst (cons 1 \"A2\") (assoc 1 d) (subst (cons 410 \"Layout2\") (assoc 410 d) d)))",
|
||||
// The same items, but the outer list ends in an atom: iterating it would drop the tail
|
||||
// and accept a list `entget` never returned.
|
||||
"(progn (setq r \"X\" p (reverse d)) (while p (setq r (cons (car p) r) p (cdr p))) (entmod r))",
|
||||
] {
|
||||
assert_eq!(ok(&mut s, code), "nil", "{code}");
|
||||
}
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "no refused edit changed the value");
|
||||
// `entdel` of a record, and `entdel` of the SEQEND, do nothing either.
|
||||
assert_eq!(ok(&mut s, "(progn (entdel a) (entdel seq))"), "nil");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "the name still holds: nothing changed");
|
||||
// The edit is one undo step: the value goes back with it.
|
||||
s.undo().unwrap();
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subentity_name_expires_when_its_record_is_rebuilt() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// Erased: the records go with the reference.
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(list (entget a) (entnext a))"), "(nil nil)");
|
||||
// Undone: the reference is back, the name given before the Undo is not.
|
||||
s.undo().unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", h.hex())), "\"A1\"");
|
||||
// ATTSYNC rebuilds the attributes in place: the old name names nothing, the values stay.
|
||||
ok(&mut s, "(setq b (entnext i))");
|
||||
s.execute("attsync", &json!({ "name": "K" })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget b)"), "nil");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
// A name never resolves to another attribute: when the record at its place has another tag
|
||||
// now, it names nothing (the change makes no new epoch), and a new walk reaches the new tag.
|
||||
ok(&mut s, "(setq c (entnext i))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget c)))"), "\"T1\"");
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind
|
||||
&& let Some(a) = i.attribs.first_mut()
|
||||
{
|
||||
a.tag = "T9".into();
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget c)"), "nil", "the record at that place has another tag now");
|
||||
assert_eq!(ok(&mut s, "(list (cdr (assoc 0 (entget (entnext i)))) (cdr (assoc 2 (entget (entnext i)))))"), "(\"ATTRIB\" \"T9\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_attrib_and_a_seqend_have_distinct_names() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) end (entnext a))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget end)))"), "\"SEQEND\"");
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
let mut blank = i.attribs[0].clone();
|
||||
blank.tag.clear();
|
||||
i.attribs.push(blank);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget end)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(setq b (entnext a)) (list (cdr (assoc 0 (entget b))) (eq b (entnext a)))"), "(\"ATTRIB\" T)");
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
i.attribs.truncate(1);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(ok(&mut s, "(list (entget b) (cdr (assoc 0 (entget (entnext a)))))"), "(nil \"SEQEND\")");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explode_and_burst_retire_the_removed_inserts_record_names() {
|
||||
for command in ["explode", "burst"] {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) end (entnext (entnext a)))");
|
||||
let original = s.doc().unwrap().entity(h).unwrap().as_ref().clone();
|
||||
inserted(&mut s, json!({ "T1": "B1" }));
|
||||
ok(&mut s, "(setq b (entnext i))");
|
||||
// A host can shorten the run before removal and later reuse the handle.
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
|
||||
i.attribs.truncate(1);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let result = s.execute(command, &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert!(!result["handles"].as_array().unwrap().is_empty(), "{command} creates pieces");
|
||||
assert!(s.doc().unwrap().entity(h).is_none(), "{command} removes the reference");
|
||||
s.doc_mut().unwrap().model.push(original);
|
||||
assert_eq!(ok(&mut s, "(list (entget a) (entget end) (cdr (assoc 1 (entget b))))"), "(nil nil \"B1\")", "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entmod_obeys_the_refedit_working_set_for_attrib_owners() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let editing = inserted(&mut s, json!({ "T1": "E1" }));
|
||||
let outside = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.execute("refedit", &json!({ "handle": editing.hex() })).unwrap();
|
||||
let read = "(cdr (assoc 1 (entget (entnext i))))";
|
||||
let edit = r#"(progn (setq d (entget (entnext i))) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#;
|
||||
assert_eq!(ok(&mut s, read), "\"A1\"");
|
||||
assert_eq!(ok(&mut s, edit), "nil");
|
||||
assert_eq!(ok(&mut s, read), "\"A1\"");
|
||||
s.execute("refset", &json!({ "add": [outside.hex()] })).unwrap();
|
||||
assert_ne!(ok(&mut s, edit), "nil");
|
||||
assert_eq!(ok(&mut s, read), "\"A2\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_reference_does_not_revive_an_old_name() {
|
||||
// entdel of the reference, then entdel again to bring it back: the name given before the
|
||||
// first entdel names nothing, also after the reference returns.
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil");
|
||||
assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil", "the name must not come back");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
// ERASE, then OOPS: the same. Erasing expires the names it took with it.
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.execute("oops", &json!({})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "OOPS must not revive the name");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erasing_another_object_keeps_an_attrib_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a))");
|
||||
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
|
||||
let line = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
// Erasing another object leaves the reference and its records as they were: the name holds
|
||||
// and takes the value edit it always took.
|
||||
s.execute("erase", &json!({ "handles": [line.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\"");
|
||||
let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
|
||||
assert!(r.contains("(1 . \"A2\")"), "{r}");
|
||||
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into())]);
|
||||
// Erasing the reference itself ends its names, and OOPS bringing it back revives none.
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.execute("oops", &json!({})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "the name of an erased reference stays dead");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entdel_of_another_object_keeps_an_attrib_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
|
||||
ok(&mut s, "(setq line (entlast))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget line)))"), "\"LINE\"");
|
||||
ok(&mut s, "(entdel line)");
|
||||
assert_eq!(ok(&mut s, "(entget line)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_given_in_the_block_editor_never_resolves_in_the_host() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.execute("bedit", &json!({ "name": "K" })).unwrap();
|
||||
// A reference made in the editor's drawing, named there. The editor starts from the host's
|
||||
// drawing, so its handle is the one the host gives its next new object.
|
||||
s.execute("insert", &json!({ "name": "K", "at": [40, 40], "attribs": { "T1": "E1" } })).unwrap();
|
||||
let editor = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
ok(&mut s, &format!("(setq a (entnext (handent \"{}\")))", editor.hex()));
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"E1\"");
|
||||
s.execute("bclose", &json!({ "save": false })).unwrap();
|
||||
// The host's next reference takes the handle the editor's reference had: the name given in
|
||||
// the editor must not reach its ATTRIB, or `entmod` through it would edit the wrong one.
|
||||
s.execute("insert", &json!({ "name": "K", "at": [80, 80], "attribs": { "T1": "H1" } })).unwrap();
|
||||
let host = *s.doc().unwrap().model.handles().last().unwrap();
|
||||
assert_eq!(host, editor, "the host takes the handle the editor's reference had");
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(entdel a)"), "nil");
|
||||
assert_eq!(
|
||||
ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", host.hex())),
|
||||
"\"H1\"",
|
||||
"the host's own attribute is untouched"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_record_provider_entnext_walks_the_next_entity() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap();
|
||||
// A host that installed no provider has no records to name: the walk goes on to the next
|
||||
// main entity as it always did, rather than answering nil at the reference.
|
||||
let next = crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(entnext i)"));
|
||||
assert_ne!(next, "nil");
|
||||
assert_eq!(crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(cdr (assoc 0 (entget (entnext i))))")), "\"LINE\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_redo_does_not_revive_an_old_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a))");
|
||||
ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
|
||||
s.undo().unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.redo().unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "Redo must not revive the name");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_replace_expires_an_old_attrib_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
// A replacement block with the same tag as K's first attribute: without the expiry, the old
|
||||
// name would keep naming that place and return the new record.
|
||||
s.cmdline(
|
||||
"(progn (entmake '((0 . \"BLOCK\") (2 . \"L\") (70 . 2) (10 0.0 0.0 0.0))) \
|
||||
(entmake '((0 . \"ATTDEF\") (10 0.0 0.0 0.0) (40 . 2.5) (1 . \"Z1\") (3 . \"P\") (2 . \"T1\") (70 . 0))) \
|
||||
(entmake '((0 . \"ENDBLK\"))))",
|
||||
)
|
||||
.unwrap();
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
s.execute("blockreplace", &json!({ "block": "K", "with": "L" })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil", "-BLOCKREPLACE rebuilt the record");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reinsert_after_undo_takes_the_handle_and_no_old_name() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// U takes the reference back; INSERT then gives a new one the handle it had.
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc().unwrap().entity(h).is_none());
|
||||
let again = inserted(&mut s, json!({ "T1": "B1" }));
|
||||
assert_eq!(again, h, "the same handle");
|
||||
assert_eq!(ok(&mut s, "(list (entget a) (cdr (assoc 1 (entget (entnext i)))))"), "(nil \"B1\")");
|
||||
}
|
||||
|
||||
/// A drawing with one reference of `attribs` attributes (all value V), for the bounds.
|
||||
fn drawing_with_attributes(attribs: usize) -> (Session, Handle) {
|
||||
let text = |v: &str| cadcraft_doc::Text {
|
||||
insert: cadcraft_geom::Vec3::ZERO,
|
||||
align_pt: None,
|
||||
height: 1.0,
|
||||
value: v.into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: cadcraft_doc::HAlign::Left,
|
||||
valign: cadcraft_doc::VAlign::Baseline,
|
||||
backwards: false,
|
||||
upside_down: false,
|
||||
};
|
||||
let mut d = cadcraft_doc::Drawing::new_metric();
|
||||
let list = (0..attribs)
|
||||
.map(|i| cadcraft_doc::Attrib {
|
||||
tag: format!("T{i}"),
|
||||
text: text("V"),
|
||||
invisible: false,
|
||||
constant: false,
|
||||
prompt: String::new(),
|
||||
props: cadcraft_doc::AttribProps::default(),
|
||||
multiline: None,
|
||||
modes: cadcraft_doc::AttribModes::default(),
|
||||
})
|
||||
.collect();
|
||||
let insert = cadcraft_doc::Insert { block: "B".into(), attribs: list, ..cadcraft_doc::Insert::default() };
|
||||
let h = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Insert(insert)).expect("add");
|
||||
let mut s = session();
|
||||
s.open_drawing(d, "attributes", None);
|
||||
ok(&mut s, &format!("(setq i (handent \"{}\"))", h.hex()));
|
||||
(s, h)
|
||||
}
|
||||
|
||||
/// The number of records a walk from `i` names.
|
||||
const COUNT: &str = "(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)";
|
||||
|
||||
#[test]
|
||||
fn a_session_names_at_most_65536_records_and_nothing_changes() {
|
||||
let (mut s, h) = drawing_with_attributes(65_537);
|
||||
assert_eq!(ok(&mut s, COUNT), "65536");
|
||||
// The names given hold: a second walk is the same, and the drawing kept every attribute.
|
||||
assert_eq!(ok(&mut s, COUNT), "65536");
|
||||
// Erasing and bringing the reference back frees the 65,536 names it held: the old name names
|
||||
// nothing, and a new walk can name the records again.
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
ok(&mut s, "(progn (entdel i) (entdel i))");
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, COUNT), "65536");
|
||||
let d = s.doc().unwrap();
|
||||
let kept = d.entity(h).and_then(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.len()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(kept, Some(65_537));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_object_at_any_handle_is_never_a_record() {
|
||||
// A hostile $HANDSEED at the top of the range: the line made after the walk takes that
|
||||
// handle, and the record keeps its own name, which is no handle.
|
||||
let (mut s, _) = drawing_with_attributes(1);
|
||||
s.doc_mut().unwrap().handseed = u64::MAX - 1;
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
assert_eq!(
|
||||
ok(&mut s, r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#),
|
||||
"\"FFFFFFFFFFFFFFFE\""
|
||||
);
|
||||
assert_eq!(
|
||||
ok(&mut s, "(list (cdr (assoc 0 (entget a))) (eq a (entlast)) (entdel a) (cdr (assoc 0 (entget (entlast)))))"),
|
||||
"(\"ATTRIB\" nil nil \"LINE\")"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_at_the_top_of_the_handle_range_walk_as_objects() {
|
||||
let (mut s, _) = drawing_with_attributes(1);
|
||||
{
|
||||
let d = s.doc_mut().unwrap();
|
||||
d.handseed = u64::MAX;
|
||||
for handle in [Handle(u64::MAX - 1), Handle(u64::MAX)] {
|
||||
let line =
|
||||
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(1.0, 0.0, 0.0) });
|
||||
d.model.push(cadcraft_doc::Entity { handle, common: cadcraft_doc::Common::default(), kind: line });
|
||||
}
|
||||
}
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// The lines' handles are theirs: `entnext` of the first finds the second, then the end.
|
||||
assert_eq!(ok(&mut s, "(equal (entnext (handent \"FFFFFFFFFFFFFFFE\")) (handent \"FFFFFFFFFFFFFFFF\"))"), "T");
|
||||
assert_eq!(ok(&mut s, "(entnext (handent \"FFFFFFFFFFFFFFFF\"))"), "nil");
|
||||
// The record, a table record and the lines each keep their own name.
|
||||
assert_eq!(
|
||||
ok(&mut s, "(list (cdr (assoc 0 (entget a))) (equal a (tblobjname \"LAYER\" \"0\")) (equal a (handent \"FFFFFFFFFFFFFFFE\")))"),
|
||||
"(\"ATTRIB\" nil nil)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_name_is_an_entity_name_but_no_handle() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) b (entnext a))");
|
||||
assert_eq!(ok(&mut s, "(type a)"), "ENAME");
|
||||
// The same record has the same name on every walk; another record and the reference have
|
||||
// their own.
|
||||
assert_eq!(ok(&mut s, "(list (eq a (entnext i)) (equal a (entnext i)) (eq a b) (eq a i) (equal a i))"), "(T T nil nil nil)");
|
||||
// It prints as the reference's handle, a dot and its number: never a handle's text.
|
||||
let printed = ok(&mut s, "a");
|
||||
assert!(printed.starts_with(&format!("<Entity name: {:x}.", h.0)) && printed.ends_with('>'), "{printed}");
|
||||
// No handle reaches it: its list has no group 5, and `handent` of the reference's handle is
|
||||
// the reference.
|
||||
assert_eq!(ok(&mut s, "(list (assoc 5 (entget a)) (eq a (handent (cdr (assoc 5 (entget i))))))"), "(nil nil)");
|
||||
// A DXF group cannot point at it: `entmake` of a list that does is refused.
|
||||
assert_eq!(ok(&mut s, "(entmake (list '(0 . \"LINE\") '(10 0.0 0.0 0.0) '(11 1.0 0.0 0.0) (cons 340 a)))"), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_sets_and_commands_take_no_record() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) ss (ssadd i))");
|
||||
// A selection set holds objects of the drawing; a record is not one on its own.
|
||||
assert_eq!(ok(&mut s, "(list (ssadd a) (ssadd a ss) (sslength ss) (ssmemb a ss) (ssdel a ss) (sslength ss))"), "(nil nil 1 nil nil 1)");
|
||||
// A command given the name picks nothing: the reference stays, and the name holds.
|
||||
ok(&mut s, "(command \"_.ERASE\" a \"\")");
|
||||
assert!(s.doc().unwrap().entity(h).is_some());
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entupd_of_a_record_answers_its_name_while_it_holds() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i) d (entget a))");
|
||||
assert_eq!(ok(&mut s, "(progn (entmod (subst (cons 1 \"A2\") (assoc 1 d) d)) (eq (entupd a) a))"), "T");
|
||||
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entupd a)"), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_name_holds_while_commands_keep_its_record() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// Moving the reference, or changing its colour, keeps its records in their places.
|
||||
s.execute("move", &json!({ "handles": [h.hex()], "delta": [5, 5] })).unwrap();
|
||||
s.execute("chprop", &json!({ "handles": [h.hex()], "color": 1 })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(list (cdr (assoc 1 (entget a))) (eq a (entnext i)))"), "(\"A1\" T)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_record_name_is_one_entry_and_walking_again_adds_none() {
|
||||
const N: usize = 64;
|
||||
let (mut s, _) = drawing_with_attributes(N);
|
||||
let before = s.state().unwrap().doc.clone();
|
||||
ok(&mut s, "(setq e nil)");
|
||||
// The R3 pattern: each new name, then state access. Nothing is copied or replayed.
|
||||
for _ in 0..=N {
|
||||
ok(&mut s, "(setq e (if e (entnext e) (entnext i)))");
|
||||
let _ = s.state_mut().unwrap();
|
||||
}
|
||||
let uid = s.state().unwrap().uid;
|
||||
let held = |s: &Session| s.lisp.records.get(&uid).map_or(0, super::drawing::RecordNames::count);
|
||||
assert_eq!(held(&s), N + 1, "the attributes and the SEQEND, one entry each");
|
||||
assert_eq!(ok(&mut s, COUNT), (N + 1).to_string());
|
||||
assert_eq!(held(&s), N + 1, "a walk again gives the same names");
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.state().unwrap().doc), "naming changes nothing in the drawing");
|
||||
// Undo or redo ends them: the next walk starts over with as many.
|
||||
s.execute("line", &json!({ "points": [[0, -4], [1, -4]] })).unwrap();
|
||||
s.undo().unwrap();
|
||||
assert_eq!(ok(&mut s, COUNT), (N + 1).to_string());
|
||||
assert_eq!(held(&s), N + 1);
|
||||
}
|
||||
|
||||
/// A saved drawing with one named attribute. The name comes from the command line, which does
|
||||
/// not run the after-command pass.
|
||||
fn clean_named() -> Session {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
{
|
||||
let st = s.state_mut().unwrap();
|
||||
st.saved = st.doc.clone();
|
||||
st.undo.clear();
|
||||
st.redo.clear();
|
||||
}
|
||||
s.cmdline("(setq a (entnext i))").unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget a)))"), "\"ATTRIB\"");
|
||||
assert!(!s.state().unwrap().is_dirty(), "naming from the command line saves nothing");
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issued_name_reads_keep_the_drawing_clean() {
|
||||
let mut s = clean_named();
|
||||
s.cmdline("(getvar \"DBMOD\")").unwrap();
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved));
|
||||
// A programmatic read runs the after-command pass. That pass must not make a saved drawing dirty.
|
||||
s.execute("lisp", &json!({ "code": "(entget a)" })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved));
|
||||
assert_eq!(s.state().unwrap().undo.len(), 0, "a read is not an undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issued_name_selection_keeps_the_drawing_clean() {
|
||||
let mut s = clean_named();
|
||||
let saved = s.state().unwrap().saved.clone();
|
||||
s.execute("select", &json!({ "clear": true })).unwrap();
|
||||
assert!(s.state().unwrap().selection.is_empty());
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved));
|
||||
assert!(!s.state().unwrap().is_dirty());
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
assert_eq!(s.state().unwrap().undo.len(), 0, "clearing an empty selection is not an undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issued_name_undo_restores_the_saved_drawing() {
|
||||
let mut s = clean_named();
|
||||
let saved = s.state().unwrap().saved.clone();
|
||||
// A selection change writes no undo step. If it also changes the drawing, the next command
|
||||
// records that copy, and undo cannot return to the saved drawing.
|
||||
s.execute("select", &json!({ "clear": true })).unwrap();
|
||||
assert_eq!(s.state().unwrap().undo.len(), 0);
|
||||
s.execute("line", &json!({ "points": [[0, -3], [1, -3]] })).unwrap();
|
||||
assert!(s.undo().unwrap().is_some());
|
||||
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved), "undo returns the saved drawing, not a reservation copy");
|
||||
assert!(!s.state().unwrap().is_dirty());
|
||||
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_given_in_the_host_never_resolves_in_the_block_editor() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
let mut same = cadcraft_doc::Entity::clone(s.doc().unwrap().entity(h).unwrap());
|
||||
if let cadcraft_doc::EntityKind::Insert(ins) = &mut same.kind
|
||||
&& let Some(at) = ins.attribs.first_mut()
|
||||
{
|
||||
at.text.value = "E1".into();
|
||||
}
|
||||
s.execute("bedit", &json!({ "name": "K" })).unwrap();
|
||||
// An object of the editor's drawing with the handle the host's reference has: the host's
|
||||
// name must not reach its ATTRIB.
|
||||
s.doc_mut().unwrap().model.push(same);
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
s.execute("bclose", &json!({ "save": false })).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drawing_put_back_after_a_refused_change_ends_its_names() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let before = s.state().unwrap().doc.clone();
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(&mut s, "(setq a (entnext i))");
|
||||
// A change with a number that is not finite: the drawing goes back as it was, without the
|
||||
// reference the name was given for.
|
||||
let bad = cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(f64::NAN, 0.0, 0.0), b: cadcraft_geom::Vec3::ZERO });
|
||||
s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), bad).unwrap();
|
||||
assert!(s.refuse_non_finite(None, &before, &[], "line").is_err());
|
||||
assert!(s.doc().unwrap().entity(h).is_none());
|
||||
// The next reference takes the handle back: the old name names nothing in it.
|
||||
assert_eq!(inserted(&mut s, json!({ "T1": "B1" })), h);
|
||||
assert_eq!(ok(&mut s, "(entget a)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"B1\"");
|
||||
}
|
||||
|
||||
/// MOCORO's own Undo puts the drawing from before the Copy back, handle seed included.
|
||||
/// The next Copy is given that handle again. The name of the removed copy's attribute
|
||||
/// must not read it, walk from it, or change it.
|
||||
#[test]
|
||||
fn mocoro_undo_does_not_let_an_old_record_name_reach_the_next_copy() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
inserted(&mut s, json!({ "T1": "A1" }));
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(sssetfirst nil nil)
|
||||
(command "_.MOCORO" i "" '(0 0) "_Copy" '(10 0))
|
||||
(setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c) v (cdr (assoc 1 (entget a))))
|
||||
(command "_Undo" "_Copy" '(20 0) "_eXit"))"#,
|
||||
);
|
||||
// The name was given for a copy with a handle of its own, and it read that copy's attribute.
|
||||
// The copy made after the Undo has the removed copy's handle.
|
||||
assert_eq!(ok(&mut s, "(list (= ch (cdr (assoc 5 (entget i)))) v (= ch (cdr (assoc 5 (entget (entlast))))))"), "(nil \"A1\" T)");
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(setq d (entget a) w (entnext a))
|
||||
(if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d)))
|
||||
(list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"#
|
||||
),
|
||||
"(T T \"A1\")"
|
||||
);
|
||||
}
|
||||
|
||||
/// A grip Copy's Undo is the same kind of restore: the next copy reuses the handle.
|
||||
#[test]
|
||||
fn grip_copy_undo_does_not_let_an_old_record_name_reach_the_next_copy() {
|
||||
let mut s = with_attributes(&[("T1", 0, "D1")]);
|
||||
let h = inserted(&mut s, json!({ "T1": "A1" }));
|
||||
s.start_grip_edit(&[(h, 0)]).unwrap();
|
||||
// Enter leaves STRETCH for MOVE, which copies the reference whole.
|
||||
s.input(crate::Input::Enter).unwrap();
|
||||
s.input(crate::Input::Keyword("Copy".into())).unwrap();
|
||||
s.input(crate::Input::Point(cadcraft_geom::Vec2::new(20.0, 10.0))).unwrap();
|
||||
// The name is given for a copy with a handle of its own, and it reads that copy's attribute.
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c))
|
||||
(list (= ch (cdr (assoc 5 (entget i)))) (cdr (assoc 1 (entget a)))))"#
|
||||
),
|
||||
"(nil \"A1\")"
|
||||
);
|
||||
s.input(crate::Input::Keyword("Undo".into())).unwrap();
|
||||
s.input(crate::Input::Point(cadcraft_geom::Vec2::new(30.0, 10.0))).unwrap();
|
||||
assert_eq!(ok(&mut s, "(= ch (cdr (assoc 5 (entget (entlast)))))"), "T", "the next copy takes the removed copy's handle");
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
r#"(progn
|
||||
(setq d (entget a) w (entnext a))
|
||||
(if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d)))
|
||||
(list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"#
|
||||
),
|
||||
"(T T \"A1\")"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//! ([`charge_bytes`]).
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use cadcraft_doc::Handle;
|
||||
@@ -207,6 +207,26 @@ pub enum BuiltinKind {
|
||||
Special(super::eval::Special),
|
||||
}
|
||||
|
||||
/// The name AutoLISP gives an INSERT's ATTRIB or SEQEND (#1660). Those records have no handle of
|
||||
/// their own in the drawing, so their names are not handles: `id` comes from one count for the
|
||||
/// whole process and is never given again, so no object of any drawing, and no other record,
|
||||
/// ever has it. `owner` is the reference's handle, for printing. What a name stands for is kept
|
||||
/// by the session; a name that no longer holds names nothing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RecordName {
|
||||
pub(crate) owner: Handle,
|
||||
pub(crate) id: u64,
|
||||
}
|
||||
|
||||
impl RecordName {
|
||||
/// A name never given before, for a record of `owner`; `None` once the count runs out.
|
||||
pub(crate) fn fresh(owner: Handle) -> Option<RecordName> {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
let id = NEXT.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)).ok()?;
|
||||
Some(RecordName { owner, id })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub enum Value {
|
||||
#[default]
|
||||
@@ -217,6 +237,8 @@ pub enum Value {
|
||||
Sym(Sym),
|
||||
Cons(Arc<Cons>),
|
||||
Ename(Handle),
|
||||
/// An INSERT's ATTRIB or SEQEND (#1660): an entity name that is no handle.
|
||||
Record(RecordName),
|
||||
PickSet(PickSet),
|
||||
File(u32),
|
||||
Subr(&'static Builtin),
|
||||
@@ -310,7 +332,7 @@ impl Value {
|
||||
Value::Str(_) => "STR",
|
||||
Value::Sym(_) => "SYM",
|
||||
Value::Cons(_) => "LIST",
|
||||
Value::Ename(_) => "ENAME",
|
||||
Value::Ename(_) | Value::Record(_) => "ENAME",
|
||||
Value::PickSet(_) => "PICKSET",
|
||||
Value::File(_) => "FILE",
|
||||
Value::Subr(_) => "SUBR",
|
||||
@@ -423,6 +445,7 @@ fn atom_equal(a: &Value, b: &Value, fuzz: f64) -> bool {
|
||||
(Value::Str(x), Value::Str(y)) => x == y,
|
||||
(Value::Sym(x), Value::Sym(y)) => x == y,
|
||||
(Value::Ename(x), Value::Ename(y)) => x == y,
|
||||
(Value::Record(x), Value::Record(y)) => x == y,
|
||||
(Value::File(x), Value::File(y)) => x == y,
|
||||
(Value::PickSet(x), Value::PickSet(y)) => x.id == y.id,
|
||||
(Value::Subr(x), Value::Subr(y)) => std::ptr::eq(*x, *y),
|
||||
@@ -567,6 +590,8 @@ fn write_value(out: &mut String, v: &Value, escape: bool, depth: usize) {
|
||||
out.push(')');
|
||||
}
|
||||
Value::Ename(h) => out.push_str(&format!("<Entity name: {:x}>", h.0)),
|
||||
// The reference's handle, a dot and the record's number: never a handle's text.
|
||||
Value::Record(r) => out.push_str(&format!("<Entity name: {:x}.{:x}>", r.owner.0, r.id)),
|
||||
Value::PickSet(p) => out.push_str(&format!("<Selection set: {:x}>", p.id)),
|
||||
Value::File(f) => out.push_str(&format!("#<FILE {f:x}>")),
|
||||
Value::Subr(b) => out.push_str(&format!("#<SUBR @{} {}>", "0", b.name)),
|
||||
|
||||
@@ -75,8 +75,8 @@ impl Axes {
|
||||
pub enum Frame {
|
||||
/// `FROM`: the base point once given, then the offset point.
|
||||
From { base: Option<Vec2> },
|
||||
/// `M2P`/`MTP`: the first point once given, then the second.
|
||||
Mid { first: Option<Vec2> },
|
||||
/// `M2P`/`MTP`: the first point once given (with its Z), then the second.
|
||||
Mid { first: Option<Vec2>, z: f64 },
|
||||
/// A point filter: the point to take `keep` from once given, then the rest.
|
||||
Filter { keep: Axes, first: Option<Vec2> },
|
||||
/// `<a`: the next point lies on the line through `base` in direction `dir` (a unit vector).
|
||||
@@ -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.
|
||||
@@ -153,8 +175,8 @@ impl Session {
|
||||
self.point_mods.iter().fold(cmd, |p, f| match *f {
|
||||
Frame::From { base: None } => Prompt::new("Base point", point),
|
||||
Frame::From { base: Some(b) } => Prompt::new("<Offset>", point).base(b),
|
||||
Frame::Mid { first: None } => Prompt::new("First point of mid", point),
|
||||
Frame::Mid { first: Some(f) } => Prompt::new("Second point of mid", point).base(f),
|
||||
Frame::Mid { first: None, .. } => Prompt::new("First point of mid", point),
|
||||
Frame::Mid { first: Some(f), .. } => Prompt::new("Second point of mid", point).base(f),
|
||||
Frame::Filter { keep, first: None } => Prompt::new(format!("{} of", keep.name()), point).base_opt(p.base),
|
||||
Frame::Filter { keep, first: Some(_) } => Prompt::new(format!("(need {})", keep.need()), point).base_opt(p.base),
|
||||
Frame::TempTrack => Prompt::new("Specify temporary OTRACK point", point),
|
||||
@@ -200,7 +222,7 @@ impl Session {
|
||||
let b = b.to_ascii_lowercase();
|
||||
match b.as_str() {
|
||||
"from" | "fro" => Some(Frame::From { base: None }),
|
||||
"m2p" | "mtp" => Some(Frame::Mid { first: None }),
|
||||
"m2p" | "mtp" => Some(Frame::Mid { first: None, z: 0.0 }),
|
||||
"tt" => Some(Frame::TempTrack),
|
||||
// TK, or TRACKING from three letters (TRA, TRACK).
|
||||
"tk" => Some(Frame::Track { last: None }),
|
||||
@@ -300,7 +322,16 @@ impl Session {
|
||||
|
||||
/// A point given while modifiers are pending: complete the top frame, and when it has its
|
||||
/// point, hand that to the frame (or command) below.
|
||||
pub(crate) fn modifier_point(&mut self, mut p: Vec2) -> Result<()> {
|
||||
pub(crate) fn modifier_point(&mut self, p: Vec2) -> Result<()> {
|
||||
// The frames below may give the point another Z (a snap's, a midpoint's); the next
|
||||
// point starts from the Z it comes with.
|
||||
let z = self.point_z;
|
||||
let result = self.modifier_point_frames(p);
|
||||
self.point_z = z;
|
||||
result
|
||||
}
|
||||
|
||||
fn modifier_point_frames(&mut self, mut p: Vec2) -> Result<()> {
|
||||
if !p.is_finite() {
|
||||
self.echo("Invalid point.");
|
||||
return Ok(());
|
||||
@@ -313,8 +344,8 @@ impl Session {
|
||||
self.last_point = p;
|
||||
return Ok(());
|
||||
}
|
||||
Frame::Mid { first: None } => {
|
||||
self.point_mods.push(Frame::Mid { first: Some(p) });
|
||||
Frame::Mid { first: None, .. } => {
|
||||
self.point_mods.push(Frame::Mid { first: Some(p), z: self.point_z });
|
||||
self.last_point = p;
|
||||
return Ok(());
|
||||
}
|
||||
@@ -336,22 +367,33 @@ impl Session {
|
||||
}
|
||||
// The offset point is already measured from the base (`@` reads the last point).
|
||||
Frame::From { base: Some(_) } => {}
|
||||
Frame::Mid { first: Some(f) } => p = (f + p) * 0.5,
|
||||
Frame::Mid { first: Some(f), z } => {
|
||||
p = (f + p) * 0.5;
|
||||
// Midway in Z too: between two snapped levels, or typed `x,y,z` points.
|
||||
self.point_z = (z + self.point_z) * 0.5;
|
||||
}
|
||||
Frame::Filter { keep, first: Some(f) } => p = keep.combine_in(&self.input_ucs(), f, p),
|
||||
Frame::Angle { base, dir } => p = base + dir * (p - base).dot(dir),
|
||||
Frame::Snap { mode: 0 } => {}
|
||||
Frame::Snap { mode } => {
|
||||
// Snap the point with this mode alone, within the aperture.
|
||||
let prompt = self.current_prompt();
|
||||
let space = self.space();
|
||||
let (doc, space, frozen) = {
|
||||
let st = self.state()?;
|
||||
(st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec())
|
||||
};
|
||||
let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
|
||||
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
|
||||
let base = prompt.as_ref().and_then(|q| q.base);
|
||||
let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
|
||||
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred);
|
||||
let hit = crate::snap::osnap_with_frozen(&doc, &space, p, aperture, mode | hatch, base, deferred, &frozen);
|
||||
match hit {
|
||||
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
|
||||
Some(h) => p = h.point,
|
||||
Some(h) => {
|
||||
// The Z of what it snapped to, as for a snapped pick (OSNAPZ-aware).
|
||||
self.point_z = if h.viewport.is_none() { self.snap_z(&h) } else { 0.0 };
|
||||
p = h.point;
|
||||
}
|
||||
None => {
|
||||
self.echo(format!("No {} found for specified point.", snap_name(mode)));
|
||||
return Ok(());
|
||||
|
||||
+67
-10
@@ -1,7 +1,7 @@
|
||||
//! Interactive commands: prompts, inputs and the command-line coordinate grammar.
|
||||
|
||||
use cadcraft_doc::{EntityKind, Handle};
|
||||
use cadcraft_geom::{Mat3, Vec2};
|
||||
use cadcraft_geom::{Mat3, Vec2, Vec3};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{Result, Session};
|
||||
@@ -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.
|
||||
@@ -511,16 +512,33 @@ pub fn parse_point(text: &str, last: Vec2) -> Option<Vec2> {
|
||||
}
|
||||
|
||||
/// `parse_point` with polar angles read per `angles` (AUNITS, ANGBASE, ANGDIR); `d<<a` and
|
||||
/// `d<<<a` measure from +X counterclockwise (in degrees and in AUNITS).
|
||||
/// `d<<<a` measure from +X counterclockwise (in degrees and in AUNITS). A third number is
|
||||
/// accepted and dropped; [`parse_point3_with`] keeps it.
|
||||
pub fn parse_point_with(text: &str, last: Vec2, angles: &crate::units::AngleSettings) -> Option<Vec2> {
|
||||
parse_point_in(text, last, angles, &crate::ucs::UcsFrame::WORLD)
|
||||
}
|
||||
|
||||
/// [`parse_point_with`] keeping Z: `x,y,z` and `#x,y,z` give that Z, `x,y` and `d<a` lie at
|
||||
/// z = 0, and the relative forms add to `last`'s Z (`@dx,dy,dz`; `@dx,dy` and `@d<a` keep it,
|
||||
/// as in AutoCAD).
|
||||
pub fn parse_point3_with(text: &str, last: Vec3, angles: &crate::units::AngleSettings) -> Option<Vec3> {
|
||||
parse_point3_in(text, last, angles, &crate::ucs::UcsFrame::WORLD)
|
||||
}
|
||||
|
||||
/// `parse_point_with` in a UCS: coordinates are UCS coordinates (`x,y` from its origin along its
|
||||
/// axes, `@dx,dy` along its axes), and polar angles are measured as `angles` says (which carries
|
||||
/// the UCS rotation, [`crate::units::AngleSettings::ucs`]). A `*` prefix reads the point in
|
||||
/// world coordinates instead. `last` and the result are world points.
|
||||
/// world coordinates instead. `last` and the result are world points. A third number is
|
||||
/// accepted and dropped; [`parse_point3_in`] keeps it.
|
||||
pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettings, ucs: &crate::ucs::UcsFrame) -> Option<Vec2> {
|
||||
parse_point3_in(text, last.to3(0.0), angles, ucs).map(Vec3::xy)
|
||||
}
|
||||
|
||||
/// [`parse_point_in`] keeping Z, as [`parse_point3_with`] does: `x,y,z` is a UCS point (its Z
|
||||
/// measured along the UCS Z axis, from its origin), `x,y` and `d<a` lie at world z = 0, and the
|
||||
/// relative forms add their Z to `last`'s (`@dx,dy` and `@d<a` keep it). `last` and the result
|
||||
/// are world points.
|
||||
pub fn parse_point3_in(text: &str, last: Vec3, angles: &crate::units::AngleSettings, ucs: &crate::ucs::UcsFrame) -> Option<Vec3> {
|
||||
let t = text.trim();
|
||||
if t.is_empty() {
|
||||
return None;
|
||||
@@ -554,7 +572,7 @@ pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettin
|
||||
// `d<<a` / `d<<<a`: the override prefixes keep their `<<` / `<<<`.
|
||||
let ang = if a.starts_with('<') { angles.direction(&format!("<{a}"))? } else { angles.direction(a)? };
|
||||
let v = Vec2::from_angle(ang) * dist;
|
||||
if rel { last + v } else { frame.origin.xy() + v }
|
||||
if rel { (last.xy() + v).to3(last.z) } else { (frame.origin.xy() + v).to3(0.0) }
|
||||
} else {
|
||||
let parts: Vec<&str> = body.split(',').collect();
|
||||
if parts.len() < 2 || parts.len() > 3 {
|
||||
@@ -562,11 +580,18 @@ pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettin
|
||||
}
|
||||
let x = crate::units::parse_distance(parts.first()?)?;
|
||||
let y = crate::units::parse_distance(parts.get(1)?)?;
|
||||
if let Some(z) = parts.get(2) {
|
||||
crate::units::parse_distance(z)?;
|
||||
}
|
||||
let z = match parts.get(2) {
|
||||
Some(z) => Some(crate::units::parse_distance(z)?),
|
||||
None => None,
|
||||
};
|
||||
let v = Vec2::new(x, y);
|
||||
if rel { last + frame.vec_to_wcs(v) } else { frame.to_wcs(v) }
|
||||
// The UCS Z axis in world coordinates (straight up for the planar UCSs points are read in).
|
||||
let dz = frame.z().z;
|
||||
if rel {
|
||||
(last.xy() + frame.vec_to_wcs(v)).to3(last.z + z.unwrap_or(0.0) * dz)
|
||||
} else {
|
||||
frame.to_wcs(v).to3(z.map_or(0.0, |z| frame.origin.z + z * dz))
|
||||
}
|
||||
};
|
||||
p.is_finite().then_some(p)
|
||||
}
|
||||
@@ -617,6 +642,38 @@ mod tests {
|
||||
assert_eq!(latin.match_keyword("Θ").as_deref(), Some("Undo"), "a Greek-layout shortcut still works");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn points_with_z() {
|
||||
let last = Vec3::new(10.0, 10.0, 1.0);
|
||||
let p3 = |t: &str| parse_point3_with(t, last, &crate::units::AngleSettings::default());
|
||||
assert_eq!(p3("1,2"), Some(Vec3::new(1.0, 2.0, 0.0)));
|
||||
assert_eq!(p3("1,2,3"), Some(Vec3::new(1.0, 2.0, 3.0)));
|
||||
assert_eq!(p3("#10,20,30"), Some(Vec3::new(10.0, 20.0, 30.0)));
|
||||
assert_eq!(p3("*1,2,3"), Some(Vec3::new(1.0, 2.0, 3.0)));
|
||||
// Relative input adds to the last point's Z; without a third number Z stays.
|
||||
assert_eq!(p3("@0,0,5"), Some(Vec3::new(10.0, 10.0, 6.0)));
|
||||
assert_eq!(p3("@1,2"), Some(Vec3::new(11.0, 12.0, 1.0)));
|
||||
assert_eq!(p3("@"), Some(last));
|
||||
assert!(p3("@5<90").is_some_and(|p| (p - Vec3::new(10.0, 15.0, 1.0)).len() < 1e-9));
|
||||
assert!(p3("5<0").is_some_and(|p| (p - Vec3::new(5.0, 0.0, 0.0)).len() < 1e-9));
|
||||
// Hostile forms: rejected, no panic.
|
||||
for t in ["1,2,3,4", "1,2,", "1,2,z", "1,2,inf", "1,2,NaN", ",,", "@,,1"] {
|
||||
assert_eq!(p3(t), None, "{t}");
|
||||
}
|
||||
let far = Vec3::new(0.0, 0.0, f64::MAX);
|
||||
assert_eq!(parse_point3_with("@0,0,1e308", far, &crate::units::AngleSettings::default()), None);
|
||||
// The 2D form is unchanged.
|
||||
assert_eq!(parse_point("3,4,5", Vec2::new(10.0, 10.0)), Some(Vec2::new(3.0, 4.0)));
|
||||
// In a UCS: a typed Z is measured from its origin; `x,y` lies at z = 0; `@` adds to `last`.
|
||||
let ucs = crate::ucs::UcsFrame::new(Vec3::new(5.0, 0.0, 2.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(-1.0, 0.0, 0.0)).unwrap();
|
||||
let angles = crate::units::AngleSettings::default();
|
||||
let u3 = |t: &str| parse_point3_in(t, Vec3::new(0.0, 0.0, 4.0), &angles, &ucs);
|
||||
assert!(u3("1,0,3").is_some_and(|p| (p - Vec3::new(5.0, 1.0, 5.0)).len() < 1e-9));
|
||||
assert!(u3("1,0").is_some_and(|p| (p - Vec3::new(5.0, 1.0, 0.0)).len() < 1e-9));
|
||||
assert!(u3("@1,0,1").is_some_and(|p| (p - Vec3::new(0.0, 1.0, 5.0)).len() < 1e-9));
|
||||
assert!(u3("*1,0,3").is_some_and(|p| (p - Vec3::new(1.0, 0.0, 3.0)).len() < 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keywords() {
|
||||
let p = Prompt::new("Specify next point", Accept::POINT).kw(&["Undo", "Close"]);
|
||||
|
||||
@@ -189,7 +189,9 @@ mod tests {
|
||||
for b in cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES {
|
||||
assert!(e.contains(b), "{b}: {e}");
|
||||
}
|
||||
assert!(e.contains("and 490 more"), "{e}");
|
||||
// At least the 490 of the drawing's own that are not listed (the user's plot style folder may add some).
|
||||
let more = e.split(" and ").last().and_then(|t| t.split_whitespace().next()).and_then(|n| n.parse::<usize>().ok());
|
||||
assert!(more.is_some_and(|n| n >= 490), "{e}");
|
||||
assert!(e.len() < 1000, "{} bytes: {e}", e.len());
|
||||
assert!(RenderLook::from_params(&d, &json!({"plot_style": d.plot_style_tables[7].name.clone()})).is_ok());
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user