mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-19 20:30:42 -06:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fdb6b6e1f1 | ||
|
|
b0f91a8116 |
@@ -26,7 +26,8 @@ permissions:
|
||||
|
||||
jobs:
|
||||
freebsd:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
|
||||
# Diagnostic-only pin to validate the shared FreeBSD sysroot change.
|
||||
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@25a199081a84a25cb43f860659a93cfad84686a1
|
||||
with:
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
architectures: '["aarch64"]'
|
||||
|
||||
@@ -114,7 +114,3 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr
|
||||
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
|
||||
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
|
||||
## Shared libraries
|
||||
|
||||
Before adding or changing file-format, codec, protocol, or reusable UI code, check `storytold/craft-libs` and its open PRs first; reuse or extend the shared library rather than duplicating it locally, keep app-specific policy and model mapping in the app, and preserve behavior, security/resource limits, attribution, and regression coverage during cutovers.
|
||||
|
||||
+1
-3
@@ -23,7 +23,6 @@ Generated-in-code assets are original and have no file to list:
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `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. |
|
||||
| `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`. |
|
||||
@@ -63,7 +62,6 @@ Generated-in-code assets are original and have no file to list:
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `crates/ui-egui/src/i18n/uk.tsv` | @dmatviichuk | Original Ukrainian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/pl.tsv` | @neronek22 (Echo Rozumu & Gadajło; AI-assisted) | Original Polish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/de.tsv` | the CADCraft contributors | Original German translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/es.tsv` | @PedroGuille | Original Spanish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
| `crates/ui-egui/src/i18n/pt_br.tsv` | @WladmirJunior | Original Brazilian Portuguese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
|
||||
@@ -78,6 +76,6 @@ Generated-in-code assets are original and have no file to list:
|
||||
| `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/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) | Original Turkish 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; the running app 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/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading 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 chosen with a native speaker, full proofreading pending |
|
||||
| `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) |
|
||||
|
||||
Generated
+3
-389
@@ -156,21 +156,6 @@ dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "allocator-api2"
|
||||
version = "0.2.21"
|
||||
@@ -299,9 +284,6 @@ name = "arrayvec"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "as-raw-xcb-connection"
|
||||
@@ -531,12 +513,6 @@ version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
|
||||
|
||||
[[package]]
|
||||
name = "bit_field"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -592,16 +568,6 @@ dependencies = [
|
||||
"piper",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "6.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
@@ -671,7 +637,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sys-locale",
|
||||
"thiserror 2.0.21",
|
||||
"uds_windows",
|
||||
"windows",
|
||||
"winit",
|
||||
"winresource",
|
||||
@@ -735,7 +700,6 @@ dependencies = [
|
||||
"cadcraft-render",
|
||||
"craft-docpath",
|
||||
"craft-dxf",
|
||||
"craft-mime",
|
||||
"libc",
|
||||
"log",
|
||||
"rstar",
|
||||
@@ -750,8 +714,6 @@ version = "0.21.0"
|
||||
dependencies = [
|
||||
"cadcraft-geom",
|
||||
"craft-dxf",
|
||||
"craft-font-catalog",
|
||||
"craft-shx",
|
||||
"encoding_rs",
|
||||
"harfrust 0.14.0",
|
||||
"icu_segmenter",
|
||||
@@ -778,15 +740,13 @@ dependencies = [
|
||||
"cadcraft-render",
|
||||
"craft-dwg",
|
||||
"craft-dxf",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-pdf",
|
||||
"craft-svg",
|
||||
"image",
|
||||
"miniz_oxide 0.9.1",
|
||||
"quick-xml 0.42.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"tiny-skia",
|
||||
]
|
||||
|
||||
@@ -798,8 +758,6 @@ dependencies = [
|
||||
"cadcraft-io",
|
||||
"cadcraft-render",
|
||||
"clap",
|
||||
"craft-jsonrpc",
|
||||
"craft-mcp",
|
||||
"getrandom 0.4.3",
|
||||
"libc",
|
||||
"log",
|
||||
@@ -815,7 +773,6 @@ dependencies = [
|
||||
"cadcraft-doc",
|
||||
"cadcraft-fonts",
|
||||
"cadcraft-geom",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"lyon_tessellation",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
@@ -834,7 +791,6 @@ dependencies = [
|
||||
"cadcraft-io",
|
||||
"cadcraft-render",
|
||||
"chrono",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"craft-window",
|
||||
@@ -1175,16 +1131,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db"
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
@@ -1202,25 +1148,13 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=006e4df225fca57e95ead0fb1f91920900798a99#006e4df225fca57e95ead0fb1f91920900798a99"
|
||||
dependencies = [
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9)",
|
||||
"encoding_rs",
|
||||
"kurbo",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c07e38090879ffa994f893df9956c6d5b96c049c#c07e38090879ffa994f893df9956c6d5b96c049c"
|
||||
dependencies = [
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
@@ -1249,123 +1183,6 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"hayro-jpeg2000",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"hayro-jpeg2000",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jsonrpc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mcp"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c"
|
||||
dependencies = [
|
||||
"craft-jsonrpc",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db)",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
@@ -1376,45 +1193,6 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-shx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=2f2d1d84e3a36b3f93e81507aeff3f0da97a7162#2f2d1d84e3a36b3f93e81507aeff3f0da97a7162"
|
||||
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"craft-xml",
|
||||
"flate2",
|
||||
"kurbo",
|
||||
"quick-xml 0.41.0",
|
||||
"roxmltree",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-pathops",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -1439,7 +1217,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1494,16 +1272,6 @@ dependencies = [
|
||||
"wayland-client",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.3"
|
||||
@@ -1993,22 +1761,6 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "exr"
|
||||
version = "1.74.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"
|
||||
dependencies = [
|
||||
"bit_field",
|
||||
"half",
|
||||
"lebe",
|
||||
"miniz_oxide 0.8.9",
|
||||
"multiversion",
|
||||
"rayon-core",
|
||||
"smallvec",
|
||||
"zune-inflate",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -2513,9 +2265,6 @@ name = "hayro-jpeg2000"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
@@ -2818,12 +2567,9 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"byteorder-lite",
|
||||
"color_quant",
|
||||
"gif",
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png",
|
||||
"qoi",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
@@ -2963,12 +2709,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jpeg-encoder"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.106"
|
||||
@@ -3052,7 +2792,6 @@ dependencies = [
|
||||
"arrayvec",
|
||||
"euclid",
|
||||
"polycool",
|
||||
"serde",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -3062,12 +2801,6 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||
|
||||
[[package]]
|
||||
name = "lebe"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
@@ -3108,19 +2841,6 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a25df1b0c5432893f41bba817150e323703ee5f6d974f3a6808ac7fd7f046d18"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo",
|
||||
"polycool",
|
||||
"rustc-hash 2.1.3",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.15"
|
||||
@@ -3273,28 +2993,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"
|
||||
dependencies = [
|
||||
"multiversion-macros",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion-macros"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion_no_op"
|
||||
version = "1.0.0"
|
||||
@@ -4163,15 +3861,6 @@ version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "qoi"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "2.0.1"
|
||||
@@ -4282,17 +3971,6 @@ dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.44.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.45.1"
|
||||
@@ -4400,15 +4078,6 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rstar"
|
||||
version = "0.13.0"
|
||||
@@ -4766,16 +4435,6 @@ dependencies = [
|
||||
"read-fonts 0.41.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.47.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.44.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.48.0"
|
||||
@@ -4999,12 +4658,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "target-features"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -5422,27 +5075,6 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-geom"
|
||||
version = "0.18.0"
|
||||
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pathops"
|
||||
version = "0.18.0"
|
||||
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-geom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.2.0"
|
||||
@@ -6618,15 +6250,6 @@ version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
|
||||
|
||||
[[package]]
|
||||
name = "zune-inflate"
|
||||
version = "0.2.54"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
|
||||
dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpeg"
|
||||
version = "0.5.15"
|
||||
@@ -6636,15 +6259,6 @@ dependencies = [
|
||||
"zune-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpegxl"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
|
||||
dependencies = [
|
||||
"zune-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zvariant"
|
||||
version = "5.15.1"
|
||||
|
||||
+2
-11
@@ -14,11 +14,8 @@ repository = "https://github.com/storytold/cadcraft"
|
||||
# internal
|
||||
cadcraft-geom = { path = "crates/geom" }
|
||||
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "9ed120e6b1bd5116a4649c578d1272d60cf932b9" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "006e4df225fca57e95ead0fb1f91920900798a99" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
|
||||
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "2f2d1d84e3a36b3f93e81507aeff3f0da97a7162" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0325b2d73676d736e94097dbcef01219cf25c7db" }
|
||||
cadcraft-color = { path = "crates/color" }
|
||||
cadcraft-doc = { path = "crates/doc" }
|
||||
cadcraft-constraints = { path = "crates/constraints" }
|
||||
@@ -28,17 +25,11 @@ cadcraft-io = { path = "crates/io" }
|
||||
cadcraft-engine = { path = "crates/engine" }
|
||||
cadcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
cadcraft-mcp = { path = "crates/mcp" }
|
||||
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" }
|
||||
# SVG/SVGZ import and export geometry (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52" }
|
||||
# Which paths stored in a drawing (xrefs, data links) may be opened.
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
|
||||
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false }
|
||||
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "c07e38090879ffa994f893df9956c6d5b96c049c", default-features = false }
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4.6.11"
|
||||
clap_mangen = { version = "0.3.3", features = ["env"] }
|
||||
@@ -81,7 +72,7 @@ egui-wgpu = "0.37"
|
||||
# Monotonic time on native and web (performance.now on wasm).
|
||||
web-time = "1.1"
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ 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
|
||||
Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source
|
||||
Mozilla Public License 2.0 and is used unmodified as a separate library (crates/dwg). Its source
|
||||
is available from crates.io and the repository above.
|
||||
|
||||
|
||||
@@ -48,127 +48,3 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
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.
|
||||
|
||||
JPEG encoding dependency: jpeg-encoder 0.6.1
|
||||
|
||||
Source: https://crates.io/crates/jpeg-encoder/0.6.1
|
||||
Declared license: (MIT OR Apache-2.0) AND IJG.
|
||||
This software is based in part on the work of the Independent JPEG Group.
|
||||
|
||||
The MIT license and unaltered upstream IJG and SIMD notices follow. The Apache-2.0
|
||||
alternative is also retained in licenses/jpeg-encoder-0.6.1 at the repository root
|
||||
(https://github.com/storytold/craft-libs/tree/main/licenses/jpeg-encoder-0.6.1).
|
||||
The dependency is used unmodified; no encoder implementation is vendored here.
|
||||
|
||||
LICENSE-MIT
|
||||
|
||||
Copyright (c) 2021 Volker Ströbel <volkerstroebel@mysurdity.de>
|
||||
|
||||
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.
|
||||
Original src/fdct.rs opening notice
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg to rust
|
||||
*
|
||||
* This file was part of the Independent JPEG Group's software:
|
||||
* Copyright (C) 1991-1996, Thomas G. Lane.
|
||||
* libjpeg-turbo Modifications:
|
||||
* Copyright (C) 2015, 2020, D. R. Commander.
|
||||
*
|
||||
* Conditions of distribution and use:
|
||||
* In plain English:
|
||||
*
|
||||
* 1. We don't promise that this software works. (But if you find any bugs,
|
||||
* please let us know!)
|
||||
* 2. You can use this software for whatever you want. You don't have to pay us.
|
||||
* 3. You may not pretend that you wrote this software. If you use it in a
|
||||
* program, you must acknowledge somewhere in your documentation that
|
||||
* you've used the IJG code.
|
||||
*
|
||||
* In legalese:
|
||||
*
|
||||
* The authors make NO WARRANTY or representation, either express or implied,
|
||||
* with respect to this software, its quality, accuracy, merchantability, or
|
||||
* fitness for a particular purpose. This software is provided "AS IS", and you,
|
||||
* its user, assume the entire risk as to its quality and accuracy.
|
||||
*
|
||||
* This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
|
||||
* All Rights Reserved except as specified below.
|
||||
*
|
||||
* Permission is hereby granted to use, copy, modify, and distribute this
|
||||
* software (or portions thereof) for any purpose, without fee, subject to these
|
||||
* conditions:
|
||||
* (1) If any part of the source code for this software is distributed, then this
|
||||
* README file must be included, with this copyright and no-warranty notice
|
||||
* unaltered; and any additions, deletions, or changes to the original files
|
||||
* must be clearly indicated in accompanying documentation.
|
||||
* (2) If only executable code is distributed, then the accompanying
|
||||
* documentation must state that "this software is based in part on the work of
|
||||
* the Independent JPEG Group".
|
||||
* (3) Permission for use of this software is granted only if the user accepts
|
||||
* full responsibility for any undesirable consequences; the authors accept
|
||||
* NO LIABILITY for damages of any kind.
|
||||
*
|
||||
* These conditions apply to any software derived from or based on the IJG code,
|
||||
* not just to the unmodified library. If you use our work, you ought to
|
||||
* acknowledge us.
|
||||
*
|
||||
* Permission is NOT granted for the use of any IJG author's name or company name
|
||||
* in advertising or publicity relating to this software or products derived from
|
||||
* it. This software may be referred to only as "the Independent JPEG Group's
|
||||
* software".
|
||||
*
|
||||
* We specifically permit and encourage the use of this software as the basis of
|
||||
* commercial products, provided that all warranty or liability claims are
|
||||
* assumed by the product vendor.
|
||||
*
|
||||
* This file contains a slower but more accurate integer implementation of the
|
||||
* forward DCT (Discrete Cosine Transform).
|
||||
*
|
||||
* A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
|
||||
* on each column. Direct algorithms are also available, but they are
|
||||
* much more complex and seem not to be any faster when reduced to code.
|
||||
*
|
||||
* This implementation is based on an algorithm described in
|
||||
* C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
|
||||
* Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
|
||||
* Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
|
||||
* The primary algorithm described there uses 11 multiplies and 29 adds.
|
||||
* We use their alternate method with 12 multiplies and 32 adds.
|
||||
* The advantage of this method is that no data path contains more than one
|
||||
* multiplication; this allows a very simple and accurate implementation in
|
||||
* scaled fixed-point arithmetic, with a minimal number of shifts.
|
||||
*/
|
||||
|
||||
Original src/avx2/fdct.rs opening notice
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg / jfdctint-avx2.asm to rust
|
||||
* Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
|
||||
* Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander.
|
||||
*
|
||||
* Based on the x86 SIMD extension for IJG JPEG library
|
||||
* Copyright (C) 1999-2006, MIYASAKA Masaru.
|
||||
*/
|
||||
|
||||
@@ -54,8 +54,6 @@ fn install_io() {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
}
|
||||
|
||||
/// `path` as text, for the engine and io calls that take a file name as a string.
|
||||
|
||||
@@ -128,8 +128,6 @@ mod web {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
let Some(canvas) = app_canvas() else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
|
||||
@@ -67,9 +67,6 @@ hidapi = { version = "2.6.7", default-features = false, features = ["windows-nat
|
||||
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: Windows' Animation effects
|
||||
# setting (system_animations.rs). Already in Cargo.lock through wgpu's DirectX 12 backend.
|
||||
windows = { version = "0.62", features = ["UI_ViewManagement"] }
|
||||
# One CADCraft per sign-in: later launches hand their files over an AF_UNIX socket
|
||||
# (single_instance.rs). Already in Cargo.lock through zbus.
|
||||
uds_windows = "1.2.1"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
hidapi = { version = "2.6.7", default-features = false, features = ["linux-native-basic-udev"] }
|
||||
|
||||
@@ -24,9 +24,6 @@ pub(crate) struct LaunchArgs {
|
||||
/// Open with the sample drawing
|
||||
#[arg(long)]
|
||||
pub(crate) sample: bool,
|
||||
/// Open the files in a new window, even if CADCraft is already running (Windows)
|
||||
#[arg(long)]
|
||||
pub(crate) new_window: bool,
|
||||
}
|
||||
|
||||
/// The command line. An empty or blank variable counts as unset.
|
||||
@@ -84,10 +81,7 @@ mod tests {
|
||||
assert_eq!((parsed.control, parsed.sample), (Some(50494), true));
|
||||
assert_eq!(parsed.files, [PathBuf::from("a.dxf"), PathBuf::from("b.dwg")]);
|
||||
let parsed = parse_args(&[]).unwrap();
|
||||
assert_eq!((parsed.control, parsed.sample, parsed.new_window, parsed.files.len()), (None, false, false, 0));
|
||||
let parsed = parse_args(&["--new-window", "a.dwg"]).unwrap();
|
||||
assert!(parsed.new_window);
|
||||
assert_eq!(parsed.files, [PathBuf::from("a.dwg")]);
|
||||
assert_eq!((parsed.control, parsed.sample, parsed.files.len()), (None, false, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! CADCraft desktop app.
|
||||
//!
|
||||
//! Usage: `cadcraft [--control <port>] [--sample] [--new-window] [files…]` (`cadcraft --help` lists the rest; see [`launch_args`])
|
||||
//! Usage: `cadcraft [--control <port>] [--sample] [files…]` (`cadcraft --help` lists the rest; see [`launch_args`])
|
||||
//!
|
||||
//! `--control <port>` (or `CADCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server:
|
||||
//! `{"id":1,"method":"cmdline.input","params":{"text":"circle 0,0 5"}}` → `{"id":1,"ok":true,…}`.
|
||||
@@ -25,7 +25,6 @@ mod logging;
|
||||
mod native_menu;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod sheet;
|
||||
mod single_instance;
|
||||
mod spacemouse;
|
||||
mod system_animations;
|
||||
mod workspace;
|
||||
@@ -43,8 +42,6 @@ struct App {
|
||||
system_animations: system_animations::SystemAnimations,
|
||||
workspace: workspace::Workspace,
|
||||
workspace_error: Option<String>,
|
||||
/// The first CADCraft of this sign-in: files that later launches hand over (Windows).
|
||||
single_instance: Option<single_instance::Server>,
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: Option<native_menu::NativeMenu>,
|
||||
/// `CADCRAFT_NO_NATIVE_MENU`: the menus stay inside the window.
|
||||
@@ -90,17 +87,6 @@ impl eframe::App for App {
|
||||
/// eframe logic callback: syncs the OS animation setting and runs `CadApp::logic`; when the pass index is 0 (the first pass or a hidden tick) it also installs/polls the macOS native menu, polls the spacemouse and persists the workspace; a quit request closes the viewport.
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
self.cad.system_animations = self.system_animations.current();
|
||||
// Files another launch handed over open as tabs here, and the window comes forward.
|
||||
if let Some(server) = &self.single_instance {
|
||||
let paths = server.take_paths();
|
||||
if !paths.is_empty() {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
|
||||
for p in &paths {
|
||||
self.cad.open_path(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Consume control/open/screenshot queues and time-based autosave, including hidden ticks.
|
||||
self.cad.guarded_logic(ctx);
|
||||
// Host frame work runs here, once per frame, and so also on a hidden logic-only tick (which
|
||||
@@ -171,8 +157,6 @@ pub fn install_io() {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
entity: cadcraft_io::entity_from_groups,
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
@@ -324,14 +308,6 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A launch that only names files hands them to the CADCraft already running and exits.
|
||||
let handed = single_instance::absolute(&files);
|
||||
let may_hand_off = handed.is_some() && !launch.new_window && !files.is_empty() && control_port.is_none() && !sample;
|
||||
let instance = match single_instance::claim(handed.as_deref().unwrap_or_default(), may_hand_off) {
|
||||
single_instance::Claim::HandedOff => return Ok(()),
|
||||
single_instance::Claim::Primary(server) => Some(server),
|
||||
single_instance::Claim::Alone => None,
|
||||
};
|
||||
install_io();
|
||||
cadcraft_engine::settings_dir::set(vars.config_dir.clone());
|
||||
if let Some(dir) = &vars.config_dir {
|
||||
@@ -452,10 +428,6 @@ fn main() -> eframe::Result {
|
||||
let metric = app.session.settings.measureinit;
|
||||
app.session.new_drawing(metric);
|
||||
}
|
||||
if let Some(server) = &instance {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
server.set_wake(move || ctx.request_repaint());
|
||||
}
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let desktop_theme = desktop_theme::DesktopTheme::start(move || ctx.request_repaint());
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
@@ -467,7 +439,6 @@ fn main() -> eframe::Result {
|
||||
spacemouse: spacemouse::SpaceMouse::start(cc.egui_ctx.clone()),
|
||||
workspace,
|
||||
workspace_error,
|
||||
single_instance: instance,
|
||||
#[cfg(target_os = "macos")]
|
||||
native_menu: None,
|
||||
#[cfg(target_os = "macos")]
|
||||
|
||||
@@ -1,393 +0,0 @@
|
||||
//! One CADCraft per Windows sign-in: a launch that only names files hands them to the CADCraft
|
||||
//! that is already running, where they open as tabs, and exits.
|
||||
//!
|
||||
//! Outlook attachments, Explorer double-clicks and Open With all start `cadcraft.exe "<file>"`, so
|
||||
//! without single instance, every file got its own process and window. The first CADCraft listens on a Unix
|
||||
//! domain socket (Windows 10 1803 and later) in `%LOCALAPPDATA%\CADCraft`. The socket is named after the
|
||||
//! Windows session (`instance-Console.sock`), so two sign-ins of the same user never open files in each
|
||||
//! other's windows. The exchange is one line each way, a JSON request naming absolute paths and `ok`,
|
||||
//! and the running app opens the paths exactly as File ▸ Open would. `--new-window` opens a window
|
||||
//! of its own, and so does a launch with anything besides files (`--control`, `--sample`).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
#[cfg(windows)]
|
||||
use std::time::Duration;
|
||||
|
||||
/// Longest request read: one line of JSON, far longer than any real list of paths.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
const MAX_REQUEST: u64 = 1 << 20;
|
||||
|
||||
/// How long either side waits for the other before giving up.
|
||||
#[cfg(windows)]
|
||||
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// What this launch should do.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
pub enum Claim {
|
||||
/// The running CADCraft took the files: exit without a window.
|
||||
HandedOff,
|
||||
/// This is the first CADCraft: open a window and accept later launches' files.
|
||||
Primary(Server),
|
||||
/// Open a window of its own and accept nothing.
|
||||
Alone,
|
||||
}
|
||||
|
||||
/// Files that later launches handed over, and how to wake the UI for them.
|
||||
#[derive(Default)]
|
||||
struct Inbox {
|
||||
paths: Vec<PathBuf>,
|
||||
wake: Option<Box<dyn Fn() + Send>>,
|
||||
}
|
||||
|
||||
/// The first CADCraft's end of the socket. A background thread accepts launches until the
|
||||
/// process exits; the UI picks their files up through [`Server::take_paths`].
|
||||
#[derive(Clone)]
|
||||
pub struct Server {
|
||||
inbox: Arc<Mutex<Inbox>>,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn new() -> Self {
|
||||
Self { inbox: Arc::default() }
|
||||
}
|
||||
|
||||
/// Queue files from another launch and wake the UI.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn deliver(&self, paths: Vec<String>) {
|
||||
let mut inbox = self.inbox.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
inbox.paths.extend(paths.into_iter().map(PathBuf::from));
|
||||
if let Some(wake) = &inbox.wake {
|
||||
wake();
|
||||
}
|
||||
}
|
||||
|
||||
/// Register a callback to wake the UI when new files arrive.
|
||||
pub fn set_wake(&self, wake: impl Fn() + Send + 'static) {
|
||||
self.inbox.lock().unwrap_or_else(PoisonError::into_inner).wake = Some(Box::new(wake));
|
||||
}
|
||||
|
||||
/// Take any queued paths delivered to this server.
|
||||
pub fn take_paths(&self) -> Vec<PathBuf> {
|
||||
std::mem::take(&mut self.inbox.lock().unwrap_or_else(PoisonError::into_inner).paths)
|
||||
}
|
||||
}
|
||||
|
||||
/// The request a launch sends: `{"open":[…]}` and a newline.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
pub fn request(paths: &[String]) -> String {
|
||||
let mut line = serde_json::json!({ "open": paths }).to_string();
|
||||
line.push('\n');
|
||||
line
|
||||
}
|
||||
|
||||
/// The paths a request names, or `None` when it isn't a request.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
pub fn parse_request(line: &str) -> Option<Vec<String>> {
|
||||
let value: serde_json::Value = serde_json::from_str(line.trim_end()).ok()?;
|
||||
let open = value.get("open")?.as_array()?;
|
||||
let paths = open.iter().map(|p| p.as_str().filter(|s| !s.is_empty()).map(str::to_string)).collect::<Option<Vec<String>>>()?;
|
||||
(!paths.is_empty()).then_some(paths)
|
||||
}
|
||||
|
||||
/// File arguments made absolute against this launch's working folder, as the request names them.
|
||||
/// `None` when one isn't valid Unicode: JSON can't carry it unchanged, so that launch opens its
|
||||
/// own window.
|
||||
pub fn absolute(paths: &[PathBuf]) -> Option<Vec<String>> {
|
||||
paths.iter().map(|p| std::path::absolute(p).unwrap_or_else(|_| p.clone()).into_os_string().into_string().ok()).collect()
|
||||
}
|
||||
|
||||
/// Decide what this launch does. `files` are absolute ([`absolute`]); `may_hand_off` is false
|
||||
/// when the launch asked for anything besides opening files, so it gets its own window.
|
||||
pub fn claim(files: &[String], may_hand_off: bool) -> Claim {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
match socket_path() {
|
||||
Some(path) => claim_at(&path, files, may_hand_off),
|
||||
None => Claim::Alone,
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = (files, may_hand_off);
|
||||
Claim::Alone
|
||||
}
|
||||
}
|
||||
|
||||
/// The socket in `%LOCALAPPDATA%\CADCraft`.
|
||||
#[cfg(windows)]
|
||||
fn socket_path() -> Option<std::path::PathBuf> {
|
||||
let name = socket_name(std::env::var("SESSIONNAME").ok().as_deref());
|
||||
std::env::var_os("LOCALAPPDATA").filter(|v| !v.is_empty()).map(|d| std::path::PathBuf::from(d).join("CADCraft").join(name))
|
||||
}
|
||||
|
||||
/// The socket's file name for a Windows session (`SESSIONNAME`: `Console`, `RDP-Tcp#3`…): a 64-bit
|
||||
/// FNV-1a hash of the whole name, so two sessions of one user practically never share a socket
|
||||
/// (`RDP-Tcp#3` and `RDP-Tcp3` stay apart; a user has a handful of sessions, not billions), and the
|
||||
/// name has a fixed, short length. A Windows socket path holds at most 107
|
||||
/// bytes including `%LOCALAPPDATA%\CADCraft\`, so the name must not grow with the session's.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn socket_name(session: Option<&str>) -> String {
|
||||
let hash = session.unwrap_or_default().bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));
|
||||
format!("{hash:016x}.sock")
|
||||
}
|
||||
|
||||
/// Held while a launch finds out whether it is the first, so launches that start together take turns.
|
||||
#[cfg(windows)]
|
||||
fn election(socket: &std::path::Path) -> Option<std::fs::File> {
|
||||
if let Some(dir) = socket.parent() {
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
}
|
||||
let file = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(socket.with_extension("lock")).ok()?;
|
||||
let deadline = std::time::Instant::now() + TIMEOUT;
|
||||
loop {
|
||||
match file.try_lock() {
|
||||
Ok(()) => return Some(file),
|
||||
Err(std::fs::TryLockError::WouldBlock) if std::time::Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)),
|
||||
Err(e) => {
|
||||
log::info!("single instance: no election lock ({e})");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`claim`] with the socket at `path`.
|
||||
#[cfg(windows)]
|
||||
fn claim_at(path: &std::path::Path, files: &[String], may_hand_off: bool) -> Claim {
|
||||
use uds_windows::{UnixListener, UnixStream};
|
||||
let _election = election(path);
|
||||
for _ in 0..3 {
|
||||
match UnixStream::connect(path) {
|
||||
Ok(stream) => {
|
||||
if !may_hand_off {
|
||||
return Claim::Alone;
|
||||
}
|
||||
return match hand_off(&stream, files) {
|
||||
Ok(()) => Claim::HandedOff,
|
||||
Err(e) => {
|
||||
log::warn!("couldn't hand the files to the running CADCraft ({e}); opening a new window");
|
||||
Claim::Alone
|
||||
}
|
||||
};
|
||||
}
|
||||
// Only a refused or missing socket is stale: any other failure may come from a
|
||||
// listener that is alive, whose socket must not be taken over.
|
||||
Err(e) if !matches!(e.kind(), std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound) => {
|
||||
log::warn!("single instance off: can't reach {} ({e})", path.display());
|
||||
return Claim::Alone;
|
||||
}
|
||||
Err(_) => match std::fs::remove_file(path) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("single instance off: can't clear {} ({e})", path.display());
|
||||
return Claim::Alone;
|
||||
}
|
||||
},
|
||||
}
|
||||
if let Some(dir) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
}
|
||||
match UnixListener::bind(path) {
|
||||
Ok(listener) => return serve(listener),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => continue,
|
||||
Err(e) => {
|
||||
log::warn!("single instance off: can't listen at {} ({e})", path.display());
|
||||
return Claim::Alone;
|
||||
}
|
||||
}
|
||||
}
|
||||
Claim::Alone
|
||||
}
|
||||
|
||||
/// Send `files` over `stream` and wait for the running app's `ok`.
|
||||
#[cfg(windows)]
|
||||
fn hand_off(stream: &uds_windows::UnixStream, files: &[String]) -> std::io::Result<()> {
|
||||
use std::io::{BufRead, Read, Write};
|
||||
stream.set_read_timeout(Some(TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(TIMEOUT))?;
|
||||
let mut writer = stream;
|
||||
writer.write_all(request(files).as_bytes())?;
|
||||
let mut reply = String::new();
|
||||
std::io::BufReader::new(stream.take(16)).read_line(&mut reply)?;
|
||||
if reply == "ok\n" { Ok(()) } else { Err(std::io::Error::other("the running CADCraft didn't confirm")) }
|
||||
}
|
||||
|
||||
/// Accept launches on a background thread for as long as the process runs.
|
||||
#[cfg(windows)]
|
||||
fn serve(listener: uds_windows::UnixListener) -> Claim {
|
||||
let server = Server::new();
|
||||
let inbox = Server { inbox: Arc::clone(&server.inbox) };
|
||||
let started = std::thread::Builder::new().name("single-instance".into()).spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let result = stream.and_then(|s| receive(&s, &inbox));
|
||||
if let Err(e) = result {
|
||||
log::warn!("single instance: a launch's request failed ({e})");
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
});
|
||||
match started {
|
||||
Ok(_) => Claim::Primary(server),
|
||||
Err(e) => {
|
||||
log::warn!("single instance off: no listener thread ({e})");
|
||||
Claim::Alone
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one launch's request, queue its files and confirm.
|
||||
#[cfg(windows)]
|
||||
fn receive(stream: &uds_windows::UnixStream, server: &Server) -> std::io::Result<()> {
|
||||
use std::io::{BufRead, Read, Write};
|
||||
stream.set_read_timeout(Some(TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(TIMEOUT))?;
|
||||
let mut line = String::new();
|
||||
std::io::BufReader::new(stream.take(MAX_REQUEST)).read_line(&mut line)?;
|
||||
if line.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let paths = parse_request(&line)
|
||||
.filter(|paths| paths.iter().all(|p| std::path::Path::new(p).is_absolute()))
|
||||
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "not an open request of absolute paths"))?;
|
||||
server.deliver(paths);
|
||||
let mut writer = stream;
|
||||
writer.write_all(b"ok\n")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_request_names_its_paths_and_parses_back() {
|
||||
let paths = vec![r"C:\Plans\Ground floor.dwg".to_string(), "C:\\Plans\\Schnitt ä.dxf".to_string()];
|
||||
let line = request(&paths);
|
||||
assert!(line.ends_with('\n') && !line.trim_end().contains('\n'), "{line:?}");
|
||||
assert_eq!(parse_request(&line), Some(paths));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anything_else_is_not_a_request() {
|
||||
for line in ["", "ok\n", "{}", r#"{"open":[]}"#, r#"{"open":[""]}"#, r#"{"open":["a",1]}"#, r#"{"open":"a"}"#, "[\"a\"]"] {
|
||||
assert_eq!(parse_request(line), None, "{line:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_socket_is_named_after_the_session() {
|
||||
let names = [None, Some(""), Some("Console"), Some("RDP-Tcp#3"), Some("RDP-Tcp3"), Some(r"..\x")];
|
||||
let sockets: Vec<String> = names.iter().map(|n| socket_name(*n)).collect();
|
||||
// No session name is the same as an empty one; every other name gets its own socket.
|
||||
assert_eq!(sockets[0], sockets[1]);
|
||||
let distinct: std::collections::HashSet<&String> = sockets[1..].iter().collect();
|
||||
assert_eq!(distinct.len(), names.len() - 1, "{sockets:?}");
|
||||
// Short, fixed and safe as a file name, whatever the session is called.
|
||||
let long = socket_name(Some(&"\u{10ffff}".repeat(32)));
|
||||
for s in sockets.iter().chain([&long]) {
|
||||
assert_eq!(s.len(), 21, "{s}");
|
||||
assert!(s.strip_suffix(".sock").is_some_and(|h| h.bytes().all(|b| b.is_ascii_hexdigit())), "{s}");
|
||||
}
|
||||
// Names that differ only past the 32nd character stay apart.
|
||||
let long = "S".repeat(40);
|
||||
assert_ne!(socket_name(Some(&long)), socket_name(Some(&long[..39])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_are_made_absolute() {
|
||||
let files = absolute(&[PathBuf::from("a.dwg")]).unwrap();
|
||||
assert_eq!(files.len(), 1);
|
||||
assert!(std::path::Path::new(&files[0]).is_absolute() && files[0].ends_with("a.dwg"), "{files:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivered_files_wait_for_the_ui_and_wake_it() {
|
||||
let server = Server::new();
|
||||
let woken = Arc::new(Mutex::new(0));
|
||||
let count = Arc::clone(&woken);
|
||||
server.set_wake(move || *count.lock().unwrap() += 1);
|
||||
server.deliver(vec!["a.dwg".into()]);
|
||||
server.deliver(vec!["b.dxf".into()]);
|
||||
assert_eq!(*woken.lock().unwrap(), 2);
|
||||
assert_eq!(server.take_paths(), [PathBuf::from("a.dwg"), PathBuf::from("b.dxf")]);
|
||||
assert!(server.take_paths().is_empty());
|
||||
}
|
||||
|
||||
/// Removes a test's folder when the test ends, best effort: the listener thread keeps its socket
|
||||
/// open until the process exits.
|
||||
#[cfg(windows)]
|
||||
struct Cleanup(PathBuf);
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for one test, and its socket path.
|
||||
#[cfg(windows)]
|
||||
fn socket_dir(test: &str) -> (Cleanup, PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-single-instance-{}-{test}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("instance-test.sock");
|
||||
(Cleanup(dir), path)
|
||||
}
|
||||
|
||||
/// The whole exchange over a real socket: a stale socket file is taken over, a later launch
|
||||
/// hands its files to that listener, one that asked for its own window gets it, and a request
|
||||
/// naming a relative path is refused.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_later_launch_hands_its_files_to_the_first() {
|
||||
let (dir, path) = socket_dir("handoff");
|
||||
drop(uds_windows::UnixListener::bind(&path).unwrap());
|
||||
assert!(path.exists(), "the stale socket file stays behind");
|
||||
|
||||
let Claim::Primary(server) = claim_at(&path, &[], false) else { panic!("the stale socket wasn't taken over") };
|
||||
let files = vec![dir.0.join("a.dwg").to_string_lossy().into_owned()];
|
||||
// The listener queues the files before it confirms, so they are there once this returns.
|
||||
assert!(matches!(claim_at(&path, &files, true), Claim::HandedOff));
|
||||
assert_eq!(server.take_paths(), [PathBuf::from(&files[0])]);
|
||||
assert!(matches!(claim_at(&path, &files, false), Claim::Alone));
|
||||
assert!(server.take_paths().is_empty());
|
||||
// Not confirmed, so that launch opens its own window and nothing is queued.
|
||||
assert!(matches!(claim_at(&path, &["a.dwg".to_string()], true), Claim::Alone));
|
||||
assert!(server.take_paths().is_empty());
|
||||
}
|
||||
|
||||
/// Launches that start together take turns: one opens the window, the others hand it their files.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn launches_at_once_open_one_window() {
|
||||
const LAUNCHES: usize = 6;
|
||||
let (dir, path) = socket_dir("together");
|
||||
let start = Arc::new(std::sync::Barrier::new(LAUNCHES));
|
||||
let launches: Vec<_> = (0..LAUNCHES)
|
||||
.map(|i| {
|
||||
let (path, start) = (path.clone(), Arc::clone(&start));
|
||||
let file = dir.0.join(format!("{i}.dwg")).to_string_lossy().into_owned();
|
||||
std::thread::spawn(move || {
|
||||
start.wait();
|
||||
(file.clone(), claim_at(&path, &[file], true))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let results: Vec<(String, Claim)> = launches.into_iter().map(|t| t.join().unwrap()).collect();
|
||||
let servers: Vec<&Server> = results.iter().filter_map(|(_, c)| if let Claim::Primary(s) = c { Some(s) } else { None }).collect();
|
||||
assert_eq!(servers.len(), 1, "one window");
|
||||
let mut handed: Vec<PathBuf> = results.iter().filter(|(_, c)| matches!(c, Claim::HandedOff)).map(|(f, _)| PathBuf::from(f)).collect();
|
||||
assert_eq!(handed.len(), LAUNCHES - 1, "the rest handed their files over");
|
||||
let mut received = servers[0].take_paths();
|
||||
handed.sort();
|
||||
received.sort();
|
||||
assert_eq!(received, handed);
|
||||
}
|
||||
}
|
||||
@@ -106,10 +106,6 @@ sync_github_name = true
|
||||
[people.GULERTOLGA]
|
||||
sync_github_name = true
|
||||
|
||||
[people.Obtrusive8276]
|
||||
display_name = "Nicopicks"
|
||||
sync_github_name = false
|
||||
|
||||
[people.Tyler-Chiriboga]
|
||||
real_name = "Tyler Chiriboga"
|
||||
sync_github_name = true
|
||||
@@ -122,9 +118,3 @@ sync_github_name = true
|
||||
|
||||
[people.helenkwok]
|
||||
real_name = "Helen Kwok"
|
||||
|
||||
[people.V1dalTheAbidal]
|
||||
sync_github_name = true
|
||||
|
||||
[people.tyrel]
|
||||
real_name = "Tyrel Haveman"
|
||||
|
||||
+26
-53
@@ -1,5 +1,5 @@
|
||||
//! CAD colours: the 256-entry colour index (ACI), 24-bit true colour, and the logical
|
||||
//! `ByLayer` / `ByBlock` values. The index palette is generated from its well-known structure
|
||||
//! ByLayer / ByBlock values. The index palette is generated from its well-known structure
|
||||
//! (24 hues × 5 values × 2 saturations, plus primaries and greys), not copied from any file.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
@@ -11,15 +11,12 @@ use serde::{Deserialize, Serialize};
|
||||
pub struct Rgb(pub u8, pub u8, pub u8);
|
||||
|
||||
impl Rgb {
|
||||
#[must_use]
|
||||
pub fn to_u32(self) -> u32 {
|
||||
(u32::from(self.0) << 16) | (u32::from(self.1) << 8) | u32::from(self.2)
|
||||
}
|
||||
#[must_use]
|
||||
pub fn from_u32(v: u32) -> Rgb {
|
||||
Rgb(((v >> 16) & 0xff) as u8, ((v >> 8) & 0xff) as u8, (v & 0xff) as u8)
|
||||
}
|
||||
#[must_use]
|
||||
pub fn hex(self) -> String {
|
||||
format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2)
|
||||
}
|
||||
@@ -32,7 +29,6 @@ impl Rgb {
|
||||
u32::from_str_radix(s, 16).ok().map(Rgb::from_u32)
|
||||
}
|
||||
/// Relative luminance (0..1) for contrast decisions.
|
||||
#[must_use]
|
||||
pub fn luma(self) -> f64 {
|
||||
(0.2126 * f64::from(self.0) + 0.7152 * f64::from(self.1) + 0.0722 * f64::from(self.2)) / 255.0
|
||||
}
|
||||
@@ -52,8 +48,7 @@ pub enum Color {
|
||||
|
||||
impl Color {
|
||||
pub const WHITE: Color = Color::Index(7);
|
||||
/// DXF group 62 value: 0 = `ByBlock`, 256 = `ByLayer`.
|
||||
#[must_use]
|
||||
/// DXF group 62 value: 0 = ByBlock, 256 = ByLayer.
|
||||
pub fn to_aci(self) -> i16 {
|
||||
match self {
|
||||
Color::ByLayer => 256,
|
||||
@@ -62,16 +57,14 @@ impl Color {
|
||||
Color::True(rgb) => i16::from(nearest_aci(rgb)),
|
||||
}
|
||||
}
|
||||
#[must_use]
|
||||
pub fn from_aci(v: i16) -> Color {
|
||||
match v {
|
||||
0 => Color::ByBlock,
|
||||
1..=255 => u8::try_from(v).map_or(Color::ByLayer, Color::Index),
|
||||
1..=255 => Color::Index(v as u8),
|
||||
_ => Color::ByLayer,
|
||||
}
|
||||
}
|
||||
/// Resolve to RGB given the layer and block colours.
|
||||
#[must_use]
|
||||
pub fn resolve(self, layer: Color, block: Color) -> Rgb {
|
||||
match self {
|
||||
Color::ByLayer => match layer {
|
||||
@@ -86,8 +79,7 @@ impl Color {
|
||||
Color::True(c) => c,
|
||||
}
|
||||
}
|
||||
/// Short display name like `AutoCAD`'s Properties palette ("`ByLayer`", "Red", "Color 34", "255,128,0").
|
||||
#[must_use]
|
||||
/// Short display name like AutoCAD's Properties palette ("ByLayer", "Red", "Color 34", "255,128,0").
|
||||
pub fn name(self) -> String {
|
||||
match self {
|
||||
Color::ByLayer => "ByLayer".into(),
|
||||
@@ -110,7 +102,7 @@ impl Color {
|
||||
let t = s.trim().to_ascii_lowercase();
|
||||
let named = ["", "red", "yellow", "green", "cyan", "blue", "magenta", "white"];
|
||||
if let Some(i) = named.iter().position(|n| !n.is_empty() && *n == t) {
|
||||
return u8::try_from(i).ok().map(Color::Index);
|
||||
return Some(Color::Index(i as u8));
|
||||
}
|
||||
match t.as_str() {
|
||||
"bylayer" => return Some(Color::ByLayer),
|
||||
@@ -125,7 +117,7 @@ impl Color {
|
||||
return match i {
|
||||
0 => Some(Color::ByBlock),
|
||||
256 => Some(Color::ByLayer),
|
||||
1..=255 => u8::try_from(i).ok().map(Color::Index),
|
||||
1..=255 => Some(Color::Index(i as u8)),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
@@ -153,16 +145,11 @@ pub fn aci_rgb(i: u8) -> Rgb {
|
||||
PALETTE.get(usize::from(i)).copied().unwrap_or(Rgb(255, 255, 255))
|
||||
}
|
||||
|
||||
/// The palette as a 256-entry table (entry 0 = `ByBlock` placeholder = black).
|
||||
/// The palette as a 256-entry table (entry 0 = ByBlock placeholder = black).
|
||||
pub static PALETTE: std::sync::LazyLock<[Rgb; 256]> = std::sync::LazyLock::new(build_palette);
|
||||
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "Palette channels are finite and clamped to the u8 range before conversion."
|
||||
)]
|
||||
fn build_palette() -> [Rgb; 256] {
|
||||
let mut palette = [Rgb(0, 0, 0); 256];
|
||||
let mut p = [Rgb(0, 0, 0); 256];
|
||||
let base = [
|
||||
Rgb(0, 0, 0),
|
||||
Rgb(255, 0, 0),
|
||||
@@ -172,38 +159,37 @@ fn build_palette() -> [Rgb; 256] {
|
||||
Rgb(0, 0, 255),
|
||||
Rgb(255, 0, 255),
|
||||
Rgb(255, 255, 255),
|
||||
Rgb(65, 65, 65),
|
||||
Rgb(128, 128, 128),
|
||||
Rgb(192, 192, 192),
|
||||
];
|
||||
for (slot, colour) in palette.iter_mut().zip(base) {
|
||||
*slot = colour;
|
||||
for (slot, c) in p.iter_mut().zip(base) {
|
||||
*slot = c;
|
||||
}
|
||||
let values = [255.0, 204.0, 153.0, 127.0, 76.0];
|
||||
for index in 10..250usize {
|
||||
let hue = (index - 10) / 10; // 0..24, 15° each
|
||||
let sub = index % 10;
|
||||
let value: f64 = values.get(sub / 2).copied().unwrap_or(255.0);
|
||||
for i in 10..250usize {
|
||||
let hue = (i - 10) / 10; // 0..24, 15° each
|
||||
let sub = i % 10;
|
||||
let v: f64 = values.get(sub / 2).copied().unwrap_or(255.0);
|
||||
let half = sub % 2 == 1;
|
||||
let (red, green, blue) = hue_fractions(hue);
|
||||
let channel = |fraction: f64| -> u8 {
|
||||
let fraction = if half { 0.5 + 0.5 * fraction } else { fraction };
|
||||
(value * fraction).floor().clamp(0.0, 255.0) as u8
|
||||
let (r, g, b) = hue_fractions(hue);
|
||||
let ch = |f: f64| -> u8 {
|
||||
let f = if half { 0.5 + 0.5 * f } else { f };
|
||||
(v * f).floor().clamp(0.0, 255.0) as u8
|
||||
};
|
||||
if let Some(slot) = palette.get_mut(index) {
|
||||
*slot = Rgb(channel(red), channel(green), channel(blue));
|
||||
if let Some(slot) = p.get_mut(i) {
|
||||
*slot = Rgb(ch(r), ch(g), ch(b));
|
||||
}
|
||||
}
|
||||
let greys = [51u8, 80, 105, 130, 190, 255];
|
||||
for (offset, shade) in greys.iter().enumerate() {
|
||||
if let Some(slot) = palette.get_mut(250 + offset) {
|
||||
*slot = Rgb(*shade, *shade, *shade);
|
||||
let greys = [51u8, 91, 132, 173, 214, 255];
|
||||
for (k, g) in greys.iter().enumerate() {
|
||||
if let Some(slot) = p.get_mut(250 + k) {
|
||||
*slot = Rgb(*g, *g, *g);
|
||||
}
|
||||
}
|
||||
palette
|
||||
p
|
||||
}
|
||||
|
||||
/// Channel fractions for hue step 0..24 (red → yellow → green → cyan → blue → magenta → red).
|
||||
#[expect(clippy::cast_precision_loss, reason = "Only the four hue offsets 0..=3 are converted; they are exact in f64.")]
|
||||
fn hue_fractions(h: usize) -> (f64, f64, f64) {
|
||||
let seg = h / 4;
|
||||
let t = (h % 4) as f64 / 4.0;
|
||||
@@ -218,7 +204,6 @@ fn hue_fractions(h: usize) -> (f64, f64, f64) {
|
||||
}
|
||||
|
||||
/// The closest index colour to an RGB value (1..=255).
|
||||
#[must_use]
|
||||
pub fn nearest_aci(c: Rgb) -> u8 {
|
||||
let mut best = (u32::MAX, 7u8);
|
||||
for i in 1..=255u8 {
|
||||
@@ -235,7 +220,6 @@ pub fn nearest_aci(c: Rgb) -> u8 {
|
||||
/// Display colour of `c` on `background`. Colour 7 (`aci7`) flips to contrast with the
|
||||
/// background, white on dark and black on light (paper), as CAD programs draw it; every other
|
||||
/// colour, including a true-colour or index white or black, keeps its RGB.
|
||||
#[must_use]
|
||||
pub fn display_rgb(c: Rgb, aci7: bool, background: Rgb) -> Rgb {
|
||||
if !aci7 {
|
||||
c
|
||||
@@ -302,17 +286,6 @@ mod tests {
|
||||
assert_eq!(aci_rgb(255), Rgb(255, 255, 255));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_fixed_greys() {
|
||||
assert_eq!(aci_rgb(8), Rgb(65, 65, 65));
|
||||
assert_eq!(aci_rgb(9), Rgb(128, 128, 128));
|
||||
for (i, g) in [(250u8, 51u8), (251, 80), (252, 105), (253, 130), (254, 190)] {
|
||||
assert_eq!(aci_rgb(i), Rgb(g, g, g));
|
||||
}
|
||||
assert_eq!(nearest_aci(Rgb(65, 65, 65)), 8);
|
||||
assert_eq!(nearest_aci(Rgb(128, 128, 128)), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aci_roundtrip_and_parse() {
|
||||
assert_eq!(Color::from_aci(256), Color::ByLayer);
|
||||
|
||||
@@ -72,10 +72,6 @@ pub struct Foreign {
|
||||
/// proxy objects or entities: a proxy's class number (group 91) is 500 plus its class's place
|
||||
/// here, and saving renumbers it to the written CLASSES (#1812).
|
||||
pub class_order: Vec<String>,
|
||||
/// The roles of every file handle of an object CADCraft writes itself (table records, tables,
|
||||
/// blocks, the named object dictionary and its entries), so that AutoLISP names those objects
|
||||
/// as the file did (`handent`). Saving gives them new handles; not part of [`Foreign::is_empty`].
|
||||
pub handles: BTreeMap<Handle, ForeignKey>,
|
||||
/// The file's data store section (ACDSDATA, AutoCAD 2013 and later), as read: its groups
|
||||
/// after the section name. It holds the ACIS geometry of 3D solids, regions, bodies and
|
||||
/// surfaces, which from 2013 on those entities don't carry themselves: each `ACDSRECORD`
|
||||
|
||||
+3
-13
@@ -209,22 +209,12 @@ impl Drawing {
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocate a fresh handle. It skips the handles the drawing's file gave the objects CADCraft
|
||||
/// writes itself ([`foreign::Foreign::handles`]): AutoLISP names those objects by them, and a
|
||||
/// file CADCraft wrote numbers them above its `$HANDSEED` (#495).
|
||||
/// Allocate a fresh handle.
|
||||
pub fn new_handle(&mut self) -> Handle {
|
||||
let h = self.next_handle();
|
||||
self.handseed = h.0.saturating_add(1);
|
||||
let h = Handle(self.handseed);
|
||||
self.handseed = self.handseed.saturating_add(1);
|
||||
h
|
||||
}
|
||||
/// The handle [`Drawing::new_handle`] gives out next (AutoCAD's `HANDSEED`), without taking it.
|
||||
pub fn next_handle(&self) -> Handle {
|
||||
let mut h = self.handseed;
|
||||
while self.foreign.handles.contains_key(&Handle(h)) && h < u64::MAX {
|
||||
h = h.saturating_add(1);
|
||||
}
|
||||
Handle(h)
|
||||
}
|
||||
/// Make sure future handles don't collide with `h` (after loading a file).
|
||||
pub fn bump_handseed(&mut self, h: Handle) {
|
||||
if h.0 >= self.handseed {
|
||||
|
||||
@@ -476,7 +476,6 @@ impl DimStyle {
|
||||
match field {
|
||||
"textHeight" | "tolScale" => x.is_some_and(|x| x <= 0.0),
|
||||
"scale" | "arrowSize" | "tickSize" | "fixedExtLength" => x.is_some_and(|x| x < 0.0),
|
||||
"decimals" | "altDecimals" | "tolDecimals" => x.is_some_and(|x| !(0.0..=8.0).contains(&x)),
|
||||
"fit" | "angularZeroSuppression" => x.is_some_and(|x| x > 3.0),
|
||||
"textMove" | "tolJust" | "arcSymbol" | "textFill" => x.is_some_and(|x| x > 2.0),
|
||||
"dimLineweight" | "extLineweight" => x.is_some_and(|x| !(-3.0..=211.0).contains(&x)),
|
||||
|
||||
@@ -715,17 +715,6 @@ fn space_names_its_tab() {
|
||||
assert_eq!(p.tab_name(), "Sheet A");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_handles_skip_the_files_object_handles() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let next = d.handseed;
|
||||
let f = std::sync::Arc::make_mut(&mut d.foreign);
|
||||
f.handles.insert(Handle(next), ("LAYER".into(), "0".into()));
|
||||
f.handles.insert(Handle(next + 1), ("NOD".into(), String::new()));
|
||||
assert_eq!(d.new_handle(), Handle(next + 2));
|
||||
assert_eq!(d.new_handle(), Handle(next + 3));
|
||||
}
|
||||
|
||||
/// Several spellings of one DIM field apply once, the last in the map's order, and none is rejected.
|
||||
#[test]
|
||||
fn dim_style_spellings_of_one_field_apply_once() {
|
||||
|
||||
@@ -12,7 +12,6 @@ workspace = true
|
||||
cadcraft-geom = { workspace = true }
|
||||
cadcraft-color = { workspace = true }
|
||||
cadcraft-doc = { workspace = true }
|
||||
craft-mime = { workspace = true }
|
||||
craft-dxf = { workspace = true }
|
||||
cadcraft-constraints = { workspace = true }
|
||||
cadcraft-fonts = { workspace = true }
|
||||
|
||||
@@ -8,8 +8,6 @@ mod audit;
|
||||
pub(crate) mod blocks;
|
||||
pub mod clipboard;
|
||||
pub mod constraints;
|
||||
mod dimstyle_cli;
|
||||
mod dimstyles;
|
||||
mod draw;
|
||||
mod draw2;
|
||||
mod draworder;
|
||||
@@ -36,8 +34,6 @@ mod overkill;
|
||||
mod pline_opts;
|
||||
pub mod plotters;
|
||||
mod props;
|
||||
pub use blocks::library::{clear_library_cache, list_library, read_library_file};
|
||||
pub use dimstyle_cli::usable_dim_style_name;
|
||||
pub use draw2::breakline::BreaklineOptions;
|
||||
pub use props::MatchProps;
|
||||
pub(crate) use props::UNIT_RANGES;
|
||||
@@ -190,8 +186,6 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(draw::specs());
|
||||
v.extend(draw2::specs());
|
||||
v.extend(annotate::specs());
|
||||
v.extend(dimstyles::specs());
|
||||
v.extend(dimstyle_cli::specs());
|
||||
v.extend(mleader_edit::specs());
|
||||
v.extend(annoscale::specs());
|
||||
v.extend(hatch::specs());
|
||||
|
||||
+11
-129
@@ -44,17 +44,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.alias(&["i", "-insert", "ddinsert"])
|
||||
.params("{name (\"*NAME\": exploded), file?: DXF/DWG path (defines or redefines block `name`, default the file name, from its model space; base point $INSBASE), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y] (block coordinates), attribs?: {TAG: value}, explode?: bool}")
|
||||
.interactive(|_| Ok(Box::new(InsertM::default()))),
|
||||
CommandSpec::new("blockspalette", "Blocks Palette", run_blockspalette)
|
||||
.params("{references?: bool (default true; counting reads every object)} → {blocks: [{name, description, references?}], truncated} (the app opens the Blocks palette instead)")
|
||||
.enabled(has_doc)
|
||||
.noundo(),
|
||||
CommandSpec::new("minsert", "Multiple Insert", run_minsert)
|
||||
.params("{name, file?: DXF/DWG path (as INSERT), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y], attribs?: {TAG: value}, rows?: 1..32767 (default 1), columns?: 1..32767 (default 1), rowSpacing?, columnSpacing? (along the reference's own axes, not scaled with it)}")
|
||||
.interactive(|_| Ok(Box::new(InsertM { minsert: true, ..InsertM::default() }))),
|
||||
CommandSpec::new("attdef", "Define Attributes...", run_attdef)
|
||||
.menu(&["Draw", "Block", "Define Attributes..."])
|
||||
.alias(&["att", "-attdef"])
|
||||
.params("{tag, prompt?, default?, at, height?, invisible?, justify?: L|C|R|M|TL|TC|TR|ML|MC|MR|BL|BC|BR, style? (default the current text style)}")
|
||||
.params("{tag, prompt?, default?, at, height?, invisible?}")
|
||||
.interactive(|_| Ok(Box::new(attdef::AttdefM::default()))),
|
||||
attedit::attedit_spec(),
|
||||
attedit::dash_attedit_spec(),
|
||||
@@ -96,7 +92,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.into_iter()
|
||||
.chain(attribs::attdisp_menu_specs())
|
||||
.chain(xref::specs())
|
||||
.chain(library::specs())
|
||||
.chain(refedit::specs())
|
||||
.chain(xclip::specs())
|
||||
.chain(bedit::specs())
|
||||
@@ -118,15 +113,6 @@ fn referenced_block(e: &Entity) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The attributes an object carries: a block reference's, or those of a multileader's block content.
|
||||
pub(crate) fn object_attribs(e: &Entity) -> &[Attrib] {
|
||||
match &e.kind {
|
||||
EntityKind::Insert(i) => &i.attribs,
|
||||
EntityKind::MLeader(m) => m.block.as_ref().map_or(&[][..], |b| b.attribs.as_slice()),
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any of `ents` refers to block `name`, directly or through nested block references,
|
||||
/// dimension blocks and multileader block content.
|
||||
pub(crate) fn references_block(d: &cadcraft_doc::Drawing, ents: &[Entity], name: &str) -> bool {
|
||||
@@ -360,40 +346,6 @@ fn run_block(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "block": name, "insert": r.map(|h| h.hex()) }))
|
||||
}
|
||||
|
||||
/// BLOCKSPALETTE as a JSON call: the drawing's own blocks (no anonymous, layout or xref blocks)
|
||||
/// with their descriptions and how many objects draw each (block references, dimensions and
|
||||
/// multileader block content). The app opens the palette instead.
|
||||
fn run_blockspalette(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = s.doc()?;
|
||||
let counting = bool_or(p, "references", true);
|
||||
let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
|
||||
if counting {
|
||||
let mut count = |store: &cadcraft_doc::EntityStore| {
|
||||
for e in store.iter() {
|
||||
if let Some(block) = referenced_block(e) {
|
||||
let n = counts.entry(block.to_ascii_lowercase()).or_insert(0);
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
}
|
||||
};
|
||||
count(&d.model);
|
||||
d.layouts.iter().for_each(|l| count(&l.entities));
|
||||
d.blocks.values().for_each(|b| count(&b.entities));
|
||||
}
|
||||
let (blocks, truncated) = library::library_blocks(d);
|
||||
let list: Vec<Value> = blocks
|
||||
.iter()
|
||||
.map(|b| {
|
||||
let mut block = json!({ "name": b.name, "description": b.description });
|
||||
if counting {
|
||||
block["references"] = json!(counts.get(&b.name.to_ascii_lowercase()).copied().unwrap_or(0));
|
||||
}
|
||||
block
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "blocks": list, "truncated": truncated }))
|
||||
}
|
||||
|
||||
fn run_insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
insert_json(s, p, "insert", Grid::ONE)
|
||||
}
|
||||
@@ -448,79 +400,21 @@ fn insert_json(s: &mut Session, p: &Value, cmd: &str, grid: Grid) -> Result<Valu
|
||||
Ok(attedit::with_unknown_tags(s, h, &vals, json!({ "handle": h.hex() })))
|
||||
}
|
||||
|
||||
/// The current text style (TEXTSTYLE).
|
||||
fn current_text_style(s: &Session) -> String {
|
||||
s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into())
|
||||
}
|
||||
|
||||
/// A text style's name as the table spells it, with the width factor and oblique angle an
|
||||
/// attribute definition takes from it (the renderer uses the entity's own values). `None` when
|
||||
/// the drawing has no such style.
|
||||
fn style_values(s: &Session, name: &str) -> Result<Option<(String, f64, f64)>> {
|
||||
Ok(s.doc()?.text_style(name).map(|t| (t.name.clone(), t.width_factor, t.oblique)))
|
||||
}
|
||||
|
||||
/// The current text style (TEXTSTYLE) with its width factor and oblique angle.
|
||||
fn current_style_values(s: &Session) -> (String, f64, f64) {
|
||||
let name = current_text_style(s);
|
||||
style_values(s, &name).ok().flatten().unwrap_or((name, 1.0, 0.0))
|
||||
}
|
||||
|
||||
/// A justification code as `-ATTDEF` takes it, typed or in `justify`. Align and Fit run between
|
||||
/// two baseline points; `attdef` has one, so it can't express them.
|
||||
fn attdef_justify(code: &str) -> Result<(HAlign, VAlign)> {
|
||||
let j = super::draw::justify(code.trim()).ok_or_else(|| bad("attdef", "unknown justification"))?;
|
||||
if matches!(j.0, HAlign::Aligned | HAlign::Fit) {
|
||||
return Err(bad("attdef", "Align and Fit need two points, which attdef doesn't take yet; use L, C, R, M or TL … BR"));
|
||||
}
|
||||
Ok(j)
|
||||
}
|
||||
|
||||
/// The named text style with its width factor and oblique angle, or the error both the JSON form
|
||||
/// and the typed `Style` option give for a style the drawing doesn't have.
|
||||
fn resolve_style(s: &Session, name: &str) -> Result<(String, f64, f64)> {
|
||||
style_values(s, name)?.ok_or_else(|| bad("attdef", format!("no text style \"{name}\"")))
|
||||
}
|
||||
|
||||
/// An optional string parameter: absent or null is `None`, a string is `Some`, anything else is
|
||||
/// an error rather than being ignored.
|
||||
fn opt_str_param<'a>(cmd: &str, p: &'a Value, key: &str) -> Result<Option<&'a str>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(v)) => Ok(Some(v)),
|
||||
Some(v) => Err(bad(cmd, format!("`{key}` must be a string, got {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute definition at `at` with justification `j` (as TEXT: any but Left keeps `at` as
|
||||
/// its alignment point) in text style `style`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn attdef_kind(
|
||||
tag: &str,
|
||||
prompt: &str,
|
||||
default: &str,
|
||||
at: Vec2,
|
||||
height: f64,
|
||||
invisible: bool,
|
||||
j: (HAlign, VAlign),
|
||||
style: (String, f64, f64),
|
||||
) -> EntityKind {
|
||||
let (halign, valign) = j;
|
||||
let (style, width_factor, oblique) = style;
|
||||
let left = halign == HAlign::Left && valign == VAlign::Baseline;
|
||||
fn attdef_kind(s: &Session, tag: &str, prompt: &str, default: &str, at: Vec2, height: f64, invisible: bool) -> EntityKind {
|
||||
let style = s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into());
|
||||
EntityKind::AttDef(Attrib {
|
||||
tag: tag.to_ascii_uppercase(),
|
||||
text: Text {
|
||||
insert: v3(at),
|
||||
align_pt: if left { None } else { Some(v3(at)) },
|
||||
align_pt: None,
|
||||
height,
|
||||
value: default.into(),
|
||||
rotation: 0.0,
|
||||
width_factor,
|
||||
oblique,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style,
|
||||
halign,
|
||||
valign,
|
||||
halign: HAlign::Left,
|
||||
valign: VAlign::Baseline,
|
||||
},
|
||||
invisible,
|
||||
constant: false,
|
||||
@@ -538,14 +432,7 @@ fn run_attdef(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let at = point_req("attdef", p, "at")?;
|
||||
let h = f64_or(p, "height", s.doc()?.header.f64("TEXTSIZE", 0.2));
|
||||
// Justification and text style as TEXT and MTEXT take them (#1658).
|
||||
let j = attdef_justify(opt_str_param("attdef", p, "justify")?.unwrap_or("L"))?;
|
||||
let style = match opt_str_param("attdef", p, "style")? {
|
||||
Some(n) => resolve_style(s, n)?,
|
||||
None => current_style_values(s),
|
||||
};
|
||||
let (prompt, default) = (str_param(p, "prompt").unwrap_or(tag), str_param(p, "default").unwrap_or(""));
|
||||
let k = attdef_kind(tag, prompt, default, at, h, bool_or(p, "invisible", false), j, style);
|
||||
let k = attdef_kind(s, tag, str_param(p, "prompt").unwrap_or(tag), str_param(p, "default").unwrap_or(""), at, h, bool_or(p, "invisible", false));
|
||||
Ok(json!({ "handle": s.add_entity(k)?.hex() }))
|
||||
}
|
||||
|
||||
@@ -714,7 +601,6 @@ impl BlockM {
|
||||
}
|
||||
|
||||
mod insert_file;
|
||||
pub(crate) mod library;
|
||||
pub(crate) mod xref;
|
||||
|
||||
/// Where the command-line INSERT is in its prompt sequence.
|
||||
@@ -819,9 +705,6 @@ impl InsertM {
|
||||
if self.explode {
|
||||
insert_file::explode_insert(s, h)?;
|
||||
}
|
||||
// Written here, not when the name is given: a cancelled INSERT leaves the drawing as
|
||||
// it was, so it takes no undo step that would undo nothing visible.
|
||||
s.doc_mut()?.header.set_str("INSNAME", &n);
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
@@ -877,14 +760,13 @@ impl InsertM {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
s.doc_mut()?.header.set_str("INSNAME", &b.name);
|
||||
self.name = Some(b.name.clone());
|
||||
self.stage = InsStage::Point;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Define the block from a file, then choose it; a file that can't be read is reported. The
|
||||
/// definition comes before the insertion point and stays when INSERT is then cancelled, as in
|
||||
/// AutoCAD 2027.
|
||||
/// Define the block from a file, then choose it; a file that can't be read is reported.
|
||||
fn choose_file(&mut self, s: &mut Session, f: &insert_file::FileRef) -> Result<()> {
|
||||
match f.define(s) {
|
||||
Ok(name) => self.choose(s, &name),
|
||||
|
||||
@@ -103,7 +103,6 @@ impl AttdefM {
|
||||
fn finish(&mut self, s: &mut Session, rotation: f64) -> Result<Step> {
|
||||
let (h, v) = self.justify;
|
||||
let left = h == HAlign::Left && v == VAlign::Baseline;
|
||||
let (style, width_factor, oblique) = super::resolve_style(s, &self.style)?;
|
||||
s.add_entity(EntityKind::AttDef(Attrib {
|
||||
tag: self.tag.to_uppercase(),
|
||||
text: Text {
|
||||
@@ -112,9 +111,9 @@ impl AttdefM {
|
||||
height: self.height,
|
||||
value: std::mem::take(&mut self.value),
|
||||
rotation,
|
||||
width_factor,
|
||||
oblique,
|
||||
style,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: self.style.clone(),
|
||||
halign: h,
|
||||
valign: v,
|
||||
},
|
||||
@@ -157,7 +156,7 @@ impl Interactive for AttdefM {
|
||||
Prompt::new(self.point_prompt(), Accept::POINT).kw(&["Justify", "Style"])
|
||||
}
|
||||
Ask::Point => Prompt::new(self.point_prompt(), Accept::POINT),
|
||||
Ask::Justify => crate::cmd::draw::justify_prompt(false),
|
||||
Ask::Justify => Prompt::new("Enter an option", Accept::TEXT).kw(&JUSTIFY),
|
||||
Ask::Style => Prompt::new("Enter style name", Accept::TEXT).kw(&["?"]).default(self.style.clone()),
|
||||
Ask::Height => {
|
||||
let th = s.doc().map(|d| d.header.f64("TEXTSIZE", 0.2)).unwrap_or(0.2);
|
||||
|
||||
@@ -184,10 +184,8 @@ impl Interactive for BlockreplaceM {
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
match self.stage {
|
||||
Stage::Old => Prompt::new("Enter the name of the block to replace", Accept::TEXT).kw(&["?", "Select"]).takes_block(),
|
||||
Stage::New => {
|
||||
Prompt::new(format!("Enter the name of the replacement block for {}", self.old), Accept::TEXT).kw(&["?", "Select"]).takes_block()
|
||||
}
|
||||
Stage::Old => Prompt::new("Enter the name of the block to replace", Accept::TEXT).kw(&["?", "Select"]),
|
||||
Stage::New => Prompt::new(format!("Enter the name of the replacement block for {}", self.old), Accept::TEXT).kw(&["?", "Select"]),
|
||||
Stage::Select => Prompt::new("Select a block reference", Accept::SELECT),
|
||||
Stage::Purge => Prompt::new(format!("Purge the unreferenced block definition {}?", self.old), KW).kw(&["Yes", "No"]).default("Yes"),
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! (names this drawing already has keep this drawing's definitions). The file is read through the
|
||||
//! host's io hooks like OPEN, so the engine stays I/O-agnostic.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::{Block, Drawing, Entity, EntityKind, Handle};
|
||||
@@ -14,8 +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::{referenced_block, references_block, valid_block_name};
|
||||
use super::{references_block, valid_block_name};
|
||||
use crate::cmd::{bad, str_param};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
@@ -38,7 +37,7 @@ impl FileRef {
|
||||
/// Read the file and (re)define its block. Returns the block's name.
|
||||
pub fn define(&self, s: &mut Session) -> Result<String> {
|
||||
let src = read_drawing(&self.path)?;
|
||||
define_from(s, &src, &self.name, false)
|
||||
define_from(s, &src, &self.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,11 +45,6 @@ impl FileRef {
|
||||
/// path (it has a folder separator or a .dwg/.dxf extension) that isn't the name of a block.
|
||||
pub(super) fn file_ref(s: &Session, t: &str) -> Option<FileRef> {
|
||||
let t = t.trim();
|
||||
// A block of this drawing is that block, whatever its name looks like: a name read from a file
|
||||
// must not pass for `name=path` and make INSERT read another file (CWE-74).
|
||||
if s.doc().is_ok_and(|d| d.block(t).is_some()) {
|
||||
return None;
|
||||
}
|
||||
if let Some((name, path)) = t.split_once('=') {
|
||||
let name = name.trim();
|
||||
let path = if path.trim().is_empty() { name } else { path.trim() };
|
||||
@@ -58,7 +52,7 @@ pub(super) fn file_ref(s: &Session, t: &str) -> Option<FileRef> {
|
||||
}
|
||||
let lower = t.to_ascii_lowercase();
|
||||
let pathlike = t.contains(['/', '\\']) || lower.ends_with(".dwg") || lower.ends_with(".dxf");
|
||||
if !pathlike {
|
||||
if !pathlike || s.doc().is_ok_and(|d| d.block(t).is_some()) {
|
||||
return None;
|
||||
}
|
||||
Some(FileRef { name: stem(t), path: t.to_string(), explicit: false })
|
||||
@@ -74,7 +68,7 @@ pub(super) fn stem(path: &str) -> String {
|
||||
}
|
||||
|
||||
/// Read a drawing file through the io hooks; a path without extension tries .dwg, then .dxf.
|
||||
pub(super) fn read_drawing(path: &str) -> Result<Drawing> {
|
||||
fn read_drawing(path: &str) -> Result<Drawing> {
|
||||
let hooks = io().ok_or_else(|| bad("insert", "file formats are not available in this build"))?;
|
||||
let has_ext = stem(path) != path.rsplit(['/', '\\']).next().unwrap_or(path);
|
||||
let candidates = if has_ext { vec![path.to_string()] } else { vec![path.to_string(), format!("{path}.dwg"), format!("{path}.dxf")] };
|
||||
@@ -99,29 +93,18 @@ fn read_file(_path: &str) -> Result<Vec<u8>> {
|
||||
}
|
||||
|
||||
/// (Re)define block `name` from `src`'s model space with base point `$INSBASE`, adding the
|
||||
/// layers, linetypes, styles and blocks of `src` this drawing doesn't have. With `only_needed`
|
||||
/// the layers, linetypes and styles that nothing uses are left out again, as when a block is
|
||||
/// taken from a library drawing: only what the block needs comes along. Nothing changes when the
|
||||
/// definition fails (an invalid name, or a block that would contain itself).
|
||||
pub(super) fn define_from(s: &mut Session, src: &Drawing, name: &str, only_needed: bool) -> Result<String> {
|
||||
/// layers, linetypes, styles and blocks of `src` this drawing doesn't have. Nothing changes when
|
||||
/// the definition fails (an invalid name, or a block that would contain itself).
|
||||
fn define_from(s: &mut Session, src: &Drawing, name: &str) -> Result<String> {
|
||||
if !valid_block_name(name) {
|
||||
return Err(bad("insert", format!("\"{name}\" is not a valid block name")));
|
||||
}
|
||||
let mut d = s.doc()?.clone();
|
||||
let before = TableNames::of(&d);
|
||||
// Redefining keeps the existing definition's name (block names are case-insensitive).
|
||||
let name = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(name)).cloned().unwrap_or_else(|| name.to_string());
|
||||
let own_dim_styles = names_of(&d, Kind::Dimstyles);
|
||||
merge_tables(&mut d, src);
|
||||
let mut renames = crate::cmd::merge::block_renames(&d, src, Some(&name));
|
||||
if only_needed {
|
||||
// The other blocks of the file are not copied at all.
|
||||
let need = needed_blocks(src);
|
||||
renames.retain(|from, _| need.contains(&from.to_ascii_uppercase()));
|
||||
}
|
||||
let renames = Renames::new(renames);
|
||||
rename_style_arrows(&mut d, &own_dim_styles, &renames);
|
||||
for (from, to) in &renames.exact {
|
||||
let renames = crate::cmd::merge::block_renames(&d, src, Some(&name));
|
||||
for (from, to) in &renames {
|
||||
let Some(b) = src.blocks.get(from) else { continue };
|
||||
let mut nb = (**b).clone();
|
||||
nb.name = to.clone();
|
||||
@@ -147,129 +130,10 @@ pub(super) fn define_from(s: &mut Session, src: &Drawing, name: &str, only_neede
|
||||
b.entities.push(e);
|
||||
}
|
||||
d.blocks.insert(name.clone(), Arc::new(b));
|
||||
if only_needed {
|
||||
drop_unused_new(&mut d, &before, &name);
|
||||
}
|
||||
*s.doc_mut()? = d;
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// The tables a drawing merge adds to, in an order where removing the unused entries of one
|
||||
/// frees the next (blocks free layers, layers free linetypes, dimension styles free text styles).
|
||||
const MERGED: [Kind; 8] =
|
||||
[Kind::Blocks, Kind::Dimstyles, Kind::MleaderStyles, Kind::MlineStyles, Kind::TableStyles, Kind::Layers, Kind::Linetypes, Kind::TextStyles];
|
||||
|
||||
/// The names (lower case) in one of those tables.
|
||||
fn names_of(d: &Drawing, kind: Kind) -> BTreeSet<String> {
|
||||
let lower = |it: &mut dyn Iterator<Item = &String>| it.map(|n| n.to_ascii_lowercase()).collect::<BTreeSet<String>>();
|
||||
match kind {
|
||||
Kind::Blocks => lower(&mut d.blocks.keys()),
|
||||
Kind::Dimstyles => lower(&mut d.dim_styles.iter().map(|t| &t.name)),
|
||||
Kind::MleaderStyles => lower(&mut d.mleader_styles.iter().map(|t| &t.name)),
|
||||
Kind::MlineStyles => lower(&mut d.mline_styles.iter().map(|t| &t.name)),
|
||||
Kind::TableStyles => lower(&mut d.table_styles.iter().map(|t| &t.name)),
|
||||
Kind::Layers => lower(&mut d.layers.iter().map(|t| &t.name)),
|
||||
Kind::Linetypes => lower(&mut d.linetypes.iter().map(|t| &t.name)),
|
||||
Kind::TextStyles => lower(&mut d.text_styles.iter().map(|t| &t.name)),
|
||||
_ => BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The names in the merged tables, by kind.
|
||||
struct TableNames(Vec<(Kind, BTreeSet<String>)>);
|
||||
|
||||
impl TableNames {
|
||||
fn of(d: &Drawing) -> Self {
|
||||
TableNames(MERGED.iter().map(|k| (*k, names_of(d, *k))).collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper-case names of the blocks `roots` and every block they need, through nested references,
|
||||
/// dimension blocks, multileader block content and dimension arrowheads.
|
||||
fn reachable(d: &Drawing, roots: Vec<String>) -> BTreeSet<String> {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut todo = roots;
|
||||
// Each block is walked once, so this ends, cycles included.
|
||||
while let Some(n) = todo.pop() {
|
||||
if !seen.insert(n.to_ascii_uppercase()) {
|
||||
continue;
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// Upper-case names of the blocks the model space of `src` needs: the ones it refers to, what
|
||||
/// those need, and the arrowheads of its dimension styles.
|
||||
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));
|
||||
}
|
||||
}
|
||||
for st in &src.dim_styles {
|
||||
let arrows = [&st.arrow_block, &st.arrow_block1, &st.arrow_block2, &st.leader_arrow_block];
|
||||
roots.extend(arrows.into_iter().map(|n| n.trim().to_string()).filter(|n| !n.is_empty()));
|
||||
}
|
||||
reachable(src, roots)
|
||||
}
|
||||
|
||||
/// Remove the blocks, layers, linetypes and styles that were not in the drawing `before` and that
|
||||
/// nothing uses (PURGE's scan), in an order where removing one frees the next. `keep` is the
|
||||
/// block just defined: nothing refers to it yet, so it and the blocks it needs stay. Nothing goes
|
||||
/// from a drawing too big for that scan: an unused entry stays, but a used one would be lost.
|
||||
fn drop_unused_new(d: &mut Drawing, before: &TableNames, keep: &str) {
|
||||
if !scan_reads_everything(d) {
|
||||
return;
|
||||
}
|
||||
// Removing a dimension style frees its arrowhead block, which an earlier table already
|
||||
// scanned: scan again until a pass removes nothing (a chain is never longer than the tables).
|
||||
for _ in 0..MERGED.len() {
|
||||
if !drop_unused_pass(d, before, keep) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One scan of the merged tables; `true` when it removed something.
|
||||
fn drop_unused_pass(d: &mut Drawing, before: &TableNames, keep: &str) -> bool {
|
||||
let mut removed = false;
|
||||
for (kind, old) in &before.0 {
|
||||
// Nothing was added to this table: nothing to scan for.
|
||||
if names_of(d, *kind).is_subset(old) {
|
||||
continue;
|
||||
}
|
||||
let keep_blocks = if matches!(kind, Kind::Blocks) { reachable(d, vec![keep.to_string()]) } else { BTreeSet::new() };
|
||||
let fresh: BTreeSet<String> = candidates(d, *kind)
|
||||
.into_iter()
|
||||
.filter(|n| !old.contains(&n.to_ascii_lowercase()) && !keep_blocks.contains(&n.to_ascii_uppercase()))
|
||||
.map(|n| n.to_ascii_lowercase())
|
||||
.collect();
|
||||
let gone = |name: &str| fresh.contains(&name.to_ascii_lowercase());
|
||||
removed |= !fresh.is_empty();
|
||||
match kind {
|
||||
Kind::Blocks => d.blocks.retain(|k, _| !gone(k)),
|
||||
Kind::Dimstyles => d.dim_styles.retain(|t| !gone(&t.name)),
|
||||
Kind::MleaderStyles => d.mleader_styles.retain(|t| !gone(&t.name)),
|
||||
Kind::MlineStyles => d.mline_styles.retain(|t| !gone(&t.name)),
|
||||
Kind::TableStyles => d.table_styles.retain(|t| !gone(&t.name)),
|
||||
Kind::Layers => d.layers.retain(|t| !gone(&t.name)),
|
||||
Kind::Linetypes => d.linetypes.retain(|t| !gone(&t.name)),
|
||||
Kind::TextStyles => d.text_styles.retain(|t| !gone(&t.name)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
/// Add the source's layers, linetypes and styles that this drawing doesn't have (a name that
|
||||
/// exists keeps this drawing's definition).
|
||||
fn merge_tables(d: &mut Drawing, src: &Drawing) {
|
||||
@@ -283,42 +147,9 @@ fn merge_tables(d: &mut Drawing, src: &Drawing) {
|
||||
merge(&mut d.mline_styles, &src.mline_styles, |t| &t.name);
|
||||
}
|
||||
|
||||
/// The names the copied source blocks take, found as `Drawing::block` finds a block: a reference
|
||||
/// may spell a name differently from its definition.
|
||||
struct Renames {
|
||||
exact: BTreeMap<String, String>,
|
||||
upper: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Renames {
|
||||
fn new(exact: BTreeMap<String, String>) -> Self {
|
||||
let mut upper = BTreeMap::new();
|
||||
for (from, to) in &exact {
|
||||
upper.entry(from.to_ascii_uppercase()).or_insert_with(|| to.clone());
|
||||
}
|
||||
Renames { exact, upper }
|
||||
}
|
||||
|
||||
fn get(&self, name: &str) -> Option<&String> {
|
||||
self.exact.get(name).or_else(|| self.upper.get(&name.to_ascii_uppercase()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Point the dimension styles the source brought at their renamed arrowhead blocks. The styles
|
||||
/// this drawing already had (`own`) name this drawing's blocks.
|
||||
fn rename_style_arrows(d: &mut Drawing, own: &BTreeSet<String>, renames: &Renames) {
|
||||
for st in d.dim_styles.iter_mut().filter(|t| !own.contains(&t.name.to_ascii_lowercase())) {
|
||||
for arrow in [&mut st.arrow_block, &mut st.arrow_block1, &mut st.arrow_block2, &mut st.leader_arrow_block] {
|
||||
if let Some(n) = renames.get(arrow.trim()) {
|
||||
arrow.clone_from(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 {
|
||||
fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &BTreeMap<String, String>) -> Entity {
|
||||
let mut e = e.clone();
|
||||
let old = e.handle;
|
||||
e.handle = d.new_handle();
|
||||
@@ -343,23 +174,6 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::MLeader(m) => {
|
||||
if let Some(b) = &mut m.block
|
||||
&& let Some(n) = renames.get(&b.block)
|
||||
{
|
||||
b.block = n.clone();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -420,78 +234,6 @@ mod tests {
|
||||
assert!(file_ref(&s, "BOLT").is_none());
|
||||
}
|
||||
|
||||
/// A block holding very many references still reaches every block it needs.
|
||||
#[test]
|
||||
fn a_block_of_many_references_keeps_all_it_needs() {
|
||||
let reference = |handle: u64, block: &str| {
|
||||
let insert: cadcraft_doc::Insert = serde_json::from_value(json!({ "block": block, "insert": [0, 0, 0] })).unwrap();
|
||||
Entity::new(Handle(handle), EntityKind::Insert(insert))
|
||||
};
|
||||
let mut big = Block::new("Big");
|
||||
big.entities.push(reference(0x100, "Deep"));
|
||||
for i in 0..100_001 {
|
||||
big.entities.push(reference(0x200 + i, "Leaf"));
|
||||
}
|
||||
let mut d = Drawing::default();
|
||||
d.blocks.insert("Big".into(), Arc::new(big));
|
||||
d.blocks.insert("Deep".into(), Arc::new(Block::new("Deep")));
|
||||
d.blocks.insert("Leaf".into(), Arc::new(Block::new("Leaf")));
|
||||
assert!(reachable(&d, vec!["Big".into()]).contains("DEEP"));
|
||||
}
|
||||
|
||||
/// A drawing with very many references does not lose the arrowhead of a merged dimension
|
||||
/// style: the arrowheads are the last thing PURGE's walk looks at.
|
||||
#[test]
|
||||
fn many_references_keep_a_merged_arrowhead() {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.blocks.insert("Leaf".into(), Arc::new(Block::new("Leaf")));
|
||||
for i in 0..100_001 {
|
||||
let insert: cadcraft_doc::Insert = serde_json::from_value(json!({ "block": "Leaf", "insert": [0, 0, 0] })).unwrap();
|
||||
d.model.push(Entity::new(Handle(0x200 + i), EntityKind::Insert(insert)));
|
||||
}
|
||||
let before = TableNames::of(&d);
|
||||
d.blocks.insert("Tip".into(), Arc::new(Block::new("Tip")));
|
||||
d.dim_styles.push(cadcraft_doc::DimStyle { name: "Late".into(), arrow_block: "Tip".into(), ..Default::default() });
|
||||
d.header.set_str("DIMSTYLE", "Late");
|
||||
d.blocks.insert("Merged".into(), Arc::new(Block::new("Merged")));
|
||||
drop_unused_new(&mut d, &before, "Merged");
|
||||
assert!(d.block("Tip").is_some());
|
||||
}
|
||||
|
||||
/// Past the purge scan's limit nothing is called unused: a merged block's dimension style and
|
||||
/// layer stay even when the scan never reaches its objects.
|
||||
#[test]
|
||||
fn a_drawing_too_big_for_the_scan_keeps_what_was_merged() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap();
|
||||
let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone();
|
||||
dim.common.layer = "Late".into();
|
||||
if let EntityKind::Dimension(dm) = &mut dim.kind {
|
||||
dm.style = "Late".into();
|
||||
}
|
||||
// One definition under many names: millions of objects for the scan, thousands in memory.
|
||||
let mut filler = Block::new("Filler");
|
||||
for i in 0..10_000 {
|
||||
filler.entities.push(Entity::new(Handle(0x1000 + i), dim.kind.clone()));
|
||||
}
|
||||
let filler = Arc::new(filler);
|
||||
let mut d = Drawing::new_metric();
|
||||
for i in 0..501 {
|
||||
d.blocks.insert(format!("F{i:03}"), filler.clone());
|
||||
}
|
||||
let before = TableNames::of(&d);
|
||||
assert!(!scan_reads_everything(&d));
|
||||
d.layers.push(cadcraft_doc::Layer { name: "Late".into(), ..Default::default() });
|
||||
d.dim_styles.push(cadcraft_doc::DimStyle { name: "Late".into(), ..Default::default() });
|
||||
// Sorted after every filler, so past the limit.
|
||||
let mut merged = Block::new("Z");
|
||||
merged.entities.push(dim);
|
||||
d.blocks.insert("Z".into(), Arc::new(merged));
|
||||
drop_unused_new(&mut d, &before, "Z");
|
||||
assert!(d.layers.iter().any(|l| l.name == "Late"));
|
||||
assert!(d.dim_styles.iter().any(|t| t.name == "Late"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserted_file_brings_its_mline_styles() {
|
||||
let mut src = Drawing::default();
|
||||
@@ -504,211 +246,4 @@ mod tests {
|
||||
merge_tables(&mut d, &src);
|
||||
assert_eq!(d.mline_styles.len(), before);
|
||||
}
|
||||
|
||||
/// A block reference, for the fixtures below.
|
||||
fn reference(handle: u64, block: &str) -> Entity {
|
||||
let insert: cadcraft_doc::Insert = serde_json::from_value(json!({ "block": block, "insert": [0, 0, 0] })).unwrap();
|
||||
Entity::new(Handle(handle), EntityKind::Insert(insert))
|
||||
}
|
||||
|
||||
/// An anonymous block `*U1` that its description tells apart.
|
||||
fn anonymous(description: &str) -> Arc<Block> {
|
||||
let mut b = Block::new("*U1");
|
||||
b.description = description.into();
|
||||
Arc::new(b)
|
||||
}
|
||||
|
||||
/// Takes `model`, whose `*U1` is the file's, into a drawing with a `*U1` of its own, and says
|
||||
/// which of the two the one object of block "Part" refers to.
|
||||
fn colliding_block_after_import(model: Entity) -> String {
|
||||
let mut src = Drawing::new_metric();
|
||||
src.blocks.insert("*U1".into(), anonymous("from the file"));
|
||||
src.model.push(model);
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().blocks.insert("*U1".into(), anonymous("from the drawing"));
|
||||
define_from(&mut s, &src, "Part", true).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
let part = d.block("Part").unwrap();
|
||||
let to = part.entities.iter().next().and_then(|e| referenced_block(e)).unwrap();
|
||||
d.block(&to).unwrap().description.clone()
|
||||
}
|
||||
|
||||
/// Block names are case-insensitive, so `*u1` is the file's `*U1` and takes its new name.
|
||||
#[test]
|
||||
fn a_renamed_block_is_found_whatever_the_case_of_the_reference() {
|
||||
assert_eq!(colliding_block_after_import(reference(0x500, "*u1")), "from the file");
|
||||
}
|
||||
|
||||
/// The block content of a multileader takes the new name like any other reference.
|
||||
#[test]
|
||||
fn a_multileader_follows_its_renamed_block() {
|
||||
let EntityKind::Insert(content) = reference(0x500, "*U1").kind else { return };
|
||||
let mut m: cadcraft_doc::MLeader =
|
||||
serde_json::from_value(json!({ "leaders": [], "landing": [0, 0, 0], "dogleg": 0.0, "text": null })).unwrap();
|
||||
m.block = Some(content);
|
||||
assert_eq!(colliding_block_after_import(Entity::new(Handle(0x501), EntityKind::MLeader(m))), "from the file");
|
||||
}
|
||||
|
||||
/// An arrowhead override given as a number names its block: the block comes along, and the
|
||||
/// override is left as given when the block keeps its name.
|
||||
#[test]
|
||||
fn a_numeric_arrowhead_override_brings_its_block() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap();
|
||||
let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone();
|
||||
if let EntityKind::Dimension(dm) = &mut dim.kind {
|
||||
dm.overrides.insert("DIMBLK1".into(), json!(45));
|
||||
}
|
||||
let mut src = Drawing::new_metric();
|
||||
src.blocks.insert("45".into(), Arc::new(Block::new("45")));
|
||||
src.model.push(dim);
|
||||
let mut t = Session::new();
|
||||
define_from(&mut t, &src, "Part", true).unwrap();
|
||||
let d = t.doc().unwrap();
|
||||
assert!(d.block("45").is_some());
|
||||
let e = d.block("Part").unwrap().entities.iter().next().unwrap().clone();
|
||||
let EntityKind::Dimension(dm) = &e.kind else { panic!("not a dimension") };
|
||||
assert_eq!(dm.overrides["DIMBLK1"], json!(45));
|
||||
}
|
||||
|
||||
/// Arrowheads are references too: a dimension style that came along and a dimension's override
|
||||
/// follow the renamed block, and a style this drawing already had keeps its own.
|
||||
#[test]
|
||||
fn arrowheads_follow_a_renamed_block() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap();
|
||||
let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone();
|
||||
if let EntityKind::Dimension(dm) = &mut dim.kind {
|
||||
dm.style = "Came".into();
|
||||
dm.overrides.insert("DIMBLK1".into(), json!("*U1"));
|
||||
}
|
||||
let style = |name: &str| cadcraft_doc::DimStyle { name: name.into(), arrow_block: "*U1".into(), ..Default::default() };
|
||||
let mut src = Drawing::new_metric();
|
||||
src.blocks.insert("*U1".into(), anonymous("from the file"));
|
||||
src.dim_styles.extend([style("Came"), style("Own")]);
|
||||
src.model.push(dim);
|
||||
let mut t = Session::new();
|
||||
let d = t.doc_mut().unwrap();
|
||||
d.blocks.insert("*U1".into(), anonymous("from the drawing"));
|
||||
d.dim_styles.push(style("Own"));
|
||||
define_from(&mut t, &src, "Part", true).unwrap();
|
||||
|
||||
let d = t.doc().unwrap();
|
||||
let of = |name: &str| d.block(name).unwrap().description.clone();
|
||||
let arrow = |name: &str| d.dim_styles.iter().find(|st| st.name == name).unwrap().arrow_block.clone();
|
||||
assert_eq!(of(&arrow("Came")), "from the file");
|
||||
assert_eq!(of(&arrow("Own")), "from the drawing");
|
||||
let e = d.block("Part").unwrap().entities.iter().next().unwrap().clone();
|
||||
let EntityKind::Dimension(dm) = &e.kind else { return };
|
||||
assert_eq!(of(dm.overrides["DIMBLK1"].as_str().unwrap()), "from the file");
|
||||
}
|
||||
|
||||
/// What the objects of an imported block name comes along, directly or through another table:
|
||||
/// a leader's dimension style, a dimension's text style override, the text style in a linetype,
|
||||
/// an attribute's layer and multiline text style, here on a block reference and on a
|
||||
/// multileader's block content. What nothing names stays out.
|
||||
#[test]
|
||||
fn an_import_keeps_every_style_and_layer_its_objects_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap();
|
||||
let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone();
|
||||
if let EntityKind::Dimension(dm) = &mut dim.kind {
|
||||
dm.overrides.insert("DIMTXSTY".into(), json!("InOverride"));
|
||||
}
|
||||
let attrib = |style: &str, layer: &str| {
|
||||
let mut a: cadcraft_doc::Attrib = serde_json::from_value(json!({
|
||||
"tag": "A",
|
||||
"text": { "insert": [0, 0, 0], "height": 1.0, "value": "1" },
|
||||
"multiline": { "mtext": { "insert": [0, 0, 0], "height": 1.0, "contents": "1", "style": style }, "readAs": "1" },
|
||||
}))
|
||||
.unwrap();
|
||||
a.props.layer = Some(layer.into());
|
||||
a
|
||||
};
|
||||
let mut placed = reference(0x500, "Inner");
|
||||
if let EntityKind::Insert(i) = &mut placed.kind {
|
||||
i.attribs.push(attrib("InAttribute", "OnAttribute"));
|
||||
}
|
||||
let EntityKind::Insert(mut content) = reference(0x501, "Inner").kind else { return };
|
||||
content.attribs.push(attrib("InContent", "OnContent"));
|
||||
let mut multileader: cadcraft_doc::MLeader =
|
||||
serde_json::from_value(json!({ "leaders": [], "landing": [0, 0, 0], "dogleg": 0.0, "text": null })).unwrap();
|
||||
multileader.block = Some(content);
|
||||
let leader: cadcraft_doc::Leader = serde_json::from_value(json!({ "vertices": [], "style": "ForLeader" })).unwrap();
|
||||
let line = cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(1.0, 0.0, 0.0) };
|
||||
let mut line = Entity::new(Handle(0x502), EntityKind::Line(line));
|
||||
line.common.linetype = "WithText".into();
|
||||
|
||||
let mut src = Drawing::new_metric();
|
||||
src.blocks.insert("Inner".into(), Arc::new(Block::new("Inner")));
|
||||
for name in ["InOverride", "InAttribute", "InContent", "InLinetype", "Spare"] {
|
||||
let mut t = src.text_styles[0].clone();
|
||||
t.name = name.into();
|
||||
src.text_styles.push(t);
|
||||
}
|
||||
for name in ["OnAttribute", "OnContent", "Unused"] {
|
||||
src.layers.push(cadcraft_doc::Layer { name: name.into(), ..Default::default() });
|
||||
}
|
||||
let dash = cadcraft_doc::DashElement { style: Some("InLinetype".into()), ..cadcraft_doc::DashElement::dash(1.0) };
|
||||
src.linetypes.push(cadcraft_doc::Linetype { name: "WithText".into(), description: String::new(), pattern: vec![dash] });
|
||||
src.dim_styles.push(cadcraft_doc::DimStyle { name: "ForLeader".into(), ..Default::default() });
|
||||
src.model.push(dim);
|
||||
src.model.push(placed);
|
||||
src.model.push(Entity::new(Handle(0x503), EntityKind::MLeader(multileader)));
|
||||
src.model.push(Entity::new(Handle(0x504), EntityKind::Leader(leader)));
|
||||
src.model.push(line);
|
||||
let mut t = Session::new();
|
||||
define_from(&mut t, &src, "Part", true).unwrap();
|
||||
|
||||
let d = t.doc().unwrap();
|
||||
let styles: Vec<&str> = d.text_styles.iter().map(|t| t.name.as_str()).collect();
|
||||
for name in ["InOverride", "InAttribute", "InContent", "InLinetype"] {
|
||||
assert!(styles.contains(&name), "{name}: {styles:?}");
|
||||
}
|
||||
assert!(!styles.contains(&"Spare"), "{styles:?}");
|
||||
let layers: Vec<&str> = d.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert!(layers.contains(&"OnAttribute") && layers.contains(&"OnContent"), "{layers:?}");
|
||||
assert!(!layers.contains(&"Unused"), "{layers:?}");
|
||||
assert!(d.dim_styles.iter().any(|st| st.name == "ForLeader"));
|
||||
}
|
||||
|
||||
/// The text style of a table style's cell style is in use.
|
||||
#[test]
|
||||
fn a_table_style_keeps_its_cell_styles_text_style() {
|
||||
let mut d = Drawing::new_metric();
|
||||
let mut t = d.text_styles[0].clone();
|
||||
t.name = "InCell".into();
|
||||
d.text_styles.push(t);
|
||||
let mut cell = cadcraft_doc::TableStyle::default().cell_style("Data");
|
||||
cell.text_style = "InCell".into();
|
||||
d.table_styles[0].cell_styles.push(cell);
|
||||
assert!(!candidates(&d, Kind::TextStyles).iter().any(|n| n == "InCell"));
|
||||
}
|
||||
|
||||
/// A linetype of the file stays when a dimension style that came along names it, and stays out
|
||||
/// when only a style that did not come along does.
|
||||
#[test]
|
||||
fn a_linetype_follows_the_dimension_style_that_names_it() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap();
|
||||
let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone();
|
||||
if let EntityKind::Dimension(dm) = &mut dim.kind {
|
||||
dm.style = "Used".into();
|
||||
}
|
||||
let mut src = Drawing::new_metric();
|
||||
for name in ["Kept", "Left"] {
|
||||
let mut lt = src.linetypes[0].clone();
|
||||
lt.name = name.into();
|
||||
src.linetypes.push(lt);
|
||||
}
|
||||
src.dim_styles.push(cadcraft_doc::DimStyle { name: "Used".into(), dim_linetype: "Kept".into(), ..Default::default() });
|
||||
src.dim_styles.push(cadcraft_doc::DimStyle { name: "Spare".into(), ext_linetype1: "Left".into(), ..Default::default() });
|
||||
src.model.push(dim);
|
||||
let mut t = Session::new();
|
||||
define_from(&mut t, &src, "Part", true).unwrap();
|
||||
let d = t.doc().unwrap();
|
||||
assert!(d.linetypes.iter().any(|l| l.name == "Kept"));
|
||||
assert!(!d.dim_styles.iter().any(|st| st.name == "Spare"));
|
||||
assert!(!d.linetypes.iter().any(|l| l.name == "Left"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,378 +0,0 @@
|
||||
//! Block libraries for the Blocks palette: a folder of drawings or a single drawing file whose
|
||||
//! blocks can be placed in the current drawing.
|
||||
//!
|
||||
//! BLOCKLIBRARY lists what a library holds, BLOCKLIBRARIES keeps the list of libraries the user
|
||||
//! added (in the settings folder; in memory where there is none), and BLOCKLIBIMPORT defines a
|
||||
//! library block in the current drawing so that INSERT can place it. Files are read through the
|
||||
//! host's io hooks like OPEN, so the engine stays I/O-agnostic.
|
||||
|
||||
use std::path::Path;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use cadcraft_doc::Drawing;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::insert_file::{define_from, read_drawing, stem};
|
||||
use super::valid_block_name;
|
||||
use crate::cmd::{CommandSpec, always, bad, has_doc, str_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Most drawings one folder library lists.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_FILES: usize = 2000;
|
||||
/// Most directory entries looked at in a folder library.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_SCANNED: usize = 100_000;
|
||||
/// Most blocks a palette listing holds: the rest of a hostile file's table is left out.
|
||||
const MAX_LISTED: usize = 10_000;
|
||||
/// Most libraries the list keeps.
|
||||
const MAX_LIBRARIES: usize = 64;
|
||||
/// The longest library path kept.
|
||||
const MAX_PATH_BYTES: usize = 4096;
|
||||
/// The file in the settings folder that keeps the library list, and its largest size.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const LIST_FILE: &str = "block-libraries.json";
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_LIST_BYTES: usize = 256 << 10;
|
||||
|
||||
/// How many parsed library drawings stay in memory.
|
||||
const CACHE_MAX: usize = 4;
|
||||
|
||||
/// A library drawing already read, and the file's size and time then.
|
||||
struct Cached {
|
||||
path: String,
|
||||
stamp: (u64, Option<SystemTime>),
|
||||
drawing: Arc<Drawing>,
|
||||
}
|
||||
|
||||
static CACHE: Mutex<Vec<Cached>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Forget the library drawings read so far: the next read parses each file again, even one whose
|
||||
/// size and time did not change (Refresh in the palette).
|
||||
pub fn clear_library_cache() {
|
||||
if let Ok(mut cache) = CACHE.lock() {
|
||||
cache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// The file's size and modification time; `None` where it cannot be told (nothing is kept then).
|
||||
fn stamp(path: &str) -> Option<(u64, Option<SystemTime>)> {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return None;
|
||||
}
|
||||
std::fs::metadata(path).ok().filter(std::fs::Metadata::is_file).map(|m| (m.len(), m.modified().ok()))
|
||||
}
|
||||
|
||||
/// A library drawing, read once and kept while the file is as it was: placing a block must not
|
||||
/// parse the whole file again.
|
||||
fn cached_drawing(path: &str) -> Result<Arc<Drawing>> {
|
||||
// The reader sniffs the bytes, so a DXF named `part.bin` would load: the contract is DWG/DXF by name.
|
||||
if !is_drawing(Path::new(path)) {
|
||||
return Err(bad("blocklibrary", format!("{path}: expected a DWG or DXF file")));
|
||||
}
|
||||
let now = stamp(path);
|
||||
if let Some(now) = now
|
||||
&& let Ok(cache) = CACHE.lock()
|
||||
&& let Some(hit) = cache.iter().find(|c| c.path == path && c.stamp == now)
|
||||
{
|
||||
return Ok(hit.drawing.clone());
|
||||
}
|
||||
// The palette reads previews outside a command, so a parser panic stops here too.
|
||||
let read = std::panic::catch_unwind(|| read_drawing(path));
|
||||
let drawing = Arc::new(read.unwrap_or_else(|p| Err(bad("blocklibrary", format!("{path}: {}", crate::guard::message(p.as_ref())))))?);
|
||||
if let Some(now) = now
|
||||
&& let Ok(mut cache) = CACHE.lock()
|
||||
{
|
||||
cache.retain(|c| c.path != path);
|
||||
cache.push(Cached { path: path.to_string(), stamp: now, drawing: drawing.clone() });
|
||||
while cache.len() > CACHE_MAX {
|
||||
cache.remove(0);
|
||||
}
|
||||
}
|
||||
Ok(drawing)
|
||||
}
|
||||
|
||||
/// The list where no settings folder keeps it, and the copy read from it.
|
||||
static MEMORY: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
/// The last write of the list failed: the copy in memory is newer than the file.
|
||||
static UNSAVED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// The commands the Blocks palette uses: BLOCKLIBRARY, BLOCKLIBIMPORT and BLOCKLIBRARIES.
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("blocklibrary", "Block Library", run_library)
|
||||
.params("{path: a folder of DWG/DXF files, or one such file} → {kind: \"folder\", path, files: [{name, file}], truncated} | {kind: \"file\", path, blocks: [{name, description}], truncated}")
|
||||
.enabled(always)
|
||||
.noundo(),
|
||||
CommandSpec::new("blocklibraries", "Block Libraries", run_libraries)
|
||||
.params("{op?: \"list\" (default)|\"add\"|\"remove\", path? (add, remove)} → {libraries: [path], path? (add: the entry as kept)}")
|
||||
.enabled(always)
|
||||
.noundo(),
|
||||
CommandSpec::new("blocklibimport", "Import Library Block", run_import)
|
||||
.params("{path: DWG/DXF file, block?: the block to take from it (default: the whole drawing), name?: the block to define (default: `block`, else the file name; never one the drawing already has)} → {name}")
|
||||
.enabled(has_doc),
|
||||
]
|
||||
}
|
||||
|
||||
/// A drawing file by its extension.
|
||||
fn is_drawing(p: &Path) -> bool {
|
||||
p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("dwg") || e.eq_ignore_ascii_case("dxf"))
|
||||
}
|
||||
|
||||
/// The drawings in a folder, by name: `(block name, full path)`, and whether some were left out.
|
||||
fn folder_files(dir: &Path) -> Result<(Vec<(String, String)>, bool)> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let rd = std::fs::read_dir(dir).map_err(|e| bad("blocklibrary", format!("{}: {e}", dir.display())))?;
|
||||
let entries: Vec<PathBuf> = rd.filter_map(|e| e.ok()).map(|e| e.path()).take(MAX_SCANNED.saturating_add(1)).collect();
|
||||
let mut truncated = entries.len() > MAX_SCANNED;
|
||||
let mut out: Vec<(String, String)> = entries
|
||||
.iter()
|
||||
.take(MAX_SCANNED)
|
||||
.filter(|p| is_drawing(p) && p.is_file())
|
||||
.filter_map(|p| p.to_str().map(|s| (stem(s), s.to_string())))
|
||||
.collect();
|
||||
out.sort_by_key(|(n, _)| n.to_ascii_lowercase());
|
||||
truncated |= out.len() > MAX_FILES;
|
||||
out.truncate(MAX_FILES);
|
||||
Ok((out, truncated))
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = dir;
|
||||
Err(bad("blocklibrary", "paths are not available on the web"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two library paths name the same place: letter case counts except where the file
|
||||
/// system ignores it (Windows, and macOS by default).
|
||||
fn same_path(a: &str, b: &str) -> bool {
|
||||
if cfg!(any(windows, target_os = "macos")) { a.eq_ignore_ascii_case(b) } else { a == b }
|
||||
}
|
||||
|
||||
/// Whether `path` is a folder.
|
||||
fn is_folder(path: &str) -> bool {
|
||||
!cfg!(target_arch = "wasm32") && Path::new(path).is_dir()
|
||||
}
|
||||
|
||||
/// The first `MAX_LISTED` named blocks of a library drawing by name (no generated or layout
|
||||
/// blocks, no xrefs), and whether there were more. The names are made lower case once, and only
|
||||
/// the blocks that are kept are sorted.
|
||||
pub(crate) fn library_blocks(d: &Drawing) -> (Vec<&std::sync::Arc<cadcraft_doc::Block>>, bool) {
|
||||
let mut keyed: Vec<(String, &std::sync::Arc<cadcraft_doc::Block>)> = d
|
||||
.blocks
|
||||
.values()
|
||||
.filter(|b| !b.anonymous && b.xref_path.is_none() && !b.name.starts_with('*') && !b.name.contains('|'))
|
||||
.map(|b| (b.name.to_ascii_lowercase(), b))
|
||||
.collect();
|
||||
let truncated = keyed.len() > MAX_LISTED;
|
||||
if truncated {
|
||||
keyed.select_nth_unstable_by(MAX_LISTED, |a, b| a.0.cmp(&b.0));
|
||||
keyed.truncate(MAX_LISTED);
|
||||
}
|
||||
keyed.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
(keyed.into_iter().map(|(_, b)| b).collect(), truncated)
|
||||
}
|
||||
|
||||
/// Read a library file (for the palette's previews too), kept until the file changes.
|
||||
pub fn read_library_file(path: &str) -> Result<Arc<Drawing>> {
|
||||
cached_drawing(path)
|
||||
}
|
||||
|
||||
/// What BLOCKLIBRARY answers for `path`. It needs no session, so the palette reads big drawings
|
||||
/// and slow folders on a worker thread.
|
||||
pub fn list_library(path: &str) -> Result<Value> {
|
||||
if is_folder(path) {
|
||||
let (files, truncated) = folder_files(Path::new(path))?;
|
||||
let list: Vec<Value> = files.iter().map(|(name, file)| json!({ "name": name, "file": file })).collect();
|
||||
return Ok(json!({ "kind": "folder", "path": path, "files": list, "truncated": truncated }));
|
||||
}
|
||||
let d = cached_drawing(path)?;
|
||||
let (blocks, truncated) = library_blocks(&d);
|
||||
let list: Vec<Value> = blocks.iter().map(|b| json!({ "name": b.name, "description": b.description })).collect();
|
||||
Ok(json!({ "kind": "file", "path": path, "blocks": list, "truncated": truncated }))
|
||||
}
|
||||
|
||||
/// BLOCKLIBRARY: list a folder's drawings or a drawing's blocks.
|
||||
fn run_library(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").map(str::trim).filter(|s| !s.is_empty()).ok_or_else(|| bad("blocklibrary", "`path` is required"))?;
|
||||
list_library(path)
|
||||
}
|
||||
|
||||
/// BLOCKLIBIMPORT: define a library block (or a whole drawing) in the current drawing, under a
|
||||
/// name it does not have yet.
|
||||
fn run_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").map(str::trim).filter(|s| !s.is_empty()).ok_or_else(|| bad("blocklibimport", "`path` is required"))?;
|
||||
let block = str_param(p, "block").map(str::trim).filter(|s| !s.is_empty());
|
||||
// A whole drawing is named after its file; a block of it after itself.
|
||||
let name = str_param(p, "name")
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| block.map_or_else(|| stem(path), str::to_string));
|
||||
if !valid_block_name(&name) {
|
||||
return Err(bad("blocklibimport", format!("\"{name}\" is not a valid block name")));
|
||||
}
|
||||
// A block the drawing already has is never replaced, as in the palette: its references
|
||||
// would change with it.
|
||||
if s.doc()?.block(&name).is_some() {
|
||||
return Err(bad("blocklibimport", format!("block \"{name}\" is already in the drawing")));
|
||||
}
|
||||
let mut src = (*cached_drawing(path)?).clone();
|
||||
let mut picked = None;
|
||||
if let Some(block) = block {
|
||||
let b = src.block(block).cloned().ok_or_else(|| bad("blocklibimport", format!("{path} has no block \"{block}\"")))?;
|
||||
// The block is a drawing of its own: its objects as model space and its base point as
|
||||
// $INSBASE, with the file's other blocks around it.
|
||||
src.model = b.entities.clone();
|
||||
src.header.set("INSBASE", cadcraft_doc::HVal::Point(b.base));
|
||||
picked = Some(b);
|
||||
}
|
||||
// Only the layers, linetypes and styles the block needs come along, not the whole file's.
|
||||
let name = define_from(s, &src, &name, true)?;
|
||||
// The definition is a new one: what the block says about itself still comes along.
|
||||
if let Some(from) = picked
|
||||
&& let Some(b) = s.doc_mut()?.blocks.get_mut(&name)
|
||||
{
|
||||
let b = Arc::make_mut(b);
|
||||
b.annotative = from.annotative;
|
||||
b.description.clone_from(&from.description);
|
||||
b.units = from.units;
|
||||
b.explodable = from.explodable;
|
||||
}
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// Where the library list is kept.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn list_path() -> Option<PathBuf> {
|
||||
crate::settings_dir::current().map(|d| d.join(LIST_FILE))
|
||||
}
|
||||
|
||||
/// A path the list can hold: short enough, with no control characters.
|
||||
fn acceptable(path: &str) -> bool {
|
||||
!path.is_empty() && path.len() <= MAX_PATH_BYTES && !path.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
/// The list in the settings folder. The file is hand-editable, so what it holds is checked here.
|
||||
/// `Ok(None)`: no settings folder or no file yet. `Err`: a file that is there but unreadable.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_list() -> std::result::Result<Option<Vec<String>>, String> {
|
||||
let Some(path) = list_path() else { return Ok(None) };
|
||||
if !path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let bytes = crate::capped_read::read_capped(&path, MAX_LIST_BYTES).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let list: Vec<String> = serde_json::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
Ok(Some(list.into_iter().filter(|p| acceptable(p)).take(MAX_LIBRARIES).collect()))
|
||||
}
|
||||
|
||||
/// On the web there is no settings folder: the list lives in memory only.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn read_list() -> std::result::Result<Option<Vec<String>>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The list, and why the file could not be read when it exists but is unreadable. Such a file is
|
||||
/// never written over: `run_libraries` refuses to change the list while it stays unreadable.
|
||||
fn load_list() -> (Vec<String>, Option<String>) {
|
||||
let memory = || MEMORY.lock().map(|m| m.clone()).unwrap_or_default();
|
||||
if UNSAVED.load(Ordering::Relaxed) {
|
||||
return (memory(), None);
|
||||
}
|
||||
match read_list() {
|
||||
Ok(Some(list)) => (list, None),
|
||||
Ok(None) => (memory(), None),
|
||||
Err(why) => (memory(), Some(why)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the list to `path`, its folder made if needed. `false` when it could not be written.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_list(path: &Path, list: &[String]) -> bool {
|
||||
let Ok(bytes) = serde_json::to_vec_pretty(list) else { return false };
|
||||
if let Some(dir) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
}
|
||||
crate::atomic_write::write_atomic(path, &bytes).is_ok()
|
||||
}
|
||||
|
||||
/// Keep the list in memory and write it to the settings folder.
|
||||
fn save_list(list: &[String]) {
|
||||
if let Ok(mut m) = MEMORY.lock() {
|
||||
*m = list.to_vec();
|
||||
}
|
||||
// A list that cannot be written is still kept for this session.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(p) = list_path() {
|
||||
UNSAVED.store(!write_list(&p, list), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// BLOCKLIBRARIES: list, add to or remove from the libraries.
|
||||
fn run_libraries(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (mut list, unreadable) = load_list();
|
||||
let op = str_param(p, "op").unwrap_or("list");
|
||||
if let (Some(why), "add" | "remove") = (&unreadable, op) {
|
||||
return Err(bad("blocklibraries", format!("the library list cannot be read, so it is left as it is ({why})")));
|
||||
}
|
||||
let path = str_param(p, "path").map(str::trim).filter(|s| !s.is_empty());
|
||||
match op {
|
||||
"list" => {}
|
||||
"add" => {
|
||||
let path = path.ok_or_else(|| bad("blocklibraries", "`path` is required"))?;
|
||||
let drawing = is_drawing(Path::new(path)) && Path::new(path).is_file();
|
||||
if !acceptable(path) || !(is_folder(path) || drawing) {
|
||||
return Err(bad("blocklibraries", "a library is a folder or a DWG/DXF file"));
|
||||
}
|
||||
let stored = match list.iter().find(|l| same_path(l, path)) {
|
||||
Some(l) => l.clone(),
|
||||
None => {
|
||||
if list.len() >= MAX_LIBRARIES {
|
||||
return Err(bad("blocklibraries", format!("at most {MAX_LIBRARIES} libraries")));
|
||||
}
|
||||
list.push(path.to_string());
|
||||
path.to_string()
|
||||
}
|
||||
};
|
||||
save_list(&list);
|
||||
return Ok(json!({ "libraries": list, "path": stored }));
|
||||
}
|
||||
"remove" => {
|
||||
let path = path.ok_or_else(|| bad("blocklibraries", "`path` is required"))?;
|
||||
list.retain(|l| !same_path(l, path));
|
||||
save_list(&list);
|
||||
}
|
||||
other => return Err(bad("blocklibraries", format!("unknown op \"{other}\""))),
|
||||
}
|
||||
Ok(json!({ "libraries": list }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A list that could not be written stays the list of this session, whatever the file says.
|
||||
#[test]
|
||||
fn a_failed_write_keeps_the_list_in_memory() {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-library-list-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let blocker = dir.join("a-file");
|
||||
std::fs::write(&blocker, b"x").unwrap();
|
||||
let list = vec!["C:/kept".to_string()];
|
||||
// A folder that is a file: neither the folder nor the list can be made.
|
||||
assert!(!write_list(&blocker.join("block-libraries.json"), &list));
|
||||
assert!(write_list(&dir.join("block-libraries.json"), &list));
|
||||
|
||||
*MEMORY.lock().unwrap() = list.clone();
|
||||
UNSAVED.store(true, Ordering::Relaxed);
|
||||
assert_eq!(load_list().0, list);
|
||||
UNSAVED.store(false, Ordering::Relaxed);
|
||||
MEMORY.lock().unwrap().clear();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -114,40 +114,17 @@ fn json_key(kind: Kind) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Most objects PURGE's scan reads, as the scan of used layers does.
|
||||
const MAX_SCAN: usize = 5_000_000;
|
||||
|
||||
fn all_entities(d: &Drawing) -> impl Iterator<Item = &std::sync::Arc<cadcraft_doc::Entity>> {
|
||||
d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter()))
|
||||
}
|
||||
|
||||
fn entities(d: &Drawing) -> impl Iterator<Item = &std::sync::Arc<cadcraft_doc::Entity>> {
|
||||
all_entities(d).take(MAX_SCAN)
|
||||
}
|
||||
|
||||
/// Whether the scan reads the whole drawing: past its limit, what is in use can look unused.
|
||||
pub(in crate::cmd) fn scan_reads_everything(d: &Drawing) -> bool {
|
||||
all_entities(d).nth(MAX_SCAN).is_none()
|
||||
}
|
||||
|
||||
/// Whether a dimension override sets an arrowhead block.
|
||||
pub(in crate::cmd) fn is_arrow_override(key: &str) -> bool {
|
||||
cadcraft_doc::DimStyle::field_name(key).is_some_and(|f| f.starts_with("arrowBlock") || f == "leaderArrowBlock")
|
||||
}
|
||||
|
||||
/// The name a dimension override gives a style, linetype or arrowhead block. A number names one
|
||||
/// too: DIMOVERRIDE keeps it as given, and the dimension is drawn with it as text.
|
||||
pub(in crate::cmd) fn override_name(v: &Value) -> Option<String> {
|
||||
match v {
|
||||
Value::String(n) => Some(n.trim().to_string()),
|
||||
Value::Number(n) => Some(n.to_string()),
|
||||
_ => None,
|
||||
}
|
||||
d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())).take(5_000_000)
|
||||
}
|
||||
|
||||
/// 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())
|
||||
dm.overrides
|
||||
.iter()
|
||||
.filter(|(k, _)| cadcraft_doc::DimStyle::field_name(k).is_some_and(|f| f.starts_with("arrowBlock") || f == "leaderArrowBlock"))
|
||||
.filter_map(|(_, v)| v.as_str().map(|n| n.trim().to_string()))
|
||||
.filter(|n| !n.is_empty())
|
||||
}
|
||||
|
||||
/// Upper-case names of blocks reachable from model space, the layouts and dimensions, and the
|
||||
@@ -174,9 +151,10 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet<String> {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Each block is walked once, so this ends, cycles included.
|
||||
let mut guard = 0;
|
||||
while let Some(n) = frontier.pop() {
|
||||
if !used.insert(n.to_ascii_uppercase()) {
|
||||
guard += 1;
|
||||
if guard > 100_000 || !used.insert(n.to_ascii_uppercase()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(b) = d.block(&n) {
|
||||
@@ -200,33 +178,6 @@ fn is(name: &str, list: &[&str]) -> bool {
|
||||
list.iter().any(|n| n.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The linetypes an object names besides its own: its attributes' overrides, its dimension
|
||||
/// overrides, and the copy of its style a multiline keeps.
|
||||
fn linetypes_inside(e: &cadcraft_doc::Entity) -> Vec<String> {
|
||||
let mut out: Vec<String> = super::object_attribs(e).iter().filter_map(|a| a.props.linetype.clone()).collect();
|
||||
match &e.kind {
|
||||
EntityKind::Dimension(dm) => out.extend(
|
||||
dm.overrides
|
||||
.iter()
|
||||
.filter(|(k, _)| cadcraft_doc::DimStyle::field_name(k).is_some_and(|f| matches!(f, "dimLinetype" | "extLinetype1" | "extLinetype2")))
|
||||
.filter_map(|(_, v)| override_name(v)),
|
||||
),
|
||||
EntityKind::MLine(m) => out.extend(m.def.elements.iter().map(|e| e.linetype.clone())),
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The linetypes named by objects, layers, dimension styles and multiline styles.
|
||||
fn linetypes_in_use(d: &Drawing) -> impl Iterator<Item = String> + '_ {
|
||||
let objects = entities(d).map(|e| e.common.linetype.clone());
|
||||
let inside = entities(d).flat_map(|e| linetypes_inside(e));
|
||||
let layers = d.layers.iter().map(|l| l.linetype.clone());
|
||||
let dims = d.dim_styles.iter().flat_map(|t| [t.dim_linetype.clone(), t.ext_linetype1.clone(), t.ext_linetype2.clone()]);
|
||||
let mlines = d.mline_styles.iter().flat_map(|t| t.elements.iter().map(|e| e.linetype.clone()));
|
||||
objects.chain(inside).chain(layers).chain(dims).chain(mlines)
|
||||
}
|
||||
|
||||
/// Names of the unused objects of a named kind, in table order. This is PURGE's scan; `USAGE`
|
||||
/// reads it too, without purging anything.
|
||||
pub(in crate::cmd) fn candidates(d: &Drawing, kind: Kind) -> Vec<String> {
|
||||
@@ -246,7 +197,21 @@ pub(in crate::cmd) fn candidates(d: &Drawing, kind: Kind) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
Kind::Linetypes => {
|
||||
let used = lower(&mut linetypes_in_use(d));
|
||||
// Objects and layers use linetypes, and so do dimension styles and a dimension's own
|
||||
// overrides (DIMLTYPE, DIMLTEX1, DIMLTEX2), and multiline styles' elements.
|
||||
let styles = d.dim_styles.iter().flat_map(|s| [s.dim_linetype.clone(), s.ext_linetype1.clone(), s.ext_linetype2.clone()]);
|
||||
let overrides = entities(d).filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { Some(dm) } else { None }).flat_map(|dm| {
|
||||
["dimLinetype", "extLinetype1", "extLinetype2"].into_iter().filter_map(|k| dm.overrides.get(k)?.as_str().map(str::to_string))
|
||||
});
|
||||
let mlines = d.mline_styles.iter().flat_map(|s| s.elements.iter().map(|el| el.linetype.clone()));
|
||||
let used = lower(
|
||||
&mut entities(d)
|
||||
.map(|e| e.common.linetype.clone())
|
||||
.chain(d.layers.iter().map(|l| l.linetype.clone()))
|
||||
.chain(styles)
|
||||
.chain(overrides)
|
||||
.chain(mlines),
|
||||
);
|
||||
let cur = d.header.str("CELTYPE", "ByLayer");
|
||||
d.linetypes
|
||||
.iter()
|
||||
|
||||
@@ -564,17 +564,7 @@ pub fn seg_param(s: &Segment, p: Vec2) -> f64 {
|
||||
match s {
|
||||
Segment::Line(l) => l.param_of(p).clamp(0.0, 1.0),
|
||||
Segment::Arc { arc, ccw } => {
|
||||
// A point just outside the sweep (on the arc within tolerance of an end) goes to the
|
||||
// nearer end: a hair before the start is the start, not round the circle to the end.
|
||||
let a = cadcraft_geom::norm_angle(arc.center.angle_to(p) - arc.start);
|
||||
let sweep = arc.sweep().max(1e-15);
|
||||
let t = if a <= sweep {
|
||||
a / sweep
|
||||
} else if a - sweep < TAU - a {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let t = (cadcraft_geom::norm_angle(arc.center.angle_to(p) - arc.start) / arc.sweep().max(1e-15)).clamp(0.0, 1.0);
|
||||
if *ccw { t } else { 1.0 - t }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,509 +0,0 @@
|
||||
//! -DIMSTYLE, dimension styles at the command line (scripts, the keyboard): save the current
|
||||
//! settings as a style (annotative or not), make a style current, list the current settings or
|
||||
//! a style's or a dimension's, compare a style with the current one, give the current settings
|
||||
//! to dimensions, list the styles. Also `dimstyle.overrides`, which sets the current style's
|
||||
//! overrides (what the Dimension Style Manager's Override edits), in one undo step.
|
||||
|
||||
use cadcraft_doc::{DimStyle, Drawing, EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::machines::{SelOutcome, SelectPhase};
|
||||
use super::{CommandSpec, bad, bool_or, curves, str_param, targets};
|
||||
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
const CMD: &str = "-dimstyle";
|
||||
|
||||
fn other(m: impl Into<String>) -> EngineError {
|
||||
EngineError::Other(m.into())
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("-dimstyle", "Dimension Style", run)
|
||||
.params(
|
||||
"{option: save | annotative | restore | status | variables | apply | list, name?, handle?, handles?, replace?: bool, pattern?} \
|
||||
→ save (annotative: an annotative style): the current settings (style and its overrides) as style `name`, made current \
|
||||
(`replace` redefines one); restore: style `name` (or dimension `handle`'s style) made current; status: {variables} of the \
|
||||
current settings; variables: {variables} of style `name` or dimension `handle`; apply: the current settings given to \
|
||||
`handles` (default: the selection); list: {styles} matching `pattern` (*, ? and #)",
|
||||
)
|
||||
.interactive(|_| Ok(Box::new(DashDimStyle::default()))),
|
||||
CommandSpec::new("dimstyle.overrides", "Dimension Style Overrides", run_overrides).params(
|
||||
"{<style fields or DIM* variables: values>, clear?: bool} → {overrides} (the current style's overrides, which new \
|
||||
dimensions take; `clear` drops them all first)",
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// What new dimensions are drawn with: the current style with its overrides.
|
||||
fn current_settings(d: &Drawing) -> DimStyle {
|
||||
let name = d.header.str("DIMSTYLE", "Standard");
|
||||
let mut st = d.dim_style(&name).cloned().unwrap_or_default().with_overrides(&d.dim_overrides());
|
||||
st.name = name;
|
||||
st
|
||||
}
|
||||
|
||||
/// A style's variables (DIM* name → value) as `dimstyle.list` reports them.
|
||||
fn variables(st: &DimStyle) -> serde_json::Map<String, Value> {
|
||||
let v = serde_json::to_value(st).unwrap_or(Value::Null);
|
||||
cadcraft_doc::DIMVARS.iter().filter_map(|(var, field)| v.get(*field).map(|x| ((*var).to_string(), x.clone()))).collect()
|
||||
}
|
||||
|
||||
/// A variable's value as the command line shows it.
|
||||
fn shown(v: &Value) -> String {
|
||||
if v.is_object()
|
||||
&& let Ok(c) = serde_json::from_value::<cadcraft_color::Color>(v.clone())
|
||||
{
|
||||
return c.name();
|
||||
}
|
||||
match v {
|
||||
Value::String(s) if s.is_empty() => "\"\"".into(),
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Bool(b) => (if *b { "On" } else { "Off" }).into(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// One line per variable: name, value and what it is.
|
||||
fn listing(vars: &serde_json::Map<String, Value>) -> Vec<String> {
|
||||
cadcraft_doc::DIMVARS
|
||||
.iter()
|
||||
.filter_map(|(var, field)| {
|
||||
let v = vars.get(*var)?;
|
||||
let label = crate::properties::dim_prop(field).map_or(*field, |p| p.label);
|
||||
Some(format!("{var:<10} {:<20} {label}", shown(v)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The variables of `b` that differ from `a`'s: (name, a's value, b's value).
|
||||
fn differences(a: &DimStyle, b: &DimStyle) -> Vec<(String, Value, Value)> {
|
||||
let (va, vb) = (variables(a), variables(b));
|
||||
cadcraft_doc::DIMVARS
|
||||
.iter()
|
||||
.filter_map(|(var, _)| {
|
||||
let (x, y) = (va.get(*var)?, vb.get(*var)?);
|
||||
(x != y).then(|| ((*var).to_string(), x.clone(), y.clone()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `name` against a pattern with `*` (any run), `?` (any character) and `#` (a digit), ignoring
|
||||
/// case: QSELECT's matcher, which takes time in proportion to the lengths (a pattern that backs
|
||||
/// up at every `*` can't hang the command).
|
||||
fn matches(pattern: &str, name: &str) -> bool {
|
||||
let p = pattern.trim();
|
||||
p.is_empty() || super::qselect::wildcard(p, name)
|
||||
}
|
||||
|
||||
fn styles_matching(d: &Drawing, pattern: &str) -> Vec<String> {
|
||||
d.dim_styles.iter().filter(|s| matches(pattern, &s.name)).map(|s| s.name.clone()).collect()
|
||||
}
|
||||
|
||||
/// A usable dimension style name, trimmed: for -DIMSTYLE and `dimstyle.saveas` alike. No `~`,
|
||||
/// which Restore reads as "compare with".
|
||||
pub(super) fn check_name(name: &str) -> Result<String> {
|
||||
let name = name.trim();
|
||||
if !usable_dim_style_name(name) {
|
||||
return Err(bad(CMD, "bad style name"));
|
||||
}
|
||||
Ok(name.to_string())
|
||||
}
|
||||
|
||||
/// Whether `name` (trimmed) is one a new dimension style can have: what -DIMSTYLE,
|
||||
/// `dimstyle.saveas`, `dimstyle` and `dimstyle.rename` take, for dialogs to check before OK.
|
||||
pub fn usable_dim_style_name(name: &str) -> bool {
|
||||
let name = name.trim();
|
||||
!(name.is_empty() || name.len() > 255 || name.contains(['<', '>', '/', '\\', '"', ':', ';', '?', '*', '|', ',', '=', '`', '~']))
|
||||
}
|
||||
|
||||
/// Save the current settings as style `name` and make it current.
|
||||
fn save(s: &mut Session, name: &str, annotative: Option<bool>, replace: bool) -> Result<Value> {
|
||||
let name = check_name(name)?;
|
||||
// Refused before the drawing is touched: a failed call leaves no (empty) undo step.
|
||||
if !replace && s.doc()?.dim_style(&name).is_some() {
|
||||
return Err(bad(CMD, format!("a dimension style `{name}` already exists")));
|
||||
}
|
||||
let d = s.doc_mut()?;
|
||||
let mut st = current_settings(d);
|
||||
if let Some(a) = annotative {
|
||||
st.annotative = a;
|
||||
}
|
||||
let name = match d.dim_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
|
||||
Some(existing) if replace => {
|
||||
let kept = existing.name.clone();
|
||||
*existing = DimStyle { name: kept.clone(), ..st };
|
||||
kept
|
||||
}
|
||||
Some(_) => return Err(bad(CMD, format!("a dimension style `{name}` already exists"))),
|
||||
None => {
|
||||
d.dim_styles.push(DimStyle { name: name.clone(), ..st });
|
||||
name
|
||||
}
|
||||
};
|
||||
d.header.set_str("DIMSTYLE", &name);
|
||||
d.sync_dim_vars();
|
||||
// A redefined style redraws the dimensions that use it.
|
||||
super::props::regen_dims(d, |dm| dm.style.eq_ignore_ascii_case(&name))?;
|
||||
Ok(json!({ "style": name }))
|
||||
}
|
||||
|
||||
/// Make style `name` current (its overrides go).
|
||||
fn restore(s: &mut Session, name: &str) -> Result<Value> {
|
||||
let n = s.doc()?.dim_style(name).map(|t| t.name.clone()).ok_or_else(|| bad(CMD, format!("no dimension style `{name}`")))?;
|
||||
let d = s.doc_mut()?;
|
||||
d.header.set_str("DIMSTYLE", &n);
|
||||
d.sync_dim_vars();
|
||||
Ok(json!({ "current": n }))
|
||||
}
|
||||
|
||||
/// Give dimensions the current settings: the current style and its overrides.
|
||||
fn apply(s: &mut Session, hs: &[Handle]) -> Result<Value> {
|
||||
// The dimensions among them, found before the drawing is touched: none leaves no undo step.
|
||||
let d = s.doc()?;
|
||||
let dims: Vec<Handle> = hs.iter().copied().filter(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Dimension(_)))).collect();
|
||||
if dims.is_empty() {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
let d = s.doc_mut()?;
|
||||
let style = d.header.str("DIMSTYLE", "Standard");
|
||||
let overrides = d.dim_overrides();
|
||||
let mut n = 0;
|
||||
for h in dims {
|
||||
d.modify_entity(h, |e| {
|
||||
if let EntityKind::Dimension(dm) = &mut e.kind {
|
||||
dm.style.clone_from(&style);
|
||||
dm.overrides.clone_from(&overrides);
|
||||
dm.block = None;
|
||||
n += 1;
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "changed": n }))
|
||||
}
|
||||
|
||||
/// The style and effective settings of dimension `h`.
|
||||
fn dimension_settings(s: &Session, h: Handle) -> Result<DimStyle> {
|
||||
let d = s.doc()?;
|
||||
match d.entity(h).map(|e| &e.kind) {
|
||||
Some(EntityKind::Dimension(dm)) => Ok(d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides)),
|
||||
_ => Err(bad(CMD, "not a dimension")),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_param(p: &Value) -> Option<Handle> {
|
||||
p.get("handle").and_then(|v| v.as_str().and_then(Handle::parse_hex).or_else(|| v.as_u64().map(Handle)))
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let option = str_param(p, "option").unwrap_or("restore").trim().to_ascii_lowercase();
|
||||
match option.as_str() {
|
||||
"save" | "annotative" => {
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string();
|
||||
let anno = if option == "annotative" { Some(true) } else { p.get("annotative").and_then(Value::as_bool) };
|
||||
save(s, &name, anno, bool_or(p, "replace", false))
|
||||
}
|
||||
"restore" => match handle_param(p) {
|
||||
Some(h) => {
|
||||
let name = dimension_settings(s, h)?.name;
|
||||
restore(s, &name)
|
||||
}
|
||||
None => restore(s, str_param(p, "name").ok_or_else(|| bad(CMD, "`name` or `handle` is required"))?),
|
||||
},
|
||||
"status" => Ok(json!({ "variables": variables(¤t_settings(s.doc()?)) })),
|
||||
"variables" => {
|
||||
let st = match handle_param(p) {
|
||||
Some(h) => dimension_settings(s, h)?,
|
||||
None => {
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(CMD, "`name` or `handle` is required"))?;
|
||||
s.doc()?.dim_style(name).cloned().ok_or_else(|| bad(CMD, format!("no dimension style `{name}`")))?
|
||||
}
|
||||
};
|
||||
Ok(json!({ "style": st.name, "variables": variables(&st) }))
|
||||
}
|
||||
"apply" => {
|
||||
let hs = targets(s, p)?;
|
||||
apply(s, &hs)
|
||||
}
|
||||
"list" | "?" => Ok(json!({ "styles": styles_matching(s.doc()?, str_param(p, "pattern").unwrap_or("*")) })),
|
||||
_ => Err(bad(CMD, "`option` is save, annotative, restore, status, variables, apply or list")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `dimstyle.overrides`: set the current style's overrides (the header DIM* variables).
|
||||
fn run_overrides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let clear = bool_or(p, "clear", false);
|
||||
let mut given = serde_json::Map::new();
|
||||
for (k, v) in p.as_object().into_iter().flatten() {
|
||||
if k == "clear" {
|
||||
continue;
|
||||
}
|
||||
let field = DimStyle::field_name(k)
|
||||
.filter(|f| !matches!(*f, "name" | "annotative"))
|
||||
.ok_or_else(|| bad("dimstyle.overrides", format!("`{k}` is not a dimension variable")))?;
|
||||
given.insert(field.to_string(), v.clone());
|
||||
}
|
||||
// Checked first (against the style alone when its overrides go), so nothing changes when
|
||||
// one value is unusable: a command's error doesn't undo what it did.
|
||||
let d = s.doc()?;
|
||||
let mut base = current_settings(d);
|
||||
if clear {
|
||||
base = d.dim_style(&base.name).cloned().unwrap_or_default();
|
||||
}
|
||||
let rejected = base.apply_fields(&given);
|
||||
if !rejected.is_empty() {
|
||||
return Err(bad("dimstyle.overrides", format!("unusable values for {}", rejected.join(", "))));
|
||||
}
|
||||
// The values as the style took them (a lineweight named ByLayer is -1, ...): what the
|
||||
// header variables hold, so writing them can't fail halfway.
|
||||
let taken = serde_json::to_value(&base).unwrap_or(Value::Null);
|
||||
if clear {
|
||||
s.doc_mut()?.sync_dim_vars();
|
||||
}
|
||||
for (field, v) in &given {
|
||||
let Some((var, _)) = cadcraft_doc::DIMVARS.iter().find(|(_, f)| f == field) else { continue };
|
||||
let v = taken.get(field.as_str()).unwrap_or(v);
|
||||
// Colors are stored as color numbers in the header.
|
||||
let v = match serde_json::from_value::<cadcraft_color::Color>(v.clone()).ok().or_else(|| v.as_str().and_then(cadcraft_color::Color::parse)) {
|
||||
Some(c) if field.ends_with("Color") => json!(c.to_aci()),
|
||||
_ => v.clone(),
|
||||
};
|
||||
crate::sysvars::set(s, var, &v)?;
|
||||
}
|
||||
Ok(json!({ "overrides": s.doc()?.dim_overrides() }))
|
||||
}
|
||||
|
||||
/// What -DIMSTYLE asks next.
|
||||
#[derive(Clone, Default)]
|
||||
enum Ask {
|
||||
#[default]
|
||||
Option,
|
||||
Annotative,
|
||||
SaveName {
|
||||
annotative: Option<bool>,
|
||||
},
|
||||
Redefine {
|
||||
name: String,
|
||||
annotative: Option<bool>,
|
||||
},
|
||||
RestoreName,
|
||||
RestorePick,
|
||||
VariablesName,
|
||||
VariablesPick,
|
||||
Apply,
|
||||
ListPattern,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DashDimStyle {
|
||||
ask: Ask,
|
||||
sel: SelectPhase,
|
||||
}
|
||||
|
||||
impl DashDimStyle {
|
||||
fn list(&self, s: &mut Session, pattern: &str) -> Result<()> {
|
||||
let names = styles_matching(s.doc()?, pattern);
|
||||
s.echo(format!("Named dimension styles: {}", if names.is_empty() { "none".into() } else { names.join(", ") }));
|
||||
Ok(())
|
||||
}
|
||||
fn show_variables(&self, s: &mut Session, st: &DimStyle) {
|
||||
s.echo(format!("Dimension style: {}", st.name));
|
||||
for line in listing(&variables(st)) {
|
||||
s.echo(line);
|
||||
}
|
||||
}
|
||||
fn answer(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
let ask = std::mem::take(&mut self.ask);
|
||||
let text = match &i {
|
||||
Input::Text(t) | Input::Keyword(t) => Some(t.trim().to_string()),
|
||||
_ => None,
|
||||
};
|
||||
match ask {
|
||||
Ask::Option => {
|
||||
let k = text.unwrap_or_else(|| "Restore".into());
|
||||
self.ask = match k.to_ascii_lowercase().as_str() {
|
||||
"annotative" | "an" => Ask::Annotative,
|
||||
"save" | "s" => Ask::SaveName { annotative: None },
|
||||
"restore" | "r" | "" => Ask::RestoreName,
|
||||
"status" | "st" => {
|
||||
let st = current_settings(s.doc()?);
|
||||
self.show_variables(s, &st);
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
"variables" | "v" => Ask::VariablesName,
|
||||
"apply" | "a" => Ask::Apply,
|
||||
"?" => Ask::ListPattern,
|
||||
_ => return Err(other("Enter one of the options.")),
|
||||
};
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Ask::Annotative => {
|
||||
let yes = !matches!(text.as_deref().map(str::to_ascii_lowercase).as_deref(), Some("no" | "n"));
|
||||
self.ask = Ask::SaveName { annotative: Some(yes) };
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Ask::SaveName { annotative } => match text.as_deref() {
|
||||
None | Some("") => Ok(Step::Done),
|
||||
Some("?") => {
|
||||
self.list(s, "*")?;
|
||||
self.ask = Ask::SaveName { annotative };
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Some(name) => {
|
||||
let name = match check_name(name) {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
self.ask = Ask::SaveName { annotative };
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
if s.doc()?.dim_style(&name).is_some() {
|
||||
self.ask = Ask::Redefine { name, annotative };
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
save(s, &name, annotative, false)?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
},
|
||||
Ask::Redefine { name, annotative } => {
|
||||
if matches!(text.as_deref().map(str::to_ascii_lowercase).as_deref(), Some("yes" | "y")) {
|
||||
save(s, &name, annotative, true)?;
|
||||
Ok(Step::Done)
|
||||
} else {
|
||||
self.ask = Ask::SaveName { annotative };
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
}
|
||||
Ask::RestoreName => match text.as_deref() {
|
||||
None | Some("") => {
|
||||
self.ask = Ask::RestorePick;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Some("?") => {
|
||||
self.list(s, "*")?;
|
||||
self.ask = Ask::RestoreName;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
// ~name: how style `name` differs from the current settings.
|
||||
Some(t) if t.starts_with('~') => {
|
||||
let d = s.doc()?;
|
||||
let other_style = d.dim_style(t.trim_start_matches('~').trim()).cloned().ok_or_else(|| other("No such dimension style."))?;
|
||||
let current = current_settings(d);
|
||||
let diff = differences(¤t, &other_style);
|
||||
s.echo(format!("Differences between {} and current settings:", other_style.name));
|
||||
if diff.is_empty() {
|
||||
s.echo("None".to_string());
|
||||
}
|
||||
for (var, cur, theirs) in diff {
|
||||
s.echo(format!("{var:<10} {:<20} {}", shown(&theirs), shown(&cur)));
|
||||
}
|
||||
self.ask = Ask::RestoreName;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Some(name) => {
|
||||
if let Err(e) = restore(s, name) {
|
||||
self.ask = Ask::RestoreName;
|
||||
return Err(e);
|
||||
}
|
||||
Ok(Step::Done)
|
||||
}
|
||||
},
|
||||
Ask::RestorePick | Ask::VariablesPick => {
|
||||
let restoring = matches!(ask, Ask::RestorePick);
|
||||
let Input::Point(p) = i else {
|
||||
if matches!(i, Input::Enter) {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
// Anything else asks for the dimension again.
|
||||
self.ask = ask;
|
||||
return Ok(Step::Continue);
|
||||
};
|
||||
let picked = curves::pick_at(s, p).and_then(|h| dimension_settings(s, h).ok());
|
||||
let Some(st) = picked else {
|
||||
self.ask = if restoring { Ask::RestorePick } else { Ask::VariablesPick };
|
||||
return Err(other("Select a dimension."));
|
||||
};
|
||||
if restoring {
|
||||
restore(s, &st.name)?;
|
||||
} else {
|
||||
self.show_variables(s, &st);
|
||||
}
|
||||
Ok(Step::Done)
|
||||
}
|
||||
Ask::VariablesName => match text.as_deref() {
|
||||
None | Some("") => {
|
||||
self.ask = Ask::VariablesPick;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Some("?") => {
|
||||
self.list(s, "*")?;
|
||||
self.ask = Ask::VariablesName;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Some(name) => {
|
||||
let Some(st) = s.doc()?.dim_style(name).cloned() else {
|
||||
self.ask = Ask::VariablesName;
|
||||
return Err(other("No such dimension style."));
|
||||
};
|
||||
self.show_variables(s, &st);
|
||||
Ok(Step::Done)
|
||||
}
|
||||
},
|
||||
Ask::Apply => match self.sel.feed(s, &i)? {
|
||||
SelOutcome::More => {
|
||||
self.ask = Ask::Apply;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
SelOutcome::Empty => Ok(Step::Done),
|
||||
SelOutcome::Done(hs) => {
|
||||
let r = apply(s, &hs)?;
|
||||
s.echo(format!("{} dimension(s) take the current settings.", r["changed"]));
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
},
|
||||
Ask::ListPattern => {
|
||||
self.list(s, text.as_deref().filter(|t| !t.is_empty()).unwrap_or("*"))?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Interactive for DashDimStyle {
|
||||
fn name(&self) -> &'static str {
|
||||
"-DIMSTYLE"
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
let d = s.doc()?;
|
||||
let current = d.header.str("DIMSTYLE", "Standard");
|
||||
let annotative = d.dim_style(¤t).is_some_and(|st| st.annotative);
|
||||
let overridden = if d.dim_overrides().is_empty() { "" } else { " (with overrides)" };
|
||||
s.echo(format!("Current dimension style: {current}{overridden} Annotative: {}", if annotative { "Yes" } else { "No" }));
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
match &self.ask {
|
||||
Ask::Option => Prompt::new("Enter a dimension style option", curves::KW)
|
||||
.kw(&["ANnotative", "Save", "Restore", "STatus", "Variables", "Apply", "?"])
|
||||
.default("Restore"),
|
||||
Ask::Annotative => Prompt::new("Create annotative dimension style", curves::KW).kw(&["Yes", "No"]).default("Yes"),
|
||||
Ask::SaveName { .. } => Prompt::new("Enter name for new dimension style or [?]", Accept::TEXT).kw(&["?"]),
|
||||
Ask::Redefine { .. } => Prompt::new("That name is already in use, redefine it?", curves::KW).kw(&["Yes", "No"]).default("No"),
|
||||
Ask::RestoreName => Prompt::new("Enter a dimension style name, [?] or <select dimension>", Accept::TEXT).kw(&["?"]),
|
||||
Ask::RestorePick | Ask::VariablesPick => Prompt::new("Select dimension", Accept::POINT),
|
||||
Ask::VariablesName => Prompt::new("Enter a dimension style name, [?] or <select dimensions>", Accept::TEXT).kw(&["?"]),
|
||||
Ask::Apply => self.sel.prompt(),
|
||||
Ask::ListPattern => Prompt::new("Enter dimension style(s) to list", Accept::TEXT).default("*"),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
// A refused answer asks the same question again.
|
||||
let asked = self.ask.clone();
|
||||
let r = self.answer(s, i);
|
||||
if r.is_err() {
|
||||
self.ask = asked;
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
//! Dimension style commands of the dimension shortcut menu: Remove Style Overrides (DIMOVERRIDE
|
||||
//! Clear for the selected dimensions) and Save as New Style (a style made of a dimension's
|
||||
//! settings, its overrides included, which the dimension then uses).
|
||||
|
||||
use cadcraft_doc::{DimStyle, EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::machines::SelectRun;
|
||||
use super::{CommandSpec, bad, curves, str_param, targets};
|
||||
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
fn other(m: impl Into<String>) -> EngineError {
|
||||
EngineError::Other(m.into())
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("dimoverride.clear", "Remove Style Overrides", run_clear)
|
||||
.params("{handles?} (dimensions; they draw with their style's settings again) → {changed}")
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("dimoverride.clear", "DIMOVERRIDE")))),
|
||||
CommandSpec::new("dimstyle.saveas", "Save as New Style...", run_save_as)
|
||||
.params(
|
||||
"{handle? (default: the first selected dimension), name} → {style, handle} (a new dimension style with the dimension's \
|
||||
settings, overrides included; the dimension takes it and its overrides are cleared; the current style is unchanged)",
|
||||
)
|
||||
.interactive(|_| Ok(Box::new(SaveAsM::default()))),
|
||||
]
|
||||
}
|
||||
|
||||
fn run_clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hs: Vec<String> = targets(s, p)?.iter().map(|h| h.hex()).collect();
|
||||
super::props::dim_override(s, &json!({ "handles": hs, "clear": true }))
|
||||
}
|
||||
|
||||
fn is_dim(s: &Session, h: Handle) -> bool {
|
||||
s.doc().ok().and_then(|d| d.entity(h)).is_some_and(|e| matches!(e.kind, EntityKind::Dimension(_)))
|
||||
}
|
||||
|
||||
/// A usable new dimension style name (as -DIMSTYLE takes one).
|
||||
fn new_name(s: &Session, name: &str) -> Result<String> {
|
||||
let name = super::dimstyle_cli::check_name(name).map_err(|_| bad("dimstyle.saveas", "bad style name"))?;
|
||||
if s.doc()?.dim_style(&name).is_some() {
|
||||
return Err(bad("dimstyle.saveas", format!("a dimension style `{name}` already exists")));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// Make style `name` from dimension `h`'s settings and give it to the dimension.
|
||||
fn save_as(s: &mut Session, h: Handle, name: &str) -> Result<Value> {
|
||||
let name = new_name(s, name)?;
|
||||
let d = s.doc_mut()?;
|
||||
let Some(EntityKind::Dimension(dm)) = d.entity(h).map(|e| e.kind.clone()) else { return Err(bad("dimstyle.saveas", "not a dimension")) };
|
||||
let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
|
||||
d.dim_styles.push(DimStyle { name: name.clone(), ..st });
|
||||
d.modify_entity(h, |e| {
|
||||
if let EntityKind::Dimension(dm) = &mut e.kind {
|
||||
dm.style.clone_from(&name);
|
||||
dm.overrides.clear();
|
||||
dm.block = None;
|
||||
}
|
||||
})?;
|
||||
Ok(json!({ "style": name, "handle": h.hex() }))
|
||||
}
|
||||
|
||||
fn run_save_as(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_param(p, "name").ok_or_else(|| bad("dimstyle.saveas", "`name` is required"))?.to_string();
|
||||
let hs = targets(s, p)?;
|
||||
let h = hs.into_iter().find(|h| is_dim(s, *h)).ok_or_else(|| bad("dimstyle.saveas", "select a dimension"))?;
|
||||
save_as(s, h, &name)
|
||||
}
|
||||
|
||||
/// Save as New Style: the selected dimension (or one picked), then the new style's name.
|
||||
#[derive(Default)]
|
||||
struct SaveAsM {
|
||||
dim: Option<Handle>,
|
||||
}
|
||||
|
||||
impl Interactive for SaveAsM {
|
||||
fn name(&self) -> &'static str {
|
||||
"DIMSTYLE"
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.dim = s.selection().into_iter().find(|h| is_dim(s, *h));
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
match self.dim {
|
||||
None => Prompt::new("Select a dimension", Accept::POINT),
|
||||
Some(_) => Prompt::new("Enter name of new dimension style", Accept::TEXT),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match (self.dim, i) {
|
||||
(None, Input::Point(p)) => {
|
||||
let h = curves::pick_at(s, p).filter(|h| is_dim(s, *h)).ok_or_else(|| other("Select a dimension."))?;
|
||||
self.dim = Some(h);
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Some(h), Input::Text(t) | Input::Keyword(t)) => {
|
||||
let r = save_as(s, h, &t)?;
|
||||
s.echo(format!("Dimension style {} created from the dimension.", r["style"].as_str().unwrap_or_default()));
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(_, Input::Enter) => Ok(Step::Done),
|
||||
_ => Ok(Step::Continue),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,9 +33,8 @@ use point::{DonutM, PointM, RayM, run_donut, run_point, run_ray};
|
||||
use polygon::{PolygonM, run_polygon};
|
||||
use solid::{SolidM, run_solid};
|
||||
use spline::{SplineM, run_spline};
|
||||
|
||||
pub(crate) use text::justify;
|
||||
use text::{MTextM, TextM, run_mtext, run_text};
|
||||
pub(crate) use text::{justify, justify_prompt};
|
||||
|
||||
/// Every draw command's spec: JSON parameters, menu path, aliases and the interactive prompt
|
||||
/// machine each command starts.
|
||||
|
||||
@@ -25,16 +25,6 @@ pub(crate) fn justify(j: &str) -> Option<(HAlign, VAlign)> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The justification options TEXT offers, in prompt order.
|
||||
const JUSTIFY_OPTIONS: [&str; 15] = ["Left", "Center", "Right", "Align", "Middle", "Fit", "TL", "TC", "TR", "ML", "MC", "MR", "BL", "BC", "BR"];
|
||||
|
||||
/// The prompt for a justification option. Align and Fit run between two baseline points, so a
|
||||
/// command that takes one point (`-ATTDEF`) passes `two_points: false` and doesn't list them.
|
||||
pub(crate) fn justify_prompt(two_points: bool) -> Prompt {
|
||||
let options: Vec<&str> = JUSTIFY_OPTIONS.into_iter().filter(|o| two_points || !matches!(*o, "Align" | "Fit")).collect();
|
||||
Prompt::new("Enter an option", Accept::TEXT).kw(&options)
|
||||
}
|
||||
|
||||
pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotation: f64, j: (HAlign, VAlign)) -> EntityKind {
|
||||
let style = s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into());
|
||||
let (h, v) = j;
|
||||
@@ -129,7 +119,8 @@ impl Interactive for TextM {
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
let th = s.doc().map(|d| d.header.f64("TEXTSIZE", 0.2)).unwrap_or(0.2);
|
||||
if self.asking_justify {
|
||||
return justify_prompt(true);
|
||||
return Prompt::new("Enter an option", Accept::TEXT)
|
||||
.kw(&["Left", "Center", "Right", "Align", "Middle", "Fit", "TL", "TC", "TR", "ML", "MC", "MR", "BL", "BC", "BR"]);
|
||||
}
|
||||
match (self.at, self.height, self.rotation) {
|
||||
(None, _, _) => Prompt::new("Specify start point of text", Accept::POINT).kw(&["Justify", "Style"]),
|
||||
|
||||
@@ -601,25 +601,6 @@ fn measure_spline_by_its_own_parameter() {
|
||||
assert!(pts.len() == 3 && [7.0, 4.0, 1.0].iter().all(|x| pts.iter().any(|p| near(*p, *x, 0.0))), "{pts:?}");
|
||||
}
|
||||
|
||||
/// A pick a hair outside an arc's sweep beside its start is at its start, for an arc and for a
|
||||
/// polyline's arc span alike: MEASURE runs from there (round the circle it was the far end).
|
||||
#[test]
|
||||
fn measure_from_a_pick_a_hair_before_an_arcs_start() {
|
||||
let curves = [
|
||||
("arc", json!({"center": [0, 0], "radius": 1, "start": 0, "end": 180})),
|
||||
("pline", json!({"vertices": [{"p": [1, 0], "bulge": 1}, [-1, 0]]})),
|
||||
];
|
||||
for (cmd, args) in curves {
|
||||
let mut s = Session::new();
|
||||
let e = h(&s.execute(cmd, &args).unwrap());
|
||||
s.execute("measure", &json!({"handle": e, "length": 1, "from": [1, -1e-13]})).unwrap();
|
||||
let pts: Vec<Vec2> =
|
||||
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p.xy()) } else { None }).collect();
|
||||
// From (1, 0), a point every radian.
|
||||
assert!(pts.len() == 3 && [1.0f64, 2.0, 3.0].iter().all(|a| pts.iter().any(|p| near(*p, a.cos(), a.sin()))), "{cmd}: {pts:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// MEASURE counts every vertex in a polyline's parameter, coincident ones too (AutoCAD's polyline
|
||||
/// parameter is the vertex index; the chain drops zero-length spans), and picks an ellipse's end
|
||||
/// by the ellipse parameter like any other curve: AutoCAD 2024 runs both measured cases below from
|
||||
|
||||
@@ -557,15 +557,9 @@ fn run_clear(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
fn run_selectall(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let space = s.space();
|
||||
let d = s.doc()?;
|
||||
let frozen = s.viewport_frozen();
|
||||
let hs: Vec<Handle> = d
|
||||
.space(&space)
|
||||
.map(|st| {
|
||||
st.iter()
|
||||
.filter(|e| crate::select::selectable(d, e, frozen) && d.layer(&e.common.layer).is_none_or(|l| !l.locked))
|
||||
.map(|e| e.handle)
|
||||
.collect()
|
||||
})
|
||||
.map(|st| st.iter().filter(|e| d.is_visible(e) && d.layer(&e.common.layer).is_none_or(|l| !l.locked)).map(|e| e.handle).collect())
|
||||
.unwrap_or_default();
|
||||
let n = hs.len();
|
||||
s.set_selection(hs);
|
||||
@@ -586,19 +580,16 @@ fn run_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let add = bool_or(p, "add", false);
|
||||
let picked: Vec<Handle> = if let Some(w) = points_param(p, "window") {
|
||||
let (Some(a), Some(b)) = (w.first(), w.get(1)) else { return Err(bad("select", "window needs 2 corners")) };
|
||||
crate::select::select_window_in(s.doc()?, &space, s.viewport_frozen(), Bounds2::new(*a, *b), bool_or(p, "crossing", false))
|
||||
crate::select::select_window(s.doc()?, &space, Bounds2::new(*a, *b), bool_or(p, "crossing", false))
|
||||
} else if let Some(at) = point_param(p, "at") {
|
||||
let ap = f64_or(p, "aperture", s.pixel_size() * s.settings.pickbox * 1.5);
|
||||
crate::select::pick_in(s.doc()?, &space, s.viewport_frozen(), at, ap).into_iter().collect()
|
||||
crate::select::pick(s.doc()?, &space, at, ap).into_iter().collect()
|
||||
} else if let Some(f) = points_param(p, "fence") {
|
||||
crate::select::select_fence_in(s.doc()?, &space, s.viewport_frozen(), &f)
|
||||
} else if ["handles", "handle"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
targets(s, p)?
|
||||
crate::select::select_fence(s.doc()?, &space, &f)
|
||||
} else {
|
||||
// Nothing to select with: the selection stays, also what the active viewport does not draw.
|
||||
s.stored_selection()
|
||||
targets(s, p)?
|
||||
};
|
||||
let mut sel = if add { s.stored_selection() } else { Vec::new() };
|
||||
let mut sel = if add { s.selection() } else { Vec::new() };
|
||||
sel.extend(picked);
|
||||
s.set_selection(sel);
|
||||
let sel = s.selection();
|
||||
|
||||
@@ -363,7 +363,7 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (a, b) = (screen(Vec2::new(min.x, max.y)), screen(Vec2::new(max.x, min.y)));
|
||||
cadcraft_render::raster::blank_outside_pixels(&mut pm, a, b);
|
||||
}
|
||||
let png = cadcraft_render::raster::encode_png(&pm).ok_or_else(|| bad("preview", "rendering the preview failed"))?;
|
||||
let png = pm.encode_png().map_err(|_| bad("preview", "rendering the preview failed"))?;
|
||||
let layout = space.tab_name();
|
||||
Ok(json!({ "data": base64_encode(&png), "width": w, "height": h, "layout": layout, "paper": page.paper, "landscape": page.landscape }))
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ use crate::{Accept, Input, Prompt, Result, Session, Step};
|
||||
|
||||
/// The rules the Command Aliases dialog checks before it sends an alias to ALIASEDIT.
|
||||
pub use pgp::{MAX_ALIAS_PROFILE_BYTES, MAX_ALIASES, alias_name, alias_profile, command_id, restore_aliases};
|
||||
pub(crate) use pgp::{greek_alias, specs as alias_specs, user_alias};
|
||||
pub(crate) use pgp::{specs as alias_specs, user_alias};
|
||||
pub use template::{qnew_template, set_qnew_template};
|
||||
|
||||
/// Largest drawing accepted from a local path, matching the per-file xref limit. A path naming an
|
||||
@@ -67,22 +67,6 @@ pub fn entity_codec() -> Option<&'static EntityCodec> {
|
||||
CODEC.get()
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// app with the DXF writer, a lower layer; kept apart from [`EntityCodec`] so hosts that only
|
||||
/// need entities don't have to provide it).
|
||||
pub type ObjectRecords = fn(&Drawing) -> Vec<(String, Vec<craft_dxf::Tag>, Option<cadcraft_doc::foreign::ForeignKey>)>;
|
||||
|
||||
static OBJECT_RECORDS: OnceLock<ObjectRecords> = OnceLock::new();
|
||||
|
||||
pub fn set_object_records(f: ObjectRecords) {
|
||||
let _ = OBJECT_RECORDS.set(f);
|
||||
}
|
||||
pub fn object_records() -> Option<ObjectRecords> {
|
||||
OBJECT_RECORDS.get().copied()
|
||||
}
|
||||
|
||||
/// COMPARE (drawing comparison).
|
||||
pub mod compare;
|
||||
|
||||
@@ -424,7 +408,6 @@ fn run_close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.cancel();
|
||||
s.docs.remove(i);
|
||||
s.lisp_forget_closed();
|
||||
if i < s.active {
|
||||
// An earlier drawing went away: the active one shifted down by one.
|
||||
s.active -= 1;
|
||||
@@ -440,7 +423,6 @@ fn run_close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn run_closeall(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
s.cancel();
|
||||
s.docs.clear();
|
||||
s.lisp_forget_closed();
|
||||
s.active = 0;
|
||||
s.bump_doc_epoch();
|
||||
ok()
|
||||
@@ -1038,14 +1020,46 @@ fn run_saveas_reporting(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
save_reporting(s, p, run_saveas, asked)
|
||||
}
|
||||
|
||||
/// Encode bytes with the standard padded Base64 alphabet.
|
||||
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
pub fn base64_encode(data: &[u8]) -> String {
|
||||
craft_mime::base64::STANDARD.encode(data)
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for chunk in data.chunks(3) {
|
||||
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
|
||||
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
|
||||
for i in 0..4 {
|
||||
if i <= chunk.len() {
|
||||
out.push(char::from(B64[((n >> (18 - 6 * i)) & 63) as usize]));
|
||||
} else {
|
||||
out.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Decode the legacy file/control Base64 form, retaining its permissive alphabet and padding.
|
||||
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
craft_mime::base64_compat::decode(s).ok()
|
||||
let mut out = Vec::with_capacity(s.len() * 3 / 4);
|
||||
let mut buf = 0u32;
|
||||
let mut bits = 0;
|
||||
for c in s.bytes() {
|
||||
let v = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' | b'-' => 62,
|
||||
b'/' | b'_' => 63,
|
||||
b'=' | b'\n' | b'\r' | b' ' => continue,
|
||||
_ => return None,
|
||||
};
|
||||
buf = (buf << 6) | u32::from(v);
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push(((buf >> bits) & 0xff) as u8);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -59,12 +59,6 @@ pub(crate) fn user_alias(name: &str) -> Option<String> {
|
||||
store().map.get(name).cloned()
|
||||
}
|
||||
|
||||
/// The user alias that is the Greek word `word` in another case or accent.
|
||||
pub(crate) fn greek_alias(word: &str) -> Option<String> {
|
||||
let same = crate::keyboard::same_greek_word_as(word)?;
|
||||
store().map.keys().find(|alias| same(alias)).cloned()
|
||||
}
|
||||
|
||||
/// The user aliases and the file REINIT reads, as the host's user profile keeps them:
|
||||
/// `{"aliases": {alias: command}, "file": path or null}`. Not drawing data.
|
||||
pub fn alias_profile() -> Value {
|
||||
|
||||
@@ -44,7 +44,7 @@ pub(crate) struct GripEdit {
|
||||
/// Typed `GRIP`: still collecting grips ("Select grips").
|
||||
picking: bool,
|
||||
/// What MOVE/ROTATE/SCALE/MIRROR transform: the hot grips' objects and the objects of the
|
||||
/// selection that the view being edited shows.
|
||||
/// selection that the drawing shows.
|
||||
targets: Vec<Handle>,
|
||||
base: Vec2,
|
||||
mode: GripMode,
|
||||
@@ -70,11 +70,10 @@ fn positive(v: Option<f64>) -> Result<f64> {
|
||||
v.filter(|f| f.is_finite() && *f > 1e-12).ok_or_else(|| other("Requires a positive number."))
|
||||
}
|
||||
|
||||
/// Whether the view being edited shows `h`. A hidden object (HIDEOBJECTS, an off or frozen layer,
|
||||
/// a layer frozen in the active MSPACE viewport) takes no part in a grip edit, even when Undo or
|
||||
/// a selection command put it back into the selection.
|
||||
/// Whether the drawing shows `h`. A hidden object (HIDEOBJECTS, an off or frozen layer) takes no
|
||||
/// part in a grip edit, even when Undo or a selection command put it back into the selection.
|
||||
fn shown(s: &Session, h: Handle) -> bool {
|
||||
s.state().is_ok_and(|st| st.doc.entity(h).is_some_and(|e| st.shows(e)))
|
||||
s.doc().is_ok_and(|d| d.entity(h).is_some_and(|e| d.is_visible(e)))
|
||||
}
|
||||
|
||||
impl GripEdit {
|
||||
@@ -96,8 +95,7 @@ impl GripEdit {
|
||||
}
|
||||
|
||||
/// Make grip `index` of `h` hot (the first one becomes the base point). The grip of an object
|
||||
/// the view being edited does not show is left out, and so are the hidden objects of the
|
||||
/// selection.
|
||||
/// the drawing does not show is left out, and so are the hidden objects of the selection.
|
||||
fn add_hot(&mut self, s: &Session, (h, i): (Handle, usize)) -> Result<()> {
|
||||
if self.hot.contains(&(h, i)) || self.hot.len() >= MAX_HOT {
|
||||
return Ok(());
|
||||
@@ -121,13 +119,13 @@ impl GripEdit {
|
||||
/// The grips of the selected objects at `p` (typed `GRIP`): all objects with a grip there.
|
||||
fn grips_at(s: &Session, p: Vec2) -> Vec<(Handle, usize)> {
|
||||
let tol = (s.pixel_size() * (s.settings.gripsize + 3.0)).max(1e-9 * (1.0 + p.len()));
|
||||
let Ok(st) = s.state() else { return Vec::new() };
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for h in s.selection().into_iter().take(MAX_HOT) {
|
||||
if super::curves::is_locked(s, h) {
|
||||
continue;
|
||||
}
|
||||
let Some(e) = st.doc.entity(h).filter(|e| st.shows(e)) else { continue };
|
||||
let Some(e) = d.entity(h).filter(|e| d.is_visible(e)) else { continue };
|
||||
let gs = e.kind.grips();
|
||||
// The nearest grip of this object within the tolerance.
|
||||
let best = gs
|
||||
@@ -485,8 +483,8 @@ impl Session {
|
||||
/// Make grips hot and start editing them (the UI's click on a grip; Shift+click collects
|
||||
/// several first). `hot` lists (object, grip index); the first is the base grip. The grip
|
||||
/// modes and their options then run at the command line like any prompt. Grips of objects the
|
||||
/// 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.
|
||||
/// drawing 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<()> {
|
||||
if self.running.is_some() {
|
||||
self.cancel();
|
||||
|
||||
@@ -28,8 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
const MEMBER_PICKS: &[&str] = &["groupedit", "-group"];
|
||||
|
||||
/// `hs` plus the other members of the selectable groups they belong to (in the space being
|
||||
/// edited, visible, and inside an MSPACE viewport not on a layer frozen in it), when PICKSTYLE
|
||||
/// has group selection on. Order: `hs` first.
|
||||
/// edited, visible), when PICKSTYLE has group selection on. Order: `hs` first.
|
||||
pub(crate) fn expand(s: &Session, hs: Vec<Handle>) -> Vec<Handle> {
|
||||
if s.settings.pickstyle & 1 == 0 || hs.is_empty() || s.running.as_ref().is_some_and(|r| MEMBER_PICKS.contains(&r.id.as_str())) {
|
||||
return hs;
|
||||
@@ -40,7 +39,6 @@ pub(crate) fn expand(s: &Session, hs: Vec<Handle>) -> Vec<Handle> {
|
||||
}
|
||||
let space = s.space();
|
||||
let Some(store) = d.space(&space) else { return hs };
|
||||
let frozen = s.viewport_frozen();
|
||||
// Member → its selectable groups, built once (window selections may hold many objects).
|
||||
let mut of: HashMap<Handle, Vec<usize>> = HashMap::new();
|
||||
for (i, g) in d.groups.iter().enumerate().filter(|(_, g)| g.selectable) {
|
||||
@@ -58,7 +56,7 @@ pub(crate) fn expand(s: &Session, hs: Vec<Handle>) -> Vec<Handle> {
|
||||
}
|
||||
let Some(g) = d.groups.get(*gi) else { continue };
|
||||
for m in &g.members {
|
||||
if store.get(*m).is_some_and(|e| crate::select::selectable(d, e, frozen)) && seen.insert(*m) {
|
||||
if store.get(*m).is_some_and(|e| d.is_visible(e)) && seen.insert(*m) {
|
||||
out.push(*m);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
|
||||
|
||||
mod patfile;
|
||||
pub(super) use edit::{set_pattern, takes_pattern};
|
||||
pub(super) use patfile::run_patterns;
|
||||
pub use patfile::{PatternChoice, pattern_choices};
|
||||
pub(super) use patfile::{lines_for, run_patterns};
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Gradient, Handle, Hatch, HatchLoop, Space, entity_bounds};
|
||||
@@ -11,7 +10,6 @@ use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::helpers::lwpoly;
|
||||
use super::machines::SelectRun;
|
||||
use super::{CommandSpec, bad, bool_or, f64_or, point_param, points_param, size_param, str_param, targets};
|
||||
|
||||
use crate::{Accept, EngineError, Input, Interactive, Picker, Prompt, Result, Session, Step};
|
||||
@@ -29,12 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("hatch", "Hatch...", run_hatch).menu(&["Draw", "Hatch..."]).alias(&["h", "bh", "-hatch"]).params("{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\" (built in, or defined by patternFile | patternText), patternFile?: path to a .pat file | patternText?: its contents (loads the patterns it defines), scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION)} — gaps up to HPGAPTOL close").interactive(|s| Ok(Box::new(HatchM::new(s, false)))),
|
||||
CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true)))),
|
||||
CommandSpec::new("boundary", "Boundary...", run_boundary).menu(&["Draw", "Boundary..."]).alias(&["bo", "bpoly"]).params("{points: [[x,y]]}").interactive(|_| Ok(Box::new(BoundaryM { region: false }))),
|
||||
CommandSpec::new("region", "Region", run_region)
|
||||
.menu(&["Draw", "Region"])
|
||||
.alias(&["reg"])
|
||||
.params("{handles?}")
|
||||
// Typed with nothing selected it asks for objects, as in AutoCAD, rather than converting none.
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("region", "REGION")))),
|
||||
CommandSpec::new("region", "Region", run_region).menu(&["Draw", "Region"]).alias(&["reg"]).params("{handles?}"),
|
||||
CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], addPoints?: [[x,y]], addBoundary?: [hex], removeLoops?: [zero-based index] (geometry edits require one hatch), style?, origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))),
|
||||
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")
|
||||
@@ -540,19 +533,6 @@ fn run_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "message": format!("{n} Region(s) created.") }))
|
||||
}
|
||||
|
||||
/// Whether the upper-case `name` is a pattern: a standard one or a loaded one.
|
||||
fn pattern_exists(name: &str) -> bool {
|
||||
cadcraft_doc::library::pattern(name).is_some() || patfile::user_pattern(name).is_some()
|
||||
}
|
||||
|
||||
/// The existing pattern `name` means, typed at the pattern prompt: read upper-cased, else a loaded
|
||||
/// pattern's own name when only its Greek spelling differs in case or accent (σολιδ for ΣΟΛΙΔ).
|
||||
pub(crate) fn pattern_named(name: &str) -> Option<String> {
|
||||
let name = name.trim();
|
||||
let up = name.to_ascii_uppercase();
|
||||
if pattern_exists(&up) { Some(up) } else { patfile::user_pattern_name(name) }
|
||||
}
|
||||
|
||||
/// The origin sub-prompt's keywords (a point sets a new origin).
|
||||
const ORIGIN_KW: [&str; 6] = ["Bottom left", "bottom Right", "Top left", "top riGht", "Center", "Use current"];
|
||||
|
||||
@@ -617,7 +597,7 @@ impl HatchM {
|
||||
Some(n) => n,
|
||||
None => t.trim().to_ascii_uppercase(),
|
||||
};
|
||||
if pattern_exists(&up) {
|
||||
if cadcraft_doc::library::pattern(&up).is_some() || patfile::user_pattern(&up).is_some() {
|
||||
self.settings.pattern = up.clone();
|
||||
s.doc_mut()?.header.set_str("HPNAME", &up);
|
||||
} else {
|
||||
|
||||
@@ -143,8 +143,21 @@ 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) {
|
||||
if let Some(v) = str_param(p, "pattern") {
|
||||
set_pattern(h, v);
|
||||
if let Some(v) = str_param(p, "pattern").map(str::trim).filter(|v| !v.is_empty()) {
|
||||
h.pattern = v.to_ascii_uppercase();
|
||||
h.solid = h.pattern == "SOLID";
|
||||
// A named pattern, SOLID included, replaces the gradient fill; the renderer draws the
|
||||
// gradient first when it is set.
|
||||
h.gradient = None;
|
||||
if !h.solid {
|
||||
// A library pattern is drawn from the library; a loaded .pat pattern brings its lines;
|
||||
// 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 let Some(user) = super::patfile::user_pattern(&h.pattern) {
|
||||
h.pattern_lines = user.lines;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(x) = p.get("scale").and_then(Value::as_f64).filter(|x| x.is_finite() && *x > 0.0) {
|
||||
h.scale = x;
|
||||
@@ -154,43 +167,6 @@ fn properties(h: &mut Hatch, p: &Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the pattern called `up` (upper case) is defined: SOLID, one CADCraft defines, or a
|
||||
/// loaded .pat pattern.
|
||||
fn defined_pattern(up: &str) -> bool {
|
||||
up == "SOLID" || cadcraft_doc::library::pattern(up).is_some() || super::patfile::user_pattern(up).is_some()
|
||||
}
|
||||
|
||||
/// Whether `h` can take the pattern called `name`: a defined one, or the hatch's own (a pattern
|
||||
/// read from a file keeps its definition).
|
||||
pub(crate) fn takes_pattern(h: &Hatch, name: &str) -> bool {
|
||||
let up = name.trim().to_ascii_uppercase();
|
||||
defined_pattern(&up) || h.pattern.eq_ignore_ascii_case(&up)
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || !takes_pattern(h, name) {
|
||||
return false;
|
||||
}
|
||||
h.pattern = name.to_ascii_uppercase();
|
||||
h.solid = h.pattern == "SOLID";
|
||||
// A named pattern, SOLID included, replaces the gradient fill; the renderer draws the
|
||||
// gradient first when it is set.
|
||||
h.gradient = None;
|
||||
if !h.solid {
|
||||
// A library pattern is drawn from the library; a loaded .pat pattern brings its lines;
|
||||
// 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 let Some(user) = super::patfile::user_pattern(&h.pattern) {
|
||||
h.pattern_lines = user.lines;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// HATCHEDIT's `gradient`: the fields to change, all checked before any hatch is touched.
|
||||
struct GradientEdit {
|
||||
name: Option<&'static str>,
|
||||
@@ -413,7 +389,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).
|
||||
if let Some(up) = str_param(p, "pattern").map(|v| v.trim().to_ascii_uppercase()).filter(|v| !v.is_empty())
|
||||
&& !defined_pattern(&up)
|
||||
&& up != "SOLID"
|
||||
&& cadcraft_doc::library::pattern(&up).is_none()
|
||||
&& super::patfile::user_pattern(&up).is_none()
|
||||
{
|
||||
let d = s.doc()?;
|
||||
let own = hs.iter().all(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if x.pattern == up));
|
||||
|
||||
@@ -28,13 +28,6 @@ pub(crate) fn user_pattern(name: &str) -> Option<UserPattern> {
|
||||
store().iter().find(|p| p.name.eq_ignore_ascii_case(name)).cloned()
|
||||
}
|
||||
|
||||
/// The name of the user pattern that is the Greek word `name` in another case or accent
|
||||
/// ([`user_pattern`] folds ASCII only).
|
||||
pub(crate) fn user_pattern_name(name: &str) -> Option<String> {
|
||||
let same = crate::keyboard::same_greek_word_as(name)?;
|
||||
store().iter().find(|p| same(&p.name)).map(|p| p.name.clone())
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
|
||||
@@ -591,7 +591,7 @@ fn run_inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"dimStyles": d.dim_styles.iter().map(|l| l.name.clone()).collect::<Vec<_>>(),
|
||||
"blocks": d.blocks.keys().filter(|k| !k.starts_with('*')).cloned().collect::<Vec<_>>(),
|
||||
"layouts": d.layouts.iter().map(|l| l.name.clone()).collect::<Vec<_>>(),
|
||||
"selection": st.shown_selection().iter().map(|h| h.hex()).collect::<Vec<_>>(),
|
||||
"selection": st.selection.iter().map(|h| h.hex()).collect::<Vec<_>>(),
|
||||
"undo": st.undo.iter().rev().take(20).map(|u| u.label.clone()).collect::<Vec<_>>(),
|
||||
"view": { "center": [st.view().center.x, st.view().center.y], "height": st.view().height },
|
||||
// Records of the file the drawing came from that the reader could not place.
|
||||
|
||||
@@ -106,10 +106,6 @@ pub fn used_layers(d: &cadcraft_doc::Drawing) -> std::collections::HashSet<Strin
|
||||
if !set.contains(&e.common.layer.to_ascii_lowercase()) {
|
||||
set.insert(e.common.layer.to_ascii_lowercase());
|
||||
}
|
||||
// An attribute can sit on a layer of its own.
|
||||
for layer in super::blocks::object_attribs(e).iter().filter_map(|a| a.props.layer.as_ref()) {
|
||||
set.insert(layer.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ mod stretch;
|
||||
mod transform;
|
||||
mod trim;
|
||||
|
||||
use break_join::{BreakAtPointM, BreakM, run_break, run_breakat, run_join};
|
||||
use break_join::{BreakM, run_break, run_breakat, run_join};
|
||||
use explode::run_explode;
|
||||
pub(crate) use explode::{explode_kind, explode_with};
|
||||
use fillet::{FilletM, run_chamfer, run_fillet};
|
||||
@@ -37,7 +37,7 @@ use select_then::{DisplaceM, Op, SelectThen};
|
||||
use stretch::{StretchM, run_stretch};
|
||||
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
|
||||
use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
|
||||
pub(crate) use trim::{CUT_ONCE, Edges, extend, json_pick_error, trim};
|
||||
pub(crate) use trim::{Edges, extend, trim};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -85,24 +85,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("trim", "Trim", trimextend::run_trim)
|
||||
.menu(&["Modify", "Trim"])
|
||||
.alias(&["tr"])
|
||||
.params(concat!(
|
||||
"{handle, pick: [x,y]} | {fence: [[x,y],...]} | {crossing: [[x,y],[x,y]]}; edges?: [hex] (default: every object; a polyline that is one of them, or every object in Standard mode, also cuts itself at its vertices and crossings), edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\" ",
|
||||
"→ {handles: the object (kept, reshaped) then the new pieces; none when it was erased} (pick) | {trimmed} (fence, crossing). ",
|
||||
"For handle+pick: handle is the object to trim; pick selects the portion of that object to remove ",
|
||||
"(normally a point on it, away from a cutting intersection); edges are the cutting edges. The JSON default is standard mode."
|
||||
))
|
||||
.params(
|
||||
"{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"} → {handles: the object (kept, reshaped) then the new pieces; none when it was erased} (pick) | {trimmed} (fence, crossing)",
|
||||
)
|
||||
.interactive(|_| Ok(Box::new(TrimM::new(false)))),
|
||||
CommandSpec::new("extend", "Extend", trimextend::run_extend)
|
||||
.menu(&["Modify", "Extend"])
|
||||
.alias(&["ex"])
|
||||
.params(concat!(
|
||||
"{handle, pick: [x,y]} | {fence: [[x,y],...]} | {crossing: [[x,y],[x,y]]}; ",
|
||||
"edges?: [hex], edgeMode?: \"extend\"|\"none\". ",
|
||||
"For handle+pick: handle is the object to extend; pick points toward the boundary to extend to ",
|
||||
"(normally a point on that boundary), selecting the nearer end of the object ",
|
||||
"(of an open polyline, the end on the pick's side of its middle parameter); ",
|
||||
"edges are the boundary edges, and the nearest forward intersection is used."
|
||||
))
|
||||
.params("{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\"}")
|
||||
.interactive(|_| Ok(Box::new(TrimM::new(true)))),
|
||||
CommandSpec::new("fillet", "Fillet", run_fillet)
|
||||
.menu(&["Modify", "Fillet"])
|
||||
@@ -124,10 +114,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.alias(&["br"])
|
||||
.params("{handle, p1, p2} → {handles: the object (kept, reshaped) then the new pieces; none when nothing is left}")
|
||||
.interactive(|_| Ok(Box::new(BreakM::default()))),
|
||||
CommandSpec::new("breakatpoint", "Break At Point", run_breakat)
|
||||
.menu(&["Modify", "Break At Point"])
|
||||
.params("{handle, at} → {handles: the object (kept, reshaped) then the new piece}")
|
||||
.interactive(|_| Ok(Box::new(BreakAtPointM::default()))),
|
||||
CommandSpec::new("breakatpoint", "Break At Point", run_breakat).menu(&["Modify", "Break At Point"]).params("{handle, at} → {handles: the object (kept, reshaped) then the new piece}"),
|
||||
CommandSpec::new("join", "Join", run_join)
|
||||
.menu(&["Modify", "Join"])
|
||||
.alias(&["j"])
|
||||
|
||||
@@ -4,6 +4,16 @@ use super::{
|
||||
Value, Vec2, arc, bad, json, lwpoly, norm_angle, point_param, point_req, targets,
|
||||
};
|
||||
|
||||
/// Gives a rebuilt arc piece its source centre Z, or a rebuilt polyline piece its source elevation.
|
||||
fn with_z(mut k: EntityKind, z: f64) -> EntityKind {
|
||||
match &mut k {
|
||||
EntityKind::Arc(a) => a.center.z = z,
|
||||
EntityKind::LwPolyline(p) => p.elevation = z,
|
||||
_ => {}
|
||||
}
|
||||
k
|
||||
}
|
||||
|
||||
/// Break `h` between two points (or at one point when p1 == p2).
|
||||
pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Result<Vec<Handle>> {
|
||||
if crate::cmd::curves::is_locked(s, h) {
|
||||
@@ -29,12 +39,12 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re
|
||||
}
|
||||
EntityKind::Circle(c) => {
|
||||
if p1.near(p2, 1e-12) {
|
||||
return Err(EngineError::Other("Arc cannot be full 360 degrees".into()));
|
||||
return Err(EngineError::Other("Arc cannot be full 360 degrees.".into()));
|
||||
}
|
||||
let a1 = c.center.xy().angle_to(p1);
|
||||
let a2 = c.center.xy().angle_to(p2);
|
||||
// AutoCAD removes the CCW portion from the first to the second point.
|
||||
vec![arc(&Arc::new(c.center.xy(), c.radius, a2, a1))]
|
||||
vec![with_z(arc(&Arc::new(c.center.xy(), c.radius, a2, a1)), c.center.z)]
|
||||
}
|
||||
EntityKind::Arc(a) => {
|
||||
let ga = Arc::new(a.center.xy(), a.radius, a.start, a.end);
|
||||
@@ -45,10 +55,10 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re
|
||||
}
|
||||
let mut v = Vec::new();
|
||||
if t1 > 1e-12 {
|
||||
v.push(arc(&Arc::new(ga.center, ga.radius, ga.start, ga.start + t1)));
|
||||
v.push(with_z(arc(&Arc::new(ga.center, ga.radius, ga.start, ga.start + t1)), a.center.z));
|
||||
}
|
||||
if t2 < ga.sweep() - 1e-12 {
|
||||
v.push(arc(&Arc::new(ga.center, ga.radius, ga.start + t2, ga.end)));
|
||||
v.push(with_z(arc(&Arc::new(ga.center, ga.radius, ga.start + t2, ga.end)), a.center.z));
|
||||
}
|
||||
v
|
||||
}
|
||||
@@ -71,32 +81,24 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re
|
||||
};
|
||||
let (mut t1, mut t2) = (lp(p1), lp(p2));
|
||||
if p.closed {
|
||||
let (lo, hi) = if t1 <= t2 { (t1, t2) } else { (t2, t1) };
|
||||
let tol = 1e-9 * (1.0 + total);
|
||||
if hi - lo < tol {
|
||||
// One point: the outline opens at its start vertex and splits at the point;
|
||||
// at the start vertex itself it stays whole and closed.
|
||||
if lo < tol || lo > total - tol {
|
||||
return Ok(vec![h]);
|
||||
}
|
||||
vec![lwpoly(sub_polyline(&segs, 0.0, lo), false), lwpoly(sub_polyline(&segs, lo, total), false)]
|
||||
} else {
|
||||
// The stretch between the points that doesn't run through the start vertex
|
||||
// goes, whichever point came first; what is left runs from the later point
|
||||
// round through the start vertex to the earlier one.
|
||||
let doubled: Vec<Segment> = segs.iter().chain(segs.iter()).copied().collect();
|
||||
vec![lwpoly(sub_polyline(&doubled, hi, lo + total), false)]
|
||||
if (t1 - t2).abs() < 1e-9 {
|
||||
return Err(EngineError::Other("Cannot break a closed polyline at a single point.".into()));
|
||||
}
|
||||
// Like a circle: the stretch from the first point to the second, along the
|
||||
// vertices, goes; what is left runs from the second point round to the first.
|
||||
let doubled: Vec<Segment> = segs.iter().chain(segs.iter()).copied().collect();
|
||||
let end = if t1 > t2 { t1 } else { t1 + total };
|
||||
vec![with_z(lwpoly(sub_polyline(&doubled, t2, end), false), p.elevation)]
|
||||
} else {
|
||||
if t1 > t2 {
|
||||
std::mem::swap(&mut t1, &mut t2);
|
||||
}
|
||||
let mut v = Vec::new();
|
||||
if t1 > 1e-12 {
|
||||
v.push(lwpoly(sub_polyline(&segs, 0.0, t1), false));
|
||||
v.push(with_z(lwpoly(sub_polyline(&segs, 0.0, t1), false), p.elevation));
|
||||
}
|
||||
if t2 < total - 1e-12 {
|
||||
v.push(lwpoly(sub_polyline(&segs, t2, total), false));
|
||||
v.push(with_z(lwpoly(sub_polyline(&segs, t2, total), false), p.elevation));
|
||||
}
|
||||
v
|
||||
}
|
||||
@@ -213,41 +215,6 @@ pub(super) fn run_join(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "handle": r.map(|h| h.hex()) }))
|
||||
}
|
||||
|
||||
/// The object picked at `p` for BREAK and BREAKATPOINT ("*Invalid selection*" when there is none).
|
||||
/// One on a locked layer is refused there, and the command asks for an object again, as AutoCAD
|
||||
/// 2024 does; the pick doesn't fall through to an object under it.
|
||||
fn pick_to_break(s: &mut Session, p: Vec2) -> Result<Option<Handle>> {
|
||||
let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5;
|
||||
let space = s.space();
|
||||
match s.pick_object(&space, p, ap)? {
|
||||
Some(h) if crate::cmd::curves::is_locked(s, h) => {
|
||||
s.echo("The object is on a locked layer.");
|
||||
Ok(None)
|
||||
}
|
||||
Some(h) => {
|
||||
s.set_selection(vec![h]);
|
||||
Ok(Some(h))
|
||||
}
|
||||
None => {
|
||||
s.echo("*Invalid selection*");
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Break `h` from `p1` to `p2` and end the command. As in AutoCAD 2024, a break that can't be made
|
||||
/// (a whole circle at one point: "Arc cannot be full 360 degrees") is reported and ends the
|
||||
/// command too, leaving the object as it was.
|
||||
fn break_and_end(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Result<Step> {
|
||||
match break_entity(s, h, p1, p2) {
|
||||
Ok(_) => {}
|
||||
Err(EngineError::Other(m)) => s.echo(m),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct BreakM {
|
||||
obj: Option<(Handle, Vec2)>,
|
||||
@@ -269,8 +236,14 @@ impl Interactive for BreakM {
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match (self.obj, i) {
|
||||
(None, Input::Point(p)) => {
|
||||
if let Some(h) = pick_to_break(s, p)? {
|
||||
self.obj = Some((h, p));
|
||||
let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5;
|
||||
let space = s.space();
|
||||
match s.pick_object(&space, p, ap)? {
|
||||
Some(h) => {
|
||||
self.obj = Some((h, p));
|
||||
s.set_selection(vec![h]);
|
||||
}
|
||||
None => s.echo("*Invalid selection*"),
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
@@ -283,46 +256,12 @@ impl Interactive for BreakM {
|
||||
self.first_point = false;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Some((h, p1)), Input::Point(p2)) => break_and_end(s, h, p1, p2),
|
||||
(Some(_), Input::Enter) => {
|
||||
(Some((h, p1)), Input::Point(p2)) => {
|
||||
break_entity(s, h, p1, p2)?;
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(None, Input::Enter) => Ok(Step::Done),
|
||||
_ => Ok(Step::Continue),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// BREAKATPOINT at the command line, with AutoCAD 2024's prompts: "Select object:", then "Specify
|
||||
/// break point:"; the object is split there with no gap (the point projects onto it).
|
||||
#[derive(Default)]
|
||||
pub(super) struct BreakAtPointM {
|
||||
obj: Option<Handle>,
|
||||
}
|
||||
|
||||
impl Interactive for BreakAtPointM {
|
||||
fn name(&self) -> &'static str {
|
||||
"BREAKATPOINT"
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
match self.obj {
|
||||
None => Prompt::new("Select object", Accept::POINT),
|
||||
Some(_) => Prompt::new("Specify break point", Accept::POINT),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match (self.obj, i) {
|
||||
(None, Input::Point(p)) => {
|
||||
self.obj = pick_to_break(s, p)?;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
(Some(h), Input::Point(p)) => break_and_end(s, h, p, p),
|
||||
(Some(_), Input::Enter) => {
|
||||
s.set_selection(Vec::new());
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(None, Input::Enter) => Ok(Step::Done),
|
||||
(_, Input::Enter) => Ok(Step::Done),
|
||||
_ => Ok(Step::Continue),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,17 +21,14 @@ impl StretchArea {
|
||||
}
|
||||
}
|
||||
|
||||
/// Add to `hs` the multilines in the edit space that a selection can take there (visible, and
|
||||
/// inside an MSPACE viewport not on a layer frozen in it) with a control vertex inside `area`. A
|
||||
/// crossing selection tests the drawn element lines, which sit away from the control vertices by
|
||||
/// the multiline's scale, so a small area around a vertex alone would miss them.
|
||||
fn add_mline_vertex_hits(s: &Session, area: &StretchArea, hs: &mut Vec<Handle>) {
|
||||
let Ok(d) = s.doc() else { return };
|
||||
let Some(store) = d.space(&s.space()) else { return };
|
||||
let frozen = s.viewport_frozen();
|
||||
/// Add to `hs` the visible multilines in `space` with a control vertex inside `area`. A crossing
|
||||
/// selection tests the drawn element lines, which sit away from the control vertices by the
|
||||
/// multiline's scale, so a small area around a vertex alone would miss them.
|
||||
fn add_mline_vertex_hits(d: &cadcraft_doc::Drawing, space: &cadcraft_doc::Space, area: &StretchArea, hs: &mut Vec<Handle>) {
|
||||
let Some(store) = d.space(space) else { return };
|
||||
for e in store.iter() {
|
||||
if let EntityKind::MLine(m) = &e.kind
|
||||
&& crate::select::selectable(d, e, frozen)
|
||||
&& d.is_visible(e)
|
||||
&& !hs.contains(&e.handle)
|
||||
&& m.vertices.iter().any(|v| area.contains(v.p.xy()))
|
||||
{
|
||||
@@ -97,19 +94,19 @@ pub(super) fn run_stretch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// A fence marks no area: the objects it crosses move whole.
|
||||
if let Some(fence) = listed("fence", 2)? {
|
||||
let hs = crate::select::select_fence_in(s.doc()?, &space, s.viewport_frozen(), &fence);
|
||||
let hs = crate::select::select_fence(s.doc()?, &space, &fence);
|
||||
let moved = transform_entities(s, &hs, &Mat3::translate(d), false)?;
|
||||
return Ok(json!({ "stretched": moved.len() }));
|
||||
}
|
||||
let (mut hs, area) = if let Some(poly) = listed("polygon", 3)? {
|
||||
(crate::select::select_polygon_in(s.doc()?, &space, s.viewport_frozen(), &poly, true), StretchArea::Polygon(poly))
|
||||
(crate::select::select_polygon(s.doc()?, &space, &poly, true), StretchArea::Polygon(poly))
|
||||
} else {
|
||||
let w = points_param(p, "window").ok_or_else(|| bad("stretch", "`window` [[x,y],[x,y]], `polygon` or `fence` is required"))?;
|
||||
let (Some(a), Some(b)) = (w.first(), w.get(1)) else { return Err(bad("stretch", "window needs 2 corners")) };
|
||||
let bx = cadcraft_geom::Bounds2::new(*a, *b);
|
||||
(crate::select::select_window_in(s.doc()?, &space, s.viewport_frozen(), bx, true), StretchArea::Box(bx))
|
||||
(crate::select::select_window(s.doc()?, &space, bx, true), StretchArea::Box(bx))
|
||||
};
|
||||
add_mline_vertex_hits(s, &area, &mut hs);
|
||||
add_mline_vertex_hits(s.doc()?, &space, &area, &mut hs);
|
||||
hs.retain(|h| !crate::cmd::curves::is_locked(s, *h));
|
||||
let doc = s.doc_mut()?;
|
||||
let areas = [area];
|
||||
@@ -176,7 +173,7 @@ impl StretchM {
|
||||
/// of two) the mode is dropped.
|
||||
fn finish_mode(&mut self, s: &mut Session, m: SelectMode) -> Result<()> {
|
||||
let space = s.space();
|
||||
let Some(mut hs) = m.select_in(s.doc()?, &space, s.viewport_frozen()) else { return Ok(()) };
|
||||
let Some(mut hs) = m.select(s.doc()?, &space) else { return Ok(()) };
|
||||
let crossing = match (m.kind, m.pts.first().zip(m.pts.get(1))) {
|
||||
(SelectKind::Crossing | SelectKind::CPolygon, _) => true,
|
||||
(SelectKind::Box, Some((a, b))) => b.x < a.x,
|
||||
@@ -192,7 +189,7 @@ impl StretchM {
|
||||
};
|
||||
let whole = area.is_none();
|
||||
if let (Some(a), true, false) = (&area, crossing, self.removing) {
|
||||
add_mline_vertex_hits(s, a, &mut hs);
|
||||
add_mline_vertex_hits(s.doc()?, &space, a, &mut hs);
|
||||
}
|
||||
if let (Some(a), false) = (area, self.removing) {
|
||||
self.windows.push(a);
|
||||
@@ -231,10 +228,10 @@ impl StretchM {
|
||||
Some(c) => {
|
||||
let bx = cadcraft_geom::Bounds2::new(c, p);
|
||||
let space = s.space();
|
||||
let mut hs = crate::select::select_window_in(s.doc()?, &space, s.viewport_frozen(), bx, p.x < c.x);
|
||||
let mut hs = crate::select::select_window(s.doc()?, &space, bx, p.x < c.x);
|
||||
if !self.removing {
|
||||
if p.x < c.x {
|
||||
add_mline_vertex_hits(s, &StretchArea::Box(bx), &mut hs);
|
||||
add_mline_vertex_hits(s.doc()?, &space, &StretchArea::Box(bx), &mut hs);
|
||||
}
|
||||
self.windows.push(StretchArea::Box(bx));
|
||||
}
|
||||
@@ -243,7 +240,7 @@ impl StretchM {
|
||||
None => {
|
||||
let aperture = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5;
|
||||
let space = s.space();
|
||||
match crate::select::pick_in(s.doc()?, &space, s.viewport_frozen(), p, aperture) {
|
||||
match crate::select::pick(s.doc()?, &space, p, aperture) {
|
||||
Some(h) => self.add(s, vec![h], true),
|
||||
None => self.corner = Some(p),
|
||||
}
|
||||
@@ -254,7 +251,6 @@ impl StretchM {
|
||||
self.corner = None;
|
||||
let d = s.doc()?;
|
||||
let store = d.space(&s.space());
|
||||
let frozen = s.viewport_frozen();
|
||||
let word = t.trim().to_ascii_lowercase();
|
||||
// `_C`, `_L`: the English name, as scripts write it.
|
||||
let word = word.strip_prefix('_').unwrap_or(&word).to_string();
|
||||
@@ -271,14 +267,9 @@ impl StretchM {
|
||||
self.removing = false;
|
||||
None
|
||||
}
|
||||
"all" => Some(
|
||||
store.map(|st| st.iter().filter(|e| crate::select::selectable(d, e, frozen)).map(|e| e.handle).collect()).unwrap_or_default(),
|
||||
),
|
||||
"l" | "last" => Some(store.and_then(|st| crate::select::last_in(st, frozen)).map(|h| vec![h]).unwrap_or_default()),
|
||||
"p" | "previous" => {
|
||||
let st = s.state()?;
|
||||
Some(st.drawn_in_viewport(&st.previous_selection))
|
||||
}
|
||||
"all" => Some(store.map(|st| st.iter().filter(|e| d.is_visible(e)).map(|e| e.handle).collect()).unwrap_or_default()),
|
||||
"l" | "last" => Some(store.and_then(|st| st.last()).map(|e| vec![e.handle]).unwrap_or_default()),
|
||||
"p" | "previous" => Some(s.state()?.previous_selection.clone()),
|
||||
_ => {
|
||||
s.echo("*Invalid selection*");
|
||||
None
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use cadcraft_geom::Bounds2;
|
||||
|
||||
use super::{
|
||||
Arc, EngineError, Entity, EntityKind, Handle, Line, PolyVertex, Polyline, Prim, Result, Segment, Session, TAU, Vec2, angle_in_sweep, arc,
|
||||
ccw_sweep, intersect_ext, line, lwpoly, norm_angle,
|
||||
@@ -93,62 +91,13 @@ fn prim_to_segments(p: &Prim) -> Vec<Segment> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Explain the generic line failures for JSON handle+pick calls, and a line TRIM picked on its
|
||||
/// only cuts ([`ON_THE_CUT`]). Other curves retain their own diagnostics: their nearest-parameter
|
||||
/// rules do not prove that a pick is invalid.
|
||||
pub(crate) fn json_pick_error(s: &Session, h: Handle, pick: Vec2, edges: Edges, extending: bool, error: EngineError) -> EngineError {
|
||||
let generic = if extending { "Object does not intersect an edge." } else { "Object does not intersect a cutting edge." };
|
||||
if !matches!(&error, EngineError::Other(message) if message == generic || (!extending && message == ON_THE_CUT)) {
|
||||
return error;
|
||||
}
|
||||
let Ok(d) = s.doc() else { return error };
|
||||
let Some(e) = d.entity(h) else { return error };
|
||||
let EntityKind::Line(l) = &e.kind else { return error };
|
||||
let Ok(cut) = edge_segments(s, edges, h) else { return error };
|
||||
let ln = Line::new(l.a.xy(), l.b.xy());
|
||||
let message = if extending {
|
||||
// The selected end already failed. Check the opposite end with the same ray and
|
||||
// forward-intersection rules before attributing the failure to the pick's end choice.
|
||||
let (fixed, end) = if pick.dist(ln.b) < pick.dist(ln.a) { (ln.b, ln.a) } else { (ln.a, ln.b) };
|
||||
let dir = (end - fixed).normalized();
|
||||
let ray = Segment::Line(Line::new(end, end + dir * 1e8));
|
||||
let opposite_hit = cut.iter().flat_map(|c| intersect_ext(&ray, c, false)).any(|x| (x - end).dot(dir) > 1e-9);
|
||||
if opposite_hit {
|
||||
"The `pick` point selects an end with no boundary ahead; choose `pick` toward the boundary to extend to."
|
||||
} else {
|
||||
"No usable boundary intersection was found for either end of the object to extend."
|
||||
}
|
||||
} else {
|
||||
let pick_param = ln.param_of(pick).clamp(0.0, 1.0);
|
||||
let has_cut = cut.iter().flat_map(|c| intersect_ext(&Segment::Line(ln), c, false)).any(|x| {
|
||||
let t = ln.param_of(x);
|
||||
t > 1e-9 && t < 1.0 - 1e-9
|
||||
});
|
||||
if !has_cut {
|
||||
"No usable cutting-edge intersection in the interior of the object to trim."
|
||||
} else if pick_param.is_nan() {
|
||||
return error;
|
||||
} else if !ln.at(pick_param).near(pick, 1e-9_f64.max(64.0 * f64::EPSILON * (1.0 + pick.len().max(ln.a.len()).max(ln.b.len())))) {
|
||||
"The `pick` point is off the line and projects onto a cutting intersection; pick away from that intersection."
|
||||
} else {
|
||||
"The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection."
|
||||
}
|
||||
};
|
||||
EngineError::Other(message.into())
|
||||
}
|
||||
|
||||
/// Trim `h` at the piece containing `pick`. Returns the handles that replace it.
|
||||
/// Trim `h` at the piece containing `pick`. Returns what it became: its pieces, `h` first
|
||||
/// ([`replace_with_pieces`]).
|
||||
pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Result<Vec<Handle>> {
|
||||
if crate::cmd::curves::is_locked(s, h) {
|
||||
return Err(EngineError::Other("The object is on a locked layer.".into()));
|
||||
}
|
||||
let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
|
||||
let cut = edge_segments(s, edges, h)?;
|
||||
// A polyline that is one of the edges (picked, or with every object in either mode) cuts
|
||||
// itself too.
|
||||
let itself = edges.only.is_none_or(|o| o.contains(&h));
|
||||
let pieces: Vec<EntityKind> = match &e.kind {
|
||||
EntityKind::Line(l) => {
|
||||
let ln = Line::new(l.a.xy(), l.b.xy());
|
||||
@@ -160,12 +109,10 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
|
||||
.collect();
|
||||
ts.sort_by(f64::total_cmp);
|
||||
let tp = ln.param_of(pick).clamp(0.0, 1.0);
|
||||
let found = ts.len();
|
||||
ts.retain(|t| (t - tp).abs() * ln.len() > ON_CUT);
|
||||
let lo = ts.iter().copied().filter(|t| *t < tp).fold(0.0, f64::max);
|
||||
let hi = ts.iter().copied().filter(|t| *t > tp).fold(1.0, f64::min);
|
||||
if lo == 0.0 && hi == 1.0 {
|
||||
return Err(EngineError::Other(if ts.len() < found { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into()));
|
||||
return Err(EngineError::Other("Object does not intersect a cutting edge.".into()));
|
||||
}
|
||||
let mut v = Vec::new();
|
||||
if lo > 0.0 {
|
||||
@@ -184,14 +131,11 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
|
||||
let mut ts: Vec<f64> =
|
||||
cut.iter().flat_map(|c| intersect_ext(&seg, c, false)).map(param).filter(|t| *t > 1e-9 && *t < sweep - 1e-9).collect();
|
||||
ts.sort_by(f64::total_cmp);
|
||||
// A pick off the arc is at the end it is nearer, round the circle.
|
||||
let tp = crate::cmd::curves::seg_param(&seg, pick) * sweep;
|
||||
let found = ts.len();
|
||||
ts.retain(|t| (t - tp).abs() * ga.radius > ON_CUT);
|
||||
let tp = param(pick).min(sweep);
|
||||
let lo = ts.iter().copied().filter(|t| *t < tp).fold(0.0, f64::max);
|
||||
let hi = ts.iter().copied().filter(|t| *t > tp).fold(sweep, f64::min);
|
||||
if lo == 0.0 && hi == sweep {
|
||||
return Err(EngineError::Other(if ts.len() < found { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into()));
|
||||
return Err(EngineError::Other("Object does not intersect a cutting edge.".into()));
|
||||
}
|
||||
let mut v = Vec::new();
|
||||
if lo > 0.0 {
|
||||
@@ -207,16 +151,10 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
|
||||
let mut angs: Vec<f64> = cut.iter().flat_map(|x| intersect_ext(&full, x, false)).map(|p| c.center.xy().angle_to(p)).collect();
|
||||
angs.sort_by(f64::total_cmp);
|
||||
angs.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
|
||||
let ap = c.center.xy().angle_to(pick);
|
||||
let found = angs.len();
|
||||
angs.retain(|a| {
|
||||
let d = norm_angle(a - ap);
|
||||
d.min(TAU - d) * c.radius > ON_CUT
|
||||
});
|
||||
if angs.len() < 2 {
|
||||
let why = if found >= 2 { ON_THE_CUT } else { "Circle must intersect cutting edges at two or more points." };
|
||||
return Err(EngineError::Other(why.into()));
|
||||
return Err(EngineError::Other("Circle must intersect cutting edges at two or more points.".into()));
|
||||
}
|
||||
let ap = c.center.xy().angle_to(pick);
|
||||
// The removed arc runs between the two intersections around the pick.
|
||||
let n = angs.len();
|
||||
let mut keep = None;
|
||||
@@ -229,10 +167,7 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
|
||||
}
|
||||
keep.into_iter().collect()
|
||||
}
|
||||
EntityKind::LwPolyline(p) => match trim_polyline(p, &cut, pick, itself)? {
|
||||
Some(pieces) => pieces,
|
||||
None => return Ok(vec![h]),
|
||||
},
|
||||
EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick)?,
|
||||
k => crate::cmd::modify2::trim_other(k, &cut, pick)?,
|
||||
};
|
||||
replace_with_pieces(s, h, pieces)
|
||||
@@ -246,20 +181,19 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
|
||||
/// in its middle keeps its handle on the piece from its start point, the piece to its end point is
|
||||
/// new; a circle broken or trimmed becomes an arc with the circle's handle.)
|
||||
///
|
||||
/// Each piece keeps what the object had beyond its outline ([`inherit`]). Dimensions attached to
|
||||
/// the object follow [`crate::assoc::follow_pieces`]. Its parametric constraints are removed: its
|
||||
/// new shape no longer meets them, and solving them again would move the objects they tie it to.
|
||||
/// Dimensions attached to the object follow [`crate::assoc::follow_pieces`]. Its parametric
|
||||
/// constraints are removed: its new shape no longer meets them, and solving them again would move
|
||||
/// the objects they tie it to.
|
||||
pub(super) fn replace_with_pieces(s: &mut Session, h: Handle, pieces: Vec<EntityKind>) -> Result<Vec<Handle>> {
|
||||
let d = s.doc_mut()?;
|
||||
if pieces.is_empty() {
|
||||
let mut pieces = pieces.into_iter();
|
||||
let Some(first) = pieces.next() else {
|
||||
d.remove_entity(h);
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
};
|
||||
let (Some(space), Some(old)) = (d.space_of(h), d.entity(h).cloned()) else {
|
||||
return Err(EngineError::Other("no such object".into()));
|
||||
};
|
||||
let mut pieces = pieces.into_iter().map(|k| inherit(&old.kind, k));
|
||||
let Some(first) = pieces.next() else { return Ok(Vec::new()) };
|
||||
d.modify_entity(h, |e| e.kind = first)?;
|
||||
let mut out = vec![h];
|
||||
for kind in pieces {
|
||||
@@ -279,31 +213,6 @@ pub(super) fn replace_with_pieces(s: &mut Session, h: Handle, pieces: Vec<Entity
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `piece`, cut from `source`, with what it keeps of it as AutoCAD 2024's BREAK and TRIM leave
|
||||
/// pieces: a line's Z along it, an arc's (or a circle's) centre Z, and a polyline's elevation,
|
||||
/// constant width and linetype generation.
|
||||
fn inherit(source: &EntityKind, mut piece: EntityKind) -> EntityKind {
|
||||
match (source, &mut piece) {
|
||||
(EntityKind::Line(s), EntityKind::Line(p)) => {
|
||||
let ln = Line::new(s.a.xy(), s.b.xy());
|
||||
if ln.len() > 0.0 {
|
||||
let z = |t: f64| s.a.z + (s.b.z - s.a.z) * t;
|
||||
p.a.z = z(ln.param_of(p.a.xy()));
|
||||
p.b.z = z(ln.param_of(p.b.xy()));
|
||||
}
|
||||
}
|
||||
(EntityKind::Arc(s), EntityKind::Arc(p)) => p.center.z = s.center.z,
|
||||
(EntityKind::Circle(s), EntityKind::Arc(p)) => p.center.z = s.center.z,
|
||||
(EntityKind::LwPolyline(s), EntityKind::LwPolyline(p)) => {
|
||||
p.elevation = s.elevation;
|
||||
p.const_width = s.const_width;
|
||||
p.plinegen = s.plinegen;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
piece
|
||||
}
|
||||
|
||||
/// Sub-polyline between length parameters `a` and `b` (open polylines).
|
||||
pub(super) fn sub_polyline(segs: &[Segment], a: f64, b: f64) -> Vec<PolyVertex> {
|
||||
let mut out: Vec<PolyVertex> = Vec::new();
|
||||
@@ -336,128 +245,15 @@ pub(super) fn sub_polyline(segs: &[Segment], a: f64, b: f64) -> Vec<PolyVertex>
|
||||
out
|
||||
}
|
||||
|
||||
/// Two line segments of a polyline within this sine of parallel run on as one, straight on or
|
||||
/// doubling back: the vertex between them doesn't cut it, and they don't cut each other. AutoCAD
|
||||
/// 2024 cuts at a bend of 1e-8 and not at one of 8e-9, whatever the lengths.
|
||||
const STRAIGHT: f64 = 1e-8;
|
||||
|
||||
/// Upper bounds on one trim's search for where a polyline crosses itself (hostile files): the pairs
|
||||
/// of segments searched (those the piece picked can reach, times those near them) and the
|
||||
/// crossings found. Past either the trim is refused, rather than made at some of its cuts.
|
||||
const MAX_SELF_PAIRS: usize = 1 << 24;
|
||||
const MAX_SELF_CROSSINGS: usize = 1 << 16;
|
||||
|
||||
/// How near a cut a pick is on it, along the object. AutoCAD 2024 trims nothing for a pick that
|
||||
/// near one of a polyline's own cuts, and passes over a cut by another edge, the trim running on
|
||||
/// across it, on lines, arcs and circles too. On open polylines from 1e-3 to 1e9 long it was within
|
||||
/// 5e-7, and 5.1e-7 away trimmed at the cut (around a closed rectangle it reached a little further,
|
||||
/// to 1e-6; on a line, further still, to 5e-4 on one 10 long).
|
||||
const ON_CUT: f64 = 5e-7;
|
||||
|
||||
/// The refusal when every cut was passed over ([`ON_CUT`]): the object meets an edge, at the pick,
|
||||
/// so Quick mode leaves it in place rather than erasing it as one no edge crosses.
|
||||
const ON_THE_CUT: &str = "The pick is on the cut: nothing to trim.";
|
||||
|
||||
/// AutoCAD 2024's refusal to trim a closed polyline cut at one point only.
|
||||
pub(crate) const CUT_ONCE: &str = "Curve must intersect cutting edges at least twice.";
|
||||
|
||||
/// Whether segments `a` and `b` of a polyline run on as one ([`STRAIGHT`]).
|
||||
fn runs_on(a: &Segment, b: &Segment) -> bool {
|
||||
let (Segment::Line(a), Segment::Line(b)) = (a, b) else { return false };
|
||||
let (u, v) = (a.b - a.a, b.b - b.a);
|
||||
u.cross(v).abs() < STRAIGHT * u.len() * v.len()
|
||||
}
|
||||
|
||||
/// Where a polyline that is one of the cutting edges cuts itself around segment `k`, the one
|
||||
/// picked, as lengths along it: at its vertices (every vertex of a closed one, its start included)
|
||||
/// but those it runs straight on through ([`runs_on`]), and, on `k` and the segments it runs
|
||||
/// straight on into, where another of its segments crosses them or a vertex of it (an end
|
||||
/// included) touches them. The piece picked lies within those segments, so crossings elsewhere
|
||||
/// don't bound it. AutoCAD 2024 trims a polyline that is one of the cutting edges at these.
|
||||
fn self_cuts(segs: &[Segment], closed: bool, k: usize) -> Result<Vec<f64>> {
|
||||
let n = segs.len();
|
||||
let mut starts = Vec::with_capacity(n);
|
||||
let mut acc = 0.0;
|
||||
for s in segs {
|
||||
starts.push(acc);
|
||||
acc += s.len();
|
||||
}
|
||||
let before = |i: usize| {
|
||||
if i > 0 {
|
||||
Some(i - 1)
|
||||
} else if closed {
|
||||
n.checked_sub(1)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let after = |i: usize| {
|
||||
if i + 1 < n {
|
||||
Some(i + 1)
|
||||
} else if closed {
|
||||
Some(0)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
// Whether the polyline runs straight on through the vertex segment `i` starts at.
|
||||
let straight = |i: usize| matches!((before(i).and_then(|j| segs.get(j)), segs.get(i)), (Some(a), Some(b)) if runs_on(a, b));
|
||||
let mut ts: Vec<f64> = (usize::from(!closed)..n).filter(|i| !straight(*i)).filter_map(|i| starts.get(i).copied()).collect();
|
||||
let mut run = vec![k];
|
||||
let mut i = k;
|
||||
while let Some(j) = before(i).filter(|_| straight(i) && run.len() < n) {
|
||||
run.push(j);
|
||||
i = j;
|
||||
}
|
||||
let mut i = k;
|
||||
while let Some(j) = after(i).filter(|j| straight(*j) && run.len() < n) {
|
||||
run.push(j);
|
||||
i = j;
|
||||
}
|
||||
let boxes: Vec<_> = segs.iter().map(Segment::bounds).collect();
|
||||
let reach = run.iter().filter_map(|i| boxes.get(*i)).fold(Bounds2::EMPTY, |r, b| r.union(b));
|
||||
let near: Vec<usize> = (0..n).filter(|j| boxes.get(*j).is_some_and(|b| b.intersects(&reach))).collect();
|
||||
if run.len().saturating_mul(near.len()) > MAX_SELF_PAIRS {
|
||||
return Err(EngineError::Other("Too many segments to trim the polyline where it crosses itself.".into()));
|
||||
}
|
||||
// A crossing, or a vertex of another segment touching this one, cuts it; so does a crossing
|
||||
// where it runs straight on into the next. Two segments meeting at a vertex cut nothing more.
|
||||
let cuts = |t: f64, i: usize| (t > 1e-9 && t < 1.0 - 1e-9) || (t <= 1e-9 && straight(i)) || (t >= 1.0 - 1e-9 && after(i).is_some_and(straight));
|
||||
let vertices = ts.len();
|
||||
for &i in &run {
|
||||
let (Some(a), Some(box_a), Some(a0)) = (segs.get(i), boxes.get(i), starts.get(i)) else { continue };
|
||||
for &j in &near {
|
||||
let (Some(b), Some(box_b)) = (segs.get(j), boxes.get(j)) else { continue };
|
||||
if j == i || runs_on(a, b) || !box_a.intersects(box_b) {
|
||||
continue;
|
||||
}
|
||||
for x in intersect_ext(a, b, false) {
|
||||
let t = param_on(a, x);
|
||||
if cuts(t, i) {
|
||||
ts.push(a0 + t * a.len());
|
||||
if ts.len() - vertices > MAX_SELF_CROSSINGS {
|
||||
return Err(EngineError::Other("Too many crossings to trim the polyline where it crosses itself.".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(ts)
|
||||
}
|
||||
|
||||
/// Trim a polyline at the piece containing `pick`, between the cuts by `cut` and, when it is one
|
||||
/// of the cutting edges (`itself`), by its own ([`self_cuts`]). `None`: the pick is on one of its
|
||||
/// own cuts ([`ON_CUT`]), which trims nothing.
|
||||
fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itself: bool) -> Result<Option<Vec<EntityKind>>> {
|
||||
fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2) -> Result<Vec<EntityKind>> {
|
||||
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
|
||||
let segs = pl.segments();
|
||||
let total: f64 = segs.iter().map(Segment::len).sum();
|
||||
let mut ts: Vec<f64> = Vec::new();
|
||||
let mut acc = 0.0;
|
||||
// The pick's length along the polyline and the segment it is on.
|
||||
let (mut tp, mut k) = (0.0, 0);
|
||||
let mut tp = 0.0;
|
||||
let mut best = f64::INFINITY;
|
||||
for (i, s) in segs.iter().enumerate() {
|
||||
for s in &segs {
|
||||
let len = s.len();
|
||||
for x in cut.iter().flat_map(|c| intersect_ext(s, c, false)) {
|
||||
ts.push(acc + param_on(s, x) * len);
|
||||
@@ -466,34 +262,13 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse
|
||||
if c.dist(pick) < best {
|
||||
best = c.dist(pick);
|
||||
tp = acc + param_on(s, c) * len;
|
||||
k = i;
|
||||
}
|
||||
acc += len;
|
||||
}
|
||||
let mut own = if itself { self_cuts(&segs, p.closed, k)? } else { Vec::new() };
|
||||
// An open polyline's ends cut nothing; a closed one's start vertex cuts it like any other (a
|
||||
// cut there is at 0 or at its length, which the pieces below take as one).
|
||||
if !p.closed {
|
||||
ts.retain(|t| *t > 1e-9 && *t < total - 1e-9);
|
||||
own.retain(|t| *t > 1e-9 && *t < total - 1e-9);
|
||||
}
|
||||
// How far apart two lengths along the polyline are, round its start too when it is closed.
|
||||
let apart = |s: f64, t: f64| if p.closed { (s - t).abs().min(total - (s - t).abs()) } else { (s - t).abs() };
|
||||
// A pick on one of its own cuts trims nothing; a cut by another edge there is passed over, and
|
||||
// the piece runs on across it.
|
||||
if own.iter().any(|t| apart(*t, tp) <= ON_CUT) {
|
||||
return Ok(None);
|
||||
}
|
||||
let found = ts.len();
|
||||
ts.retain(|t| apart(*t, tp) > ON_CUT);
|
||||
let passed = ts.len() < found;
|
||||
ts.extend(own);
|
||||
ts.retain(|t| *t > 1e-9 && *t < total - 1e-9);
|
||||
ts.sort_by(f64::total_cmp);
|
||||
if ts.is_empty() {
|
||||
return Err(EngineError::Other(if passed { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into()));
|
||||
}
|
||||
if p.closed && ts.first().is_some_and(|f| ts.iter().all(|t| apart(*f, *t) <= ON_CUT)) {
|
||||
return Err(EngineError::Other(CUT_ONCE.into()));
|
||||
return Err(EngineError::Other("Object does not intersect a cutting edge.".into()));
|
||||
}
|
||||
let lo = ts.iter().copied().filter(|t| *t < tp).fold(f64::NEG_INFINITY, f64::max);
|
||||
let hi = ts.iter().copied().filter(|t| *t > tp).fold(f64::INFINITY, f64::min);
|
||||
@@ -508,31 +283,33 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse
|
||||
if hi.is_finite() { hi } else { ts.first().copied().unwrap_or(total) + total },
|
||||
);
|
||||
let doubled: Vec<Segment> = segs.iter().chain(segs.iter()).copied().collect();
|
||||
let (a, b) = if hi > total { (hi - total, lo) } else { (hi, lo + total) };
|
||||
let (a, mut b) = if hi > total { (hi - total, lo) } else { (hi, lo + total) };
|
||||
// A single cut leaves the whole outline, opened there.
|
||||
if b <= a + 1e-9 {
|
||||
b += total;
|
||||
}
|
||||
out.push(mk(sub_polyline(&doubled, a, b)));
|
||||
} else {
|
||||
// A piece whose ends meet (the polyline touched itself there) is closed, without its
|
||||
// repeated vertex, as AutoCAD leaves it.
|
||||
let piece = |mut vs: Vec<PolyVertex>| {
|
||||
// Within rounding of the coordinates, however far from the origin, and no more.
|
||||
let meets = vs.len() >= 4
|
||||
&& matches!((vs.first(), vs.last()), (Some(a), Some(b)) if a.p.near(b.p, 64.0 * f64::EPSILON * (1.0 + a.p.len().max(b.p.len()))));
|
||||
if meets {
|
||||
vs.pop();
|
||||
}
|
||||
lwpoly(vs, meets)
|
||||
};
|
||||
if lo.is_finite() {
|
||||
out.push(piece(sub_polyline(&segs, 0.0, lo)));
|
||||
out.push(mk(sub_polyline(&segs, 0.0, lo)));
|
||||
}
|
||||
if hi.is_finite() {
|
||||
out.push(piece(sub_polyline(&segs, hi, total)));
|
||||
out.push(mk(sub_polyline(&segs, hi, total)));
|
||||
}
|
||||
}
|
||||
Ok(Some(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect()))
|
||||
Ok(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect())
|
||||
}
|
||||
|
||||
pub(super) use crate::cmd::curves::seg_param as param_on;
|
||||
pub(super) fn param_on(s: &Segment, p: Vec2) -> f64 {
|
||||
match s {
|
||||
Segment::Line(l) => l.param_of(p).clamp(0.0, 1.0),
|
||||
Segment::Arc { arc, ccw } => {
|
||||
let t = norm_angle(arc.center.angle_to(p) - arc.start) / arc.sweep().max(1e-15);
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
if *ccw { t } else { 1.0 - t }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A polyline arc segment on `ga`'s circle that ends at `end` after turning through `sweep`
|
||||
/// (signed, positive counterclockwise), run on round the circle to the nearest boundary edge: the
|
||||
@@ -595,13 +372,7 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re
|
||||
EntityKind::LwPolyline(p) if !p.closed && p.vertices.len() >= 2 => {
|
||||
let mut vs = p.vertices.clone();
|
||||
let n = vs.len();
|
||||
// The pick's parameter: the segment it is nearest, plus how far along it. AutoCAD 2024
|
||||
// extends the end on that side of the polyline's middle parameter, the last from the
|
||||
// middle on, not the end nearer the pick. A repeated vertex counts as a segment, so
|
||||
// these come from the vertices, not `Polyline::segments`, which skips it.
|
||||
let spans: Vec<_> = vs.windows(2).filter_map(|w| Some((w.first()?.p, w.get(1)?.p, w.first()?.bulge))).collect();
|
||||
let at = crate::cmd::curves::vertex_param_of(&spans, pick);
|
||||
let from_end = 2.0 * at >= (n - 1) as f64;
|
||||
let from_end = vs.last().is_some_and(|l| pick.dist(l.p) < vs.first().map(|f| pick.dist(f.p)).unwrap_or(f64::INFINITY));
|
||||
let (i_end, i_prev) = if from_end { (n - 1, n - 2) } else { (0, 1) };
|
||||
let end = vs.get(i_end).map(|v| v.p).unwrap_or_default();
|
||||
let prev = vs.get(i_prev).map(|v| v.p).unwrap_or_default();
|
||||
|
||||
+374
-107
@@ -6,31 +6,22 @@ mod chprop;
|
||||
mod dash_units;
|
||||
mod matchprop;
|
||||
mod rename;
|
||||
mod set;
|
||||
|
||||
pub use matchprop::MatchProps;
|
||||
use set::run_set;
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::{EntityKind, Lineweight, Transparency};
|
||||
use cadcraft_doc::{EntityKind, Handle, Lineweight, Transparency};
|
||||
use cadcraft_geom::Vec3;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, always, bad, bool_or, f64_req, find_command, ok, point_req, str_param, targets};
|
||||
use super::{CommandSpec, always, bad, bool_or, f64_req, find_command, ok, point_req, point_value, str_param, targets};
|
||||
|
||||
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(),
|
||||
CommandSpec::new("properties.set", "Set Properties", run_set).params(
|
||||
"{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, annotative?, \
|
||||
<geometry fields: radius, center, start, end, text, height, rotation…>, text: style?, justify?, oblique?, positionX/Y/Z?, alignmentX/Y?, \
|
||||
mtext: style?, justify?, lineSpacing?, lineSpacingDistance?, lineSpacingStyle?: atLeast | exactly, positionX/Y/Z?, \
|
||||
dimension: dimStyle?, textOverride?, textRotation?, textPositionX/Y?, prefix?, suffix?, altPrefix?, altSuffix?, dimScale?, precision?, \
|
||||
<dimension style variables (field or DIM* name, e.g. textHeight / DIMTXT) set as overrides of each dimension>, clearOverrides?, clear?: [variable]} \
|
||||
→ {changed, locked, message?, ignored: keys no selected object took} (the keys are those of `properties.describe` rows): objects on locked layers \
|
||||
(and, during REFEDIT, outside the working set) are left out, and `message` says how many",
|
||||
),
|
||||
CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, <geometry fields: radius, center, start, end, text, height, rotation…>; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)} → {changed, locked, message?}: objects on locked layers (and, during REFEDIT, outside the working set) are left out, and `message` says how many"),
|
||||
CommandSpec::new("chprop", "Change Properties", run_set)
|
||||
.params("as properties.set, leaving out objects on locked layers (and, during REFEDIT, outside the working set) → {changed, locked, message?} (the command line asks Color, LAyer, LType, ltScale, LWeight, Thickness and TRansparency in turn)")
|
||||
.interactive(|_| Ok(Box::new(chprop::ChpropM::new()))),
|
||||
@@ -38,13 +29,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.alias(&["-ch"])
|
||||
.params("{handles?, point?: [x, y], elevation?} → {changed, ignored, differingZ, detachedHatches, locked}: the point moves the nearer end of each line to it (level or plumb with the other end under ORTHOMODE) and, when it is the one object, passes a circle through it or places a text, attribute definition or block reference at it (`ignored` otherwise); `elevation` sets the z of objects whose points share one (`differingZ` otherwise); objects on locked layers are left out (the command line asks Specify change point or [Properties], then about each circle, text, attribute definition and block reference in turn)")
|
||||
.interactive(|_| Ok(Box::new(change::ChangeM::new()))),
|
||||
CommandSpec::new("properties.describe", "Describe Properties", run_describe)
|
||||
.params(
|
||||
"{handles?, type?: one of the `types` names, to describe only those objects} → {types: [{type, count}], filter?, count, \
|
||||
groups: [{name, rows: [{key, label, kind, value, varies, display, editable, note?, overridden?, options?: [{value, label}], quick?}]}]} \
|
||||
(each row's `key` is the `properties.set` key that changes it; text, mtext and dimensions have their own groups)",
|
||||
)
|
||||
.noundo(),
|
||||
CommandSpec::new("matchprop", "Match Properties", matchprop::run_matchprop)
|
||||
.menu(&["Modify", "Match Properties"])
|
||||
.alias(&["ma", "painter"])
|
||||
@@ -188,13 +172,10 @@ fn parse_color(v: &Value) -> Option<Color> {
|
||||
|
||||
/// A transparency as JSON, in the form `properties.set` takes: "ByLayer", "ByBlock" or a percentage.
|
||||
pub(super) fn transparency_value(t: Transparency) -> Value {
|
||||
crate::properties::transparency_value(t)
|
||||
}
|
||||
|
||||
fn run_describe(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hs = targets(s, p)?;
|
||||
let d = s.doc()?;
|
||||
Ok(serde_json::to_value(crate::properties::describe(d, &hs, str_param(p, "type"))).unwrap_or(Value::Null))
|
||||
match t {
|
||||
Transparency::Percent(p) => json!(p),
|
||||
other => json!(other.name()),
|
||||
}
|
||||
}
|
||||
|
||||
/// "ByLayer", "ByBlock" or a percentage 0..=90 (a number, or a string such as "50" or "50%").
|
||||
@@ -208,6 +189,369 @@ fn parse_transparency(v: &Value) -> Option<Transparency> {
|
||||
(pct.is_finite() && (0.0..=90.0).contains(&pct)).then(|| Transparency::Percent(pct.round() as u8))
|
||||
}
|
||||
|
||||
fn set_xy(p: &mut Vec3, v: &Value) {
|
||||
if let Some(q) = point_value(v) {
|
||||
p.x = q.x;
|
||||
p.y = q.y;
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects `properties.set` leaves alone, as CHPROP, MATCHPROP and MOVE do: those on locked
|
||||
/// layers and, while a reference is edited in place, those outside the working set.
|
||||
#[derive(Default)]
|
||||
struct LeftOut {
|
||||
locked: usize,
|
||||
outside: usize,
|
||||
}
|
||||
|
||||
impl LeftOut {
|
||||
/// `hs` without the objects that can't be edited, each object once, and how many those were. A
|
||||
/// handle that names no object is an error, before anything changes.
|
||||
fn split(s: &Session, hs: Vec<Handle>) -> Result<(Vec<Handle>, LeftOut)> {
|
||||
let d = s.doc()?;
|
||||
// The working set, once: `RefEdit::is_working` searches a list.
|
||||
let working: Option<std::collections::HashSet<Handle>> = d.refedit.as_ref().map(|r| r.items.iter().map(|i| i.copy).collect());
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out = LeftOut::default();
|
||||
let mut free = Vec::new();
|
||||
for h in hs {
|
||||
let Some(e) = d.entity(h) else {
|
||||
return Err(cadcraft_doc::DocError::NoEntity(h).into());
|
||||
};
|
||||
if !seen.insert(h) {
|
||||
continue;
|
||||
}
|
||||
if working.as_ref().is_some_and(|w| !w.contains(&h)) {
|
||||
out.outside += 1;
|
||||
} else if d.layer(&e.common.layer).is_some_and(|l| l.locked) {
|
||||
out.locked += 1;
|
||||
} else {
|
||||
free.push(h);
|
||||
}
|
||||
}
|
||||
Ok((free, out))
|
||||
}
|
||||
|
||||
/// `{changed, locked}`, and a message saying how many were left out when any were.
|
||||
fn result(&self, changed: usize) -> Value {
|
||||
let mut notes = Vec::new();
|
||||
match self.locked {
|
||||
0 => {}
|
||||
1 => notes.push("1 object was on a locked layer.".to_string()),
|
||||
n => notes.push(format!("{n} objects were on a locked layer.")),
|
||||
}
|
||||
match self.outside {
|
||||
0 => {}
|
||||
1 => notes.push("1 object was not in the working set.".to_string()),
|
||||
n => notes.push(format!("{n} objects were not in the working set.")),
|
||||
}
|
||||
if changed == 0 && !notes.is_empty() {
|
||||
notes.push("Nothing was changed.".to_string());
|
||||
}
|
||||
let mut r = json!({ "changed": changed, "locked": self.locked + self.outside });
|
||||
if !notes.is_empty()
|
||||
&& let Some(o) = r.as_object_mut()
|
||||
{
|
||||
o.insert("message".into(), json!(notes.join(" ")));
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hs = targets(s, p)?;
|
||||
if hs.is_empty() {
|
||||
return Err(bad("properties.set", "nothing selected"));
|
||||
}
|
||||
let (hs, left_out) = LeftOut::split(s, hs)?;
|
||||
let color = p.get("color").map(|c| parse_color(c).ok_or_else(|| bad("properties.set", "bad colour"))).transpose()?;
|
||||
let transparency = p
|
||||
.get("transparency")
|
||||
.map(|v| parse_transparency(v).ok_or_else(|| bad("properties.set", "transparency must be ByLayer, ByBlock or a percentage from 0 to 90")))
|
||||
.transpose()?;
|
||||
let thickness = p
|
||||
.get("thickness")
|
||||
.map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number")))
|
||||
.transpose()?;
|
||||
let lw = p.get("lineweight").map(|v| super::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?;
|
||||
let d = s.doc()?;
|
||||
// An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires).
|
||||
let linetype = str_param(p, "linetype")
|
||||
.map(|n| {
|
||||
if n.eq_ignore_ascii_case("ByLayer") || n.eq_ignore_ascii_case("ByBlock") {
|
||||
Ok(n.to_string())
|
||||
} else {
|
||||
d.linetype(n).map(|t| t.name.clone()).ok_or_else(|| bad("properties.set", format!("linetype `{n}` is not loaded")))
|
||||
}
|
||||
})
|
||||
.transpose()?;
|
||||
let dim_style = str_param(p, "dimStyle")
|
||||
.map(|n| d.dim_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("dimension style `{n}` not found"))))
|
||||
.transpose()?;
|
||||
let dim_over = dim_overrides(p)?;
|
||||
if hs.is_empty() {
|
||||
// Every object was left out: the drawing stays as it was, with no undo step.
|
||||
return Ok(left_out.result(0));
|
||||
}
|
||||
let d = s.doc_mut()?;
|
||||
if let Some(l) = str_param(p, "layer") {
|
||||
d.ensure_layer(l);
|
||||
}
|
||||
let anno_scale = d.current_anno_scale();
|
||||
let common = CommonEntityProperties { anno_scale: &anno_scale, color, linetype: linetype.as_deref(), lineweight: lw, transparency, thickness };
|
||||
for h in &hs {
|
||||
d.modify_entity(*h, |e| {
|
||||
set_common_properties(e, p, &common);
|
||||
apply_kind_properties(e, p, dim_style.as_ref(), &dim_over);
|
||||
})?;
|
||||
}
|
||||
Ok(left_out.result(hs.len()))
|
||||
}
|
||||
|
||||
fn apply_kind_properties(
|
||||
entity: &mut cadcraft_doc::Entity,
|
||||
params: &Value,
|
||||
dim_style: Option<&String>,
|
||||
dim_overrides: &serde_json::Map<String, Value>,
|
||||
) {
|
||||
let num = |key: &str| params.get(key).and_then(Value::as_f64).filter(|value| value.is_finite());
|
||||
match &mut entity.kind {
|
||||
EntityKind::Line(l) => {
|
||||
if let Some(v) = params.get("start") {
|
||||
set_xy(&mut l.a, v);
|
||||
}
|
||||
if let Some(v) = params.get("end") {
|
||||
set_xy(&mut l.b, v);
|
||||
}
|
||||
// Length / angle keep the start point and move the end point.
|
||||
let (a, b) = (l.a.xy(), l.b.xy());
|
||||
let len = num("length").filter(|x| *x > 0.0 && *x < 1e15).unwrap_or_else(|| a.dist(b));
|
||||
let ang = num("angle").map(f64::to_radians).unwrap_or_else(|| a.angle_to(b));
|
||||
if num("length").is_some() || num("angle").is_some() {
|
||||
let e = cadcraft_geom::Vec2::polar(a, len, ang);
|
||||
if e.is_finite() {
|
||||
l.b.x = e.x;
|
||||
l.b.y = e.y;
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::Circle(c) => {
|
||||
if let Some(v) = params.get("center") {
|
||||
set_xy(&mut c.center, v);
|
||||
}
|
||||
if let Some(r) = num("radius").filter(|r| *r > 0.0) {
|
||||
c.radius = r;
|
||||
}
|
||||
if let Some(dm) = num("diameter").filter(|r| *r > 0.0) {
|
||||
c.radius = dm / 2.0;
|
||||
}
|
||||
if let Some(cf) = num("circumference").filter(|x| *x > 0.0) {
|
||||
c.radius = cf / cadcraft_geom::TAU;
|
||||
}
|
||||
if let Some(a) = num("area").filter(|x| *x > 0.0) {
|
||||
c.radius = (a / cadcraft_geom::PI).sqrt();
|
||||
}
|
||||
}
|
||||
EntityKind::Arc(a) => {
|
||||
if let Some(v) = params.get("center") {
|
||||
set_xy(&mut a.center, v);
|
||||
}
|
||||
if let Some(r) = num("radius").filter(|r| *r > 0.0) {
|
||||
a.radius = r;
|
||||
}
|
||||
if let Some(x) = num("startAngle") {
|
||||
a.start = cadcraft_geom::norm_angle(x.to_radians());
|
||||
}
|
||||
if let Some(x) = num("endAngle") {
|
||||
a.end = cadcraft_geom::norm_angle(x.to_radians());
|
||||
}
|
||||
}
|
||||
EntityKind::Text(t) => {
|
||||
if let Some(v) = str_param(params, "text") {
|
||||
t.value = v.to_string();
|
||||
}
|
||||
if let Some(x) = num("height").filter(|x| *x > 0.0) {
|
||||
t.height = x;
|
||||
}
|
||||
if let Some(x) = num("rotation") {
|
||||
t.rotation = x.to_radians();
|
||||
}
|
||||
if let Some(x) = num("widthFactor").filter(|x| *x > 0.0) {
|
||||
t.width_factor = x;
|
||||
}
|
||||
// The position is the point the text is placed by: moving it moves the text.
|
||||
if let Some(to) = params.get("position").and_then(point_value) {
|
||||
let d = to - t.justify_point();
|
||||
for q in std::iter::once(&mut t.insert).chain(t.align_pt.as_mut()) {
|
||||
q.x += d.x;
|
||||
q.y += d.y;
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::MText(t) => {
|
||||
if let Some(v) = str_param(params, "text") {
|
||||
t.contents = v.replace('\n', "\\P");
|
||||
}
|
||||
if let Some(x) = num("height").filter(|x| *x > 0.0) {
|
||||
t.height = x;
|
||||
}
|
||||
if let Some(x) = num("width").filter(|x| *x >= 0.0) {
|
||||
t.width = x;
|
||||
}
|
||||
if let Some(x) = num("rotation") {
|
||||
t.rotation = x.to_radians();
|
||||
}
|
||||
}
|
||||
// A multileader's text: its contents (#1081) and height.
|
||||
EntityKind::MLeader(m) => {
|
||||
if let Some(t) = &mut m.text {
|
||||
if let Some(v) = str_param(params, "text") {
|
||||
t.contents = v.replace('\n', "\\P");
|
||||
}
|
||||
if let Some(x) = num("height").filter(|x| *x > 0.0) {
|
||||
t.height = x;
|
||||
}
|
||||
}
|
||||
}
|
||||
EntityKind::LwPolyline(pl) => {
|
||||
if let Some(x) = num("width").filter(|x| *x >= 0.0) {
|
||||
pl.const_width = x;
|
||||
}
|
||||
if let Some(c) = params.get("closed").and_then(Value::as_bool) {
|
||||
pl.closed = c;
|
||||
}
|
||||
}
|
||||
EntityKind::Insert(insert) => set_insert_properties(insert, params),
|
||||
EntityKind::Dimension(dimension) => set_dimension_properties(dimension, params, dim_style, dim_overrides),
|
||||
EntityKind::Hatch(hatch) => set_hatch_properties(hatch, params),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_insert_properties(insert: &mut cadcraft_doc::Insert, params: &Value) {
|
||||
let number = |key: &str| params.get(key).and_then(Value::as_f64).filter(|value| value.is_finite());
|
||||
|
||||
if let Some(x) = number("rotation") {
|
||||
let turn = x.to_radians() - insert.rotation;
|
||||
insert.rotation = x.to_radians();
|
||||
// The attached text turns with the reference, around its insertion point (as ROTATE does).
|
||||
let base = insert.insert.xy();
|
||||
for a in &mut insert.attribs {
|
||||
let t = &mut a.text;
|
||||
for q in std::iter::once(&mut t.insert).chain(t.align_pt.as_mut()) {
|
||||
let r = q.xy().rotate_about(base, turn);
|
||||
q.x = r.x;
|
||||
q.y = r.y;
|
||||
}
|
||||
t.rotation = cadcraft_geom::norm_angle(t.rotation + turn);
|
||||
if let Some(ml) = &mut a.multiline {
|
||||
let r = ml.mtext.insert.xy().rotate_about(base, turn);
|
||||
ml.mtext.insert.x = r.x;
|
||||
ml.mtext.insert.y = r.y;
|
||||
ml.mtext.rotation = cadcraft_geom::norm_angle(ml.mtext.rotation + turn);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(x) = number("scale").filter(|x| *x != 0.0) {
|
||||
// A new positive scale carries the attached attribute text with it, like SCALE about the insertion point.
|
||||
if x > 0.0 && insert.scale.x > 0.0 {
|
||||
let m = cadcraft_geom::Mat3::scale_about(insert.insert.xy(), x / insert.scale.x);
|
||||
for a in &mut insert.attribs {
|
||||
let mut k = EntityKind::Text(a.text.clone());
|
||||
k.transform(&m);
|
||||
if let EntityKind::Text(t) = k {
|
||||
a.text = t;
|
||||
}
|
||||
a.transform_multiline(&m);
|
||||
}
|
||||
}
|
||||
insert.scale = Vec3::new(x, x, x);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_dimension_properties(
|
||||
dimension: &mut cadcraft_doc::Dimension,
|
||||
params: &Value,
|
||||
style: Option<&String>,
|
||||
overrides: &serde_json::Map<String, Value>,
|
||||
) {
|
||||
if let Some(v) = str_param(params, "textOverride") {
|
||||
dimension.text = v.to_string();
|
||||
dimension.block = None;
|
||||
}
|
||||
if let Some(st) = style {
|
||||
dimension.style.clone_from(st);
|
||||
dimension.block = None;
|
||||
}
|
||||
if !overrides.is_empty() {
|
||||
dimension.overrides.extend(overrides.clone());
|
||||
dimension.block = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn set_hatch_properties(hatch: &mut cadcraft_doc::Hatch, params: &Value) {
|
||||
let number = |key: &str| params.get(key).and_then(Value::as_f64).filter(|value| value.is_finite());
|
||||
|
||||
if let Some(v) = str_param(params, "pattern") {
|
||||
if !hatch.pattern.eq_ignore_ascii_case(v) {
|
||||
hatch.pattern_lines = super::hatch::lines_for(v);
|
||||
}
|
||||
hatch.pattern = v.to_ascii_uppercase();
|
||||
// The old pattern's definition lines no longer apply.
|
||||
hatch.pattern_lines.clear();
|
||||
hatch.solid = hatch.pattern == "SOLID";
|
||||
if !hatch.solid {
|
||||
// A named pattern replaces the gradient fill; the renderer draws the gradient first when it is set.
|
||||
hatch.gradient = None;
|
||||
}
|
||||
}
|
||||
if let Some(x) = number("scale").filter(|x| *x > 0.0) {
|
||||
hatch.scale = x;
|
||||
}
|
||||
if let Some(x) = number("angle") {
|
||||
hatch.angle = x.to_radians();
|
||||
}
|
||||
}
|
||||
|
||||
struct CommonEntityProperties<'a> {
|
||||
anno_scale: &'a cadcraft_doc::AnnoScale,
|
||||
color: Option<Color>,
|
||||
linetype: Option<&'a str>,
|
||||
lineweight: Option<Lineweight>,
|
||||
transparency: Option<Transparency>,
|
||||
thickness: Option<f64>,
|
||||
}
|
||||
|
||||
fn set_common_properties(entity: &mut cadcraft_doc::Entity, params: &Value, common: &CommonEntityProperties<'_>) {
|
||||
if let Some(annotative) = params.get("annotative").and_then(Value::as_bool) {
|
||||
cadcraft_doc::set_annotative(entity, annotative, common.anno_scale);
|
||||
}
|
||||
if let Some(layer) = str_param(params, "layer") {
|
||||
entity.common.layer = layer.to_string();
|
||||
}
|
||||
if let Some(color) = common.color {
|
||||
entity.common.color = color;
|
||||
}
|
||||
if let Some(linetype) = common.linetype {
|
||||
entity.common.linetype = linetype.to_string();
|
||||
}
|
||||
if let Some(lineweight) = common.lineweight {
|
||||
entity.common.lineweight = lineweight;
|
||||
}
|
||||
if let Some(scale) = params.get("ltscale").and_then(Value::as_f64).filter(|scale| *scale > 0.0) {
|
||||
entity.common.ltscale = scale;
|
||||
}
|
||||
if let Some(transparency) = common.transparency {
|
||||
entity.common.transparency = transparency;
|
||||
}
|
||||
if let Some(thickness) = common.thickness {
|
||||
entity.common.thickness = thickness;
|
||||
}
|
||||
if let Some(visible) = params.get("visible").and_then(Value::as_bool) {
|
||||
entity.common.visible = visible;
|
||||
}
|
||||
}
|
||||
|
||||
fn run_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = p.get("color").and_then(parse_color).ok_or_else(|| bad("color", "`color` is required"))?;
|
||||
set_current_color(s.doc_mut()?, c);
|
||||
@@ -447,8 +791,6 @@ fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad("style", "bad style name"));
|
||||
}
|
||||
let d = s.doc_mut()?;
|
||||
// As it was (none for a new style), so dimensions are redrawn only when it changes.
|
||||
let before = d.text_style(&name).cloned();
|
||||
let idx = match d.text_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
@@ -484,13 +826,6 @@ fn run_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Dimensions whose text uses the style drop the geometry they were read with when it
|
||||
// changed: their text changes with it. Only making it current keeps that geometry.
|
||||
if before.as_ref() != d.text_styles.get(idx) {
|
||||
let text_style_of: std::collections::HashMap<String, String> =
|
||||
d.dim_styles.iter().map(|st| (st.name.to_ascii_lowercase(), st.text_style.clone())).collect();
|
||||
regen_dims(d, |dm| dim_text_style(dm, &text_style_of).eq_ignore_ascii_case(&name))?;
|
||||
}
|
||||
if bool_or(p, "current", true) {
|
||||
d.header.set_str("TEXTSTYLE", &name);
|
||||
}
|
||||
@@ -519,19 +854,12 @@ pub(super) fn text_styles_in_use(d: &cadcraft_doc::Drawing) -> Vec<String> {
|
||||
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities));
|
||||
for st in stores {
|
||||
for e in st.iter() {
|
||||
out.extend(super::blocks::object_attribs(e).iter().flat_map(attrib_text_styles));
|
||||
match &e.kind {
|
||||
EntityKind::Text(t) => out.push(t.style.clone()),
|
||||
EntityKind::MText(t) => out.push(t.style.clone()),
|
||||
EntityKind::AttDef(a) => out.extend(attrib_text_styles(a)),
|
||||
EntityKind::AttDef(a) => out.push(a.text.style.clone()),
|
||||
EntityKind::Insert(i) => out.extend(i.attribs.iter().map(|a| a.text.style.clone())),
|
||||
EntityKind::MLeader(m) => out.extend(m.text.iter().map(|t| t.style.clone())),
|
||||
// A dimension's own text style (a DIMTXSTY override), which a rename follows too.
|
||||
EntityKind::Dimension(dm) => out.extend(
|
||||
dm.overrides
|
||||
.iter()
|
||||
.filter(|(k, _)| cadcraft_doc::DimStyle::field_name(k) == Some("textStyle"))
|
||||
.filter_map(|(_, v)| super::blocks::purge::override_name(v)),
|
||||
),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -539,11 +867,6 @@ pub(super) fn text_styles_in_use(d: &cadcraft_doc::Drawing) -> Vec<String> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The text styles of an attribute or attribute definition, its multiline text included.
|
||||
fn attrib_text_styles(a: &cadcraft_doc::Attrib) -> impl Iterator<Item = String> + '_ {
|
||||
std::iter::once(a.text.style.clone()).chain(a.multiline.iter().map(|m| m.mtext.style.clone()))
|
||||
}
|
||||
|
||||
fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let from = str_param(p, "from").ok_or_else(|| bad("style.rename", "`from` is required"))?.to_string();
|
||||
let to = str_param(p, "to").map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| bad("style.rename", "`to` is required"))?.to_string();
|
||||
@@ -573,7 +896,6 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
EntityKind::AttDef(a) => a.text.style.eq_ignore_ascii_case(&from),
|
||||
EntityKind::Insert(i) => i.attribs.iter().any(|a| a.text.style.eq_ignore_ascii_case(&from)),
|
||||
EntityKind::MLeader(m) => m.text.iter().any(|t| t.style.eq_ignore_ascii_case(&from)),
|
||||
EntityKind::Dimension(dm) => dm.overrides.iter().any(|(k, v)| is_text_style_override(k, v, &from)),
|
||||
_ => false,
|
||||
};
|
||||
let repoint = |k: &mut EntityKind| match k {
|
||||
@@ -582,8 +904,6 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
EntityKind::AttDef(a) => fix(&mut a.text.style),
|
||||
EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| fix(&mut a.text.style)),
|
||||
EntityKind::MLeader(m) => m.text.iter_mut().for_each(|t| fix(&mut t.style)),
|
||||
// A dimension's own text style (a DIMTXSTY override).
|
||||
EntityKind::Dimension(dm) => dm.overrides.iter_mut().filter(|(k, v)| is_text_style_override(k, v, &from)).for_each(|(_, v)| *v = json!(to)),
|
||||
_ => {}
|
||||
};
|
||||
let mut hs: Vec<cadcraft_doc::Handle> = d.model.iter().filter(|e| uses(&e.kind)).map(|e| e.handle).collect();
|
||||
@@ -633,14 +953,7 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if name.is_empty() || name.len() > 255 {
|
||||
return Err(bad("dimstyle", "bad style name"));
|
||||
}
|
||||
// A new style's name is one -DIMSTYLE takes (no `~`, which its Restore reads as compare, or
|
||||
// wildcards); a style read from a file keeps the name it has.
|
||||
if s.doc()?.dim_style(&name).is_none() {
|
||||
super::dimstyle_cli::check_name(&name).map_err(|_| bad("dimstyle", "bad style name"))?;
|
||||
}
|
||||
let d = s.doc_mut()?;
|
||||
// As it was (none for a new style), so dimensions are redrawn only when it changes.
|
||||
let before = d.dim_style(&name).cloned();
|
||||
let base = d.dim_style(&d.header.str("DIMSTYLE", "Standard")).cloned().unwrap_or_default();
|
||||
let idx = match d.dim_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&name)) {
|
||||
Some(i) => i,
|
||||
@@ -655,12 +968,6 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
src.iter().filter(|(k, _)| !matches!(k.as_str(), "name" | "current")).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
rejected = st.apply_fields(&fields);
|
||||
}
|
||||
// Dimensions with the style drop the geometry they were read with when it changed, so they
|
||||
// show the edit (as AutoCAD updates every dimension that uses a style; their overrides still
|
||||
// win). Only making it current keeps that geometry.
|
||||
if before.as_ref() != d.dim_styles.get(idx) {
|
||||
regen_dims(d, |dm| dm.style.eq_ignore_ascii_case(&name))?;
|
||||
}
|
||||
if bool_or(p, "current", true) {
|
||||
d.header.set_str("DIMSTYLE", &name);
|
||||
}
|
||||
@@ -672,8 +979,7 @@ fn run_dimstyle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !rejected.is_empty()
|
||||
&& let Some(o) = out.as_object_mut()
|
||||
{
|
||||
o.insert("ignored".into(), json!(rejected.clone()));
|
||||
o.insert("message".into(), json!(format!("Ignored invalid value for: {}", rejected.join(", "))));
|
||||
o.insert("ignored".into(), json!(rejected));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -704,44 +1010,6 @@ fn run_dimstyle_current(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(dimstyles_json(d))
|
||||
}
|
||||
|
||||
/// Dimensions (in model space, layouts and block definitions) that `uses` matches drop the
|
||||
/// geometry block they were read with, so they are drawn and saved from their style again.
|
||||
pub(super) fn regen_dims(d: &mut cadcraft_doc::Drawing, uses: impl Fn(&cadcraft_doc::Dimension) -> bool) -> Result<()> {
|
||||
let stale = |e: &cadcraft_doc::Entity| matches!(&e.kind, EntityKind::Dimension(dm) if dm.block.is_some() && uses(dm));
|
||||
let regen = |e: &mut cadcraft_doc::Entity| {
|
||||
if let EntityKind::Dimension(dm) = &mut e.kind {
|
||||
dm.block = None;
|
||||
}
|
||||
};
|
||||
let mut hs: Vec<cadcraft_doc::Handle> = d.model.iter().filter(|e| stale(e)).map(|e| e.handle).collect();
|
||||
hs.extend(d.layouts.iter().flat_map(|l| l.entities.iter().filter(|e| stale(e)).map(|e| e.handle)));
|
||||
for h in hs {
|
||||
d.modify_entity(h, regen)?;
|
||||
}
|
||||
for block in d.blocks.values_mut() {
|
||||
let hs: Vec<cadcraft_doc::Handle> = block.entities.iter().filter(|e| stale(e)).map(|e| e.handle).collect();
|
||||
if !hs.is_empty() {
|
||||
let b = std::sync::Arc::make_mut(block);
|
||||
for h in hs {
|
||||
b.entities.modify(h, regen);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The text style a dimension's text is drawn with: its DIMTXSTY override, else its style's
|
||||
/// (`text_style_of`: lower-case dimension style name → text style).
|
||||
fn dim_text_style(dm: &cadcraft_doc::Dimension, text_style_of: &std::collections::HashMap<String, String>) -> String {
|
||||
let own = dm.overrides.iter().find(|(k, _)| cadcraft_doc::DimStyle::field_name(k) == Some("textStyle")).and_then(|(_, v)| v.as_str());
|
||||
own.map(str::to_string).or_else(|| text_style_of.get(&dm.style.to_ascii_lowercase()).cloned()).unwrap_or_else(|| "Standard".into())
|
||||
}
|
||||
|
||||
/// Whether a dimension override `k: v` names text style `style`.
|
||||
fn is_text_style_override(k: &str, v: &Value, style: &str) -> bool {
|
||||
cadcraft_doc::DimStyle::field_name(k) == Some("textStyle") && v.as_str().is_some_and(|n| n.eq_ignore_ascii_case(style))
|
||||
}
|
||||
|
||||
fn dims_using(d: &cadcraft_doc::Drawing, name: &str) -> Vec<(cadcraft_doc::Space, cadcraft_doc::Handle)> {
|
||||
let mut out = Vec::new();
|
||||
for space in std::iter::once(cadcraft_doc::Space::Model).chain(d.layouts.iter().map(|l| cadcraft_doc::Space::Paper(l.name.clone()))) {
|
||||
@@ -784,7 +1052,6 @@ fn block_dims_using(d: &cadcraft_doc::Drawing, name: &str) -> Vec<(String, cadcr
|
||||
fn run_dimstyle_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let from = str_param(p, "from").ok_or_else(|| bad("dimstyle.rename", "`from` is required"))?.to_string();
|
||||
let to = str_param(p, "to").map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| bad("dimstyle.rename", "`to` is required"))?.to_string();
|
||||
let to = super::dimstyle_cli::check_name(&to).map_err(|_| bad("dimstyle.rename", "bad style name"))?;
|
||||
let d = s.doc_mut()?;
|
||||
if from.eq_ignore_ascii_case("Standard") {
|
||||
return Err(bad("dimstyle.rename", "the Standard style cannot be renamed"));
|
||||
|
||||
@@ -1,781 +0,0 @@
|
||||
//! `properties.set`: change properties of the selected objects, the way the Properties palette
|
||||
//! edits them. Keys that no selected object takes come back in `ignored`.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use cadcraft_color::Color;
|
||||
use cadcraft_doc::{
|
||||
AnnoScale, Arc, Circle, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, Handle, Hatch, Insert, Line, Lineweight, MText, Text,
|
||||
Transparency, VAlign,
|
||||
};
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{parse_color, parse_transparency};
|
||||
use crate::cmd::{bad, point_value, str_param, targets};
|
||||
use crate::properties::{LINE_PITCH, is_dim_linetype, join_post, split_post};
|
||||
use crate::{Result, Session};
|
||||
|
||||
fn set_xy(p: &mut Vec3, v: &Value) {
|
||||
if let Some(q) = point_value(v) {
|
||||
p.x = q.x;
|
||||
p.y = q.y;
|
||||
}
|
||||
}
|
||||
|
||||
/// Keys `properties.set` handles itself; the rest that name a dimension style variable (a field
|
||||
/// such as `textHeight` or a DIM* name such as `DIMTXT`) set per-dimension overrides.
|
||||
const SET_KEYS: &[&str] = &[
|
||||
"handles",
|
||||
"handle",
|
||||
"layer",
|
||||
"color",
|
||||
"linetype",
|
||||
"lineweight",
|
||||
"ltscale",
|
||||
"thickness",
|
||||
"transparency",
|
||||
"visible",
|
||||
"annotative",
|
||||
"dimStyle",
|
||||
"textOverride",
|
||||
"textRotation",
|
||||
"textPositionX",
|
||||
"textPositionY",
|
||||
"clearOverrides",
|
||||
"clear",
|
||||
"prefix",
|
||||
"suffix",
|
||||
"altPrefix",
|
||||
"altSuffix",
|
||||
// An insert's or hatch's scale; a dimension's overall scale is `dimScale` (or DIMSCALE).
|
||||
"scale",
|
||||
];
|
||||
|
||||
/// The dimension style variables of a call, checked once: canonical field names with their
|
||||
/// values, and the keys they were given as. Unusable values are left out (and so `ignored`).
|
||||
struct DimVars {
|
||||
fields: Vec<(&'static str, Value)>,
|
||||
keys: Vec<String>,
|
||||
}
|
||||
|
||||
impl DimVars {
|
||||
fn new(d: &Drawing, p: &Value) -> Result<Self> {
|
||||
// Text height, arrow size, overall scale (`dimScale`) and precision are refused, not
|
||||
// ignored, when unusable, and the last two have names of their own (#1473).
|
||||
let checked = super::dim_overrides(p)?;
|
||||
let mut given = serde_json::Map::new();
|
||||
for (k, v) in p.as_object().into_iter().flatten() {
|
||||
if SET_KEYS.contains(&k.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Some(field) = DimStyle::field_name(k).filter(|f| !matches!(*f, "name" | "annotative")) else { continue };
|
||||
let v = match (field, v.as_str()) {
|
||||
// A text style or linetype that doesn't exist would fall back without a word.
|
||||
("textStyle", Some(n)) => {
|
||||
json!(d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found")))?)
|
||||
}
|
||||
(f, Some(n)) if is_dim_linetype(f) => {
|
||||
if n.is_empty() || n.eq_ignore_ascii_case("ByBlock") {
|
||||
json!("")
|
||||
} else {
|
||||
json!(d.linetype(n).map(|t| t.name.clone()).ok_or_else(|| bad("properties.set", format!("linetype `{n}` is not loaded")))?)
|
||||
}
|
||||
}
|
||||
// Closed filled is `""` among the arrowheads, but an empty per-end arrowhead draws
|
||||
// DIMBLK's: chosen for one end, it's named.
|
||||
("arrowBlock1" | "arrowBlock2", Some("")) => json!("_CLOSEDFILLED"),
|
||||
_ => v.clone(),
|
||||
};
|
||||
given.insert(k.clone(), v);
|
||||
}
|
||||
let rejected = DimStyle::default().apply_fields(&given);
|
||||
let mut out = DimVars { fields: Vec::new(), keys: Vec::new() };
|
||||
for (k, v) in given {
|
||||
if rejected.contains(&k) {
|
||||
continue;
|
||||
}
|
||||
if let Some(f) = DimStyle::field_name(&k) {
|
||||
out.fields.push((f, v));
|
||||
out.keys.push(k);
|
||||
}
|
||||
}
|
||||
for (key, field) in [("dimScale", "scale"), ("precision", "decimals")] {
|
||||
if let Some(v) = checked.get(field) {
|
||||
out.fields.push((field, v.clone()));
|
||||
out.keys.push(key.to_string());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// What some edits need to know about objects before they change.
|
||||
#[derive(Default)]
|
||||
struct Prepared {
|
||||
/// TEXT made aligned or fit: where its baseline ends (its width along its rotation).
|
||||
ends: HashMap<Handle, Vec2>,
|
||||
/// Dimensions: where their text is drawn now.
|
||||
text_pos: HashMap<Handle, Vec2>,
|
||||
/// The DIMPOST and DIMAPOST templates of each dimension style (by lowercase name), when a
|
||||
/// prefix or suffix is edited: a dimension's are worked out after its other edits.
|
||||
posts: Option<HashMap<String, (String, String)>>,
|
||||
}
|
||||
|
||||
impl Prepared {
|
||||
fn new(d: &Drawing, p: &Value, hs: &[Handle]) -> Self {
|
||||
let mut out = Prepared::default();
|
||||
let two_points = str_param(p, "justify").and_then(crate::cmd::draw::justify).is_some_and(|(h, _)| matches!(h, HAlign::Aligned | HAlign::Fit));
|
||||
let moves_text = p.get("textPositionX").is_some() || p.get("textPositionY").is_some();
|
||||
let posts = ["prefix", "suffix", "altPrefix", "altSuffix"].iter().any(|k| p.get(*k).is_some());
|
||||
if !(two_points || moves_text || posts) {
|
||||
return out;
|
||||
}
|
||||
for h in hs {
|
||||
let Some(e) = d.entity(*h) else { continue };
|
||||
match &e.kind {
|
||||
EntityKind::Text(t) if two_points => {
|
||||
// The text as this call leaves it: its contents, style, height, width factor
|
||||
// and rotation, where the call sets them too.
|
||||
let num = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite());
|
||||
let style = str_param(p, "style").and_then(|n| d.text_style(n)).map_or(t.style.as_str(), |s| s.name.as_str());
|
||||
let value = str_param(p, "text").unwrap_or(&t.value);
|
||||
let height = num("height").filter(|x| *x > 0.0).unwrap_or(t.height);
|
||||
let width_factor = num("widthFactor").filter(|x| *x > 0.0).unwrap_or(t.width_factor);
|
||||
let rotation = num("rotation").map_or(t.rotation, f64::to_radians);
|
||||
let font = cadcraft_fonts::TextFont::resolve(&d.text_style(style).cloned().unwrap_or_default().font);
|
||||
let w = cadcraft_fonts::text_width(&font, value, height, width_factor);
|
||||
let w = if w.is_finite() && w > 1e-9 { w } else { height.max(1e-9) };
|
||||
out.ends.insert(*h, Vec2::polar(t.justify_point(), w, rotation));
|
||||
}
|
||||
EntityKind::Dimension(dm) if moves_text => {
|
||||
out.text_pos.insert(*h, cadcraft_render::dimension_in(d, dm).text_pos);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if posts {
|
||||
out.posts = Some(d.dim_styles.iter().map(|st| (st.name.to_ascii_lowercase(), (st.post.clone(), st.alt_post.clone()))).collect());
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Give TEXT a justification. It keeps the point it is placed by, so the text moves (as
|
||||
/// AutoCAD's Properties Justify does); aligned and fit text then ends at `end`.
|
||||
fn set_justify(t: &mut Text, h: HAlign, v: VAlign, end: Option<Vec2>) {
|
||||
let at = t.justify_point();
|
||||
let z = t.insert.z;
|
||||
let was_two_points = matches!(t.halign, HAlign::Aligned | HAlign::Fit) && t.align_pt.is_some();
|
||||
let two_points = matches!(h, HAlign::Aligned | HAlign::Fit);
|
||||
t.halign = h;
|
||||
t.valign = if two_points { VAlign::Baseline } else { v };
|
||||
if two_points {
|
||||
// Between aligned and fit the two points stay.
|
||||
if !was_two_points {
|
||||
t.insert = at.to3(z);
|
||||
t.align_pt = Some(end.unwrap_or_else(|| Vec2::polar(at, t.height.max(1e-9), t.rotation)).to3(z));
|
||||
}
|
||||
} else if (h, v) == (HAlign::Left, VAlign::Baseline) {
|
||||
t.insert = at.to3(z);
|
||||
t.align_pt = None;
|
||||
} else {
|
||||
t.insert = at.to3(z);
|
||||
t.align_pt = Some(at.to3(z));
|
||||
}
|
||||
}
|
||||
|
||||
/// Move TEXT by `d` (both of its points).
|
||||
fn shift(t: &mut Text, d: Vec2) {
|
||||
for q in std::iter::once(&mut t.insert).chain(t.align_pt.as_mut()) {
|
||||
q.x += d.x;
|
||||
q.y += d.y;
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a per-dimension override, replacing the same variable under another spelling (a DIM*
|
||||
/// name read from a file).
|
||||
fn set_override(dm: &mut cadcraft_doc::Dimension, field: &'static str, v: Value) {
|
||||
dm.overrides.retain(|k, _| DimStyle::field_name(k) != Some(field));
|
||||
dm.overrides.insert(field.to_string(), v);
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
p: &'a Value,
|
||||
color: Option<Color>,
|
||||
transparency: Option<Transparency>,
|
||||
thickness: Option<f64>,
|
||||
lineweight: Option<Lineweight>,
|
||||
linetype: Option<String>,
|
||||
dim_style: Option<String>,
|
||||
text_style: Option<String>,
|
||||
dim_vars: DimVars,
|
||||
prep: Prepared,
|
||||
anno_scale: AnnoScale,
|
||||
}
|
||||
|
||||
/// The keys some object took.
|
||||
type Used<'c> = BTreeSet<&'c str>;
|
||||
|
||||
impl Call<'_> {
|
||||
/// A finite number under `k`.
|
||||
fn num(&self, k: &str) -> Option<f64> {
|
||||
self.p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite())
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects `properties.set` leaves alone, as CHPROP, MATCHPROP and MOVE do: those on locked
|
||||
/// layers and, while a reference is edited in place, those outside the working set.
|
||||
#[derive(Default)]
|
||||
struct LeftOut {
|
||||
locked: usize,
|
||||
outside: usize,
|
||||
}
|
||||
|
||||
impl LeftOut {
|
||||
/// `hs` without the objects that can't be edited, each object once, and how many those were. A
|
||||
/// handle that names no object is an error, before anything changes.
|
||||
fn split(s: &Session, hs: Vec<Handle>) -> Result<(Vec<Handle>, LeftOut)> {
|
||||
let d = s.doc()?;
|
||||
// The working set, once: `RefEdit::is_working` searches a list.
|
||||
let working: Option<std::collections::HashSet<Handle>> = d.refedit.as_ref().map(|r| r.items.iter().map(|i| i.copy).collect());
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out = LeftOut::default();
|
||||
let mut free = Vec::new();
|
||||
for h in hs {
|
||||
let Some(e) = d.entity(h) else {
|
||||
return Err(cadcraft_doc::DocError::NoEntity(h).into());
|
||||
};
|
||||
if !seen.insert(h) {
|
||||
continue;
|
||||
}
|
||||
if working.as_ref().is_some_and(|w| !w.contains(&h)) {
|
||||
out.outside += 1;
|
||||
} else if d.layer(&e.common.layer).is_some_and(|l| l.locked) {
|
||||
out.locked += 1;
|
||||
} else {
|
||||
free.push(h);
|
||||
}
|
||||
}
|
||||
Ok((free, out))
|
||||
}
|
||||
|
||||
/// `{changed, locked, ignored}`, and a message saying how many were left out when any were.
|
||||
fn result(&self, changed: usize, ignored: &[&str]) -> Value {
|
||||
let mut notes = Vec::new();
|
||||
match self.locked {
|
||||
0 => {}
|
||||
1 => notes.push("1 object was on a locked layer.".to_string()),
|
||||
n => notes.push(format!("{n} objects were on a locked layer.")),
|
||||
}
|
||||
match self.outside {
|
||||
0 => {}
|
||||
1 => notes.push("1 object was not in the working set.".to_string()),
|
||||
n => notes.push(format!("{n} objects were not in the working set.")),
|
||||
}
|
||||
if changed == 0 && !notes.is_empty() {
|
||||
notes.push("Nothing was changed.".to_string());
|
||||
}
|
||||
let mut r = json!({ "changed": changed, "locked": self.locked + self.outside, "ignored": ignored });
|
||||
if !notes.is_empty()
|
||||
&& let Some(o) = r.as_object_mut()
|
||||
{
|
||||
o.insert("message".into(), json!(notes.join(" ")));
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hs = targets(s, p)?;
|
||||
if hs.is_empty() {
|
||||
return Err(bad("properties.set", "nothing selected"));
|
||||
}
|
||||
let (hs, left_out) = LeftOut::split(s, hs)?;
|
||||
let color = p.get("color").map(|c| parse_color(c).ok_or_else(|| bad("properties.set", "bad colour"))).transpose()?;
|
||||
let transparency = p
|
||||
.get("transparency")
|
||||
.map(|v| parse_transparency(v).ok_or_else(|| bad("properties.set", "transparency must be ByLayer, ByBlock or a percentage from 0 to 90")))
|
||||
.transpose()?;
|
||||
let thickness = p
|
||||
.get("thickness")
|
||||
.map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number")))
|
||||
.transpose()?;
|
||||
let lineweight =
|
||||
p.get("lineweight").map(|v| crate::cmd::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?;
|
||||
// Every check reads the drawing first: a refused call leaves no empty undo step.
|
||||
let d = s.doc()?;
|
||||
// An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires).
|
||||
let linetype = str_param(p, "linetype")
|
||||
.map(|n| {
|
||||
if n.eq_ignore_ascii_case("ByLayer") || n.eq_ignore_ascii_case("ByBlock") {
|
||||
Ok(n.to_string())
|
||||
} else {
|
||||
d.linetype(n).map(|t| t.name.clone()).ok_or_else(|| bad("properties.set", format!("linetype `{n}` is not loaded")))
|
||||
}
|
||||
})
|
||||
.transpose()?;
|
||||
let dim_style = str_param(p, "dimStyle")
|
||||
.map(|n| d.dim_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("dimension style `{n}` not found"))))
|
||||
.transpose()?;
|
||||
let text_style = str_param(p, "style")
|
||||
.map(|n| d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found"))))
|
||||
.transpose()?;
|
||||
let dim_vars = DimVars::new(d, p)?;
|
||||
// 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())
|
||||
&& 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())));
|
||||
}
|
||||
if hs.is_empty() {
|
||||
// Every object was left out: the drawing stays as it was, with no undo step.
|
||||
return Ok(left_out.result(0, &[]));
|
||||
}
|
||||
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 };
|
||||
// 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()?;
|
||||
if let Some(l) = str_param(p, "layer") {
|
||||
d.ensure_layer(l);
|
||||
}
|
||||
let mut used = Used::new();
|
||||
for h in &hs {
|
||||
let h = *h;
|
||||
d.modify_entity(h, |e| {
|
||||
common(e, &c, &mut used);
|
||||
match &mut e.kind {
|
||||
EntityKind::Line(l) => line(l, &c, &mut used),
|
||||
EntityKind::Circle(ci) => circle(ci, &c, &mut used),
|
||||
EntityKind::Arc(a) => arc(a, &c, &mut used),
|
||||
EntityKind::Text(t) => {
|
||||
text(t, &c, h, &mut used);
|
||||
text_position(t, &c, &mut used);
|
||||
}
|
||||
EntityKind::MText(t) => mtext(t, &c, &mut used),
|
||||
EntityKind::MLeader(m) => mleader(m, &c, &mut used),
|
||||
EntityKind::LwPolyline(pl) => {
|
||||
if let Some(x) = c.num("width").filter(|x| *x >= 0.0) {
|
||||
pl.const_width = x;
|
||||
used.insert("width");
|
||||
}
|
||||
if let Some(closed) = p.get("closed").and_then(Value::as_bool) {
|
||||
pl.closed = closed;
|
||||
used.insert("closed");
|
||||
}
|
||||
}
|
||||
EntityKind::Insert(i) => insert(i, &c, &mut used),
|
||||
EntityKind::Dimension(dm) => dimension(dm, &c, h, &mut used),
|
||||
EntityKind::Hatch(ha) => hatch(ha, &c, &mut used),
|
||||
_ => {}
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let ignored: Vec<&str> = p
|
||||
.as_object()
|
||||
.map(|o| o.keys().map(String::as_str).filter(|k| !matches!(*k, "handles" | "handle") && !used.contains(k)).collect())
|
||||
.unwrap_or_default();
|
||||
Ok(left_out.result(hs.len(), &ignored))
|
||||
}
|
||||
|
||||
/// A multileader's text: its contents (#1081) and height.
|
||||
fn mleader<'c>(m: &mut cadcraft_doc::MLeader, c: &'c Call<'_>, used: &mut Used<'c>) {
|
||||
let Some(t) = &mut m.text else { return };
|
||||
if let Some(v) = str_param(c.p, "text") {
|
||||
t.contents = v.replace('\n', "\\P");
|
||||
used.insert("text");
|
||||
}
|
||||
if let Some(x) = c.num("height").filter(|x| *x > 0.0) {
|
||||
t.height = x;
|
||||
used.insert("height");
|
||||
}
|
||||
}
|
||||
|
||||
/// The properties every object has: annotative, layer, color, linetype, lineweight, linetype
|
||||
/// scale, transparency, thickness and visibility.
|
||||
fn common<'c>(e: &mut Entity, c: &'c Call<'_>, used: &mut Used<'c>) {
|
||||
let p = c.p;
|
||||
// Annotative: Yes supports the current annotation scale; No drops every scale.
|
||||
if let Some(a) = p.get("annotative").and_then(Value::as_bool)
|
||||
&& cadcraft_doc::can_be_annotative(&e.kind)
|
||||
{
|
||||
cadcraft_doc::set_annotative(e, a, &c.anno_scale);
|
||||
if let EntityKind::Dimension(dm) = &mut e.kind {
|
||||
dm.block = None;
|
||||
}
|
||||
used.insert("annotative");
|
||||
}
|
||||
if let Some(l) = str_param(p, "layer") {
|
||||
e.common.layer = l.to_string();
|
||||
used.insert("layer");
|
||||
}
|
||||
if let Some(color) = c.color {
|
||||
e.common.color = color;
|
||||
used.insert("color");
|
||||
}
|
||||
if let Some(lt) = &c.linetype {
|
||||
e.common.linetype.clone_from(lt);
|
||||
used.insert("linetype");
|
||||
}
|
||||
if let Some(w) = c.lineweight {
|
||||
e.common.lineweight = w;
|
||||
used.insert("lineweight");
|
||||
}
|
||||
if let Some(x) = p.get("ltscale").and_then(Value::as_f64).filter(|x| *x > 0.0 && x.is_finite()) {
|
||||
e.common.ltscale = x;
|
||||
used.insert("ltscale");
|
||||
}
|
||||
if let Some(t) = c.transparency {
|
||||
e.common.transparency = t;
|
||||
used.insert("transparency");
|
||||
}
|
||||
if let Some(th) = c.thickness {
|
||||
e.common.thickness = th;
|
||||
used.insert("thickness");
|
||||
}
|
||||
if let Some(v) = p.get("visible").and_then(Value::as_bool) {
|
||||
e.common.visible = v;
|
||||
used.insert("visible");
|
||||
}
|
||||
}
|
||||
|
||||
fn line(l: &mut Line, c: &Call<'_>, used: &mut Used<'_>) {
|
||||
if let Some(v) = c.p.get("start") {
|
||||
set_xy(&mut l.a, v);
|
||||
used.insert("start");
|
||||
}
|
||||
if let Some(v) = c.p.get("end") {
|
||||
set_xy(&mut l.b, v);
|
||||
used.insert("end");
|
||||
}
|
||||
// Length / angle keep the start point and move the end point.
|
||||
let (a, b) = (l.a.xy(), l.b.xy());
|
||||
let length = c.num("length").filter(|x| *x > 0.0 && *x < 1e15);
|
||||
let len = length.unwrap_or_else(|| a.dist(b));
|
||||
let ang = c.num("angle").map(f64::to_radians).unwrap_or_else(|| a.angle_to(b));
|
||||
if length.is_some() || c.num("angle").is_some() {
|
||||
let e = Vec2::polar(a, len, ang);
|
||||
if e.is_finite() {
|
||||
l.b.x = e.x;
|
||||
l.b.y = e.y;
|
||||
if length.is_some() {
|
||||
used.insert("length");
|
||||
}
|
||||
if c.num("angle").is_some() {
|
||||
used.insert("angle");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn circle(ci: &mut Circle, c: &Call<'_>, used: &mut Used<'_>) {
|
||||
if let Some(v) = c.p.get("center") {
|
||||
set_xy(&mut ci.center, v);
|
||||
used.insert("center");
|
||||
}
|
||||
if let Some(r) = c.num("radius").filter(|r| *r > 0.0) {
|
||||
ci.radius = r;
|
||||
used.insert("radius");
|
||||
}
|
||||
if let Some(dm) = c.num("diameter").filter(|r| *r > 0.0) {
|
||||
ci.radius = dm / 2.0;
|
||||
used.insert("diameter");
|
||||
}
|
||||
if let Some(cf) = c.num("circumference").filter(|x| *x > 0.0) {
|
||||
ci.radius = cf / cadcraft_geom::TAU;
|
||||
used.insert("circumference");
|
||||
}
|
||||
if let Some(a) = c.num("area").filter(|x| *x > 0.0) {
|
||||
ci.radius = (a / cadcraft_geom::PI).sqrt();
|
||||
used.insert("area");
|
||||
}
|
||||
}
|
||||
|
||||
fn arc(a: &mut Arc, c: &Call<'_>, used: &mut Used<'_>) {
|
||||
if let Some(v) = c.p.get("center") {
|
||||
set_xy(&mut a.center, v);
|
||||
used.insert("center");
|
||||
}
|
||||
if let Some(r) = c.num("radius").filter(|r| *r > 0.0) {
|
||||
a.radius = r;
|
||||
used.insert("radius");
|
||||
}
|
||||
if let Some(x) = c.num("startAngle") {
|
||||
a.start = cadcraft_geom::norm_angle(x.to_radians());
|
||||
used.insert("startAngle");
|
||||
}
|
||||
if let Some(x) = c.num("endAngle") {
|
||||
a.end = cadcraft_geom::norm_angle(x.to_radians());
|
||||
used.insert("endAngle");
|
||||
}
|
||||
}
|
||||
|
||||
/// TEXT's contents, style, size, angles and justification.
|
||||
fn text(t: &mut Text, c: &Call<'_>, h: Handle, used: &mut Used<'_>) {
|
||||
let p = c.p;
|
||||
if let Some(v) = str_param(p, "text") {
|
||||
t.value = v.to_string();
|
||||
used.insert("text");
|
||||
}
|
||||
if let Some(st) = &c.text_style {
|
||||
t.style.clone_from(st);
|
||||
used.insert("style");
|
||||
}
|
||||
if let Some(x) = c.num("height").filter(|x| *x > 0.0) {
|
||||
t.height = x;
|
||||
used.insert("height");
|
||||
}
|
||||
if let Some(x) = c.num("rotation") {
|
||||
t.rotation = x.to_radians();
|
||||
// Aligned and fit text run along their baseline's two ends: it turns too.
|
||||
if matches!(t.halign, HAlign::Aligned | HAlign::Fit)
|
||||
&& let Some(end) = t.align_pt
|
||||
{
|
||||
let e = Vec2::polar(t.insert.xy(), t.insert.xy().dist(end.xy()), t.rotation);
|
||||
t.align_pt = Some(Vec3::new(e.x, e.y, end.z));
|
||||
}
|
||||
used.insert("rotation");
|
||||
}
|
||||
if let Some(x) = c.num("widthFactor").filter(|x| *x > 0.0) {
|
||||
t.width_factor = x;
|
||||
used.insert("widthFactor");
|
||||
}
|
||||
if let Some(x) = c.num("oblique").filter(|x| x.abs() <= 85.0) {
|
||||
t.oblique = x.to_radians();
|
||||
used.insert("oblique");
|
||||
}
|
||||
if let Some((ha, va)) = str_param(p, "justify").and_then(crate::cmd::draw::justify) {
|
||||
set_justify(t, ha, va, c.prep.ends.get(&h).copied());
|
||||
used.insert("justify");
|
||||
}
|
||||
}
|
||||
|
||||
/// Where TEXT is: its position (the point it's placed by), and an aligned or fit text's second
|
||||
/// point.
|
||||
fn text_position(t: &mut Text, c: &Call<'_>, used: &mut Used<'_>) {
|
||||
// The position is the point the text is placed by: moving it moves the text.
|
||||
if let Some(to) = c.p.get("position").and_then(point_value) {
|
||||
shift(t, to - t.justify_point());
|
||||
used.insert("position");
|
||||
}
|
||||
let (x, y) = (c.num("positionX"), c.num("positionY"));
|
||||
if x.is_some() || y.is_some() {
|
||||
let at = t.justify_point();
|
||||
shift(t, Vec2::new(x.unwrap_or(at.x), y.unwrap_or(at.y)) - at);
|
||||
used.extend(["positionX", "positionY"].into_iter().filter(|k| c.num(k).is_some()));
|
||||
}
|
||||
if let Some(z) = c.num("positionZ") {
|
||||
t.insert.z = z;
|
||||
if let Some(a) = &mut t.align_pt {
|
||||
a.z = z;
|
||||
}
|
||||
used.insert("positionZ");
|
||||
}
|
||||
// Aligned and fit text: the second point alone (the text refits between them).
|
||||
if matches!(t.halign, HAlign::Aligned | HAlign::Fit)
|
||||
&& let Some(a) = &mut t.align_pt
|
||||
{
|
||||
if let Some(x) = c.num("alignmentX") {
|
||||
a.x = x;
|
||||
used.insert("alignmentX");
|
||||
}
|
||||
if let Some(y) = c.num("alignmentY") {
|
||||
a.y = y;
|
||||
used.insert("alignmentY");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mtext(t: &mut MText, c: &Call<'_>, used: &mut Used<'_>) {
|
||||
let p = c.p;
|
||||
if let Some(v) = str_param(p, "text") {
|
||||
t.contents = v.replace('\n', "\\P");
|
||||
used.insert("text");
|
||||
}
|
||||
if let Some(st) = &c.text_style {
|
||||
t.style.clone_from(st);
|
||||
used.insert("style");
|
||||
}
|
||||
if let Some(x) = c.num("height").filter(|x| *x > 0.0) {
|
||||
t.height = x;
|
||||
used.insert("height");
|
||||
}
|
||||
if let Some(x) = c.num("width").filter(|x| *x >= 0.0) {
|
||||
t.width = x;
|
||||
used.insert("width");
|
||||
}
|
||||
if let Some(x) = c.num("rotation") {
|
||||
t.rotation = x.to_radians();
|
||||
used.insert("rotation");
|
||||
}
|
||||
// The attachment point stays where it is; the text moves around it.
|
||||
if let Some(n) = str_param(p, "justify").and_then(crate::cmd::mtext_opts::attach_code) {
|
||||
t.attach = n;
|
||||
used.insert("justify");
|
||||
}
|
||||
mtext_spacing(t, c, used);
|
||||
if let Some(to) = p.get("position").and_then(point_value) {
|
||||
t.insert.x = to.x;
|
||||
t.insert.y = to.y;
|
||||
used.insert("position");
|
||||
}
|
||||
for (k, slot) in [("positionX", &mut t.insert.x), ("positionY", &mut t.insert.y), ("positionZ", &mut t.insert.z)] {
|
||||
if let Some(v) = c.num(k) {
|
||||
*slot = v;
|
||||
used.insert(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// MTEXT's line spacing: a factor, a distance, or its style.
|
||||
fn mtext_spacing(t: &mut MText, c: &Call<'_>, used: &mut Used<'_>) {
|
||||
// MTEXT's Line spacing option takes factors from 0.25 to 4.
|
||||
let factor = |f: f64| f.is_finite() && (0.25 - 1e-9..=4.0 + 1e-9).contains(&f);
|
||||
if let Some(x) = c.num("lineSpacing").filter(|x| factor(*x)) {
|
||||
t.line_spacing = x;
|
||||
used.insert("lineSpacing");
|
||||
}
|
||||
if let Some(f) = c.num("lineSpacingDistance").map(|x| x / (t.height * LINE_PITCH)).filter(|f| factor(*f)) {
|
||||
t.line_spacing = f;
|
||||
used.insert("lineSpacingDistance");
|
||||
}
|
||||
// "atLeast", "At least", "exactly"…
|
||||
let spacing = str_param(c.p, "lineSpacingStyle").map(|v| v.chars().filter(char::is_ascii_alphabetic).collect::<String>().to_ascii_lowercase());
|
||||
if let Some(exact) = match spacing.as_deref() {
|
||||
Some("atleast") => Some(false),
|
||||
Some("exactly") => Some(true),
|
||||
_ => None,
|
||||
} {
|
||||
t.line_spacing_exact = exact;
|
||||
used.insert("lineSpacingStyle");
|
||||
}
|
||||
}
|
||||
|
||||
fn insert(i: &mut Insert, c: &Call<'_>, used: &mut Used<'_>) {
|
||||
if let Some(x) = c.num("rotation") {
|
||||
let turn = x.to_radians() - i.rotation;
|
||||
i.rotation = x.to_radians();
|
||||
// The attached text turns with the reference, around its insertion point (as ROTATE does).
|
||||
let base = i.insert.xy();
|
||||
for a in &mut i.attribs {
|
||||
let t = &mut a.text;
|
||||
for q in std::iter::once(&mut t.insert).chain(t.align_pt.as_mut()) {
|
||||
let r = q.xy().rotate_about(base, turn);
|
||||
q.x = r.x;
|
||||
q.y = r.y;
|
||||
}
|
||||
t.rotation = cadcraft_geom::norm_angle(t.rotation + turn);
|
||||
if let Some(ml) = &mut a.multiline {
|
||||
let r = ml.mtext.insert.xy().rotate_about(base, turn);
|
||||
ml.mtext.insert.x = r.x;
|
||||
ml.mtext.insert.y = r.y;
|
||||
ml.mtext.rotation = cadcraft_geom::norm_angle(ml.mtext.rotation + turn);
|
||||
}
|
||||
}
|
||||
used.insert("rotation");
|
||||
}
|
||||
if let Some(x) = c.num("scale").filter(|x| *x != 0.0) {
|
||||
// A new positive scale carries the attached attribute text with it, like SCALE about the insertion point.
|
||||
if x > 0.0 && i.scale.x > 0.0 {
|
||||
let m = cadcraft_geom::Mat3::scale_about(i.insert.xy(), x / i.scale.x);
|
||||
for a in &mut i.attribs {
|
||||
let mut k = EntityKind::Text(a.text.clone());
|
||||
k.transform(&m);
|
||||
if let EntityKind::Text(t) = k {
|
||||
a.text = t;
|
||||
}
|
||||
a.transform_multiline(&m);
|
||||
}
|
||||
}
|
||||
i.scale = Vec3::new(x, x, x);
|
||||
used.insert("scale");
|
||||
}
|
||||
}
|
||||
|
||||
fn dimension<'c>(dm: &mut Dimension, c: &'c Call<'_>, h: Handle, used: &mut Used<'c>) {
|
||||
let p = c.p;
|
||||
let before = dm.clone();
|
||||
if let Some(v) = str_param(p, "textOverride") {
|
||||
dm.text = v.to_string();
|
||||
used.insert("textOverride");
|
||||
}
|
||||
if let Some(st) = &c.dim_style {
|
||||
dm.style.clone_from(st);
|
||||
used.insert("dimStyle");
|
||||
}
|
||||
// Overrides: clear first, then set (as DIMOVERRIDE does).
|
||||
if p.get("clearOverrides").and_then(Value::as_bool) == Some(true) {
|
||||
dm.overrides.clear();
|
||||
used.insert("clearOverrides");
|
||||
}
|
||||
if let Some(names) = p.get("clear").and_then(Value::as_array) {
|
||||
// Prefix and suffix rows reset DIMPOST (DIMAPOST), the variable they're halves of.
|
||||
let field = |n: &str| match n {
|
||||
"prefix" | "suffix" => Some("post"),
|
||||
"altPrefix" | "altSuffix" => Some("altPost"),
|
||||
n => DimStyle::field_name(n),
|
||||
};
|
||||
for f in names.iter().filter_map(Value::as_str).filter_map(field) {
|
||||
dm.overrides.retain(|k, _| DimStyle::field_name(k) != Some(f));
|
||||
}
|
||||
used.insert("clear");
|
||||
}
|
||||
for (f, v) in &c.dim_vars.fields {
|
||||
set_override(dm, f, v.clone());
|
||||
}
|
||||
used.extend(c.dim_vars.keys.iter().map(String::as_str));
|
||||
if let Some(x) = c.num("textRotation") {
|
||||
dm.text_rotation = x.to_radians();
|
||||
used.insert("textRotation");
|
||||
}
|
||||
let (x, y) = (c.num("textPositionX"), c.num("textPositionY"));
|
||||
if x.is_some() || y.is_some() {
|
||||
let at = c.prep.text_pos.get(&h).copied().unwrap_or_else(|| dm.text_mid.xy());
|
||||
dm.text_mid.x = x.unwrap_or(at.x);
|
||||
dm.text_mid.y = y.unwrap_or(at.y);
|
||||
dm.user_text_pos = true;
|
||||
used.extend(["textPositionX", "textPositionY"].into_iter().filter(|k| c.num(k).is_some()));
|
||||
}
|
||||
dimension_posts(dm, c, used);
|
||||
// The geometry block read from a file no longer matches: draw and save it anew.
|
||||
if *dm != before {
|
||||
dm.block = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// A dimension's prefix and suffix edits, which go into the DIMPOST and DIMAPOST templates it
|
||||
/// draws with after the call's other edits (its style, cleared and new overrides).
|
||||
fn dimension_posts(dm: &mut Dimension, c: &Call<'_>, used: &mut Used<'_>) {
|
||||
let Some(styles) = &c.prep.posts else { return };
|
||||
let (post, alt) = styles.get(&dm.style.to_ascii_lowercase()).cloned().unwrap_or_default();
|
||||
let st = DimStyle { post, alt_post: alt, ..DimStyle::default() }.with_overrides(&dm.overrides);
|
||||
for (field, template, keys) in [("post", &st.post, ["prefix", "suffix"]), ("altPost", &st.alt_post, ["altPrefix", "altSuffix"])] {
|
||||
let (pre, suf) = (str_param(c.p, keys[0]), str_param(c.p, keys[1]));
|
||||
if pre.is_some() || suf.is_some() {
|
||||
let (pre0, suf0) = split_post(template);
|
||||
set_override(dm, field, json!(join_post(pre.unwrap_or(&pre0), suf.unwrap_or(&suf0))));
|
||||
used.extend(keys.into_iter().filter(|k| str_param(c.p, k).is_some()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
used.insert("pattern");
|
||||
}
|
||||
if let Some(x) = c.num("scale").filter(|x| *x > 0.0) {
|
||||
ha.scale = x;
|
||||
used.insert("scale");
|
||||
}
|
||||
if let Some(x) = c.num("angle") {
|
||||
ha.angle = x.to_radians();
|
||||
used.insert("angle");
|
||||
}
|
||||
}
|
||||
@@ -280,7 +280,7 @@ fn run_qselect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sel = match mode.as_str() {
|
||||
"exclude" => excluded,
|
||||
"append" => {
|
||||
let mut cur = s.stored_selection();
|
||||
let mut cur = s.selection();
|
||||
for h in matched {
|
||||
if !cur.contains(&h) {
|
||||
cur.push(h);
|
||||
|
||||
@@ -99,21 +99,14 @@ pub(crate) fn similar(e: &Entity, r: &Entity, mode: u32) -> bool {
|
||||
&& (mode & NAME == 0 || same_text(object_name(e), object_name(r)))
|
||||
}
|
||||
|
||||
/// The objects of the current space like any of `refs` that a selection can take there: visible,
|
||||
/// and inside an MSPACE viewport not on a layer frozen in it.
|
||||
/// The visible objects of the current space like any of `refs`.
|
||||
fn similar_objects(s: &Session, d: &Drawing, refs: &[Handle], mode: u32) -> Vec<Handle> {
|
||||
let refs: Vec<&Entity> = refs.iter().filter_map(|h| d.entity(*h).map(|e| e.as_ref())).collect();
|
||||
if refs.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(store) = d.space(&s.space()) else { return Vec::new() };
|
||||
let frozen = s.viewport_frozen();
|
||||
store
|
||||
.iter()
|
||||
.take(MAX_SCAN)
|
||||
.filter(|e| crate::select::selectable(d, e, frozen) && refs.iter().any(|r| similar(e, r, mode)))
|
||||
.map(|e| e.handle)
|
||||
.collect()
|
||||
store.iter().take(MAX_SCAN).filter(|e| d.is_visible(e) && refs.iter().any(|r| similar(e, r, mode))).map(|e| e.handle).collect()
|
||||
}
|
||||
|
||||
fn mode_param(s: &Session, p: &Value) -> Result<u32> {
|
||||
|
||||
@@ -8,9 +8,8 @@ use cadcraft_doc::{Drawing, EntityKind, Handle};
|
||||
use cadcraft_geom::{Bounds2, Line, Vec2, line_line};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::curves::KW;
|
||||
use super::helpers::{line, lwpoly, rect_vertices};
|
||||
use super::modify::{CUT_ONCE, Edges, extend, json_pick_error, trim};
|
||||
use super::modify::{Edges, extend, trim};
|
||||
use super::{bad, point_param, points_param};
|
||||
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
@@ -32,10 +31,8 @@ fn proj_mode(s: &Session) -> i64 {
|
||||
}
|
||||
|
||||
/// Whether a trim error says the object meets no cutting edge (a Quick-mode trim then erases it).
|
||||
/// A closed polyline cut at one point meets one, and is left as it is.
|
||||
fn misses_edges(e: &EngineError) -> bool {
|
||||
let m = e.to_string();
|
||||
m.contains("intersect") && m != CUT_ONCE
|
||||
e.to_string().contains("intersect")
|
||||
}
|
||||
|
||||
/// Trim or extend `h` at `at`. A Quick-mode (`quick`) trim of an object no cutting edge crosses
|
||||
@@ -62,7 +59,7 @@ fn fence(s: &mut Session, pts: &[Vec2], extending: bool, edges: Edges, quick: bo
|
||||
let fb = Bounds2::from_points(pts.iter().copied());
|
||||
let tol = crate::select::window_tol(&fb);
|
||||
let mut work: Vec<(Handle, Vec<Vec2>)> = Vec::new();
|
||||
for h in crate::select::select_fence_in(d, &space, s.viewport_frozen(), pts) {
|
||||
for h in crate::select::select_fence(d, &space, pts) {
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let polys = crate::select::hit_polylines(d, e, tol);
|
||||
let mut xs: Vec<Vec2> = Vec::new();
|
||||
@@ -99,19 +96,14 @@ fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, qu
|
||||
];
|
||||
let inside = |p: Vec2| bx.expand(tol).contains(p);
|
||||
let mut work: Vec<(Handle, Vec<Vec2>)> = Vec::new();
|
||||
for h in crate::select::select_window_in(d, &space, s.viewport_frozen(), bx, true) {
|
||||
for h in crate::select::select_window(d, &space, bx, true) {
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let mut best: Option<Vec2> = None;
|
||||
for pl in crate::select::hit_polylines(d, e, tol) {
|
||||
for w in pl.windows(2) {
|
||||
let (Some(p), Some(q)) = (w.first(), w.get(1)) else { continue };
|
||||
let seg = Line::new(*p, *q);
|
||||
// Kept `tol` inside the segment: a vertex, where two segments meet, is a cut of a
|
||||
// polyline that is one of its own edges, and a pick on a cut trims nothing.
|
||||
let e = (tol / seg.len()).min(0.5);
|
||||
let cands = [seg.at(e), seg.at(1.0 - e), seg.at(seg.param_of(a).clamp(e, 1.0 - e))]
|
||||
.into_iter()
|
||||
.chain(sides.iter().filter_map(|sd| line_line(sd, &seg)));
|
||||
let cands = [*p, *q, seg.closest(a)].into_iter().chain(sides.iter().filter_map(|sd| line_line(sd, &seg)));
|
||||
for c in cands.filter(|c| inside(*c)) {
|
||||
if best.is_none_or(|b| c.dist(a) < b.dist(a)) {
|
||||
best = Some(c);
|
||||
@@ -181,6 +173,7 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result<Value> {
|
||||
let cmd = if extending { "extend" } else { "trim" };
|
||||
let only: Option<Vec<Handle>> =
|
||||
p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().and_then(Handle::parse_hex)).collect());
|
||||
let edges = Edges { only: only.as_deref(), implied: edge_mode_param(cmd, p)? };
|
||||
let quick = match p.get("mode") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(v) => match v.as_str().map(|m| m.trim().to_ascii_lowercase()).as_deref() {
|
||||
@@ -189,7 +182,6 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result<Value> {
|
||||
_ => return Err(bad(cmd, "`mode` must be \"quick\" or \"standard\"")),
|
||||
},
|
||||
};
|
||||
let edges = Edges { only: only.as_deref(), implied: edge_mode_param(cmd, p)? };
|
||||
let key = if extending { "extended" } else { "trimmed" };
|
||||
if p.get("fence").is_some_and(|v| !v.is_null()) {
|
||||
let pts = points_param(p, "fence")
|
||||
@@ -205,19 +197,8 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result<Value> {
|
||||
return Ok(json!({ key: n }));
|
||||
}
|
||||
let h = super::targets(s, p)?.first().copied().ok_or_else(|| bad(cmd, "`handle` is required"))?;
|
||||
let pick = point_param(p, "pick").ok_or_else(|| {
|
||||
bad(
|
||||
cmd,
|
||||
if extending {
|
||||
"`pick` ([x, y]) is required: point toward the boundary to extend to, selecting the nearer end"
|
||||
} else {
|
||||
"`pick` ([x, y]) is required: select the portion of the object to trim away"
|
||||
},
|
||||
)
|
||||
})?;
|
||||
// Diagnose only an existing single-pick JSON failure. Successful calls, Quick-mode
|
||||
// erasure, fence/crossing and the interactive command keep their existing behavior.
|
||||
let r = apply(s, h, pick, extending, edges, quick).map_err(|e| json_pick_error(s, h, pick, edges, extending, e))?;
|
||||
let pick = point_param(p, "pick").ok_or_else(|| bad(cmd, "`pick` ([x, y]) is required"))?;
|
||||
let r = apply(s, h, pick, extending, edges, quick)?;
|
||||
if extending { Ok(Value::Null) } else { Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() })) }
|
||||
}
|
||||
|
||||
@@ -239,8 +220,6 @@ enum Stage {
|
||||
Edges(Vec<Handle>),
|
||||
/// Fence points so far.
|
||||
Fence(Vec<Vec2>),
|
||||
/// Quick mode's two-point fence, started by a pick in empty space: its first point.
|
||||
QuickFence(Vec2),
|
||||
/// A crossing window: its first corner once picked.
|
||||
Crossing(Option<Vec2>),
|
||||
Mode,
|
||||
@@ -377,12 +356,11 @@ impl Interactive for TrimM {
|
||||
None => Prompt::new("Specify first fence point", Accept::POINT),
|
||||
Some(l) => Prompt::new("Specify next fence point", Accept::POINT).kw(&["Undo"]).base(*l),
|
||||
},
|
||||
Stage::QuickFence(a) => Prompt::new("Specify next fence point", Accept::POINT).base(*a),
|
||||
Stage::Crossing(None) => Prompt::new("Specify first corner", Accept::POINT),
|
||||
Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT),
|
||||
Stage::Mode => {
|
||||
let msg = if self.extend { "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" })
|
||||
Prompt::new(msg, Accept::TEXT).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
|
||||
}
|
||||
Stage::Project => {
|
||||
let cur = match proj_mode(s) {
|
||||
@@ -390,9 +368,9 @@ impl Interactive for TrimM {
|
||||
2 => "View",
|
||||
_ => "Ucs",
|
||||
};
|
||||
Prompt::new("Enter a projection option", KW).kw(&["None", "Ucs", "View"]).default(cur)
|
||||
Prompt::new("Enter a projection option", Accept::TEXT).kw(&["None", "Ucs", "View"]).default(cur)
|
||||
}
|
||||
Stage::Edge => Prompt::new("Enter an implied edge extension mode", KW).kw(&["Extend", "No extend"]).default(if edge_mode(s) {
|
||||
Stage::Edge => Prompt::new("Enter an implied edge extension mode", Accept::TEXT).kw(&["Extend", "No extend"]).default(if edge_mode(s) {
|
||||
"Extend"
|
||||
} else {
|
||||
"No extend"
|
||||
@@ -477,16 +455,6 @@ impl Interactive for TrimM {
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Stage::QuickFence(a) => {
|
||||
self.stage = Stage::Pick;
|
||||
if let Input::Point(b) = i {
|
||||
let r = self.step(s, |m, s| fence(s, &[a, b], extending, m.edges(quick, implied), quick).map(|_| ()));
|
||||
if let Err(e) = r {
|
||||
s.echo(e.to_string());
|
||||
}
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
Stage::Crossing(first) => {
|
||||
match (first, i) {
|
||||
(None, Input::Point(p)) => self.stage = Stage::Crossing(Some(p)),
|
||||
@@ -507,9 +475,8 @@ impl Interactive for TrimM {
|
||||
let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5;
|
||||
let space = s.space();
|
||||
let Some(h) = s.pick_object(&space, p, ap)? else {
|
||||
// A pick in empty space starts a two-point fence in Quick mode (as in
|
||||
// AutoCAD, #1594) and a crossing window in Standard mode.
|
||||
self.stage = if quick { Stage::QuickFence(p) } else { Stage::Crossing(Some(p)) };
|
||||
// A pick in empty space opens a crossing window there.
|
||||
self.stage = Stage::Crossing(Some(p));
|
||||
return Ok(Step::Continue);
|
||||
};
|
||||
let r = self.step(s, |m, s| apply(s, h, p, extending, m.edges(quick, implied), quick).map(|_| ()));
|
||||
@@ -558,7 +525,6 @@ impl Interactive for TrimM {
|
||||
.windows(2)
|
||||
.filter_map(|w| Some(line(*w.first()?, *w.get(1)?)))
|
||||
.collect(),
|
||||
Stage::QuickFence(a) => vec![line(*a, c)],
|
||||
Stage::Crossing(Some(a)) => vec![lwpoly(rect_vertices(*a, c), true)],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
|
||||
@@ -8,12 +8,6 @@ pub struct Snapshot {
|
||||
pub selection: Vec<Handle>,
|
||||
}
|
||||
|
||||
/// [`DocState::drawn_in_viewport`] looks its handles up one by one while there is fewer than one
|
||||
/// of them for every `LOOKUP_COST` objects of model space, and passes over model space once
|
||||
/// otherwise. Timed on drawings of 40,000 and of 200,000 lines, the two cost the same at about
|
||||
/// one handle for every 47 and for every 18 objects.
|
||||
const LOOKUP_COST: usize = 32;
|
||||
|
||||
/// One open drawing.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DocState {
|
||||
@@ -125,65 +119,13 @@ impl DocState {
|
||||
}
|
||||
/// The active MSPACE viewport, if it still exists in the current layout.
|
||||
pub fn active_viewport(&self) -> Option<(Handle, cadcraft_doc::Viewport)> {
|
||||
self.active_viewport_ref().map(|(h, v)| (h, v.clone()))
|
||||
}
|
||||
/// [`DocState::active_viewport`] without copying the viewport.
|
||||
fn active_viewport_ref(&self) -> Option<(Handle, &cadcraft_doc::Viewport)> {
|
||||
let h = self.mspace?;
|
||||
let e = self.doc.space(&self.space)?.get(h)?;
|
||||
match &e.kind {
|
||||
cadcraft_doc::EntityKind::Viewport(v) if v.height > 1e-12 && v.view_height > 1e-12 => Some((h, v)),
|
||||
cadcraft_doc::EntityKind::Viewport(v) if v.height > 1e-12 && v.view_height > 1e-12 => Some((h, v.clone())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// 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.
|
||||
pub fn viewport_frozen(&self) -> &[String] {
|
||||
match self.active_viewport_ref() {
|
||||
Some((_, v)) => &v.frozen_layers,
|
||||
None => &[],
|
||||
}
|
||||
}
|
||||
/// Whether `e` is a model-space object the active MSPACE viewport does not draw: it is on a
|
||||
/// layer frozen in that viewport ([`DocState::viewport_frozen`]). Objects on the sheet are not
|
||||
/// drawn through the viewport, so its frozen layers do not hide them.
|
||||
pub fn hidden_in_viewport(&self, e: &cadcraft_doc::Entity) -> bool {
|
||||
crate::select::on_frozen_layer(self.viewport_frozen(), e) && self.doc.model.contains(e.handle)
|
||||
}
|
||||
/// Whether the view being edited shows `e`: the drawing shows it ([`Drawing::is_visible`]),
|
||||
/// and the active MSPACE viewport, if there is one, draws it
|
||||
/// ([`DocState::hidden_in_viewport`]).
|
||||
pub fn shows(&self, e: &cadcraft_doc::Entity) -> bool {
|
||||
self.doc.is_visible(e) && !self.hidden_in_viewport(e)
|
||||
}
|
||||
/// `handles` without the objects the active MSPACE viewport does not draw
|
||||
/// ([`DocState::hidden_in_viewport`]): a set of objects made earlier (the selection, the
|
||||
/// Previous set) as that viewport takes it. All of them anywhere else.
|
||||
pub(crate) fn drawn_in_viewport(&self, handles: &[Handle]) -> Vec<Handle> {
|
||||
let frozen = self.viewport_frozen();
|
||||
if frozen.is_empty() || handles.is_empty() {
|
||||
return handles.to_vec();
|
||||
}
|
||||
let model = &self.doc.model;
|
||||
let hidden = |e: &Arc<cadcraft_doc::Entity>| crate::select::on_frozen_layer(frozen, e);
|
||||
// The UI asks for the selection several times a frame. A few handles are looked up one
|
||||
// by one; beyond that, one pass over model space costs less than the lookups.
|
||||
if handles.len().saturating_mul(LOOKUP_COST) < model.len() {
|
||||
return handles.iter().copied().filter(|h| !model.get(*h).is_some_and(hidden)).collect();
|
||||
}
|
||||
let mut gone: Vec<Handle> = model.iter().filter(|e| hidden(e)).map(|e| e.handle).collect();
|
||||
gone.sort_unstable();
|
||||
handles.iter().copied().filter(|h| gone.binary_search(h).is_err()).collect()
|
||||
}
|
||||
/// The selection as the view being edited has it: [`DocState::selection`] without the objects
|
||||
/// the active MSPACE viewport does not draw. Those stay in [`DocState::selection`] until the
|
||||
/// selection is replaced or cleared, and count as selected again once that viewport draws
|
||||
/// them; until then nothing that starts from the selection (a command, a grip, a palette)
|
||||
/// edits them through that viewport.
|
||||
pub fn shown_selection(&self) -> Vec<Handle> {
|
||||
self.drawn_in_viewport(&self.selection)
|
||||
}
|
||||
pub fn paper_view(&self) -> View {
|
||||
self.views.iter().find(|(s, _)| *s == self.space).map(|(_, v)| *v).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
//! Words typed on a Greek keyboard layout.
|
||||
//!
|
||||
//! With the Greek layout active, the keys that type LINE produce ΛΙΝΕ. Command names, aliases and
|
||||
//! prompt keywords are Latin, so a Greek speaker would have to switch layouts for every command.
|
||||
//! [`latin_keys`] reads a word as the Latin keys that produced it (the layout puts each Greek
|
||||
//! letter on the key of the Latin letter it sounds like): the command line then accepts ΛΙΝΕ and
|
||||
//! ΣΤΡΕΤΨΗ as LINE and STRETCH. Accents (the layout's dead key) are ignored.
|
||||
|
||||
/// The Latin key a Greek letter is typed on (lower case, accents removed).
|
||||
fn key_of(c: char) -> Option<char> {
|
||||
Some(match c {
|
||||
'α' | 'ά' => 'a',
|
||||
'β' => 'b',
|
||||
'γ' => 'g',
|
||||
'δ' => 'd',
|
||||
'ε' | 'έ' => 'e',
|
||||
'ζ' => 'z',
|
||||
'η' | 'ή' => 'h',
|
||||
'θ' => 'u',
|
||||
'ι' | 'ί' | 'ϊ' | 'ΐ' => 'i',
|
||||
'κ' => 'k',
|
||||
'λ' => 'l',
|
||||
'μ' => 'm',
|
||||
'ν' => 'n',
|
||||
'ξ' => 'j',
|
||||
'ο' | 'ό' => 'o',
|
||||
'π' => 'p',
|
||||
'ρ' => 'r',
|
||||
'σ' => 's',
|
||||
// The W key types the final sigma.
|
||||
'ς' => 'w',
|
||||
'τ' => 't',
|
||||
'υ' | 'ύ' | 'ϋ' | 'ΰ' => 'y',
|
||||
'φ' => 'f',
|
||||
'χ' => 'x',
|
||||
'ψ' => 'c',
|
||||
'ω' | 'ώ' => 'v',
|
||||
// The Q key types the semicolon, which Greek text writes as ";" or U+037E.
|
||||
';' | '\u{37e}' => 'q',
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `c` is a Greek letter (the basic and accented ranges the layout types).
|
||||
fn is_greek_letter(c: char) -> bool {
|
||||
matches!(c, '\u{386}'..='\u{3ce}') && c != '\u{387}'
|
||||
}
|
||||
|
||||
/// `word` read as the Latin keys of a Greek-layout keyboard, lower case: `Some` only when the word
|
||||
/// has a Greek letter and every character is a Greek letter the layout types, the semicolon on
|
||||
/// the Q key, or ASCII (itself, in lower case). A combining tonos or dialytika, the accent of
|
||||
/// decomposed text, is ignored like the accent of a precomposed letter, but only straight after
|
||||
/// the Greek letter it accents and once each: anywhere else the word is not Greek-layout typing.
|
||||
pub fn latin_keys(word: &str) -> Option<String> {
|
||||
let mut greek = false;
|
||||
// What the previous Greek letter already carries (tonos, dialytika); `None` when the previous
|
||||
// character is not a Greek letter, which leaves a combining mark nothing to accent.
|
||||
let mut marks: Option<(bool, bool)> = None;
|
||||
let mut out = String::with_capacity(word.len());
|
||||
for c in word.chars() {
|
||||
if matches!(c, '\u{301}' | '\u{308}') {
|
||||
let (tonos, dialytika) = marks.as_mut()?;
|
||||
if std::mem::replace(if c == '\u{301}' { tonos } else { dialytika }, true) {
|
||||
return None;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if c.is_ascii() {
|
||||
// The Q key types the ASCII semicolon in the Greek layout; every other ASCII character is itself.
|
||||
out.push(if c == ';' { 'q' } else { c.to_ascii_lowercase() });
|
||||
marks = None;
|
||||
continue;
|
||||
}
|
||||
let lower = c.to_lowercase().next().unwrap_or(c);
|
||||
out.push(key_of(lower)?);
|
||||
let letter = is_greek_letter(lower);
|
||||
greek |= letter;
|
||||
marks = letter.then_some((false, false));
|
||||
}
|
||||
greek.then_some(out)
|
||||
}
|
||||
|
||||
/// `word` with its case, accents and final sigma folded away, when it is Greek-layout typing: every
|
||||
/// spelling of one Greek word gives the same string. It is the word's keys, with the final sigma
|
||||
/// read as the letter sigma instead of the W key.
|
||||
pub fn greek_fold(word: &str) -> Option<String> {
|
||||
latin_keys(&word.replace('ς', "σ"))
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are one Greek word, whatever their case, accents or final sigma.
|
||||
pub fn same_greek_word(a: &str, b: &str) -> bool {
|
||||
same_greek_word_as(b).is_some_and(|same| same(a))
|
||||
}
|
||||
|
||||
/// A test for "is the Greek word `word`, whatever the case, accents or final sigma", or `None`
|
||||
/// when `word` is not Greek-layout typing. `word` is folded here, once: looking a typed word up
|
||||
/// among many names costs its length once, not once for every name.
|
||||
pub fn same_greek_word_as(word: &str) -> Option<impl Fn(&str) -> bool> {
|
||||
let fold = greek_fold(word)?;
|
||||
Some(move |name: &str| greek_fold(name).as_deref() == Some(fold.as_str()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{latin_keys, same_greek_word};
|
||||
|
||||
/// One Greek word compares equal in any case, accent or final sigma; another word, or a Latin
|
||||
/// one, does not.
|
||||
#[test]
|
||||
fn one_greek_word_is_the_same_in_any_case_accent_or_final_sigma() {
|
||||
for (a, b) in [("ΣΟΛΙΔ", "σολιδ"), ("ΣΟΛΙΔ", "σολίδ"), ("ΛΑΣ", "λας"), ("ΛΑΣ", "λασ"), ("ΛΙ\u{301}ΝΕ", "λινε")]
|
||||
{
|
||||
assert!(same_greek_word(a, b), "{a} {b}");
|
||||
}
|
||||
for (a, b) in [("ΣΟΛΙΔ", "ΣΟΛΙ"), ("ΣΟΛΙΔ", "solid"), ("solid", "SOLID")] {
|
||||
assert!(!same_greek_word(a, b), "{a} {b}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A character the layout does not type is never taken for the Greek letter Unicode upper-cases
|
||||
/// it to: the micro sign is not μ, the long s and the sharp s are not σ, an alpha with an iota
|
||||
/// subscript is not αι, the theta symbol is not θ.
|
||||
#[test]
|
||||
fn a_character_the_layout_does_not_type_is_no_spelling_of_a_greek_letter() {
|
||||
let pairs = [("\u{b5}", "μ"), ("Λ\u{17f}", "ΛΣ"), ("Λ\u{df}", "ΛΣΣ"), ("\u{1fb3}", "αι"), ("\u{3d1}", "θ")];
|
||||
let same: Vec<_> = pairs.iter().filter(|(a, b)| same_greek_word(a, b) || same_greek_word(b, a)).collect();
|
||||
assert!(same.is_empty(), "{same:?}");
|
||||
}
|
||||
|
||||
/// Greek-layout typing reads as its Latin keys: plain, accented and decomposed letters, the Q
|
||||
/// and W keys, ASCII prefixes.
|
||||
#[test]
|
||||
fn greek_layout_commands_read_as_their_latin_keys() {
|
||||
assert_eq!(latin_keys("ΛΙΝΕ").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("λινε").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("ΣΤΡΕΤΨΗ").as_deref(), Some("stretch"));
|
||||
assert_eq!(latin_keys("ΜΙΡΡΟΡ").as_deref(), Some("mirror"));
|
||||
assert_eq!(latin_keys("ΘΝΔΟ").as_deref(), Some("undo"));
|
||||
// The Q key types ";", the W key the final sigma.
|
||||
assert_eq!(latin_keys(";ΣΑΩΕ").as_deref(), Some("qsave"));
|
||||
assert_eq!(latin_keys("ςΒΛΟΨΚ").as_deref(), Some("wblock"));
|
||||
// Accented letters (the layout's dead key) read as the plain letter.
|
||||
assert_eq!(latin_keys("ΛΊΝΕ").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("ΆΡΡΑΥ").as_deref(), Some("array"));
|
||||
// The same accents written as a combining mark after the letter (decomposed text).
|
||||
assert_eq!(latin_keys("ΛΙ\u{301}ΝΕ").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("ΛΙΝΕ\u{301}").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("ΛΙ\u{308}ΝΕ").as_deref(), Some("line"));
|
||||
assert_eq!(latin_keys("ΛΙ\u{308}\u{301}ΝΕ").as_deref(), Some("line"), "dialytika and tonos on one letter");
|
||||
// Prefixes and digits are kept.
|
||||
assert_eq!(latin_keys("-ΛΑΥΕΡ").as_deref(), Some("-layer"));
|
||||
assert_eq!(latin_keys("_ΛΙΝΕ").as_deref(), Some("_line"));
|
||||
}
|
||||
|
||||
/// A word with no Greek letter, or with a character the layout does not type, is not read.
|
||||
#[test]
|
||||
fn words_that_are_not_greek_layout_typing_are_left_alone() {
|
||||
assert_eq!(latin_keys("line"), None, "no Greek letter");
|
||||
assert_eq!(latin_keys(""), None);
|
||||
assert_eq!(latin_keys(";"), None, "a semicolon alone is not a word");
|
||||
assert_eq!(latin_keys("ΛΙΝΕ Ж"), None, "a letter the layout does not type");
|
||||
assert_eq!(latin_keys("ΛΙΝΕ 日本"), None);
|
||||
assert_eq!(latin_keys("\u{387}"), None, "the ano teleia is punctuation, not a letter");
|
||||
}
|
||||
|
||||
/// A combining tonos or dialytika counts only straight after a Greek letter, and once each.
|
||||
#[test]
|
||||
fn a_combining_mark_must_follow_the_greek_letter_it_accents() {
|
||||
assert_eq!(latin_keys("\u{301}ΛΙΝΕ"), None, "no letter before the mark");
|
||||
assert_eq!(latin_keys("\u{308}ΛΙΝΕ"), None);
|
||||
assert_eq!(latin_keys("ΛΙΝΕ-\u{301}"), None, "after punctuation");
|
||||
assert_eq!(latin_keys("a\u{301}ΛΙΝΕ"), None, "after a Latin letter");
|
||||
assert_eq!(latin_keys("Λ\u{301}\u{301}ΙΝΕ"), None, "a second tonos on one letter");
|
||||
assert_eq!(latin_keys("Λ\u{308}\u{308}ΙΝΕ"), None, "a second dialytika on one letter");
|
||||
}
|
||||
|
||||
/// A 100 000-letter word and odd code points are read or refused; nothing panics.
|
||||
#[test]
|
||||
fn hostile_text_never_panics() {
|
||||
let long = "Ω".repeat(100_000);
|
||||
assert_eq!(latin_keys(&long).map(|s| s.len()), Some(100_000));
|
||||
for s in ["\u{0}", "\u{301}", "ΛΙΝΕ\u{301}", "\u{10ffff}", "ς\u{3c2}\u{3a3}"] {
|
||||
let _ = latin_keys(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,12 +22,10 @@ mod finite;
|
||||
pub mod grip_dims;
|
||||
pub mod grips;
|
||||
mod guard;
|
||||
pub mod keyboard;
|
||||
pub mod lisp;
|
||||
pub mod mtext_edit;
|
||||
pub mod pointmod;
|
||||
pub mod prompt;
|
||||
pub mod properties;
|
||||
mod recent;
|
||||
pub mod render_look;
|
||||
pub mod sample;
|
||||
@@ -86,11 +84,6 @@ pub struct Session {
|
||||
pub doc_epoch: u64,
|
||||
pub settings: Settings,
|
||||
pub running: Option<Running>,
|
||||
/// How many commands were started, nested transparent ones left out.
|
||||
pub commands_started: u64,
|
||||
/// The last command that ended by itself, not cancelled: its number in `commands_started`, and
|
||||
/// whether it took new handles (it added to the drawing, and nothing took that back).
|
||||
pub last_finished: Option<(u64, bool)>,
|
||||
/// A script is running ([`Session::script`]); a SCRIPT command inside it is refused.
|
||||
in_script: bool,
|
||||
/// The command suspended while a transparent command (`'ZOOM`, `'PAN`…) prompts inside it;
|
||||
@@ -182,8 +175,6 @@ impl Session {
|
||||
doc_epoch: 0,
|
||||
settings: Settings::default(),
|
||||
running: None,
|
||||
commands_started: 0,
|
||||
last_finished: None,
|
||||
in_script: false,
|
||||
suspended: None,
|
||||
log: Vec::new(),
|
||||
@@ -245,25 +236,11 @@ impl Session {
|
||||
pub fn space(&self) -> Space {
|
||||
self.state().map(DocState::edit_space).unwrap_or_default()
|
||||
}
|
||||
/// The layers frozen in the active MSPACE viewport ([`DocState::viewport_frozen`]): what a
|
||||
/// pick or a selection in [`Session::space`] leaves out. Empty with no drawing open.
|
||||
pub fn viewport_frozen(&self) -> &[String] {
|
||||
self.state().map(DocState::viewport_frozen).unwrap_or_default()
|
||||
}
|
||||
/// The tab being displayed: Model or a layout, regardless of MSPACE.
|
||||
pub fn layout_space(&self) -> Space {
|
||||
self.state().map(|s| s.space.clone()).unwrap_or_default()
|
||||
}
|
||||
/// The selected objects as the view being edited has them ([`DocState::shown_selection`]):
|
||||
/// inside an MSPACE viewport, without the objects on layers frozen in that viewport. Commands,
|
||||
/// grips and palettes start from this; [`DocState::selection`] holds every selected object.
|
||||
pub fn selection(&self) -> Vec<Handle> {
|
||||
self.state().map(DocState::shown_selection).unwrap_or_default()
|
||||
}
|
||||
/// Every selected object ([`DocState::selection`]), also the ones the active MSPACE viewport
|
||||
/// does not draw, which [`Session::selection`] leaves out. Adding to the selection or removing
|
||||
/// from it starts from this, so that it keeps them.
|
||||
pub(crate) fn stored_selection(&self) -> Vec<Handle> {
|
||||
self.state().map(|s| s.selection.clone()).unwrap_or_default()
|
||||
}
|
||||
pub fn set_selection(&mut self, sel: Vec<Handle>) {
|
||||
|
||||
@@ -5,14 +5,10 @@
|
||||
//! (`getpoint`, `pause`) and carry on later, so the interface keeps drawing while a routine
|
||||
//! waits. Each drawing has its own symbols, as in AutoCAD. A run is one undo step.
|
||||
|
||||
/// A block-definition entity and its successor in the block, by handle.
|
||||
pub type BlockSlots = HashMap<Handle, (Arc<cadcraft_doc::Entity>, Option<Handle>)>;
|
||||
|
||||
pub mod builtins;
|
||||
mod drawing;
|
||||
pub mod eval;
|
||||
pub mod input;
|
||||
mod objects;
|
||||
pub mod read;
|
||||
mod startup;
|
||||
pub mod value;
|
||||
@@ -58,20 +54,13 @@ pub struct Env {
|
||||
pub next_file: u32,
|
||||
/// Entities `entdel` deleted (it brings them back when called again), with their space.
|
||||
pub deleted: HashMap<Handle, (cadcraft_doc::Space, Arc<cadcraft_doc::Entity>)>,
|
||||
/// Every entity's handle in creation order (`entlast`, `entnext`), with clones of the spaces
|
||||
/// it was taken from (model space, then each layout): it is reused only while the drawing's
|
||||
/// spaces still share every chunk with them ([`cadcraft_doc::EntityStore::same_as`]).
|
||||
pub order: Option<(Vec<cadcraft_doc::EntityStore>, Arc<Vec<Handle>>)>,
|
||||
/// Each block-definition entity with its successor in its block (None for the last), for the drawing
|
||||
/// it was taken from: `entnext`'s indexed lookup, which also tells whether a handle is a block's.
|
||||
pub block_next: Option<(usize, Arc<BlockSlots>)>,
|
||||
/// Every entity's handle in creation order, for the drawing it was taken from (`entnext`).
|
||||
pub order: Option<(usize, Arc<Vec<Handle>>)>,
|
||||
/// `tblnext`'s place in each table.
|
||||
pub tblnext: HashMap<String, usize>,
|
||||
/// A block definition `entmake` has begun (a BLOCK list) and not yet ended (ENDBLK): the
|
||||
/// entities made meanwhile go into it, numbered when it ends.
|
||||
pub pending_block: Option<(cadcraft_doc::Block, Vec<cadcraft_doc::Entity>)>,
|
||||
/// Entity names of non-graphic objects (dictionaries, table records, layouts).
|
||||
pub(crate) objects: objects::Names,
|
||||
/// The command history's length after LISP last printed a line: when something else wrote since
|
||||
/// (a prompt, a command's echo), a leading newline only ends that line.
|
||||
pub printed_at: Option<usize>,
|
||||
@@ -88,10 +77,8 @@ impl Default for Env {
|
||||
next_file: 1,
|
||||
deleted: HashMap::new(),
|
||||
order: None,
|
||||
block_next: None,
|
||||
tblnext: HashMap::new(),
|
||||
pending_block: None,
|
||||
objects: objects::Names::default(),
|
||||
printed_at: None,
|
||||
};
|
||||
builtins::install(&mut e);
|
||||
@@ -220,19 +207,8 @@ impl Session {
|
||||
self.lisp.envs.remove(&uid).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Put a drawing's environment back, unless the drawing was closed meanwhile (a routine
|
||||
/// cancelled by CLOSE ends after its drawing went away).
|
||||
fn lisp_env_put(&mut self, uid: u64, env: Env) {
|
||||
if uid == 0 || self.docs.iter().any(|d| d.uid == uid) {
|
||||
self.lisp.envs.insert(uid, env);
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop the environments of drawings no longer open: one holds clones of its drawing's
|
||||
/// entity stores ([`Env::order`]), which would otherwise outlive the drawing.
|
||||
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.envs.insert(uid, env);
|
||||
}
|
||||
|
||||
/// A routine is running (possibly waiting for input).
|
||||
@@ -475,7 +451,7 @@ impl Session {
|
||||
let steps = std::mem::take(&mut self.lisp.steps);
|
||||
let mut env = self.lisp.envs.remove(&run.uid).unwrap_or_default();
|
||||
self.lisp_flush(&mut env, true);
|
||||
self.lisp_env_put(run.uid, env);
|
||||
self.lisp.envs.insert(run.uid, env);
|
||||
if let (Ok(v), true) = (&result, run.print) {
|
||||
let text = value::to_text(v, true);
|
||||
if !builtins::is_null_symbol(v) {
|
||||
|
||||
@@ -234,40 +234,3 @@ fn a_definition_that_isnt_added_leaves_no_layer() {
|
||||
assert_eq!(ok(&mut s, ENDBLK), "\"EB\"");
|
||||
assert!(has(&s, "PARTS"), "the block's layer exists once it is added");
|
||||
}
|
||||
|
||||
/// entnext walks entmade block entities in order through the cached successor index, and a
|
||||
/// redefinition (same drawing, same block name) is not served from the stale index.
|
||||
#[test]
|
||||
fn entnext_walks_entmade_blocks_and_sees_a_redefinition() {
|
||||
let mut s = session();
|
||||
let walk = r#"(progn (setq e (cdr (assoc -2 (tblsearch "BLOCK" "EB"))) types nil)
|
||||
(while e (setq types (cons (cdr (assoc 0 (entget e))) types) e (entnext e)))
|
||||
(reverse types))"#;
|
||||
for code in [BLOCK_EB, LINE, CIRCLE, ENDBLK] {
|
||||
ok(&mut s, code);
|
||||
}
|
||||
assert_eq!(ok(&mut s, walk), "(\"LINE\" \"CIRCLE\")");
|
||||
assert_eq!(ok(&mut s, walk), "(\"LINE\" \"CIRCLE\")", "second walk from the cache");
|
||||
for code in [BLOCK_EB, CIRCLE, LINE, LINE, ENDBLK] {
|
||||
ok(&mut s, code);
|
||||
}
|
||||
assert_eq!(ok(&mut s, walk), "(\"CIRCLE\" \"LINE\" \"LINE\")");
|
||||
}
|
||||
|
||||
/// entget and handent reach every entity of an entmade block through the cached index, and a
|
||||
/// redefinition shows the new entities, not the old ones.
|
||||
#[test]
|
||||
fn entget_and_handent_reach_every_block_entity_also_after_a_redefinition() {
|
||||
let mut s = session();
|
||||
let walk = r#"(progn (setq e (cdr (assoc -2 (tblsearch "BLOCK" "EB"))) r nil)
|
||||
(while e (setq r (cons (list (cdr (assoc 0 (entget e))) (equal (handent (cdr (assoc 5 (entget e)))) e)) r) e (entnext e)))
|
||||
(reverse r))"#;
|
||||
for code in [BLOCK_EB, LINE, CIRCLE, LINE, ENDBLK] {
|
||||
ok(&mut s, code);
|
||||
}
|
||||
assert_eq!(ok(&mut s, walk), "((\"LINE\" T) (\"CIRCLE\" T) (\"LINE\" T))");
|
||||
for code in [BLOCK_EB, CIRCLE, ENDBLK] {
|
||||
ok(&mut s, code);
|
||||
}
|
||||
assert_eq!(ok(&mut s, walk), "((\"CIRCLE\" T))");
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::sync::Arc;
|
||||
|
||||
use super::eval::{Ctx, Flow, Special};
|
||||
use super::value::{Builtin, BuiltinKind, Sym, Value, charge_bytes, check_string_len, eq, equal, real_text, to_text};
|
||||
use super::{Env, LispError, drawing, input, objects, read};
|
||||
use super::{Env, LispError, drawing, input, read};
|
||||
|
||||
macro_rules! cxrs {
|
||||
($($name:ident $path:literal),*) => {
|
||||
@@ -262,10 +262,6 @@ static BUILTINS: &[Builtin] = &[
|
||||
ctx!("SSGETFIRST", drawing::ssgetfirst),
|
||||
ctx!("TBLSEARCH", drawing::tblsearch),
|
||||
ctx!("TBLNEXT", drawing::tblnext),
|
||||
ctx!("TBLOBJNAME", objects::tblobjname),
|
||||
ctx!("NAMEDOBJDICT", objects::namedobjdict),
|
||||
ctx!("DICTSEARCH", objects::dictsearch),
|
||||
ctx!("DICTNEXT", objects::dictnext),
|
||||
ctx!("RTOS", drawing::rtos),
|
||||
ctx!("ANGTOS", drawing::angtos),
|
||||
ctx!("DISTOF", drawing::distof),
|
||||
|
||||
@@ -126,11 +126,9 @@ fn write_text_file(path: &str, text: &str, append: bool) {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn write_text_file(_path: &str, _text: &str, _append: bool) {}
|
||||
|
||||
/// A file or a folder: routines test whether a module is installed with `(findfile "module/.")`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn file_exists(path: &str) -> bool {
|
||||
let p = std::path::Path::new(path);
|
||||
p.is_file() || p.is_dir()
|
||||
std::path::Path::new(path).is_file()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Drawing access from LISP: `command`, system variables, entity lists (`entget`, `entmake`,
|
||||
//! `entmod`, `entdel`, `entlast`, `entnext`, `handent`; non-graphic objects are in
|
||||
//! [`super::objects`]), selection sets (`ssget` and friends),
|
||||
//! `entmod`, `entdel`, `entlast`, `entnext`, `handent`), selection sets (`ssget` and friends),
|
||||
//! symbol tables (`tblsearch`, `tblnext`) and unit conversions (`rtos`, `angtos`, `distof`,
|
||||
//! `angtof`).
|
||||
//!
|
||||
@@ -8,21 +7,19 @@
|
||||
//! [`crate::cmd::file::entity_codec`]), so what `entget` shows is what a DXF file holds, except
|
||||
//! for angles, which are radians in a list and degrees in a file.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use cadcraft_doc::{Entity, Handle, Space};
|
||||
use cadcraft_geom::Vec2;
|
||||
use craft_dxf::Tag;
|
||||
|
||||
use super::LispError;
|
||||
use super::builtins::args_err;
|
||||
use super::eval::{Ctx, Flow, Need};
|
||||
use super::value::{PickSet, Value, to_text};
|
||||
use super::{BlockSlots, LispError};
|
||||
use crate::{Input, Session};
|
||||
|
||||
pub(super) fn arity(a: &[Value], min: usize, max: usize) -> Result<(), LispError> {
|
||||
fn arity(a: &[Value], min: usize, max: usize) -> Result<(), LispError> {
|
||||
if a.len() < min {
|
||||
return Err(args_err(true));
|
||||
}
|
||||
@@ -32,14 +29,14 @@ pub(super) fn arity(a: &[Value], min: usize, max: usize) -> Result<(), LispError
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn ename(v: &Value) -> Result<Handle, LispError> {
|
||||
fn ename(v: &Value) -> Result<Handle, LispError> {
|
||||
match v {
|
||||
Value::Ename(h) => Ok(*h),
|
||||
other => Err(LispError::bad_arg("lentityp", other)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn string(v: &Value) -> Result<String, LispError> {
|
||||
fn string(v: &Value) -> Result<String, LispError> {
|
||||
match v {
|
||||
Value::Str(s) => Ok(s.to_string()),
|
||||
other => Err(LispError::bad_arg("stringp", other)),
|
||||
@@ -274,7 +271,7 @@ fn tag_value(t: &Tag) -> Value {
|
||||
}
|
||||
|
||||
/// DXF groups as an association list: points combined into lists `(10 x y z)`.
|
||||
pub(super) fn groups_to_list(tags: &[Tag]) -> Vec<Value> {
|
||||
fn groups_to_list(tags: &[Tag]) -> Vec<Value> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while let Some(t) = tags.get(i) {
|
||||
@@ -359,16 +356,8 @@ fn space_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option<Space> {
|
||||
pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 2)?;
|
||||
let h = ename(&a[0])?;
|
||||
let drawn = ctx.s.doc().is_ok_and(|d| d.entity(h).is_some());
|
||||
let from_block = if drawn { None } else { block_entity(ctx, h) };
|
||||
let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
// An entity of a block definition (#1700) has no layout.
|
||||
let (e, in_block) = match (d.entity(h), &from_block) {
|
||||
(Some(e), _) => (e, false),
|
||||
(None, Some(e)) => (e, true),
|
||||
// Not an entity: a table record, layout or dictionary (#1659, #1661).
|
||||
(None, None) => return Ok(Flow::Value(super::objects::entget(ctx, h))),
|
||||
};
|
||||
let Some(e) = d.entity(h) else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let (kind, mut tags) = (codec()?.groups)(d, e);
|
||||
convert_angles(&kind, &mut tags, f64::to_radians);
|
||||
let layout = match space_of(d, h) {
|
||||
@@ -376,7 +365,7 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
_ => "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;
|
||||
let mut placed_layout = false;
|
||||
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");
|
||||
@@ -504,7 +493,6 @@ fn end_block(ctx: &mut Ctx<'_>) -> Value {
|
||||
}
|
||||
let name = b.name.clone();
|
||||
d.blocks.insert(name.clone(), Arc::new(b));
|
||||
ctx.env.block_next = None;
|
||||
ctx.s.touch();
|
||||
Value::str(&name)
|
||||
}
|
||||
@@ -516,7 +504,7 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
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)) };
|
||||
let (kind_name, common, mut kind) = match entity_from_list(ctx, list) {
|
||||
let (kind_name, common, kind) = match entity_from_list(ctx, list) {
|
||||
Ok(x) => x,
|
||||
Err(_) => return Ok(Flow::Value(Value::Nil)),
|
||||
};
|
||||
@@ -524,13 +512,6 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
if !kind_name.eq_ignore_ascii_case(old.kind.dxf_name()) {
|
||||
return Ok(Flow::Value(Value::Nil));
|
||||
}
|
||||
// A block reference's attributes are entities of their own in AutoCAD, which entmod of the
|
||||
// INSERT leaves alone; its list doesn't hold them, so they are kept from the reference.
|
||||
if let (cadcraft_doc::EntityKind::Insert(new), cadcraft_doc::EntityKind::Insert(was)) = (&mut kind, &old.kind)
|
||||
&& new.attribs.is_empty()
|
||||
{
|
||||
new.attribs = was.attribs.clone();
|
||||
}
|
||||
let Ok(d) = ctx.s.doc_mut() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
d.ensure_layer(&common.layer);
|
||||
let ok = d
|
||||
@@ -576,76 +557,24 @@ pub fn entdel(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `b` holds the same handles as `a`, in the same chunks and order. A chunk `b` still shares
|
||||
/// with `a` (which is held, so its chunks stay alive) is the same; only a chunk an edit copied is
|
||||
/// compared handle by handle.
|
||||
fn same_handles(a: &cadcraft_doc::EntityStore, b: &cadcraft_doc::EntityStore) -> bool {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let (mut x, mut y) = (a.chunk_slices(), b.chunk_slices());
|
||||
loop {
|
||||
match (x.next(), y.next()) {
|
||||
(None, None) => return true,
|
||||
(Some((ka, sa)), Some((kb, sb))) => {
|
||||
if ka != kb && (sa.len() != sb.len() || sa.iter().zip(sb).any(|(p, q)| p.handle != q.handle)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every entity's handle in creation order (model space and layouts), cached per drawing.
|
||||
///
|
||||
/// The cache is keyed by content identity, as the spatial index is: it holds clones of the
|
||||
/// spaces it was taken from, so any edit (`entmake`, `entmod`, `entdel`, a command, undo) copies
|
||||
/// the chunk it touches and the cache no longer matches. The drawing's address is no key: an
|
||||
/// edit in place keeps it, and a new drawing can be given the address of a dropped one.
|
||||
fn handles_in_order(ctx: &mut Ctx<'_>) -> Arc<Vec<Handle>> {
|
||||
let Ok(d) = ctx.s.doc() else { return Arc::default() };
|
||||
let spaces = || std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities));
|
||||
if let Some((stores, v)) = &mut ctx.env.order
|
||||
&& stores.len() == 1 + d.layouts.len()
|
||||
&& stores.iter().zip(spaces()).all(|(a, b)| same_handles(a, b))
|
||||
{
|
||||
// An edit that left every handle in place (a property `entmod`) keeps the order: hold
|
||||
// the spaces as they are now, so the next call finds their chunks shared again.
|
||||
if !stores.iter().zip(spaces()).all(|(a, b)| a.same_as(b)) {
|
||||
*stores = spaces().cloned().collect();
|
||||
}
|
||||
return v.clone();
|
||||
}
|
||||
let mut v: Vec<Handle> = spaces().flat_map(|s| s.iter().map(|e| e.handle)).collect();
|
||||
v.sort_unstable();
|
||||
let v = Arc::new(v);
|
||||
ctx.env.order = Some((spaces().cloned().collect(), v.clone()));
|
||||
v
|
||||
}
|
||||
|
||||
/// Every block-definition entity with its successor within its block, cached per drawing like
|
||||
/// [`handles_in_order`]: one pass over the blocks, then `entnext`, `entget` and `handent` on a
|
||||
/// block's entity are hash lookups instead of scans of the block (and of every block, to find
|
||||
/// which holds the entity).
|
||||
fn block_slots(ctx: &mut Ctx<'_>) -> Arc<BlockSlots> {
|
||||
let Ok(st) = ctx.s.state() else { return Arc::default() };
|
||||
let key = Arc::as_ptr(&st.doc) as usize;
|
||||
if let Some((k, v)) = &ctx.env.block_next
|
||||
if let Some((k, v)) = &ctx.env.order
|
||||
&& *k == key
|
||||
{
|
||||
return v.clone();
|
||||
}
|
||||
let mut m = HashMap::new();
|
||||
for b in st.doc.blocks.values() {
|
||||
let mut it = b.entities.iter().peekable();
|
||||
while let Some(e) = it.next() {
|
||||
m.insert(e.handle, (e.clone(), it.peek().map(|n| n.handle)));
|
||||
}
|
||||
let d = &st.doc;
|
||||
let mut v: Vec<Handle> = d.model.handles();
|
||||
for l in &d.layouts {
|
||||
v.extend(l.entities.handles());
|
||||
}
|
||||
let m = Arc::new(m);
|
||||
ctx.env.block_next = Some((key, m.clone()));
|
||||
m
|
||||
v.sort_unstable();
|
||||
let v = Arc::new(v);
|
||||
ctx.env.order = Some((key, v.clone()));
|
||||
v
|
||||
}
|
||||
|
||||
pub fn entlast(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
@@ -655,15 +584,6 @@ 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 order = handles_in_order(ctx);
|
||||
let next = match a.first() {
|
||||
None | Some(Value::Nil) => order.first().copied(),
|
||||
@@ -679,14 +599,8 @@ pub fn entnext(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
pub fn handent(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 1)?;
|
||||
let s = string(&a[0])?;
|
||||
let Some(h) = Handle::parse_hex(&s) else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let found = ctx.s.doc().is_ok_and(|d| d.entity(h).is_some()) || block_entity(ctx, h).is_some() || super::objects::exists(ctx, h);
|
||||
Ok(Flow::Value(if found { Value::Ename(h) } else { Value::Nil }))
|
||||
}
|
||||
|
||||
/// Entity `h` of a block definition (#1700), by the cached index.
|
||||
fn block_entity(ctx: &mut Ctx<'_>, h: Handle) -> Option<Arc<Entity>> {
|
||||
block_slots(ctx).get(&h).map(|(e, _)| e.clone())
|
||||
let h = Handle::parse_hex(&s).filter(|h| ctx.s.doc().is_ok_and(|d| d.entity(*h).is_some()));
|
||||
Ok(Flow::Value(h.map(Value::Ename).unwrap_or_default()))
|
||||
}
|
||||
|
||||
// ---------------- selection sets ----------------
|
||||
@@ -737,19 +651,15 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
Some("X") => all(s, true),
|
||||
Some("L") => {
|
||||
let order = handles_in_order(ctx);
|
||||
// Inside an MSPACE viewport, the objects that viewport does not draw are passed over.
|
||||
let st = ctx.s.state().ok();
|
||||
let drawn = |h: &Handle| st.is_none_or(|st| st.doc.entity(*h).is_none_or(|e| !st.hidden_in_viewport(e)));
|
||||
order.iter().rev().copied().find(drawn).into_iter().collect()
|
||||
order.last().copied().into_iter().collect()
|
||||
}
|
||||
Some("P") => ctx.s.state().map(|st| st.drawn_in_viewport(&st.previous_selection)).unwrap_or_default(),
|
||||
Some("P") => ctx.s.state().map(|st| st.previous_selection.clone()).unwrap_or_default(),
|
||||
Some("I") => ctx.s.selection(),
|
||||
Some("W") | Some("C") => {
|
||||
let (p1, p2) = (point(0)?, point(1)?);
|
||||
let s = &*ctx.s;
|
||||
let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let bx = cadcraft_geom::Bounds2::from_points([p1, p2]);
|
||||
crate::select::select_window_in(d, &space, s.viewport_frozen(), bx, mode.as_deref() == Some("C"))
|
||||
crate::select::select_window(d, &space, cadcraft_geom::Bounds2::from_points([p1, p2]), mode.as_deref() == Some("C"))
|
||||
}
|
||||
Some("F") | Some("WP") | Some("CP") => {
|
||||
let poly: Vec<Vec2> =
|
||||
@@ -757,8 +667,8 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
let s = &*ctx.s;
|
||||
let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
match mode.as_deref() {
|
||||
Some("F") => crate::select::select_fence_in(d, &space, s.viewport_frozen(), &poly),
|
||||
m => crate::select::select_polygon_in(d, &space, s.viewport_frozen(), &poly, m == Some("CP")),
|
||||
Some("F") => crate::select::select_fence(d, &space, &poly),
|
||||
m => crate::select::select_polygon(d, &space, &poly, m == Some("CP")),
|
||||
}
|
||||
}
|
||||
Some(":S") | Some("A") | None => {
|
||||
@@ -774,7 +684,7 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
let s = &*ctx.s;
|
||||
let ap = s.settings.pickbox.max(1.0) * s.pixel_size();
|
||||
let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
crate::select::pick_in(d, &space, s.viewport_frozen(), p, ap).into_iter().collect()
|
||||
crate::select::pick(d, &space, p, ap).into_iter().collect()
|
||||
}
|
||||
}
|
||||
Some(m) => return Err(LispError::new(format!("bad argument value: ssget mode {m}"))),
|
||||
@@ -1078,17 +988,12 @@ fn table_records(d: &cadcraft_doc::Drawing, table: &str) -> Vec<Value> {
|
||||
.blocks
|
||||
.values()
|
||||
.map(|b| {
|
||||
let mut items = vec![
|
||||
Value::list(vec![
|
||||
pair(0, Value::str("BLOCK")),
|
||||
pair(2, Value::str(&b.name)),
|
||||
pair(70, Value::Int(0)),
|
||||
Value::list(vec![Value::Int(10), Value::Real(b.base.x), Value::Real(b.base.y), Value::Real(b.base.z)]),
|
||||
];
|
||||
// Its first entity (-2): entnext walks the rest of the definition (#1700).
|
||||
if let Some(first) = b.entities.iter().next() {
|
||||
items.push(pair(-2, Value::Ename(first.handle)));
|
||||
}
|
||||
Value::list(items)
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
"DIMSTYLE" => d
|
||||
|
||||
@@ -141,7 +141,7 @@ impl GetRequest {
|
||||
let ap = s.settings.pickbox.max(1.0) * s.pixel_size();
|
||||
let space = s.state().map(|st| st.edit_space()).map_err(|e| Again::Msg(e.to_string()))?;
|
||||
let d = s.doc().map_err(|e| Again::Msg(e.to_string()))?;
|
||||
match crate::select::pick_in(d, &space, s.viewport_frozen(), Vec2::new(p[0], p[1]), ap) {
|
||||
match crate::select::pick(d, &space, Vec2::new(p[0], p[1]), ap) {
|
||||
Some(h) => Ok(Value::list(vec![Value::Ename(h), Value::point(&p)])),
|
||||
None => Err("Missed, try again.".into()),
|
||||
}
|
||||
|
||||
@@ -1,281 +0,0 @@
|
||||
//! Non-graphic objects from LISP: the named object dictionary and its dictionaries, table records
|
||||
//! and layouts (`namedobjdict`, `dictsearch`, `dictnext`, `tblobjname`, and `handent` and
|
||||
//! `entget` of such an object).
|
||||
//!
|
||||
//! CADCraft writes these objects from its own model and gives them handles only in a file, so
|
||||
//! they are read from the drawing's records as a DXF file of it holds them
|
||||
//! ([`crate::cmd::file::EntityCodec::objects`]). Each object gets an entity name that stays the
|
||||
//! same for the drawing's session: the handle the drawing's file gave it, when the drawing was
|
||||
//! read from a file that had it, otherwise a name above any file's handles. An object is known by
|
||||
//! its role (a layer's name, a dictionary key, a layout's name), so its name follows it across
|
||||
//! edits; one without a role (an object of a deeper dictionary) is known by its handle in the
|
||||
//! written records, so its name holds only until the drawing changes (then it names nothing). Lists of these objects are
|
||||
//! read-only: `entmod` and `entmake` don't take them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use cadcraft_doc::foreign::ForeignKey;
|
||||
use cadcraft_doc::{Drawing, Handle};
|
||||
use craft_dxf::Tag;
|
||||
|
||||
use super::LispError;
|
||||
use super::drawing::{arity, ename, groups_to_list, string};
|
||||
use super::eval::{Ctx, Flow};
|
||||
use super::value::Value;
|
||||
|
||||
/// The first entity name given to an object its drawing's file didn't name.
|
||||
const OWN_NAMES: u64 = 0x7F00_0000_0000_0000;
|
||||
/// The kind of a key for an object without a role: its written handle is the name.
|
||||
const BY_HANDLE: &str = "@";
|
||||
|
||||
/// The entity names given to non-graphic objects, and what they are read from.
|
||||
#[derive(Default)]
|
||||
pub struct Names {
|
||||
by_key: HashMap<ForeignKey, Handle>,
|
||||
by_name: HashMap<Handle, ForeignKey>,
|
||||
next: u64,
|
||||
/// The written records of the drawing they were taken from (held weakly, so its address
|
||||
/// can't be reused for another drawing while the records are kept).
|
||||
records: Option<(Weak<Drawing>, Arc<Records>)>,
|
||||
/// `dictnext`'s place in each dictionary.
|
||||
dictnext: HashMap<Handle, usize>,
|
||||
}
|
||||
|
||||
/// A drawing's non-graphic records as written.
|
||||
struct Records {
|
||||
list: Vec<(String, Vec<Tag>, Option<ForeignKey>)>,
|
||||
/// Written handle → index in `list`.
|
||||
by_handle: HashMap<String, usize>,
|
||||
/// Role → written handle.
|
||||
by_role: HashMap<ForeignKey, String>,
|
||||
}
|
||||
|
||||
impl Records {
|
||||
fn key(&self, written: &str) -> Option<ForeignKey> {
|
||||
let i = *self.by_handle.get(written)?;
|
||||
let (_, _, role) = self.list.get(i)?;
|
||||
Some(role.clone().unwrap_or_else(|| (BY_HANDLE.into(), written.to_string())))
|
||||
}
|
||||
|
||||
fn written(&self, key: &ForeignKey) -> Option<&str> {
|
||||
if key.0 == BY_HANDLE {
|
||||
return self.by_handle.get_key_value(&key.1).map(|(h, _)| h.as_str());
|
||||
}
|
||||
self.by_role.get(key).map(String::as_str)
|
||||
}
|
||||
|
||||
fn record(&self, written: &str) -> Option<&(String, Vec<Tag>, Option<ForeignKey>)> {
|
||||
self.list.get(*self.by_handle.get(written)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// A record's own handle: group 5, or 105 for a DIMSTYLE (before any xdata).
|
||||
fn own_handle(tags: &[Tag]) -> Option<&Tag> {
|
||||
tags.iter().take_while(|t| t.code < 1000).find(|t| matches!(t.code, 5 | 105))
|
||||
}
|
||||
|
||||
/// A handle as the records spell it (upper-case hex without leading zeros).
|
||||
fn norm(hex: &str) -> Option<String> {
|
||||
Handle::parse_hex(hex.trim()).map(Handle::hex)
|
||||
}
|
||||
|
||||
fn records(names: &mut Names, d: &Arc<Drawing>) -> Option<Arc<Records>> {
|
||||
if let Some((w, r)) = &names.records
|
||||
&& std::ptr::eq(w.as_ptr(), Arc::as_ptr(d))
|
||||
{
|
||||
return Some(r.clone());
|
||||
}
|
||||
let list = crate::cmd::file::object_records()?(d);
|
||||
let mut by_handle = HashMap::new();
|
||||
let mut by_role = HashMap::new();
|
||||
for (i, (_, tags, role)) in list.iter().enumerate() {
|
||||
let Some(h) = own_handle(tags).and_then(|t| norm(&t.str())) else { continue };
|
||||
if let Some(role) = role {
|
||||
by_role.entry(role.clone()).or_insert_with(|| h.clone());
|
||||
}
|
||||
by_handle.entry(h).or_insert(i);
|
||||
}
|
||||
let r = Arc::new(Records { list, by_handle, by_role });
|
||||
// Written handles change with the drawing: names given by them no longer hold.
|
||||
names.by_key.retain(|k, _| k.0 != BY_HANDLE);
|
||||
names.by_name.retain(|_, k| k.0 != BY_HANDLE);
|
||||
names.records = Some((Arc::downgrade(d), r.clone()));
|
||||
Some(r)
|
||||
}
|
||||
|
||||
/// The entity name of the object with `key`, given out now if it has none yet.
|
||||
fn name_of(names: &mut Names, d: &Drawing, key: &ForeignKey) -> Option<Handle> {
|
||||
if let Some(h) = names.by_key.get(key) {
|
||||
return Some(*h);
|
||||
}
|
||||
let free = |names: &Names, h: Handle| d.entity(h).is_none() && !names.by_name.contains_key(&h);
|
||||
let file = (key.0 != BY_HANDLE).then(|| d.foreign.handles.iter().find(|(_, k)| *k == key).map(|(h, _)| *h)).flatten();
|
||||
let h = match file.filter(|h| free(names, *h)) {
|
||||
Some(h) => h,
|
||||
None => {
|
||||
// A name of its own, past any that is taken (a hostile file can use this range too).
|
||||
let mut found = None;
|
||||
for _ in 0..1024 {
|
||||
let h = Handle(OWN_NAMES.checked_add(names.next)?);
|
||||
names.next = names.next.checked_add(1)?;
|
||||
if free(names, h) && !d.foreign.handles.contains_key(&h) {
|
||||
found = Some(h);
|
||||
break;
|
||||
}
|
||||
}
|
||||
found?
|
||||
}
|
||||
};
|
||||
names.by_key.insert(key.clone(), h);
|
||||
names.by_name.insert(h, key.clone());
|
||||
Some(h)
|
||||
}
|
||||
|
||||
/// What an entity name of a non-graphic object stands for.
|
||||
fn key_of(names: &Names, d: &Drawing, h: Handle) -> Option<ForeignKey> {
|
||||
names.by_name.get(&h).cloned().or_else(|| d.foreign.handles.get(&h).cloned())
|
||||
}
|
||||
|
||||
/// Groups that hold a handle (DXF Reference, group code value types): soft and hard pointers and
|
||||
/// owners, arbitrary object handles and plot style handles.
|
||||
fn pointer_group(code: i32) -> bool {
|
||||
matches!(code, 320..=369 | 390..=399 | 480..=481)
|
||||
}
|
||||
|
||||
/// The object `written` as an entity list: `(-1 . name)`, its type and its groups, with its
|
||||
/// handle (group 5, a DIMSTYLE's 105) as its name's and pointers as entity names.
|
||||
fn object_list(names: &mut Names, d: &Drawing, recs: &Records, name: Handle, written: &str) -> Value {
|
||||
let Some((kind, tags, _)) = recs.record(written) else { return Value::Nil };
|
||||
let mut items = vec![Value::cons(Value::Int(-1), Value::Ename(name)), Value::cons(Value::Int(0), Value::str(kind))];
|
||||
for v in groups_to_list(tags) {
|
||||
let code = v.car().as_number().map(|c| c as i32);
|
||||
let text = match v.cdr() {
|
||||
Value::Str(s) => Some(s.to_string()),
|
||||
_ => None,
|
||||
};
|
||||
match (code, text) {
|
||||
(Some(c @ (5 | 105)), Some(_)) => items.push(Value::cons(Value::Int(c), Value::str(&name.hex()))),
|
||||
(Some(c), Some(t)) if pointer_group(c) => {
|
||||
let Some(h) = norm(&t).filter(|h| h != "0") else { continue };
|
||||
let target = Handle::parse_hex(&h).filter(|e| d.entity(*e).is_some());
|
||||
let target = target.or_else(|| recs.key(&h).and_then(|k| name_of(names, d, &k)));
|
||||
items.push(match target {
|
||||
Some(e) => Value::cons(Value::Int(c), Value::Ename(e)),
|
||||
None => v,
|
||||
});
|
||||
}
|
||||
_ => items.push(v),
|
||||
}
|
||||
}
|
||||
Value::list(items)
|
||||
}
|
||||
|
||||
/// The written handle of the non-graphic object named `h`, if it still exists.
|
||||
fn written_of(names: &Names, d: &Drawing, recs: &Records, h: Handle) -> Option<String> {
|
||||
let key = key_of(names, d, h)?;
|
||||
recs.written(&key).map(str::to_string)
|
||||
}
|
||||
|
||||
/// `entget` of a non-graphic object: nil when `h` names none.
|
||||
pub fn entget(ctx: &mut Ctx<'_>, h: Handle) -> Value {
|
||||
let Ok(st) = ctx.s.state() else { return Value::Nil };
|
||||
let names = &mut ctx.env.objects;
|
||||
let Some(recs) = records(names, &st.doc) else { return Value::Nil };
|
||||
let Some(w) = written_of(names, &st.doc, &recs, h) else { return Value::Nil };
|
||||
object_list(names, &st.doc, &recs, h, &w)
|
||||
}
|
||||
|
||||
/// `handent` of a non-graphic object: whether `h` names one that exists.
|
||||
pub fn exists(ctx: &mut Ctx<'_>, h: Handle) -> bool {
|
||||
let Ok(st) = ctx.s.state() else { return false };
|
||||
let names = &mut ctx.env.objects;
|
||||
let Some(recs) = records(names, &st.doc) else { return false };
|
||||
written_of(names, &st.doc, &recs, h).is_some()
|
||||
}
|
||||
|
||||
/// `(namedobjdict)`: the named object dictionary's entity name.
|
||||
pub fn namedobjdict(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 0, 0)?;
|
||||
let Ok(st) = ctx.s.state() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let names = &mut ctx.env.objects;
|
||||
let key: ForeignKey = ("NOD".into(), String::new());
|
||||
let found = records(names, &st.doc).filter(|r| r.written(&key).is_some()).and_then(|_| name_of(names, &st.doc, &key));
|
||||
Ok(Flow::Value(found.map(Value::Ename).unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// `(tblobjname table name)`: the entity name of a symbol table record (of the BLOCK entity for
|
||||
/// the BLOCK table), nil when there is none.
|
||||
pub fn tblobjname(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 2)?;
|
||||
let table = string(&a[0])?.trim().to_ascii_uppercase();
|
||||
// As the roles spell names (upper case in ASCII only).
|
||||
let name = string(&a[1])?.trim().to_ascii_uppercase();
|
||||
let Ok(st) = ctx.s.state() else { return Ok(Flow::Value(Value::Nil)) };
|
||||
let names = &mut ctx.env.objects;
|
||||
let key: ForeignKey = (table, name);
|
||||
let found = records(names, &st.doc).filter(|r| r.written(&key).is_some()).and_then(|_| name_of(names, &st.doc, &key));
|
||||
Ok(Flow::Value(found.map(Value::Ename).unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// A dictionary's entries: (key, written handle of the entry), in order.
|
||||
fn entries(kind: &str, tags: &[Tag]) -> Vec<(String, String)> {
|
||||
if !matches!(kind, "DICTIONARY" | "ACDBDICTIONARYWDFLT") {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut key: Option<String> = None;
|
||||
for t in tags {
|
||||
match t.code {
|
||||
3 => key = Some(t.str()),
|
||||
350 | 360 => {
|
||||
if let (Some(k), Some(h)) = (key.take(), norm(&t.str())) {
|
||||
out.push((k, h));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The entity list of entry `i` of the dictionary named `dict`, and the number of entries.
|
||||
fn entry(ctx: &mut Ctx<'_>, dict: Handle, pick: impl Fn(&[(String, String)]) -> Option<usize>) -> (Value, Option<usize>) {
|
||||
let Ok(st) = ctx.s.state() else { return (Value::Nil, None) };
|
||||
let names = &mut ctx.env.objects;
|
||||
let Some(recs) = records(names, &st.doc) else { return (Value::Nil, None) };
|
||||
let Some(w) = written_of(names, &st.doc, &recs, dict) else { return (Value::Nil, None) };
|
||||
let Some((kind, tags, _)) = recs.record(&w) else { return (Value::Nil, None) };
|
||||
let list = entries(kind, tags);
|
||||
let Some(i) = pick(&list) else { return (Value::Nil, None) };
|
||||
let Some((_, eh)) = list.get(i) else { return (Value::Nil, None) };
|
||||
let Some(name) = recs.key(eh).and_then(|k| name_of(names, &st.doc, &k)) else { return (Value::Nil, Some(i)) };
|
||||
(object_list(names, &st.doc, &recs, name, eh), Some(i))
|
||||
}
|
||||
|
||||
/// `(dictsearch dict key [setnext])`: the entity list of the entry `key` (any case) of a
|
||||
/// dictionary, nil when it has none; with `setnext`, `dictnext` goes on after it.
|
||||
pub fn dictsearch(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 2, 3)?;
|
||||
let dict = ename(&a[0])?;
|
||||
let key = string(&a[1])?;
|
||||
let (v, i) = entry(ctx, dict, |list| list.iter().position(|(k, _)| k.eq_ignore_ascii_case(&key)));
|
||||
if let Some(i) = i
|
||||
&& a.get(2).is_some_and(|v| !v.is_nil())
|
||||
{
|
||||
ctx.env.objects.dictnext.insert(dict, i.saturating_add(1));
|
||||
}
|
||||
Ok(Flow::Value(v))
|
||||
}
|
||||
|
||||
/// `(dictnext dict [rewind])`: the entity list of a dictionary's next entry (its first with
|
||||
/// `rewind`, or on the first call), nil after the last.
|
||||
pub fn dictnext(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
|
||||
arity(&a, 1, 2)?;
|
||||
let dict = ename(&a[0])?;
|
||||
let rewind = a.get(1).is_some_and(|v| !v.is_nil());
|
||||
let at = if rewind { 0 } else { ctx.env.objects.dictnext.get(&dict).copied().unwrap_or(0) };
|
||||
let (v, _) = entry(ctx, dict, |list| (at < list.len()).then_some(at));
|
||||
ctx.env.objects.dictnext.insert(dict, at.saturating_add(1));
|
||||
Ok(Flow::Value(v))
|
||||
}
|
||||
@@ -2,12 +2,10 @@
|
||||
|
||||
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};
|
||||
|
||||
pub(super) fn session() -> Session {
|
||||
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
set_object_records(cadcraft_io::object_records);
|
||||
Session::new()
|
||||
}
|
||||
|
||||
@@ -406,147 +404,6 @@ fn entity_lists_round_trip() {
|
||||
assert_eq!(ok(&mut s, "(handent \"ZZZZZZ\")"), "nil");
|
||||
}
|
||||
|
||||
/// entlast, entnext and (ssget "L") see what the routine itself just made, changed or deleted:
|
||||
/// the order they share isn't kept past an edit, even one that leaves the drawing where it was.
|
||||
#[test]
|
||||
fn entlast_follows_edits_within_one_routine() {
|
||||
let mut s = session();
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
"(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (setq a (entlast))
|
||||
(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 2.0 0.0 0.0))) (setq b (entlast))
|
||||
(list (eq a b) (cdr (assoc 11 (entget b))) (eq (entnext a) b) (eq (ssname (ssget \"L\") 0) b))"
|
||||
),
|
||||
"(nil (2.0 0.0 0.0) T T)"
|
||||
);
|
||||
// Deleting the last makes the one before it last; entdel brings it back last again.
|
||||
assert_eq!(ok(&mut s, "(entdel b) (setq c (entlast)) (entdel b) (list (eq c a) (eq (entlast) b))"), "(T T)");
|
||||
// A command, an entmod and entlast, over and over in one routine: each entlast is the line
|
||||
// just drawn.
|
||||
assert_eq!(
|
||||
ok(
|
||||
&mut s,
|
||||
"(setq seen nil i 0)
|
||||
(repeat 40
|
||||
(command \"_.LINE\" (list i 10) (list i 20) \"\")
|
||||
(setq e (entlast) d (entget e))
|
||||
(entmod (subst (cons 8 \"MOVED\") (assoc 8 d) d))
|
||||
(if (and (not (member e seen)) (equal (cdr (assoc 10 (entget (entlast)))) (list (float i) 10.0 0.0) 1e-9))
|
||||
(setq seen (cons e seen)))
|
||||
(setq i (1+ i)))
|
||||
(list (length seen) (cdr (assoc 8 (entget (entlast)))))"
|
||||
),
|
||||
"(40 \"MOVED\")"
|
||||
);
|
||||
// The same across routines, with an undo between them.
|
||||
for i in 0..10 {
|
||||
ok(&mut s, &format!("(entmake '((0 . \"CIRCLE\") (10 {i}.0 50.0 0.0) (40 . 1.0)))"));
|
||||
assert_eq!(ok(&mut s, "(cadr (assoc 10 (entget (entlast))))"), format!("{i}.0"));
|
||||
s.undo().unwrap();
|
||||
ok(&mut s, &format!("(entmake '((0 . \"CIRCLE\") (10 {i}.0 60.0 0.0) (40 . 1.0)))"));
|
||||
assert_eq!(ok(&mut s, "(caddr (assoc 10 (entget (entlast))))"), "60.0");
|
||||
}
|
||||
}
|
||||
|
||||
/// entmod of a block reference keeps its attributes and their values: they aren't in its list
|
||||
/// (in AutoCAD they are entities of their own, which entmod of the INSERT leaves alone).
|
||||
#[test]
|
||||
fn entmod_of_a_block_reference_keeps_its_attributes() {
|
||||
let mut s = session();
|
||||
ok(
|
||||
&mut s,
|
||||
"(entmake '((0 . \"BLOCK\") (2 . \"TAGGED\") (70 . 0) (10 0.0 0.0 0.0)))
|
||||
(entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 1.0)))
|
||||
(entmake '((0 . \"ATTDEF\") (10 0.0 2.0 0.0) (40 . 1.0) (1 . \"\") (3 . \"Name\") (2 . \"PSTN\") (70 . 0)))
|
||||
(entmake '((0 . \"ENDBLK\")))",
|
||||
);
|
||||
s.execute("insert", &serde_json::json!({"name": "TAGGED", "at": [10, 10], "attribs": {"PSTN": "ARK1"}})).unwrap();
|
||||
let insert = |s: &Session| {
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Insert(i) => {
|
||||
Some((e.common.layer.clone(), i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect::<Vec<_>>()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let want = vec![("PSTN".to_string(), "ARK1".to_string())];
|
||||
assert_eq!(insert(&s).1, want);
|
||||
ok(&mut s, "(setq d (entget (entlast))) (entmod (subst (cons 8 \"UGO\") (assoc 8 d) d))");
|
||||
assert_eq!(insert(&s), ("UGO".to_string(), want.clone()));
|
||||
// A new rotation keeps them too.
|
||||
ok(&mut s, "(setq d (entget (entlast))) (entmod (subst (cons 50 (/ pi 2)) (assoc 50 d) d))");
|
||||
let rotation = s
|
||||
.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
cadcraft_doc::EntityKind::Insert(i) => Some(i.rotation),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!((rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "the entmod took: {rotation}");
|
||||
assert_eq!(insert(&s).1, want);
|
||||
}
|
||||
|
||||
/// 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]
|
||||
fn entlast_keeps_its_order_across_property_edits() {
|
||||
let mut s = session();
|
||||
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (entlast)");
|
||||
let uid = s.state().unwrap().uid;
|
||||
// The cached order itself is held, so a rebuilt one can't take its address.
|
||||
let order = |s: &Session| s.lisp.envs[&uid].order.as_ref().unwrap().1.clone();
|
||||
let before = order(&s);
|
||||
assert_eq!(
|
||||
ok(&mut s, "(setq d (entget (entlast))) (entmod (subst (cons 8 \"MOVED\") (assoc 8 d) d)) (cdr (assoc 8 (entget (entlast))))"),
|
||||
"\"MOVED\""
|
||||
);
|
||||
assert!(std::sync::Arc::ptr_eq(&order(&s), &before), "a layer change keeps the order");
|
||||
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 2.0 0.0 0.0))) (entlast)");
|
||||
assert!(!std::sync::Arc::ptr_eq(&order(&s), &before), "a new entity rebuilds it");
|
||||
}
|
||||
|
||||
/// Closing a drawing drops its LISP environment, and with it the entity stores its cached
|
||||
/// order holds.
|
||||
#[test]
|
||||
fn closing_a_drawing_drops_its_environment() {
|
||||
let mut s = session();
|
||||
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (entlast)");
|
||||
let uid = s.state().unwrap().uid;
|
||||
assert!(s.lisp.envs.get(&uid).is_some_and(|e| e.order.is_some()));
|
||||
s.execute("close", &serde_json::json!({})).unwrap();
|
||||
assert!(!s.lisp.envs.contains_key(&uid));
|
||||
}
|
||||
|
||||
/// HANDSEED is the next handle the drawing gives out, in hex, and moves as objects are made.
|
||||
#[test]
|
||||
fn handseed_follows_new_objects() {
|
||||
let mut s = session();
|
||||
let seed = |s: &Session| format!("\"{:X}\"", s.doc().unwrap().next_handle().0);
|
||||
let before = ok(&mut s, "(getvar \"HANDSEED\")");
|
||||
assert_eq!(before, seed(&s));
|
||||
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0)))");
|
||||
let after = ok(&mut s, "(getvar \"HANDSEED\")");
|
||||
assert_eq!(after, seed(&s));
|
||||
assert_ne!(after, before);
|
||||
assert!(eval(&mut s, "(setvar \"HANDSEED\" \"FFFFFF\")").is_err(), "read-only");
|
||||
// A handle the file's own objects hold is skipped, as allocation skips it.
|
||||
let d = s.doc_mut().unwrap();
|
||||
let held = d.handseed;
|
||||
std::sync::Arc::make_mut(&mut d.foreign).handles.insert(cadcraft_doc::Handle(held), ("NOD".into(), String::new()));
|
||||
assert_eq!(ok(&mut s, "(getvar \"HANDSEED\")"), format!("\"{:X}\"", held + 1));
|
||||
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0)))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 5 (entget (entlast))))"), format!("\"{:X}\"", held + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entity_lists_hold_angles_in_radians() {
|
||||
let mut s = session();
|
||||
@@ -1191,253 +1048,6 @@ fn a_panic_inside_a_routine_ends_it_with_an_error() {
|
||||
assert_eq!(ok(&mut s, "(+ 1 2)"), "3");
|
||||
}
|
||||
|
||||
/// The handle (group 5, a DIMSTYLE's 105) of the `kind` record named `name` (group 2, or 1 for a
|
||||
/// LAYOUT; any for "") in DXF text.
|
||||
fn dxf_handle(dxf: &str, kind: &str, name: &str) -> String {
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
let pairs: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect();
|
||||
let mut i = 0;
|
||||
while i < pairs.len() {
|
||||
if pairs[i] == ("0", kind) {
|
||||
let rec: Vec<(&str, &str)> = pairs[i + 1..].iter().take_while(|p| p.0 != "0").copied().collect();
|
||||
let named = name.is_empty() || rec.iter().any(|p| (p.0 == "2" || (kind == "LAYOUT" && p.0 == "1")) && p.1 == name);
|
||||
if named {
|
||||
return rec.iter().find(|p| p.0 == "5" || p.0 == "105").unwrap().1.to_string();
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
panic!("no {kind} {name}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namedobjdict_and_dictsearch_reach_the_layouts() {
|
||||
let mut s = session();
|
||||
assert!(ok(&mut s, "(namedobjdict)").starts_with("<Entity name: "));
|
||||
assert_eq!(ok(&mut s, "(eq (namedobjdict) (namedobjdict))"), "T");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (namedobjdict))))"), "\"DICTIONARY\"");
|
||||
// Keys in any case; the entry's own list, owned by the dictionary it is in.
|
||||
ok(&mut s, "(setq layouts (dictsearch (namedobjdict) \"acad_layout\"))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 layouts))"), "\"DICTIONARY\"");
|
||||
assert_eq!(ok(&mut s, "(eq (cdr (assoc 330 layouts)) (namedobjdict))"), "T");
|
||||
ok(&mut s, "(setq l1 (dictsearch (cdr (assoc -1 layouts)) \"Layout1\"))");
|
||||
assert_eq!(ok(&mut s, "(list (cdr (assoc 0 l1)) (cdr (assoc 1 (member '(100 . \"AcDbLayout\") l1))))"), "(\"LAYOUT\" \"Layout1\")");
|
||||
// The plot settings are there to read; the layout's block record is an entity name.
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 l1))"), "\"none_device\"");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (cdr (assoc 330 (reverse l1))))))"), "\"BLOCK_RECORD\"");
|
||||
// The name in group 5 leads back to the object.
|
||||
assert_eq!(ok(&mut s, "(eq (handent (cdr (assoc 5 l1))) (cdr (assoc -1 l1)))"), "T");
|
||||
assert_eq!(ok(&mut s, "(dictsearch (namedobjdict) \"NO_SUCH_KEY\")"), "nil");
|
||||
// A layer is not a dictionary: nothing to search.
|
||||
assert_eq!(ok(&mut s, "(dictsearch (tblobjname \"LAYER\" \"0\") \"ACAD_LAYOUT\")"), "nil");
|
||||
assert!(eval(&mut s, "(dictsearch \"ACAD_LAYOUT\" \"x\")").unwrap_err().contains("lentityp"));
|
||||
assert!(eval(&mut s, "(namedobjdict 1)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dictnext_walks_a_dictionary() {
|
||||
let mut s = session();
|
||||
ok(&mut s, "(setq d (cdr (assoc -1 (dictsearch (namedobjdict) \"ACAD_LAYOUT\"))))");
|
||||
let names = "(progn (setq out nil e (dictnext d T)) (while e (setq out (cons (cdr (assoc 1 (member '(100 . \"AcDbLayout\") e))) out) e (dictnext d))) (reverse out))";
|
||||
assert_eq!(ok(&mut s, names), "(\"Model\" \"Layout1\" \"Layout2\")");
|
||||
// Past the end it stays nil until rewound.
|
||||
assert_eq!(ok(&mut s, "(dictnext d)"), "nil");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (dictnext d T)))"), "\"LAYOUT\"");
|
||||
// dictsearch with setnext: dictnext goes on after the entry found.
|
||||
ok(&mut s, "(dictsearch d \"Model\" T)");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (member '(100 . \"AcDbLayout\") (dictnext d))))"), "\"Layout1\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tblobjname_names_table_records() {
|
||||
let mut s = session();
|
||||
ok(&mut s, "(setq l (tblobjname \"layer\" \"0\"))");
|
||||
assert_eq!(ok(&mut s, "(list (cdr (assoc 0 (entget l))) (cdr (assoc 2 (entget l))))"), "(\"LAYER\" \"0\")");
|
||||
// Its owner is the LAYER table.
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget (cdr (assoc 330 (entget l))))))"), "\"LAYER\"");
|
||||
// The BLOCK table gives the block's BLOCK entity.
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (tblobjname \"BLOCK\" \"*Model_Space\"))))"), "\"BLOCK\"");
|
||||
assert_eq!(ok(&mut s, "(tblobjname \"LAYER\" \"NO_SUCH_LAYER\")"), "nil");
|
||||
// Names outside ASCII: found in the case they have, ASCII letters in any case.
|
||||
s.execute("layer.new", &serde_json::json!({"name": "ébauche"})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget (tblobjname \"LAYER\" \"éBAUCHE\"))))"), "\"ébauche\"");
|
||||
assert_eq!(ok(&mut s, "(tblobjname \"NO_SUCH_TABLE\" \"0\")"), "nil");
|
||||
// A DIMSTYLE has its handle in group 105.
|
||||
ok(&mut s, "(setq ds (tblobjname \"DIMSTYLE\" (cdr (assoc 2 (tblnext \"DIMSTYLE\" T)))))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget ds)))"), "\"DIMSTYLE\"");
|
||||
assert_eq!(ok(&mut s, "(eq ds (handent (cdr (assoc 105 (entget ds)))))"), "T");
|
||||
assert!(eval(&mut s, "(tblobjname \"LAYER\")").is_err());
|
||||
// The name holds while the drawing changes.
|
||||
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 10.0 0.0 0.0)))");
|
||||
assert_eq!(ok(&mut s, "(eq l (tblobjname \"LAYER\" \"0\"))"), "T");
|
||||
assert_eq!(ok(&mut s, "(eq l (handent (cdr (assoc 5 (entget l)))))"), "T");
|
||||
}
|
||||
|
||||
/// #1661: the handles of a layer and a layout in a file lead to them once the file is open.
|
||||
#[test]
|
||||
fn handent_names_a_files_layer_and_layout() {
|
||||
let mut s = session();
|
||||
ok(&mut s, "(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 10.0 0.0 0.0)))");
|
||||
let bytes = cadcraft_io::write(s.doc().unwrap(), "h.dxf").unwrap();
|
||||
let dxf = String::from_utf8(bytes.clone()).unwrap();
|
||||
let (layer, layout) = (dxf_handle(&dxf, "LAYER", "0"), dxf_handle(&dxf, "LAYOUT", "Layout1"));
|
||||
let line = dxf_handle(&dxf, "LINE", "");
|
||||
let dimstyle = dxf_handle(&dxf, "DIMSTYLE", "Standard");
|
||||
let mut s = session();
|
||||
s.open_drawing(cadcraft_io::read(&bytes, "h.dxf").unwrap(), "h.dxf", None);
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 0 (entget (handent \"{line}\"))))")), "\"LINE\"");
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 2 (entget (handent \"{layer}\"))))")), "\"0\"");
|
||||
assert_eq!(ok(&mut s, &format!("(eq (handent \"{layer}\") (tblobjname \"LAYER\" \"0\"))")), "T");
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 0 (entget (handent \"{layout}\"))))")), "\"LAYOUT\"");
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 5 (entget (handent \"{layout}\"))))")), format!("\"{layout}\""));
|
||||
// A DIMSTYLE's handle is in group 105, in the file and in its list.
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 0 (entget (handent \"{dimstyle}\"))))")), "\"DIMSTYLE\"");
|
||||
assert_eq!(ok(&mut s, &format!("(cdr (assoc 105 (entget (handent \"{dimstyle}\"))))")), format!("\"{dimstyle}\""));
|
||||
assert_eq!(ok(&mut s, &format!("(eq (handent \"{dimstyle}\") (tblobjname \"DIMSTYLE\" \"Standard\"))")), "T");
|
||||
assert_eq!(ok(&mut s, "(handent \"FFFFF\")"), "nil");
|
||||
assert_eq!(ok(&mut s, "(handent \"not hex\")"), "nil");
|
||||
}
|
||||
|
||||
/// A drawing with a dictionary two levels below the named object dictionary (kept from its file):
|
||||
/// NOD › MY_DICT › INNER › LEAF (an XRECORD).
|
||||
fn nested_dictionary_file() -> Vec<u8> {
|
||||
let s = session();
|
||||
let bytes = cadcraft_io::write(s.doc().unwrap(), "n.dxf").unwrap();
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let mut pairs: Vec<(String, String)> = lines.chunks(2).map(|c| (c[0].trim().to_string(), c[1].to_string())).collect();
|
||||
let objects = pairs.iter().position(|p| p.0 == "2" && p.1 == "OBJECTS").unwrap();
|
||||
let nod = objects + pairs[objects..].iter().position(|p| p.0 == "0" && p.1 == "DICTIONARY").unwrap();
|
||||
let nod_handle = pairs[nod + 1].1.clone();
|
||||
let after = nod + pairs[nod..].iter().position(|p| p.0 == "281").unwrap() + 1;
|
||||
pairs.splice(after..after, [("3".into(), "MY_DICT".into()), ("350".into(), "AAA1".into())]);
|
||||
let end = objects + pairs[objects..].iter().position(|p| p.0 == "0" && p.1 == "ENDSEC").unwrap();
|
||||
let p = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
let added = vec![
|
||||
p("0", "DICTIONARY"),
|
||||
p("5", "AAA1"),
|
||||
p("330", &nod_handle),
|
||||
p("100", "AcDbDictionary"),
|
||||
p("281", "1"),
|
||||
p("3", "INNER"),
|
||||
p("350", "AAA2"),
|
||||
p("0", "DICTIONARY"),
|
||||
p("5", "AAA2"),
|
||||
p("330", "AAA1"),
|
||||
p("100", "AcDbDictionary"),
|
||||
p("281", "1"),
|
||||
p("3", "LEAF"),
|
||||
p("350", "AAA3"),
|
||||
p("0", "XRECORD"),
|
||||
p("5", "AAA3"),
|
||||
p("330", "AAA2"),
|
||||
p("100", "AcDbXrecord"),
|
||||
p("280", "1"),
|
||||
p("1", "hello"),
|
||||
];
|
||||
pairs.splice(end..end, added);
|
||||
pairs.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::<String>().into_bytes()
|
||||
}
|
||||
|
||||
/// An object found below a dictionary entry has no role: once the drawing changes, its old name
|
||||
/// finds nothing rather than whatever now has its written handle.
|
||||
#[test]
|
||||
fn a_deeper_objects_name_lapses_when_the_drawing_changes() {
|
||||
let mut s = session();
|
||||
s.open_drawing(cadcraft_io::read(&nested_dictionary_file(), "n.dxf").unwrap(), "n.dxf", None);
|
||||
ok(&mut s, "(setq inner (cdr (assoc -1 (dictsearch (cdr (assoc -1 (dictsearch (namedobjdict) \"MY_DICT\"))) \"INNER\"))))");
|
||||
ok(&mut s, "(setq leaf (cdr (assoc -1 (dictsearch inner \"LEAF\"))))");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget leaf)))"), "\"hello\"");
|
||||
// Unchanged drawing: the same name.
|
||||
assert_eq!(ok(&mut s, "(eq leaf (cdr (assoc -1 (dictsearch inner \"LEAF\"))))"), "T");
|
||||
s.execute("layer.new", &serde_json::json!({"name": "Walls"})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(entget leaf)"), "nil");
|
||||
// Looked up again, it is there (under a new name); the entry with a role kept its name.
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 1 (dictsearch inner \"LEAF\")))"), "\"hello\"");
|
||||
}
|
||||
|
||||
// ---------------- entities of block definitions (#1700) ----------------
|
||||
|
||||
/// A drawing with one linear dimension measuring 100 whose `*D1` block, as stored in the file,
|
||||
/// says 99.5 (a stale block: the defpoints moved, the block wasn't rebuilt).
|
||||
fn stale_dimension() -> Session {
|
||||
let mut s = session();
|
||||
s.execute("dimlinear", &serde_json::json!({"p1": [0, 0], "p2": [100, 0], "at": [50, -20], "rotation": 0})).unwrap();
|
||||
let dxf = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
// The *D1 block's MTEXT says 100 (100.0000 here); make the file say 99.5.
|
||||
let lines: Vec<&str> = dxf.lines().collect();
|
||||
let (mut kind, mut block, mut out, mut changed) = (String::new(), String::new(), Vec::new(), 0);
|
||||
for (i, l) in lines.iter().enumerate() {
|
||||
let code = if i % 2 == 0 { l.trim() } else { "" };
|
||||
let value = lines.get(i + 1).map(|v| v.trim()).unwrap_or("");
|
||||
if code == "0" {
|
||||
kind = value.to_string();
|
||||
}
|
||||
if code == "2" && kind == "BLOCK" {
|
||||
block = value.to_string();
|
||||
}
|
||||
if i % 2 == 1 && kind == "MTEXT" && block == "*D1" && lines.get(i - 1).map(|c| c.trim()) == Some("1") && l.trim().starts_with("100") {
|
||||
out.push("99.5".to_string());
|
||||
changed += 1;
|
||||
continue;
|
||||
}
|
||||
out.push(l.to_string());
|
||||
}
|
||||
assert_eq!(changed, 1, "the fixture found the *D1 text");
|
||||
let mut s = session();
|
||||
s.open_drawing(cadcraft_io::read_dxf(out.join("\n").as_bytes()).unwrap(), "stale", None);
|
||||
s
|
||||
}
|
||||
|
||||
/// The issue's use: a routine reads the text a dimension's block stores and compares it with the
|
||||
/// measurement, so it finds the stale block.
|
||||
#[test]
|
||||
fn a_routine_reads_the_text_a_dimension_block_stores() {
|
||||
let mut s = stale_dimension();
|
||||
let code = r#"(progn
|
||||
(defun dtext (dim / e txt)
|
||||
(setq e (cdr (assoc -2 (tblsearch "BLOCK" (cdr (assoc 2 (entget dim)))))))
|
||||
(while e
|
||||
(if (= (cdr (assoc 0 (entget e))) "MTEXT") (setq txt (cdr (assoc 1 (entget e)))))
|
||||
(setq e (entnext e)))
|
||||
txt)
|
||||
(setq dim (entlast))
|
||||
(list (dtext dim) (cdr (assoc 42 (entget dim)))))"#;
|
||||
assert_eq!(ok(&mut s, code), "(\"99.5\" 100.0)");
|
||||
}
|
||||
|
||||
/// tblsearch names a block's first entity (-2); entnext walks the definition in order and ends
|
||||
/// with nil; entget lists each one (without a layout); handent finds them by handle.
|
||||
#[test]
|
||||
fn entnext_and_entget_walk_a_block_definition() {
|
||||
let mut s = session();
|
||||
let l = s.execute("line", &serde_json::json!({"points": [[0, 0], [10, 0]]})).unwrap()["handles"][0].as_str().unwrap().to_string();
|
||||
let c = s.execute("circle", &serde_json::json!({"center": [5, 5], "radius": 2})).unwrap()["handle"].as_str().unwrap().to_string();
|
||||
s.execute("block", &serde_json::json!({"name": "B", "base": [0, 0], "handles": [l, c], "keep": "delete"})).unwrap();
|
||||
s.execute("line", &serde_json::json!({"points": [[50, 0], [60, 0]]})).unwrap();
|
||||
let walk = r#"(progn (setq e (cdr (assoc -2 (tblsearch "BLOCK" "B"))) types nil)
|
||||
(while e (setq types (cons (cdr (assoc 0 (entget e))) types) e (entnext e)))
|
||||
(reverse types))"#;
|
||||
assert_eq!(ok(&mut s, walk), "(\"LINE\" \"CIRCLE\")", "the block's own entities, not the drawing's");
|
||||
let first = "(cdr (assoc -2 (tblsearch \"BLOCK\" \"B\")))";
|
||||
assert_eq!(ok(&mut s, &format!("(assoc 410 (entget {first}))")), "nil", "no layout");
|
||||
assert_eq!(ok(&mut s, &format!("(equal (handent (cdr (assoc 5 (entget {first})))) {first})")), "T");
|
||||
// The drawing's own entities walk as before.
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entnext))))"), "\"LINE\"");
|
||||
assert_eq!(ok(&mut s, "(entnext (entlast))"), "nil");
|
||||
// Editing a block's entity through entmod or entdel isn't offered: nil, nothing changes.
|
||||
assert_eq!(ok(&mut s, &format!("(entdel {first})")), "nil");
|
||||
assert_eq!(ok(&mut s, &format!("(entmod (entget {first}))")), "nil");
|
||||
assert_eq!(s.doc().unwrap().block("B").unwrap().entities.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_block_has_no_first_entity() {
|
||||
let mut s = session();
|
||||
s.doc_mut().unwrap().blocks.insert("EMPTY".into(), std::sync::Arc::new(cadcraft_doc::Block::new("EMPTY")));
|
||||
assert_eq!(ok(&mut s, "(assoc -2 (tblsearch \"BLOCK\" \"EMPTY\"))"), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angtof_reads_the_string_in_the_given_units() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -102,10 +102,6 @@ pub struct Prompt {
|
||||
/// the routine writes, so it cannot be read for the word "Select" (#1598).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub picks_one: bool,
|
||||
/// The prompt takes a block's name as well as its keywords: a Greek word that is an existing
|
||||
/// block's name is that block, not a keyword read from its Latin keys.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub takes_block: bool,
|
||||
}
|
||||
|
||||
/// Parse `@distance<angle` (relative polar), returning `(distance, angle in radians)`.
|
||||
@@ -140,11 +136,6 @@ impl Prompt {
|
||||
self.picker = Some(p);
|
||||
self
|
||||
}
|
||||
/// Takes a block's name besides its keywords (the `takes_block` field).
|
||||
pub fn takes_block(mut self) -> Self {
|
||||
self.takes_block = true;
|
||||
self
|
||||
}
|
||||
pub fn kw(mut self, k: &[&str]) -> Self {
|
||||
self.keywords = k.iter().map(ToString::to_string).collect();
|
||||
self
|
||||
@@ -224,24 +215,6 @@ impl Prompt {
|
||||
return None;
|
||||
}
|
||||
let tl = t.to_ascii_lowercase();
|
||||
// A keyword typed with the Greek keyboard layout active (ΘΝΔΟ for Undo) is its Latin keys, unless
|
||||
// the prompt offers that spelling itself (a Greek keyword in a LISP program's list): its word
|
||||
// or a prefix of it as typed (ΘΝ for ΘΝΔΟ, not UN for Undo) is read before the Latin keys.
|
||||
if let Some(latin) = crate::keyboard::latin_keys(t) {
|
||||
// Greek letters have case, accents and a final sigma, which the ASCII-only folding above does not see.
|
||||
let typed = crate::keyboard::greek_fold(t).unwrap_or_else(|| latin.clone());
|
||||
let greek = || self.keywords.iter().filter_map(|k| crate::keyboard::greek_fold(k).map(|fold| (k, fold)));
|
||||
return greek()
|
||||
.find(|(_, k)| *k == typed)
|
||||
.or_else(|| greek().find(|(_, k)| k.starts_with(&typed)))
|
||||
.map(|(k, _)| k.clone())
|
||||
.or_else(|| self.match_latin_keyword(&latin));
|
||||
}
|
||||
self.match_latin_keyword(&tl)
|
||||
}
|
||||
|
||||
/// [`Prompt::match_keyword`] for text already read as Latin letters, in lower case.
|
||||
fn match_latin_keyword(&self, tl: &str) -> Option<String> {
|
||||
let keys = self.keywords.iter().map(|k| {
|
||||
let shortcut: String = k.chars().filter(|c| c.is_ascii_uppercase() || c.is_ascii_digit()).collect::<String>().to_ascii_lowercase();
|
||||
let shortcut =
|
||||
@@ -254,8 +227,8 @@ impl Prompt {
|
||||
// CHPROP: "Ambiguous response, please clarify..."), `LTS` is ltScale.
|
||||
let past_capitals = |k: &str| k.char_indices().rfind(|(_, c)| c.is_ascii_uppercase() || c.is_ascii_digit()).map_or(1, |(i, _)| i + 1);
|
||||
keys.clone()
|
||||
.find(|(_, kl, sc)| tl == kl.as_str() || tl == sc.as_str())
|
||||
.or_else(|| keys.clone().find(|(k, kl, _)| tl.len() >= past_capitals(k) && kl.starts_with(tl)))
|
||||
.find(|(_, kl, sc)| tl == *kl || tl == *sc)
|
||||
.or_else(|| keys.clone().find(|(k, kl, _)| tl.len() >= past_capitals(k) && kl.starts_with(&tl)))
|
||||
.map(|(k, _, _)| k.clone())
|
||||
}
|
||||
}
|
||||
@@ -421,29 +394,6 @@ mod tests {
|
||||
assert_eq!(parse_point("1,2,3,4", last), None);
|
||||
}
|
||||
|
||||
/// A keyword the prompt offers in Greek is matched as spelled (any case, accent or final sigma,
|
||||
/// or a prefix) before the Latin reading of the same keys; without one, the keys answer the
|
||||
/// Latin keyword.
|
||||
#[test]
|
||||
fn a_greek_keyword_is_matched_as_spelled_before_its_latin_reading() {
|
||||
// ΘΝΔΟ is the keys U-N-D-O, so it answers Undo, unless the prompt offers the Greek word itself
|
||||
// (a LISP program's keyword list).
|
||||
let both = Prompt::new("", Accept::TEXT).kw(&["Undo", "ΘΝΔΟ"]);
|
||||
assert_eq!(both.match_keyword("ΘΝΔΟ").as_deref(), Some("ΘΝΔΟ"));
|
||||
assert_eq!(both.match_keyword("θνδο").as_deref(), Some("ΘΝΔΟ"), "Greek case is folded like Latin case");
|
||||
assert_eq!(both.match_keyword("Undo").as_deref(), Some("Undo"));
|
||||
// A prefix of the Greek word as typed (ΘΝ) is that keyword, not the Latin prefix UN of Undo.
|
||||
assert_eq!(both.match_keyword("ΘΝ").as_deref(), Some("ΘΝΔΟ"));
|
||||
assert_eq!(both.match_keyword("θν").as_deref(), Some("ΘΝΔΟ"), "in either case");
|
||||
assert_eq!(both.match_keyword("θνδό").as_deref(), Some("ΘΝΔΟ"), "with an accent");
|
||||
let sigma = Prompt::new("", Accept::TEXT).kw(&["Last", "ΛΑΣΤ"]);
|
||||
assert_eq!(sigma.match_keyword("λας").as_deref(), Some("ΛΑΣΤ"), "a final sigma folds too");
|
||||
let latin = Prompt::new("", Accept::TEXT).kw(&["Undo"]);
|
||||
assert_eq!(latin.match_keyword("ΘΝ").as_deref(), Some("Undo"));
|
||||
assert_eq!(latin.match_keyword("ΘΝΔΟ").as_deref(), Some("Undo"));
|
||||
assert_eq!(latin.match_keyword("Θ").as_deref(), Some("Undo"), "a Greek-layout shortcut still works");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keywords() {
|
||||
let p = Prompt::new("Specify next point", Accept::POINT).kw(&["Undo", "Close"]);
|
||||
|
||||
@@ -1,806 +0,0 @@
|
||||
//! What the Properties palette shows for a selection: groups of rows, each with the
|
||||
//! `properties.set` key that changes it, the value the objects share (or *VARIES*), how the
|
||||
//! value reads in the drawing's units, and whether it can be edited. `properties.describe`
|
||||
//! returns the same description, so the palette, Quick Properties and agents read one list.
|
||||
//!
|
||||
//! Text, MText and Dimension have their own groups; other objects have the General group only
|
||||
//! (the palette draws their rows itself). Dimension rows are the dimension style variables,
|
||||
//! valued as the dimension draws them (its style with its overrides); setting one stores a
|
||||
//! per-dimension override, as AutoCAD's Properties palette does (DIMOVERRIDE).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use cadcraft_doc::{DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, Handle, Lineweight, MText, Text, Transparency, VAlign};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::units;
|
||||
|
||||
/// What a row shows when the described objects don't share a value.
|
||||
pub const VARIES: &str = "*VARIES*";
|
||||
|
||||
/// MTEXT line pitch per unit of text height at line spacing factor 1 (the layout's 5/3 in
|
||||
/// `cadcraft_fonts`): Line space distance = factor × text height × `LINE_PITCH`.
|
||||
pub const LINE_PITCH: f64 = 5.0 / 3.0;
|
||||
|
||||
/// Above this many dimensions, their measurement and text position aren't worked out (each
|
||||
/// needs the dimension's geometry); the rows show *VARIES*.
|
||||
const GEOMETRY_CAP: usize = 256;
|
||||
|
||||
/// The Properties of a selection.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct Description {
|
||||
/// The object types selected and how many of each, in the order first selected.
|
||||
pub types: Vec<TypeCount>,
|
||||
/// The type the description is limited to; `None`: every selected object.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub filter: Option<&'static str>,
|
||||
/// How many objects the rows describe.
|
||||
pub count: usize,
|
||||
pub groups: Vec<Group>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct TypeCount {
|
||||
#[serde(rename = "type")]
|
||||
pub name: &'static str,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct Group {
|
||||
pub name: &'static str,
|
||||
pub rows: Vec<Row>,
|
||||
}
|
||||
|
||||
/// One property of the described objects.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Row {
|
||||
/// The `properties.set` key that changes it.
|
||||
pub key: &'static str,
|
||||
pub label: &'static str,
|
||||
pub kind: Kind,
|
||||
/// The value every described object has; `null` when they differ.
|
||||
pub value: Value,
|
||||
pub varies: bool,
|
||||
/// The value as shown: lengths in the drawing's units (LUNITS/LUPREC), angles in its angle
|
||||
/// units (AUNITS/AUPREC), choices by their label; *VARIES* when the objects differ.
|
||||
pub display: String,
|
||||
pub editable: bool,
|
||||
/// Why the row can't be edited, or what decides its value.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub note: Option<String>,
|
||||
/// Dimension rows: a described dimension overrides its style here.
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub overridden: bool,
|
||||
/// The values a choice or style row can take.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub options: Vec<Choice>,
|
||||
/// One of the rows Quick Properties shows.
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub quick: bool,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
impl Row {
|
||||
fn quick(mut self) -> Self {
|
||||
self.quick = true;
|
||||
self
|
||||
}
|
||||
fn read_only(mut self) -> Self {
|
||||
self.editable = false;
|
||||
self
|
||||
}
|
||||
fn overridden_if(mut self, overridden: bool) -> Self {
|
||||
self.overridden = overridden;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct Choice {
|
||||
pub value: Value,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
impl Choice {
|
||||
fn new(value: Value, label: impl Into<String>) -> Self {
|
||||
Choice { value, label: label.into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// How a row's value is entered and shown.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Kind {
|
||||
/// One line of text.
|
||||
Text,
|
||||
/// MTEXT contents, inline formatting codes included.
|
||||
Contents,
|
||||
/// A plain number (factors, scales).
|
||||
Number,
|
||||
/// A length in drawing units.
|
||||
Distance,
|
||||
/// An angle in degrees.
|
||||
Angle,
|
||||
/// A direction (a text's rotation): `value` is in degrees counterclockwise from +X, as
|
||||
/// `properties.set` takes it; `display` shows it as the drawing measures directions, from
|
||||
/// ANGBASE in the ANGDIR sense (#1275).
|
||||
Direction,
|
||||
Bool,
|
||||
/// One of `options`.
|
||||
Choice,
|
||||
Color,
|
||||
Layer,
|
||||
Linetype,
|
||||
Lineweight,
|
||||
Transparency,
|
||||
TextStyle,
|
||||
DimStyle,
|
||||
}
|
||||
|
||||
/// A transparency as `properties.set` takes it: "ByLayer", "ByBlock" or a percentage.
|
||||
pub fn transparency_value(t: Transparency) -> Value {
|
||||
match t {
|
||||
Transparency::Percent(p) => json!(p),
|
||||
other => json!(other.name()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Properties of the objects `handles` (model space and layouts), limited to the objects
|
||||
/// of type `filter` (a name from [`Description::types`]) when it names one. Handles that don't
|
||||
/// name an object are left out.
|
||||
pub fn describe(d: &Drawing, handles: &[Handle], filter: Option<&str>) -> Description {
|
||||
let mut seen = HashSet::new();
|
||||
let all: Vec<&Entity> = handles.iter().filter(|h| seen.insert(**h)).filter_map(|h| d.entity(*h).map(|e| &**e)).collect();
|
||||
let mut types: Vec<TypeCount> = Vec::new();
|
||||
for e in &all {
|
||||
let name = e.kind.type_name();
|
||||
match types.iter_mut().find(|t| t.name == name) {
|
||||
Some(t) => t.count += 1,
|
||||
None => types.push(TypeCount { name, count: 1 }),
|
||||
}
|
||||
}
|
||||
let filter = filter.and_then(|f| types.iter().find(|t| t.name.eq_ignore_ascii_case(f.trim())).map(|t| t.name));
|
||||
let ents: Vec<&Entity> = all.into_iter().filter(|e| filter.is_none_or(|f| e.kind.type_name() == f)).collect();
|
||||
let c = Ctx::new(d);
|
||||
let mut groups = Vec::new();
|
||||
if !ents.is_empty() {
|
||||
groups.push(general(&c, &ents));
|
||||
let texts: Vec<&Text> = ents.iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t) } else { None }).collect();
|
||||
let mtexts: Vec<&MText> = ents.iter().filter_map(|e| if let EntityKind::MText(t) = &e.kind { Some(t) } else { None }).collect();
|
||||
let dims: Vec<&Dimension> = ents.iter().filter_map(|e| if let EntityKind::Dimension(t) = &e.kind { Some(t) } else { None }).collect();
|
||||
// Type groups only when every described object is of that type (AutoCAD shows the
|
||||
// common properties of a mixed selection).
|
||||
if texts.len() == ents.len() {
|
||||
groups.extend(text_groups(&c, &ents, &texts));
|
||||
} else if mtexts.len() == ents.len() {
|
||||
groups.extend(mtext_groups(&c, &ents, &mtexts));
|
||||
} else if dims.len() == ents.len() {
|
||||
groups.extend(dimension_groups(&c, &ents, &dims));
|
||||
}
|
||||
}
|
||||
Description { types, filter, count: ents.len(), groups }
|
||||
}
|
||||
|
||||
/// Unit settings and the drawing, for formatting rows.
|
||||
struct Ctx<'a> {
|
||||
d: &'a Drawing,
|
||||
lunits: i64,
|
||||
luprec: i64,
|
||||
aunits: i64,
|
||||
auprec: i64,
|
||||
angles: units::AngleSettings,
|
||||
}
|
||||
|
||||
impl<'a> Ctx<'a> {
|
||||
fn new(d: &'a Drawing) -> Self {
|
||||
let h = &d.header;
|
||||
Ctx {
|
||||
d,
|
||||
lunits: h.i64("LUNITS", 2),
|
||||
luprec: h.i64("LUPREC", 4),
|
||||
aunits: h.i64("AUNITS", 0),
|
||||
auprec: h.i64("AUPREC", 0),
|
||||
angles: units::AngleSettings::from_header(h),
|
||||
}
|
||||
}
|
||||
|
||||
fn distance(&self, v: f64) -> String {
|
||||
units::format_distance(v, self.lunits, self.luprec)
|
||||
}
|
||||
|
||||
/// `deg` in the drawing's angle units.
|
||||
fn angle(&self, deg: f64) -> String {
|
||||
units::format_angle(deg.to_radians(), self.aunits, self.auprec)
|
||||
}
|
||||
|
||||
fn show(&self, kind: Kind, v: &Value, options: &[Choice]) -> String {
|
||||
match kind {
|
||||
Kind::Distance => v.as_f64().map(|x| self.distance(x)).unwrap_or_default(),
|
||||
Kind::Number => v.as_f64().map(|x| format!("{x:.4}")).unwrap_or_default(),
|
||||
Kind::Angle => v.as_f64().map(|x| self.angle(x)).unwrap_or_default(),
|
||||
Kind::Direction => v.as_f64().map(|x| self.angle(self.angles.shown(x.to_radians()).to_degrees())).unwrap_or_default(),
|
||||
Kind::Bool => (if v.as_bool() == Some(true) { "Yes" } else { "No" }).to_string(),
|
||||
Kind::Choice => options.iter().find(|o| o.value == *v).map(|o| o.label.clone()).unwrap_or_else(|| plain(v)),
|
||||
_ => plain(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// A row valued by `values` (one per described object).
|
||||
fn row(&self, key: &'static str, label: &'static str, kind: Kind, values: impl IntoIterator<Item = Value>) -> Row {
|
||||
self.choice(key, label, kind, Vec::new(), values)
|
||||
}
|
||||
|
||||
/// A row with options (a choice, or a style picked from the drawing's styles).
|
||||
fn choice(&self, key: &'static str, label: &'static str, kind: Kind, options: Vec<Choice>, values: impl IntoIterator<Item = Value>) -> Row {
|
||||
let mut it = values.into_iter();
|
||||
let first = it.next().unwrap_or(Value::Null);
|
||||
let varies = it.any(|v| !same(&v, &first));
|
||||
let (value, display) = if varies { (Value::Null, VARIES.to_string()) } else { (first.clone(), self.show(kind, &first, &options)) };
|
||||
Row { key, label, kind, value, varies, display, editable: true, note: None, overridden: false, options, quick: false }
|
||||
}
|
||||
|
||||
fn text_styles(&self) -> Vec<Choice> {
|
||||
self.d.text_styles.iter().map(|t| Choice::new(json!(t.name), t.name.clone())).collect()
|
||||
}
|
||||
|
||||
fn dim_styles(&self) -> Vec<Choice> {
|
||||
self.d.dim_styles.iter().map(|t| Choice::new(json!(t.name), t.name.clone())).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A value as plain text: strings as they are, numbers and booleans as JSON writes them.
|
||||
fn plain(v: &Value) -> String {
|
||||
match v {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Null => String::new(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn general(c: &Ctx, ents: &[&Entity]) -> Group {
|
||||
let rows = vec![
|
||||
c.row("color", "Color", Kind::Color, ents.iter().map(|e| json!(e.common.color.name()))),
|
||||
c.row("layer", "Layer", Kind::Layer, ents.iter().map(|e| json!(e.common.layer))).quick(),
|
||||
c.row("linetype", "Linetype", Kind::Linetype, ents.iter().map(|e| json!(e.common.linetype))),
|
||||
c.row("ltscale", "Linetype scale", Kind::Number, ents.iter().map(|e| json!(e.common.ltscale))),
|
||||
c.row("lineweight", "Lineweight", Kind::Lineweight, ents.iter().map(|e| json!(e.common.lineweight.name()))),
|
||||
c.row("transparency", "Transparency", Kind::Transparency, ents.iter().map(|e| transparency_value(e.common.transparency))),
|
||||
];
|
||||
Group { name: "General", rows }
|
||||
}
|
||||
|
||||
fn annotative(c: &Ctx, ents: &[&Entity]) -> Row {
|
||||
c.row("annotative", "Annotative", Kind::Bool, ents.iter().map(|e| json!(cadcraft_doc::is_annotative(e)))).quick()
|
||||
}
|
||||
|
||||
/// TEXT justifications as `properties.set` takes them, with their labels.
|
||||
pub const TEXT_JUSTIFY: &[(&str, &str)] = &[
|
||||
("Left", "Left"),
|
||||
("Center", "Center"),
|
||||
("Right", "Right"),
|
||||
("Align", "Align"),
|
||||
("Middle", "Middle"),
|
||||
("Fit", "Fit"),
|
||||
("TL", "Top left"),
|
||||
("TC", "Top center"),
|
||||
("TR", "Top right"),
|
||||
("ML", "Middle left"),
|
||||
("MC", "Middle center"),
|
||||
("MR", "Middle right"),
|
||||
("BL", "Bottom left"),
|
||||
("BC", "Bottom center"),
|
||||
("BR", "Bottom right"),
|
||||
];
|
||||
|
||||
/// MTEXT attachments 1–9 as `properties.set` takes them, with their labels.
|
||||
pub const MTEXT_JUSTIFY: &[(&str, &str)] = &[
|
||||
("TL", "Top left"),
|
||||
("TC", "Top center"),
|
||||
("TR", "Top right"),
|
||||
("ML", "Middle left"),
|
||||
("MC", "Middle center"),
|
||||
("MR", "Middle right"),
|
||||
("BL", "Bottom left"),
|
||||
("BC", "Bottom center"),
|
||||
("BR", "Bottom right"),
|
||||
];
|
||||
|
||||
fn options(list: &[(&str, &str)]) -> Vec<Choice> {
|
||||
list.iter().map(|(v, l)| Choice::new(json!(v), *l)).collect()
|
||||
}
|
||||
|
||||
/// The justification code of a TEXT (one of [`TEXT_JUSTIFY`]).
|
||||
pub fn text_justify(t: &Text) -> &'static str {
|
||||
match (t.halign, t.valign) {
|
||||
(HAlign::Aligned, _) => "Align",
|
||||
(HAlign::Fit, _) => "Fit",
|
||||
(HAlign::Middle, _) => "Middle",
|
||||
(HAlign::Left, VAlign::Baseline) => "Left",
|
||||
(HAlign::Center, VAlign::Baseline) => "Center",
|
||||
(HAlign::Right, VAlign::Baseline) => "Right",
|
||||
(HAlign::Left, VAlign::Top) => "TL",
|
||||
(HAlign::Center, VAlign::Top) => "TC",
|
||||
(HAlign::Right, VAlign::Top) => "TR",
|
||||
(HAlign::Left, VAlign::Middle) => "ML",
|
||||
(HAlign::Center, VAlign::Middle) => "MC",
|
||||
(HAlign::Right, VAlign::Middle) => "MR",
|
||||
(HAlign::Left, VAlign::Bottom) => "BL",
|
||||
(HAlign::Center, VAlign::Bottom) => "BC",
|
||||
(HAlign::Right, VAlign::Bottom) => "BR",
|
||||
}
|
||||
}
|
||||
|
||||
/// The justification code of an MTEXT attachment (1–9; anything else reads as top left).
|
||||
pub fn mtext_justify(attach: u8) -> &'static str {
|
||||
MTEXT_JUSTIFY.get(usize::from(attach.max(1)) - 1).map_or("TL", |(code, _)| *code)
|
||||
}
|
||||
|
||||
fn text_groups(c: &Ctx, ents: &[&Entity], texts: &[&Text]) -> Vec<Group> {
|
||||
let mut text = vec![
|
||||
c.row("text", "Contents", Kind::Text, texts.iter().map(|t| json!(t.value))).quick(),
|
||||
c.choice("style", "Style", Kind::TextStyle, c.text_styles(), texts.iter().map(|t| json!(t.style))).quick(),
|
||||
annotative(c, ents),
|
||||
c.choice("justify", "Justification", Kind::Choice, options(TEXT_JUSTIFY), texts.iter().map(|t| json!(text_justify(t)))).quick(),
|
||||
c.row("height", "Height", Kind::Distance, texts.iter().map(|t| json!(t.height))).quick(),
|
||||
c.row("rotation", "Rotation", Kind::Direction, texts.iter().map(|t| json!(t.rotation.to_degrees()))).quick(),
|
||||
c.row("widthFactor", "Width factor", Kind::Number, texts.iter().map(|t| json!(t.width_factor))),
|
||||
c.row("oblique", "Obliquing", Kind::Angle, texts.iter().map(|t| json!(t.oblique.to_degrees()))),
|
||||
];
|
||||
// Aligned and fit text sit between two points: the second is the text alignment point.
|
||||
let second: Option<Vec<cadcraft_geom::Vec3>> =
|
||||
texts.iter().map(|t| if matches!(t.halign, HAlign::Aligned | HAlign::Fit) { t.align_pt } else { None }).collect();
|
||||
if let Some(pts) = second {
|
||||
text.push(c.row("alignmentX", "Text alignment X", Kind::Distance, pts.iter().map(|p| json!(p.x))));
|
||||
text.push(c.row("alignmentY", "Text alignment Y", Kind::Distance, pts.iter().map(|p| json!(p.y))));
|
||||
}
|
||||
// The position is the point the text is placed by (see `Text::justify_point`).
|
||||
let geometry = vec![
|
||||
c.row("positionX", "Position X", Kind::Distance, texts.iter().map(|t| json!(t.justify_point().x))),
|
||||
c.row("positionY", "Position Y", Kind::Distance, texts.iter().map(|t| json!(t.justify_point().y))),
|
||||
c.row("positionZ", "Position Z", Kind::Distance, texts.iter().map(|t| json!(t.insert.z))),
|
||||
];
|
||||
vec![Group { name: "Text", rows: text }, Group { name: "Geometry", rows: geometry }]
|
||||
}
|
||||
|
||||
fn mtext_groups(c: &Ctx, ents: &[&Entity], mts: &[&MText]) -> Vec<Group> {
|
||||
let spacing = vec![Choice::new(json!("atLeast"), "At least"), Choice::new(json!("exactly"), "Exactly")];
|
||||
let columns = |t: &MText| match &t.columns {
|
||||
None => "None".to_string(),
|
||||
Some(col) => match col.kind {
|
||||
cadcraft_doc::MTextColumnType::Static => format!("Static ({})", col.count.max(1)),
|
||||
cadcraft_doc::MTextColumnType::Dynamic => "Dynamic".to_string(),
|
||||
},
|
||||
};
|
||||
let text = vec![
|
||||
c.row("text", "Contents", Kind::Contents, mts.iter().map(|t| json!(t.contents))).quick(),
|
||||
c.choice("style", "Style", Kind::TextStyle, c.text_styles(), mts.iter().map(|t| json!(t.style))).quick(),
|
||||
annotative(c, ents),
|
||||
c.choice("justify", "Justification", Kind::Choice, options(MTEXT_JUSTIFY), mts.iter().map(|t| json!(mtext_justify(t.attach)))).quick(),
|
||||
c.row("height", "Text height", Kind::Distance, mts.iter().map(|t| json!(t.height))).quick(),
|
||||
c.row("rotation", "Rotation", Kind::Direction, mts.iter().map(|t| json!(t.rotation.to_degrees()))).quick(),
|
||||
c.row("lineSpacing", "Line space factor", Kind::Number, mts.iter().map(|t| json!(t.line_spacing))),
|
||||
c.row("lineSpacingDistance", "Line space distance", Kind::Distance, mts.iter().map(|t| json!(t.line_spacing * t.height * LINE_PITCH))),
|
||||
c.choice(
|
||||
"lineSpacingStyle",
|
||||
"Line space style",
|
||||
Kind::Choice,
|
||||
spacing,
|
||||
mts.iter().map(|t| json!(if t.line_spacing_exact { "exactly" } else { "atLeast" })),
|
||||
),
|
||||
c.row("width", "Defined width", Kind::Distance, mts.iter().map(|t| json!(t.width))),
|
||||
c.row("columns", "Columns", Kind::Text, mts.iter().map(|t| json!(columns(t)))).read_only(),
|
||||
];
|
||||
let geometry = vec![
|
||||
c.row("positionX", "Position X", Kind::Distance, mts.iter().map(|t| json!(t.insert.x))),
|
||||
c.row("positionY", "Position Y", Kind::Distance, mts.iter().map(|t| json!(t.insert.y))),
|
||||
c.row("positionZ", "Position Z", Kind::Distance, mts.iter().map(|t| json!(t.insert.z))),
|
||||
];
|
||||
vec![Group { name: "Text", rows: text }, Group { name: "Geometry", rows: geometry }]
|
||||
}
|
||||
|
||||
/// How a dimension style variable is entered.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DimPropKind {
|
||||
Distance,
|
||||
Number,
|
||||
/// Degrees.
|
||||
Angle,
|
||||
Bool,
|
||||
/// Numbers with labels.
|
||||
Choice(&'static [(i64, &'static str)]),
|
||||
/// Decimal places 0–8.
|
||||
Precision,
|
||||
Color,
|
||||
TextStyle,
|
||||
/// A linetype name; "" (and "ByBlock") is ByBlock.
|
||||
Linetype,
|
||||
/// Hundredths of a millimetre, or -1 ByLayer, -2 ByBlock, -3 Default.
|
||||
Lineweight,
|
||||
/// An arrowhead name ("" is closed filled).
|
||||
Arrow,
|
||||
/// The decimal separator.
|
||||
Separator,
|
||||
}
|
||||
|
||||
/// A dimension style variable as a Properties row.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct DimProp {
|
||||
/// The [`DimStyle`] field (camelCase), which is also the `properties.set` key.
|
||||
pub field: &'static str,
|
||||
pub group: &'static str,
|
||||
pub label: &'static str,
|
||||
pub kind: DimPropKind,
|
||||
/// Shown in the Properties palette (the rest belong to the style dialog only).
|
||||
pub palette: bool,
|
||||
}
|
||||
|
||||
const fn prop(field: &'static str, group: &'static str, label: &'static str, kind: DimPropKind) -> DimProp {
|
||||
DimProp { field, group, label, kind, palette: true }
|
||||
}
|
||||
|
||||
const fn style_only(field: &'static str, group: &'static str, label: &'static str, kind: DimPropKind) -> DimProp {
|
||||
DimProp { field, group, label, kind, palette: false }
|
||||
}
|
||||
|
||||
/// The groups dimension rows come in, in order (after Misc).
|
||||
pub const DIM_GROUPS: &[&str] = &["Lines & Arrows", "Text", "Fit", "Primary Units", "Alternate Units", "Tolerances"];
|
||||
|
||||
const TEXT_POS_HOR: &[(i64, &str)] = &[(0, "Centered"), (1, "At Ext Line 1"), (2, "At Ext Line 2"), (3, "Over Ext Line 1"), (4, "Over Ext Line 2")];
|
||||
const TEXT_POS_VERT: &[(i64, &str)] = &[(0, "Centered"), (1, "Above"), (2, "Outside"), (3, "JIS"), (4, "Below")];
|
||||
const FIT: &[(i64, &str)] = &[(0, "Text and arrows"), (1, "Arrows"), (2, "Text"), (3, "Best fit")];
|
||||
const TEXT_MOVE: &[(i64, &str)] = &[(0, "Keep dim line with text"), (1, "Move text, add leader"), (2, "Move text, no leader")];
|
||||
const LINEAR_UNITS: &[(i64, &str)] =
|
||||
&[(1, "Scientific"), (2, "Decimal"), (3, "Engineering"), (4, "Architectural"), (5, "Fractional"), (6, "Windows desktop")];
|
||||
const ALT_UNITS: &[(i64, &str)] = &[
|
||||
(1, "Scientific"),
|
||||
(2, "Decimal"),
|
||||
(3, "Engineering"),
|
||||
(4, "Architectural stacked"),
|
||||
(5, "Fractional stacked"),
|
||||
(6, "Architectural"),
|
||||
(7, "Fractional"),
|
||||
(8, "Windows desktop"),
|
||||
];
|
||||
const ANGLE_FORMAT: &[(i64, &str)] = &[(0, "Decimal degrees"), (1, "Degrees Minutes Seconds"), (2, "Gradians"), (3, "Radians")];
|
||||
const FRACTION_FORMAT: &[(i64, &str)] = &[(0, "Horizontal stacking"), (1, "Diagonal stacking"), (2, "Not stacked")];
|
||||
const TOL_POS: &[(i64, &str)] = &[(0, "Bottom"), (1, "Middle"), (2, "Top")];
|
||||
const ARC_SYMBOL: &[(i64, &str)] = &[(0, "Before text"), (1, "Above text"), (2, "None")];
|
||||
|
||||
/// Every modeled dimension style variable as a row, grouped as AutoCAD's Properties palette
|
||||
/// groups dimension properties. The rows not shown in the palette are style settings only.
|
||||
pub const DIM_PROPS: &[DimProp] = &[
|
||||
// Lines & Arrows
|
||||
prop("arrowBlock1", "Lines & Arrows", "Arrow 1", DimPropKind::Arrow),
|
||||
prop("arrowBlock2", "Lines & Arrows", "Arrow 2", DimPropKind::Arrow),
|
||||
style_only("arrowBlock", "Lines & Arrows", "Arrowheads", DimPropKind::Arrow),
|
||||
prop("arrowSize", "Lines & Arrows", "Arrow size", DimPropKind::Distance),
|
||||
prop("tickSize", "Lines & Arrows", "Tick size", DimPropKind::Distance),
|
||||
prop("dimLineColor", "Lines & Arrows", "Dim line color", DimPropKind::Color),
|
||||
prop("dimLinetype", "Lines & Arrows", "Dim line linetype", DimPropKind::Linetype),
|
||||
prop("dimLineweight", "Lines & Arrows", "Dim line lineweight", DimPropKind::Lineweight),
|
||||
prop("dimLineExtend", "Lines & Arrows", "Dim line ext", DimPropKind::Distance),
|
||||
prop("suppressDim1", "Lines & Arrows", "Hide dim line 1", DimPropKind::Bool),
|
||||
prop("suppressDim2", "Lines & Arrows", "Hide dim line 2", DimPropKind::Bool),
|
||||
prop("extLineColor", "Lines & Arrows", "Ext line color", DimPropKind::Color),
|
||||
prop("extLinetype1", "Lines & Arrows", "Ext line 1 linetype", DimPropKind::Linetype),
|
||||
prop("extLinetype2", "Lines & Arrows", "Ext line 2 linetype", DimPropKind::Linetype),
|
||||
prop("extLineweight", "Lines & Arrows", "Ext line lineweight", DimPropKind::Lineweight),
|
||||
prop("extExtend", "Lines & Arrows", "Ext line ext", DimPropKind::Distance),
|
||||
prop("extOffset", "Lines & Arrows", "Ext line offset", DimPropKind::Distance),
|
||||
prop("fixedExt", "Lines & Arrows", "Ext line fixed", DimPropKind::Bool),
|
||||
prop("fixedExtLength", "Lines & Arrows", "Ext line length", DimPropKind::Distance),
|
||||
prop("suppressExt1", "Lines & Arrows", "Hide ext line 1", DimPropKind::Bool),
|
||||
prop("suppressExt2", "Lines & Arrows", "Hide ext line 2", DimPropKind::Bool),
|
||||
prop("centerMark", "Lines & Arrows", "Center mark size", DimPropKind::Distance),
|
||||
prop("jogAngle", "Lines & Arrows", "Jog angle", DimPropKind::Angle),
|
||||
prop("arcSymbol", "Lines & Arrows", "Arc length symbol", DimPropKind::Choice(ARC_SYMBOL)),
|
||||
style_only("leaderArrowBlock", "Lines & Arrows", "Leader arrow", DimPropKind::Arrow),
|
||||
style_only("baselineSpacing", "Lines & Arrows", "Baseline spacing", DimPropKind::Distance),
|
||||
// Text
|
||||
prop("textColor", "Text", "Text color", DimPropKind::Color),
|
||||
prop("textHeight", "Text", "Text height", DimPropKind::Distance),
|
||||
prop("textGap", "Text", "Text offset", DimPropKind::Distance),
|
||||
prop("textOutsideHorizontal", "Text", "Text outside align", DimPropKind::Bool),
|
||||
prop("textJust", "Text", "Text pos hor", DimPropKind::Choice(TEXT_POS_HOR)),
|
||||
prop("textAbove", "Text", "Text pos vert", DimPropKind::Choice(TEXT_POS_VERT)),
|
||||
prop("textStyle", "Text", "Text style", DimPropKind::TextStyle),
|
||||
prop("textInsideHorizontal", "Text", "Text inside align", DimPropKind::Bool),
|
||||
style_only("textVerticalPos", "Text", "Text vertical position", DimPropKind::Number),
|
||||
// Fit
|
||||
prop("forceLineInside", "Fit", "Dim line forced", DimPropKind::Bool),
|
||||
prop("suppressOutsideArrows", "Fit", "Suppress arrows", DimPropKind::Bool),
|
||||
prop("scale", "Fit", "Dim scale overall", DimPropKind::Number),
|
||||
prop("fit", "Fit", "Fit", DimPropKind::Choice(FIT)),
|
||||
prop("textInside", "Fit", "Text inside", DimPropKind::Bool),
|
||||
prop("textMove", "Fit", "Text movement", DimPropKind::Choice(TEXT_MOVE)),
|
||||
// Primary Units
|
||||
prop("decimalSeparator", "Primary Units", "Decimal separator", DimPropKind::Separator),
|
||||
prop("round", "Primary Units", "Dim roundoff", DimPropKind::Distance),
|
||||
prop("linearFactor", "Primary Units", "Dim scale linear", DimPropKind::Number),
|
||||
prop("linearUnit", "Primary Units", "Dim units", DimPropKind::Choice(LINEAR_UNITS)),
|
||||
prop("decimals", "Primary Units", "Precision", DimPropKind::Precision),
|
||||
prop("fractionFormat", "Primary Units", "Fraction format", DimPropKind::Choice(FRACTION_FORMAT)),
|
||||
prop("angularUnit", "Primary Units", "Angle format", DimPropKind::Choice(ANGLE_FORMAT)),
|
||||
prop("angularDecimals", "Primary Units", "Angle precision", DimPropKind::Precision),
|
||||
style_only("post", "Primary Units", "Prefix and suffix", DimPropKind::Number),
|
||||
style_only("zeroSuppression", "Primary Units", "Zero suppression", DimPropKind::Number),
|
||||
style_only("angularZeroSuppression", "Primary Units", "Angular zero suppression", DimPropKind::Number),
|
||||
// Alternate Units
|
||||
prop("alt", "Alternate Units", "Alt enabled", DimPropKind::Bool),
|
||||
prop("altUnit", "Alternate Units", "Alt format", DimPropKind::Choice(ALT_UNITS)),
|
||||
prop("altDecimals", "Alternate Units", "Alt precision", DimPropKind::Precision),
|
||||
prop("altFactor", "Alternate Units", "Alt scale factor", DimPropKind::Number),
|
||||
prop("altRound", "Alternate Units", "Alt round", DimPropKind::Number),
|
||||
style_only("altPost", "Alternate Units", "Alt prefix and suffix", DimPropKind::Number),
|
||||
style_only("altZeroSuppression", "Alternate Units", "Alt zero suppression", DimPropKind::Number),
|
||||
// Tolerances
|
||||
prop("tolerance", "Tolerances", "Tolerances", DimPropKind::Bool),
|
||||
prop("limits", "Tolerances", "Limits", DimPropKind::Bool),
|
||||
prop("tolPlus", "Tolerances", "Upper tolerance", DimPropKind::Number),
|
||||
prop("tolMinus", "Tolerances", "Lower tolerance", DimPropKind::Number),
|
||||
prop("tolDecimals", "Tolerances", "Tolerance precision", DimPropKind::Precision),
|
||||
prop("tolScale", "Tolerances", "Tolerance height", DimPropKind::Number),
|
||||
prop("tolJust", "Tolerances", "Tolerance pos vert", DimPropKind::Choice(TOL_POS)),
|
||||
style_only("tolZeroSuppression", "Tolerances", "Tolerance zero suppression", DimPropKind::Number),
|
||||
];
|
||||
|
||||
/// The arrowheads drawn in code, by the DIMBLK name stored for them and their label.
|
||||
pub const ARROWHEADS: &[(&str, &str)] = &[
|
||||
("", "Closed filled"),
|
||||
("_CLOSEDBLANK", "Closed blank"),
|
||||
("_CLOSED", "Closed"),
|
||||
("_DOT", "Dot"),
|
||||
("_ARCHTICK", "Architectural tick"),
|
||||
("_OBLIQUE", "Oblique"),
|
||||
("_OPEN", "Open arrow"),
|
||||
("_ORIGIN", "Origin indicator"),
|
||||
("_ORIGIN2", "Origin indicator 2"),
|
||||
("_OPEN90", "Right angle"),
|
||||
("_OPEN30", "Open 30"),
|
||||
("_DOTSMALL", "Dot small"),
|
||||
("_DOTBLANK", "Dot blank"),
|
||||
("_SMALL", "Small"),
|
||||
("_BOXBLANK", "Box blank"),
|
||||
("_BOXFILLED", "Box filled"),
|
||||
("_DATUMBLANK", "Datum triangle"),
|
||||
("_DATUMFILLED", "Datum triangle filled"),
|
||||
("_INTEGRAL", "Integral"),
|
||||
("_NONE", "None"),
|
||||
];
|
||||
|
||||
/// The row for dimension style field `field`, if it has one.
|
||||
pub fn dim_prop(field: &str) -> Option<&'static DimProp> {
|
||||
DIM_PROPS.iter().find(|p| p.field.eq_ignore_ascii_case(field))
|
||||
}
|
||||
|
||||
/// The dimension style fields whose value is a linetype name ("" is ByBlock).
|
||||
pub fn is_dim_linetype(field: &str) -> bool {
|
||||
matches!(field, "dimLinetype" | "extLinetype1" | "extLinetype2")
|
||||
}
|
||||
|
||||
impl DimPropKind {
|
||||
/// The values a choice kind can take, with their labels (none for the other kinds; text
|
||||
/// styles are the drawing's).
|
||||
pub fn options(self) -> Vec<Choice> {
|
||||
match self {
|
||||
DimPropKind::Choice(list) => list.iter().map(|(v, l)| Choice::new(json!(v), *l)).collect(),
|
||||
DimPropKind::Precision => {
|
||||
(0..=8u8).map(|n| Choice::new(json!(n), if n == 0 { "0".into() } else { format!("0.{}", "0".repeat(usize::from(n))) })).collect()
|
||||
}
|
||||
DimPropKind::Lineweight => {
|
||||
let mut o = vec![Choice::new(json!(-2), "ByBlock"), Choice::new(json!(-1), "ByLayer"), Choice::new(json!(-3), "Default")];
|
||||
o.extend(Lineweight::STANDARD.iter().map(|w| Choice::new(json!(w), Lineweight::Mm100(*w).name())));
|
||||
o
|
||||
}
|
||||
DimPropKind::Arrow => ARROWHEADS.iter().map(|(v, l)| Choice::new(json!(v), *l)).collect(),
|
||||
DimPropKind::Separator => [(".", "Period"), (",", "Comma"), (" ", "Space")].iter().map(|(v, l)| Choice::new(json!(v), *l)).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn row_kind(self, c: &Ctx) -> (Kind, Vec<Choice>) {
|
||||
match self {
|
||||
DimPropKind::Distance => (Kind::Distance, Vec::new()),
|
||||
DimPropKind::Number => (Kind::Number, Vec::new()),
|
||||
DimPropKind::Angle => (Kind::Angle, Vec::new()),
|
||||
DimPropKind::Bool => (Kind::Bool, Vec::new()),
|
||||
DimPropKind::Color => (Kind::Color, Vec::new()),
|
||||
DimPropKind::TextStyle => (Kind::TextStyle, c.text_styles()),
|
||||
DimPropKind::Linetype => (Kind::Linetype, Vec::new()),
|
||||
DimPropKind::Choice(_) | DimPropKind::Precision | DimPropKind::Lineweight | DimPropKind::Arrow | DimPropKind::Separator => {
|
||||
(Kind::Choice, self.options())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` normalized as the renderer reads arrowhead names ("_DOT", "dot" and "Dot" alike).
|
||||
fn arrow_key(name: &str) -> String {
|
||||
name.trim().trim_start_matches('_').chars().filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase()
|
||||
}
|
||||
|
||||
/// A dimension style field's value as the row shows and `properties.set` takes it: a color's
|
||||
/// name, ByBlock for an empty linetype, and the arrowhead an empty per-end arrowhead draws.
|
||||
pub fn dim_value(p: &DimProp, st: &Value) -> Value {
|
||||
let v = st.get(p.field).cloned().unwrap_or(Value::Null);
|
||||
match p.kind {
|
||||
DimPropKind::Color => serde_json::from_value::<cadcraft_color::Color>(v).map(|c| json!(c.name())).unwrap_or(Value::Null),
|
||||
DimPropKind::Linetype => match v.as_str() {
|
||||
Some("") | None => json!("ByBlock"),
|
||||
Some(_) => v,
|
||||
},
|
||||
DimPropKind::Arrow => {
|
||||
// Per-end arrowheads left empty use DIMBLK (an empty leader arrowhead is closed filled).
|
||||
let name = v.as_str().filter(|s| !s.is_empty() || !matches!(p.field, "arrowBlock1" | "arrowBlock2")).map(str::to_string);
|
||||
let name = name.unwrap_or_else(|| st.get("arrowBlock").and_then(Value::as_str).unwrap_or_default().to_string());
|
||||
// A drawn arrowhead reads as its standard name; a block of the user's stays as it is.
|
||||
match ARROWHEADS.iter().find(|(n, _)| arrow_key(n) == arrow_key(&name) || (n.is_empty() && arrow_key(&name) == "closedfilled")) {
|
||||
Some((n, _)) => json!(n),
|
||||
None => json!(name),
|
||||
}
|
||||
}
|
||||
_ => v,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether dimension `dm` overrides style field `field`.
|
||||
fn overrides(dm: &Dimension, field: &str) -> bool {
|
||||
dm.overrides.keys().any(|k| DimStyle::field_name(k) == Some(field))
|
||||
}
|
||||
|
||||
/// The prefix and suffix of a DIMPOST/DIMAPOST template: around `<>`, or the whole template
|
||||
/// as a suffix when it has no `<>` (as the renderer reads it).
|
||||
pub fn split_post(template: &str) -> (String, String) {
|
||||
match template.split_once("<>") {
|
||||
Some((pre, post)) => (pre.to_string(), post.to_string()),
|
||||
None => (String::new(), template.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A DIMPOST/DIMAPOST template from a prefix and a suffix.
|
||||
pub fn join_post(prefix: &str, suffix: &str) -> String {
|
||||
if prefix.is_empty() { suffix.to_string() } else { format!("{prefix}<>{suffix}") }
|
||||
}
|
||||
|
||||
/// The measurement as the dimension writes it (its own units and precision).
|
||||
fn measurement_text(dm: &Dimension, st: &DimStyle, meas: f64) -> String {
|
||||
match dm.kind {
|
||||
// As the renderer writes angles: DIMAUNIT, DIMADEC, and DIMAZIN's leading and trailing zeros.
|
||||
DimKind::Angular | DimKind::Angular3P => {
|
||||
cadcraft_render::units::format_angle(meas, st.angular_unit, st.angular_decimals, (st.angular_zero_suppression & 3) * 4)
|
||||
}
|
||||
_ => cadcraft_render::format_linear_value(meas, st),
|
||||
}
|
||||
}
|
||||
|
||||
fn dimension_groups(c: &Ctx, ents: &[&Entity], dims: &[&Dimension]) -> Vec<Group> {
|
||||
let styles: Vec<DimStyle> = dims.iter().map(|dm| c.d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides)).collect();
|
||||
let values: Vec<Value> = styles.iter().map(|st| serde_json::to_value(st).unwrap_or(Value::Null)).collect();
|
||||
// Measurement and text position need each dimension's geometry.
|
||||
let geometry: Option<Vec<cadcraft_render::DimGeometry>> =
|
||||
(dims.len() <= GEOMETRY_CAP).then(|| dims.iter().map(|dm| cadcraft_render::dimension_in(c.d, dm)).collect());
|
||||
let mut groups = vec![Group {
|
||||
name: "Misc",
|
||||
rows: vec![
|
||||
c.choice("dimStyle", "Dim style", Kind::DimStyle, c.dim_styles(), dims.iter().map(|dm| json!(dm.style))).quick(),
|
||||
annotative(c, ents),
|
||||
],
|
||||
}];
|
||||
for &name in DIM_GROUPS {
|
||||
let mut rows: Vec<Row> = Vec::new();
|
||||
for p in DIM_PROPS.iter().filter(|p| p.group == name && p.palette) {
|
||||
let (kind, options) = p.kind.row_kind(c);
|
||||
let mut r = c.choice(p.field, p.label, kind, options, values.iter().map(|v| dim_value(p, v)));
|
||||
r.overridden = dims.iter().any(|dm| overrides(dm, p.field));
|
||||
if p.field == "textHeight" {
|
||||
fixed_height(c, &mut r, &styles);
|
||||
}
|
||||
rows.push(r);
|
||||
}
|
||||
match name {
|
||||
"Text" => {
|
||||
let (xs, ys): (Vec<Value>, Vec<Value>) = match &geometry {
|
||||
Some(g) => g.iter().map(|g| (json!(g.text_pos.x), json!(g.text_pos.y))).unzip(),
|
||||
None => (vec![Value::Null, json!(VARIES)], vec![Value::Null, json!(VARIES)]),
|
||||
};
|
||||
rows.push(c.row("textPositionX", "Text position X", Kind::Distance, xs));
|
||||
rows.push(c.row("textPositionY", "Text position Y", Kind::Distance, ys));
|
||||
rows.push(c.row("textRotation", "Text rotation", Kind::Angle, dims.iter().map(|dm| json!(dm.text_rotation.to_degrees()))));
|
||||
let measured: Vec<(Value, String)> = match &geometry {
|
||||
Some(g) => g
|
||||
.iter()
|
||||
.zip(dims)
|
||||
.zip(&styles)
|
||||
.map(|((g, dm), st)| {
|
||||
let angular = matches!(dm.kind, DimKind::Angular | DimKind::Angular3P);
|
||||
(json!(if angular { g.measurement.to_degrees() } else { g.measurement }), measurement_text(dm, st, g.measurement))
|
||||
})
|
||||
.collect(),
|
||||
None => vec![(Value::Null, String::new()), (json!(VARIES), String::new())],
|
||||
};
|
||||
// A length, or an angle in degrees, shown as the dimension writes it.
|
||||
let mut m = c.row("measurement", "Measurement", Kind::Number, measured.iter().map(|(v, _)| v.clone())).read_only().quick();
|
||||
let shown = measured.first().map(|(_, s)| s.clone()).unwrap_or_default();
|
||||
// Equal measurements written differently (units, precision) vary too.
|
||||
if measured.iter().any(|(_, s)| *s != shown) {
|
||||
(m.value, m.varies, m.display) = (Value::Null, true, VARIES.to_string());
|
||||
} else if !m.varies {
|
||||
m.display = shown;
|
||||
}
|
||||
rows.push(m);
|
||||
rows.push(c.row("textOverride", "Text override", Kind::Text, dims.iter().map(|dm| json!(dm.text))).quick());
|
||||
}
|
||||
"Primary Units" => {
|
||||
let (pre, suf): (Vec<Value>, Vec<Value>) = styles.iter().map(|st| split_post(&st.post)).map(|(p, s)| (json!(p), json!(s))).unzip();
|
||||
let at = rows.iter().position(|r| r.key == "round").unwrap_or(rows.len());
|
||||
// Prefix and suffix are DIMPOST's two halves: overridden with it, and reset with it.
|
||||
let posted = dims.iter().any(|dm| overrides(dm, "post"));
|
||||
rows.insert(at, c.row("prefix", "Dim prefix", Kind::Text, pre).overridden_if(posted));
|
||||
let at = rows.iter().position(|r| r.key == "linearUnit").unwrap_or(rows.len());
|
||||
rows.insert(at, c.row("suffix", "Dim suffix", Kind::Text, suf).overridden_if(posted));
|
||||
}
|
||||
"Alternate Units" => {
|
||||
let (pre, suf): (Vec<Value>, Vec<Value>) =
|
||||
styles.iter().map(|st| split_post(&st.alt_post)).map(|(p, s)| (json!(p), json!(s))).unzip();
|
||||
let posted = dims.iter().any(|dm| overrides(dm, "altPost"));
|
||||
rows.push(c.row("altPrefix", "Alt prefix", Kind::Text, pre).overridden_if(posted));
|
||||
rows.push(c.row("altSuffix", "Alt suffix", Kind::Text, suf).overridden_if(posted));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
groups.push(Group { name, rows });
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// Equal values, numbers to 12 significant digits, as the palette compares them: float noise
|
||||
/// (7 and 7.0000000000001, or 1.2e-16 next to zero) is no difference, while values the display
|
||||
/// rounds alike (7 and 7.000001) still differ.
|
||||
fn same(a: &Value, b: &Value) -> bool {
|
||||
fn tag(v: f64) -> String {
|
||||
let v = if v.abs() < 1e-12 { 0.0 } else { v };
|
||||
format!("{:.11e}", v + 0.0)
|
||||
}
|
||||
match (a, b) {
|
||||
(Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
|
||||
(Some(x), Some(y)) => tag(x) == tag(y),
|
||||
_ => x == y,
|
||||
},
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
/// A fixed-height text style decides the dimension text height whatever DIMTXT says (as in
|
||||
/// AutoCAD); the row says so instead of taking edits that change nothing.
|
||||
fn fixed_height(c: &Ctx, r: &mut Row, styles: &[DimStyle]) {
|
||||
let fixed: Vec<Option<(&str, f64)>> = styles
|
||||
.iter()
|
||||
.map(|st| c.d.text_style(&st.text_style).filter(|ts| ts.height > 0.0 && ts.height.is_finite()).map(|ts| (ts.name.as_str(), ts.height)))
|
||||
.collect();
|
||||
let Some(&Some((name, h))) = fixed.iter().find(|f| f.is_some()) else { return };
|
||||
if fixed.iter().all(|f| *f == Some((name, h))) {
|
||||
r.value = json!(h);
|
||||
r.varies = false;
|
||||
r.display = c.distance(h);
|
||||
r.editable = false;
|
||||
r.note =
|
||||
Some(format!("Set by text style \"{name}\", which has a fixed height. Give the style a height of 0 to use the dimension text height."));
|
||||
} else {
|
||||
// Each dimension's text is its style's fixed height or its own DIMTXT.
|
||||
let heights: Vec<f64> = fixed.iter().zip(styles).map(|(f, st)| f.map_or(st.text_height, |(_, h)| h)).collect();
|
||||
let first = heights.first().copied().unwrap_or_default();
|
||||
if heights.iter().all(|h| *h == first) {
|
||||
(r.value, r.varies, r.display) = (json!(first), false, c.distance(first));
|
||||
} else {
|
||||
(r.value, r.varies, r.display) = (Value::Null, true, VARIES.to_string());
|
||||
}
|
||||
r.editable = fixed.iter().any(Option::is_none);
|
||||
r.note = Some("Some of these dimensions take their text height from a fixed-height text style.".into());
|
||||
}
|
||||
}
|
||||
+18
-98
@@ -152,28 +152,8 @@ fn in_box(pts: impl Iterator<Item = Vec2>, angle: f64, p: Vec2) -> bool {
|
||||
!b.is_empty() && b.contains(turn(p))
|
||||
}
|
||||
|
||||
/// Whether `e` is on one of the layers in `frozen`: the layers frozen in a layout viewport, which
|
||||
/// does not draw their objects. The names are compared as the renderer compares them.
|
||||
pub(crate) fn on_frozen_layer(frozen: &[String], e: &Entity) -> bool {
|
||||
frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer))
|
||||
}
|
||||
|
||||
/// The last object of `store`, in draw order, that is not on one of the layers in `frozen`, the
|
||||
/// layers frozen in the layout viewport the selection is made through: what the Last option
|
||||
/// takes there. With no such layers it is the last object, whether the drawing shows it or not.
|
||||
pub(crate) fn last_in(store: &cadcraft_doc::EntityStore, frozen: &[String]) -> Option<Handle> {
|
||||
if frozen.is_empty() {
|
||||
return store.last().map(|e| e.handle);
|
||||
}
|
||||
store.iter().filter(|e| !on_frozen_layer(frozen, e)).last().map(|e| e.handle)
|
||||
}
|
||||
|
||||
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]) and it is not
|
||||
/// on one of the layers in `frozen`, the layers frozen in the layout viewport the selection is
|
||||
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else). A viewport shows
|
||||
/// model space, so `frozen` goes with a selection in model space only.
|
||||
pub(crate) fn selectable(d: &Drawing, e: &Entity, frozen: &[String]) -> bool {
|
||||
d.is_visible(e) && !on_frozen_layer(frozen, e)
|
||||
fn selectable(d: &Drawing, e: &Entity) -> bool {
|
||||
d.is_visible(e)
|
||||
}
|
||||
|
||||
/// Entities to test, in the order to test them, each with its bounds when already known.
|
||||
@@ -216,28 +196,15 @@ pub(crate) fn candidates<'a>(
|
||||
/// the nearest, as AutoCAD 2024 picks (two objects under the pickbox: the one drawn later is
|
||||
/// picked, and DRAWORDER changes which).
|
||||
pub fn pick(d: &Drawing, space: &Space, p: Vec2, aperture: f64) -> Option<Handle> {
|
||||
pick_in(d, space, &[], p, aperture)
|
||||
}
|
||||
|
||||
/// [`pick`] through a layout viewport: the objects on the layers in `frozen`, the layers frozen
|
||||
/// in that viewport, are not drawn there and are not picked.
|
||||
pub fn pick_in(d: &Drawing, space: &Space, frozen: &[String], p: Vec2, aperture: f64) -> Option<Handle> {
|
||||
let ix = spatial::index(d, space);
|
||||
pick_with(d, space, &ix, frozen, p, aperture)
|
||||
pick_with(d, space, &ix, p, aperture)
|
||||
}
|
||||
|
||||
pub(crate) fn pick_with(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<SpatialIndex>>,
|
||||
frozen: &[String],
|
||||
p: Vec2,
|
||||
aperture: f64,
|
||||
) -> Option<Handle> {
|
||||
pub(crate) fn pick_with(d: &Drawing, space: &Space, ix: &Option<std::sync::Arc<SpatialIndex>>, p: Vec2, aperture: f64) -> Option<Handle> {
|
||||
let probe = Bounds2::new(p, p).expand(aperture);
|
||||
// Candidates come topmost first: the first within the aperture is the one.
|
||||
for (e, known) in candidates(d, space, ix, &probe.expand(aperture), true, true)? {
|
||||
if !selectable(d, e, frozen) {
|
||||
if !selectable(d, e) {
|
||||
continue;
|
||||
}
|
||||
let infinite = is_infinite(e);
|
||||
@@ -254,16 +221,11 @@ pub(crate) fn pick_with(
|
||||
/// Every entity within `aperture` of `p`, topmost first (so the first is what [`pick`] chooses):
|
||||
/// the objects selection cycling lists.
|
||||
pub fn pick_all(d: &Drawing, space: &Space, p: Vec2, aperture: f64) -> Vec<Handle> {
|
||||
pick_all_in(d, space, &[], p, aperture)
|
||||
}
|
||||
|
||||
/// [`pick_all`] through a layout viewport that freezes the layers in `frozen` ([`pick_in`]).
|
||||
pub fn pick_all_in(d: &Drawing, space: &Space, frozen: &[String], p: Vec2, aperture: f64) -> Vec<Handle> {
|
||||
let ix = spatial::index(d, space);
|
||||
let probe = Bounds2::new(p, p).expand(aperture);
|
||||
let Some(cands) = candidates(d, space, &ix, &probe.expand(aperture), true, true) else { return Vec::new() };
|
||||
cands
|
||||
.filter(|(e, known)| selectable(d, e, frozen) && (is_infinite(e) || bounds_of(d, e, *known).expand(aperture).intersects(&probe)))
|
||||
.filter(|(e, known)| selectable(d, e) && (is_infinite(e) || bounds_of(d, e, *known).expand(aperture).intersects(&probe)))
|
||||
.filter(|(e, _)| entity_distance(d, e, p, aperture / 4.0) <= aperture)
|
||||
.map(|(e, _)| e.handle)
|
||||
.collect()
|
||||
@@ -291,27 +253,14 @@ fn seg_hits_box(a: Vec2, b: Vec2, bx: &Bounds2) -> bool {
|
||||
|
||||
/// Window selection (entirely inside) or crossing selection (inside or touching).
|
||||
pub fn select_window(d: &Drawing, space: &Space, bx: Bounds2, crossing: bool) -> Vec<Handle> {
|
||||
select_window_in(d, space, &[], bx, crossing)
|
||||
}
|
||||
|
||||
/// [`select_window`] through a layout viewport: the objects on the layers in `frozen`, the layers
|
||||
/// frozen in that viewport, are not drawn there and are not selected.
|
||||
pub fn select_window_in(d: &Drawing, space: &Space, frozen: &[String], bx: Bounds2, crossing: bool) -> Vec<Handle> {
|
||||
let ix = spatial::index(d, space);
|
||||
select_window_with(d, space, &ix, frozen, bx, crossing)
|
||||
select_window_with(d, space, &ix, bx, crossing)
|
||||
}
|
||||
|
||||
pub(crate) fn select_window_with(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<SpatialIndex>>,
|
||||
frozen: &[String],
|
||||
bx: Bounds2,
|
||||
crossing: bool,
|
||||
) -> Vec<Handle> {
|
||||
pub(crate) fn select_window_with(d: &Drawing, space: &Space, ix: &Option<std::sync::Arc<SpatialIndex>>, bx: Bounds2, crossing: bool) -> Vec<Handle> {
|
||||
let Some(cands) = candidates(d, space, ix, &bx, crossing, false) else { return Vec::new() };
|
||||
let tol = window_tol(&bx);
|
||||
cands.filter(|(e, known)| selectable(d, e, frozen) && in_window(d, e, *known, &bx, crossing, tol)).map(|(e, _)| e.handle).collect()
|
||||
cands.filter(|(e, known)| selectable(d, e) && in_window(d, e, *known, &bx, crossing, tol)).map(|(e, _)| e.handle).collect()
|
||||
}
|
||||
|
||||
/// The tessellation tolerance window and crossing tests use for a box.
|
||||
@@ -357,23 +306,11 @@ pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option<Bounds2>, bx: &Bo
|
||||
|
||||
/// Fence selection: entities crossed by the fence polyline.
|
||||
pub fn select_fence(d: &Drawing, space: &Space, fence: &[Vec2]) -> Vec<Handle> {
|
||||
select_fence_in(d, space, &[], fence)
|
||||
}
|
||||
|
||||
/// [`select_fence`] through a layout viewport that freezes the layers in `frozen`
|
||||
/// ([`select_window_in`]).
|
||||
pub fn select_fence_in(d: &Drawing, space: &Space, frozen: &[String], fence: &[Vec2]) -> Vec<Handle> {
|
||||
let ix = spatial::index(d, space);
|
||||
select_fence_with(d, space, &ix, frozen, fence)
|
||||
select_fence_with(d, space, &ix, fence)
|
||||
}
|
||||
|
||||
pub(crate) fn select_fence_with(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<SpatialIndex>>,
|
||||
frozen: &[String],
|
||||
fence: &[Vec2],
|
||||
) -> Vec<Handle> {
|
||||
pub(crate) fn select_fence_with(d: &Drawing, space: &Space, ix: &Option<std::sync::Arc<SpatialIndex>>, fence: &[Vec2]) -> Vec<Handle> {
|
||||
let fb = Bounds2::from_points(fence.iter().copied());
|
||||
let tol = (fb.width() + fb.height()).max(1e-9) / 2000.0;
|
||||
let probe = fb.expand(tol);
|
||||
@@ -381,7 +318,7 @@ pub(crate) fn select_fence_with(
|
||||
let mut out = Vec::new();
|
||||
for (e, known) in cands {
|
||||
// Infinite objects have no useful bounds; like window selection, test their geometry directly.
|
||||
if !selectable(d, e, frozen) || (!is_infinite(e) && !bounds_of(d, e, known).intersects(&probe)) {
|
||||
if !selectable(d, e) || (!is_infinite(e) && !bounds_of(d, e, known).intersects(&probe)) {
|
||||
continue;
|
||||
}
|
||||
let polys = hit_polylines(d, e, tol);
|
||||
@@ -402,12 +339,6 @@ pub(crate) fn select_fence_with(
|
||||
/// Window polygon selection (entities entirely inside `poly`) or crossing polygon selection
|
||||
/// (inside or crossing its edges). The polygon closes back to its first point.
|
||||
pub fn select_polygon(d: &Drawing, space: &Space, poly: &[Vec2], crossing: bool) -> Vec<Handle> {
|
||||
select_polygon_in(d, space, &[], poly, crossing)
|
||||
}
|
||||
|
||||
/// [`select_polygon`] through a layout viewport that freezes the layers in `frozen`
|
||||
/// ([`select_window_in`]).
|
||||
pub fn select_polygon_in(d: &Drawing, space: &Space, frozen: &[String], poly: &[Vec2], crossing: bool) -> Vec<Handle> {
|
||||
let (Some(first), true) = (poly.first(), poly.len() >= 3) else { return Vec::new() };
|
||||
let ix = spatial::index(d, space);
|
||||
let pb = Bounds2::from_points(poly.iter().copied());
|
||||
@@ -418,7 +349,7 @@ pub fn select_polygon_in(d: &Drawing, space: &Space, frozen: &[String], poly: &[
|
||||
let mut out = Vec::new();
|
||||
for (e, known) in cands {
|
||||
let infinite = is_infinite(e);
|
||||
if !selectable(d, e, frozen) || (infinite && !crossing) {
|
||||
if !selectable(d, e) || (infinite && !crossing) {
|
||||
continue;
|
||||
}
|
||||
let eb = bounds_of(d, e, known);
|
||||
@@ -447,15 +378,9 @@ pub fn select_polygon_in(d: &Drawing, space: &Space, frozen: &[String], poly: &[
|
||||
/// The visible objects in `space` of the group called `name` (any case), or `None` when the
|
||||
/// drawing has no such group.
|
||||
pub fn select_group(d: &Drawing, space: &Space, name: &str) -> Option<Vec<Handle>> {
|
||||
select_group_in(d, space, &[], name)
|
||||
}
|
||||
|
||||
/// [`select_group`] through a layout viewport that freezes the layers in `frozen`: the group's
|
||||
/// objects on those layers are left out.
|
||||
pub fn select_group_in(d: &Drawing, space: &Space, frozen: &[String], name: &str) -> Option<Vec<Handle>> {
|
||||
let g = d.groups.iter().find(|g| g.name.eq_ignore_ascii_case(name.trim()))?;
|
||||
let store = d.space(space)?;
|
||||
Some(g.members.iter().copied().filter(|h| store.get(*h).is_some_and(|e| selectable(d, e, frozen))).collect())
|
||||
Some(g.members.iter().copied().filter(|h| store.get(*h).is_some_and(|e| d.is_visible(e))).collect())
|
||||
}
|
||||
|
||||
/// A selection mode typed at "Select objects", collecting its points before it selects.
|
||||
@@ -529,19 +454,14 @@ impl SelectMode {
|
||||
}
|
||||
/// The objects the mode selects, or `None` while it has too few points.
|
||||
pub fn select(&self, d: &Drawing, space: &Space) -> Option<Vec<Handle>> {
|
||||
self.select_in(d, space, &[])
|
||||
}
|
||||
/// [`SelectMode::select`] through a layout viewport: the objects on the layers in `frozen`,
|
||||
/// the layers frozen in that viewport, are not drawn there and are not selected.
|
||||
pub fn select_in(&self, d: &Drawing, space: &Space, frozen: &[String]) -> Option<Vec<Handle>> {
|
||||
match (self.kind, self.pts.as_slice()) {
|
||||
(SelectKind::Window | SelectKind::Crossing, [a, b, ..]) => {
|
||||
Some(select_window_in(d, space, frozen, Bounds2::new(*a, *b), self.kind == SelectKind::Crossing))
|
||||
Some(select_window(d, space, Bounds2::new(*a, *b), self.kind == SelectKind::Crossing))
|
||||
}
|
||||
(SelectKind::Box, [a, b, ..]) => Some(select_window_in(d, space, frozen, Bounds2::new(*a, *b), b.x < a.x)),
|
||||
(SelectKind::Fence, pts) if pts.len() >= 2 => Some(select_fence_in(d, space, frozen, pts)),
|
||||
(SelectKind::Box, [a, b, ..]) => Some(select_window(d, space, Bounds2::new(*a, *b), b.x < a.x)),
|
||||
(SelectKind::Fence, pts) if pts.len() >= 2 => Some(select_fence(d, space, pts)),
|
||||
(SelectKind::WPolygon | SelectKind::CPolygon, pts) if pts.len() >= 3 => {
|
||||
Some(select_polygon_in(d, space, frozen, pts, self.kind == SelectKind::CPolygon))
|
||||
Some(select_polygon(d, space, pts, self.kind == SelectKind::CPolygon))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
|
||||
@@ -116,26 +116,9 @@ impl Session {
|
||||
};
|
||||
}
|
||||
// At "Select objects" prompts the selection modes (Previous, Last, ALL) win over a command
|
||||
// keyword sharing the letter (HATCH's "picK internal point" against `P`). A word typed with
|
||||
// the Greek keyboard layout active is read by its keys there too: Λ is Last at COUNT's prompt,
|
||||
// not List.
|
||||
let selection_mode = prompt.accept.select && {
|
||||
let word = tt.strip_prefix('_').unwrap_or(tt);
|
||||
let keys = crate::keyboard::latin_keys(word).unwrap_or_else(|| word.to_ascii_lowercase());
|
||||
matches!(keys.as_str(), "all" | "l" | "last" | "p" | "previous")
|
||||
};
|
||||
// A Greek word that is an existing name at a prompt that takes one is that name, in any case:
|
||||
// ΣΟΛΙΔ is also the keys of Solid.
|
||||
let existing = if matches!(prompt.picker, Some(crate::Picker::HatchPattern(_))) {
|
||||
crate::keyboard::greek_fold(tt).and_then(|_| cmd::hatch::pattern_named(tt))
|
||||
} else if prompt.takes_block {
|
||||
self.greek_block_name(tt)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(name) = existing {
|
||||
return self.input(Input::Text(name));
|
||||
}
|
||||
// keyword sharing the letter (HATCH's "picK internal point" against `P`).
|
||||
let selection_mode = prompt.accept.select
|
||||
&& matches!(tt.strip_prefix('_').unwrap_or(tt).to_ascii_lowercase().as_str(), "all" | "l" | "last" | "p" | "previous");
|
||||
// A leading underscore asks for a keyword by its English name, whatever the interface
|
||||
// language (`_M`, `_Yes`): scripts and LISP routines write them that way. (Snap
|
||||
// overrides such as `_cen` were taken above.)
|
||||
|
||||
@@ -61,7 +61,6 @@ impl Session {
|
||||
Ok(r) => r,
|
||||
Err(_) => {
|
||||
self.docs.truncate(n);
|
||||
self.lisp_forget_closed();
|
||||
self.active = self.active.min(self.docs.len().saturating_sub(1));
|
||||
self.bump_doc_epoch();
|
||||
Err(EngineError::Internal("open".into(), "panic".into()))
|
||||
|
||||
@@ -8,39 +8,6 @@ use super::{
|
||||
impl Session {
|
||||
// ---------------- interactive commands ----------------
|
||||
|
||||
/// Whether `name`, as typed, is a command, an alias or a LISP command: the lookups
|
||||
/// [`Session::start`] dispatches by, so only ASCII is lower-cased and a Greek alias stays as stored.
|
||||
fn names_a_command(&self, name: &str) -> bool {
|
||||
let lower = name.trim_start_matches(['_', '.', '-']).to_ascii_lowercase();
|
||||
let dashed = name.trim_start_matches(['_', '.']);
|
||||
find_command(&cmd::resolve_alias(dashed)).is_some()
|
||||
|| find_command(&cmd::resolve_alias(&lower)).is_some()
|
||||
|| self.lisp_command(&lower).is_some()
|
||||
}
|
||||
|
||||
/// The alias or LISP command that is the Greek word `name` in another case or accent (λινε for
|
||||
/// c:ΛΙΝΕ): those lookups fold ASCII only.
|
||||
fn greek_command_name(&self, name: &str) -> Option<String> {
|
||||
let bare = name.trim_start_matches(['_', '.', '-']);
|
||||
let same = crate::keyboard::same_greek_word_as(bare)?;
|
||||
let lisp = || self.lisp_commands().into_iter().find(|c| same(c) && self.lisp_command(c).is_some());
|
||||
cmd::file::greek_alias(bare).or_else(lisp)
|
||||
}
|
||||
|
||||
/// Whether the Greek word `name` is a command of its own, which [`Session::start`] runs instead
|
||||
/// of the Latin name its keys type.
|
||||
pub fn greek_word_is_a_command(&self, name: &str) -> bool {
|
||||
self.names_a_command(name) || self.greek_command_name(name).is_some()
|
||||
}
|
||||
|
||||
/// The existing block that is the Greek word `word`: as spelled, else in another case or accent
|
||||
/// (μ for Μ).
|
||||
pub(super) fn greek_block_name(&self, word: &str) -> Option<String> {
|
||||
let same = crate::keyboard::same_greek_word_as(word)?;
|
||||
let blocks = &self.doc().ok()?.blocks;
|
||||
blocks.keys().find(|k| *k == word).or_else(|| blocks.keys().find(|k| same(k))).cloned()
|
||||
}
|
||||
|
||||
/// Start a command by name or alias as if typed at the command line.
|
||||
pub fn start(&mut self, name: &str) -> Result<()> {
|
||||
self.last_polar = None;
|
||||
@@ -50,12 +17,6 @@ impl Session {
|
||||
Some(n) => (true, n),
|
||||
None => (false, name),
|
||||
};
|
||||
// A name typed with the Greek keyboard layout active (ΛΙΝΕ for LINE) is the Latin name's keys,
|
||||
// unless it is a command, alias or LISP function of its own, in any case or accent.
|
||||
let typed = name;
|
||||
let latin =
|
||||
crate::keyboard::latin_keys(name).filter(|_| !self.names_a_command(name)).map(|latin| self.greek_command_name(name).unwrap_or(latin));
|
||||
let name = latin.as_deref().unwrap_or(name);
|
||||
let lower = name.trim_start_matches(['_', '.', '-']).to_ascii_lowercase();
|
||||
// A command-line form with an id of its own (-ATTEDIT) is not the command it prefixes.
|
||||
let dashed = cmd::resolve_alias(&name.trim_start_matches(['_', '.']).to_ascii_lowercase());
|
||||
@@ -63,7 +24,6 @@ impl Session {
|
||||
let Some(spec) = find_command(&id) else {
|
||||
// A command defined in LISP: (defun c:NAME …).
|
||||
if !transparent && let Some(f) = self.lisp_command(&lower) {
|
||||
self.commands_started = self.commands_started.wrapping_add(1);
|
||||
if self.running.is_some() {
|
||||
self.cancel();
|
||||
}
|
||||
@@ -77,7 +37,7 @@ impl Session {
|
||||
self.start(if transparent { "'setvar" } else { "setvar" })?;
|
||||
return self.input(Input::Text(var));
|
||||
}
|
||||
return Err(EngineError::UnknownCommand(typed.to_string()));
|
||||
return Err(EngineError::UnknownCommand(name.to_string()));
|
||||
};
|
||||
if transparent && spec.transparent && self.running.is_some() {
|
||||
// Transparent commands (zoom, pan…) run without cancelling the active one.
|
||||
@@ -97,11 +57,8 @@ impl Session {
|
||||
self.echo(format!("Command: {}", spec.id.to_ascii_uppercase()));
|
||||
return self.input(Input::Keyword("Undo".into()));
|
||||
}
|
||||
if !nested {
|
||||
self.commands_started = self.commands_started.wrapping_add(1);
|
||||
if self.running.is_some() {
|
||||
self.cancel();
|
||||
}
|
||||
if !nested && self.running.is_some() {
|
||||
self.cancel();
|
||||
}
|
||||
(spec.enabled)(self).map_err(|m| EngineError::Disabled(spec.id.into(), m))?;
|
||||
if let Some(why) = cmd::blocks::bedit::refused_in_editor(self, spec.id) {
|
||||
@@ -218,33 +175,17 @@ impl Session {
|
||||
Input::Text(t) => Input::Text(t.trim().strip_prefix('_').map(str::to_string).unwrap_or(t)),
|
||||
other => other,
|
||||
};
|
||||
// A selection word typed with the Greek keyboard layout active (ΑΛΛ for ALL) is looked up as its
|
||||
// Latin keys. Only the lookup is: text that is no selection word (a block name at BEDIT's prompt,
|
||||
// which also takes a selection) reaches the command as typed. The name of an existing block at
|
||||
// a prompt that takes a name reaches it as stored, in whatever case it was typed: a block
|
||||
// called Μ is that block there, not Multiple.
|
||||
let block = match &input {
|
||||
Input::Text(t) if prompt.accept.text => self.greek_block_name(t.trim()),
|
||||
_ => None,
|
||||
};
|
||||
let is_block = block.is_some();
|
||||
let input = block.map_or(input, Input::Text);
|
||||
let word = match &input {
|
||||
Input::Text(t) => Some(crate::keyboard::latin_keys(t.trim()).filter(|_| !is_block).unwrap_or_else(|| t.clone())),
|
||||
Input::Keyword(k) => Some(k.clone()),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(w) = &word
|
||||
&& let Some(m) = select::SelectMode::from_keyword(w)
|
||||
if let Input::Text(t) | Input::Keyword(t) = &input
|
||||
&& let Some(m) = select::SelectMode::from_keyword(t)
|
||||
{
|
||||
self.pending_window = None;
|
||||
self.select_mode = Some(m);
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(w) = &word
|
||||
&& !prompt.keywords.iter().any(|k| k.eq_ignore_ascii_case(w.trim()))
|
||||
if let Input::Text(t) | Input::Keyword(t) = &input
|
||||
&& !prompt.keywords.iter().any(|k| k.eq_ignore_ascii_case(t.trim()))
|
||||
{
|
||||
match w.trim().to_ascii_lowercase().as_str() {
|
||||
match t.trim().to_ascii_lowercase().as_str() {
|
||||
"si" | "single" => {
|
||||
self.select_single = true;
|
||||
return Ok(None);
|
||||
@@ -261,10 +202,10 @@ impl Session {
|
||||
let ap = self.pixel_size() * self.settings.pickbox.max(1.0) * 1.5;
|
||||
if let Some(pw) = self.pending_window.take() {
|
||||
let crossing = self.window_is_crossing(pw.corner, p);
|
||||
let hs = select::select_window_in(self.doc()?, &space, self.viewport_frozen(), Bounds2::new(pw.corner, p), crossing);
|
||||
let hs = select::select_window(self.doc()?, &space, Bounds2::new(pw.corner, p), crossing);
|
||||
return Ok(Some(Input::Pick(cmd::groups::expand(self, hs))));
|
||||
}
|
||||
match select::pick_in(self.doc()?, &space, self.viewport_frozen(), p, ap) {
|
||||
match select::pick(self.doc()?, &space, p, ap) {
|
||||
Some(h) => Ok(Some(Input::Pick(cmd::groups::expand(self, vec![h])))),
|
||||
None => {
|
||||
self.pending_window = Some(PendingWindow { corner: p, during_command: true });
|
||||
@@ -272,18 +213,14 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
Input::Text(_) | Input::Keyword(_) => {
|
||||
let tl = word.as_deref().unwrap_or_default().trim().to_ascii_lowercase();
|
||||
Input::Text(ref t) | Input::Keyword(ref t) => {
|
||||
let tl = t.trim().to_ascii_lowercase();
|
||||
let d = self.doc()?;
|
||||
let store = d.space(&space);
|
||||
let frozen = self.viewport_frozen();
|
||||
let picked = match tl.as_str() {
|
||||
"all" => store.map(|s| s.iter().filter(|e| select::selectable(d, e, frozen)).map(|e| e.handle).collect()),
|
||||
"l" | "last" => store.and_then(|s| select::last_in(s, frozen)).map(|h| vec![h]),
|
||||
"p" | "previous" => {
|
||||
let st = self.state()?;
|
||||
Some(st.drawn_in_viewport(&st.previous_selection))
|
||||
}
|
||||
"all" => store.map(|s| s.iter().filter(|e| d.is_visible(e)).map(|e| e.handle).collect()),
|
||||
"l" | "last" => store.and_then(|s| s.last()).map(|e| vec![e.handle]),
|
||||
"p" | "previous" => Some(self.state()?.previous_selection.clone()),
|
||||
_ => None,
|
||||
};
|
||||
match picked {
|
||||
@@ -304,9 +241,8 @@ impl Session {
|
||||
fn select_mode_input(&mut self, input: Input) -> Result<Option<Input>> {
|
||||
let Some(mut mode) = self.select_mode.take() else { return Ok(Some(input)) };
|
||||
if mode.kind == select::SelectKind::Group {
|
||||
let space = self.space();
|
||||
return match input {
|
||||
Input::Text(name) | Input::Keyword(name) => match select::select_group_in(self.doc()?, &space, self.viewport_frozen(), &name) {
|
||||
Input::Text(name) | Input::Keyword(name) => match select::select_group(self.doc()?, &self.space(), &name) {
|
||||
Some(hs) => Ok(Some(Input::Pick(hs))),
|
||||
None => {
|
||||
self.echo(format!("No group named \"{}\".", name.trim()));
|
||||
@@ -326,14 +262,14 @@ impl Session {
|
||||
match input {
|
||||
Input::Point(p) => {
|
||||
if mode.push(p) {
|
||||
return Ok(mode.select_in(self.doc()?, &self.space(), self.viewport_frozen()).map(Input::Pick));
|
||||
return Ok(mode.select(self.doc()?, &self.space()).map(Input::Pick));
|
||||
}
|
||||
}
|
||||
Input::Keyword(k) if k == "Undo" => {
|
||||
mode.pts.pop();
|
||||
}
|
||||
// Enter ends a fence or polygon; with too few points the mode is dropped.
|
||||
Input::Enter => return Ok(mode.select_in(self.doc()?, &self.space(), self.viewport_frozen()).map(Input::Pick)),
|
||||
Input::Enter => return Ok(mode.select(self.doc()?, &self.space()).map(Input::Pick)),
|
||||
Input::Cancel | Input::Pick(_) => return Ok(Some(input)),
|
||||
_ => self.echo("Invalid point."),
|
||||
}
|
||||
@@ -382,14 +318,7 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
Ok(Step::Done) => {
|
||||
let seed = run.before.handseed;
|
||||
self.finish(run, false);
|
||||
let added = self.doc().is_ok_and(|d| d.handseed != seed);
|
||||
// A transparent command ending inside another (`'ZOOM` in an INSERT) is not that
|
||||
// command ending: it shares its number.
|
||||
if self.suspended.is_none() {
|
||||
self.last_finished = Some((self.commands_started, added));
|
||||
}
|
||||
self.resume_suspended();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -32,9 +32,9 @@ impl Session {
|
||||
let pickadd = self.settings.pickadd;
|
||||
if let Some(pw) = self.pending_window.take() {
|
||||
let crossing = self.window_is_crossing(pw.corner, p);
|
||||
let hs = select::select_window_in(self.doc()?, &space, self.viewport_frozen(), Bounds2::new(pw.corner, p), crossing);
|
||||
let hs = select::select_window(self.doc()?, &space, Bounds2::new(pw.corner, p), crossing);
|
||||
let hs = cmd::groups::expand(self, hs);
|
||||
let mut sel = if pickadd || shift { self.stored_selection() } else { Vec::new() };
|
||||
let mut sel = if pickadd || shift { self.selection() } else { Vec::new() };
|
||||
if shift && pickadd {
|
||||
sel.retain(|h| !hs.contains(h));
|
||||
} else {
|
||||
@@ -44,7 +44,7 @@ impl Session {
|
||||
return Ok(());
|
||||
}
|
||||
let ap = self.pixel_size() * self.settings.pickbox.max(1.0) * 1.5;
|
||||
match select::pick_in(self.doc()?, &space, self.viewport_frozen(), p, ap) {
|
||||
match select::pick(self.doc()?, &space, p, ap) {
|
||||
Some(h) => self.idle_pick(h, shift),
|
||||
None => self.pending_window = Some(PendingWindow { corner: p, during_command: false }),
|
||||
}
|
||||
@@ -56,7 +56,7 @@ impl Session {
|
||||
let pickadd = self.settings.pickadd;
|
||||
// With group selection the object's selectable groups come (or go) with it.
|
||||
let hs = cmd::groups::expand(self, vec![h]);
|
||||
let mut sel = if pickadd || shift { self.stored_selection() } else { Vec::new() };
|
||||
let mut sel = if pickadd || shift { self.selection() } else { Vec::new() };
|
||||
let had = sel.contains(&h);
|
||||
if shift && (pickadd || had) {
|
||||
sel.retain(|x| !hs.contains(x));
|
||||
@@ -93,7 +93,7 @@ impl Session {
|
||||
return Vec::new();
|
||||
}
|
||||
let ap = self.pixel_size() * self.settings.pickbox.max(1.0) * 1.5;
|
||||
self.doc().map(|d| select::pick_all_in(d, &self.space(), self.viewport_frozen(), p, ap)).unwrap_or_default()
|
||||
self.doc().map(|d| select::pick_all(d, &self.space(), p, ap)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether selection cycling marks `p` with its badge (SELECTIONCYCLING 1 or 2): overlapping
|
||||
@@ -155,8 +155,7 @@ impl Session {
|
||||
|
||||
/// The object a prompt picking one object finds at `p` in `space`: the one named for that
|
||||
/// point ([`Session::input_object`]), which is none when it lies in another space, else the
|
||||
/// object under `p` within `aperture`. Inside an MSPACE viewport a pick in model space finds
|
||||
/// what that viewport draws: not the objects on the layers frozen in it.
|
||||
/// object under `p` within `aperture`.
|
||||
pub fn pick_object(&self, space: &Space, p: Vec2, aperture: f64) -> Result<Option<Handle>> {
|
||||
let d = self.doc()?;
|
||||
if let Some((h, q)) = self.pick_hint
|
||||
@@ -164,9 +163,7 @@ impl Session {
|
||||
{
|
||||
return Ok((d.space_of(h).as_ref() == Some(space)).then_some(h));
|
||||
}
|
||||
// The viewport shows model space only: its frozen layers hide nothing on the sheet.
|
||||
let frozen = if *space == Space::Model { self.viewport_frozen() } else { &[] };
|
||||
Ok(select::pick_in(d, space, frozen, p, aperture))
|
||||
Ok(select::pick(d, space, p, aperture))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -424,8 +424,8 @@ mod tests {
|
||||
for k in 0..400 {
|
||||
let p = Vec2::new(r.r(-5.0, 105.0), r.r(-5.0, 105.0));
|
||||
let ap = [0.05, 0.3, 1.5][k % 3];
|
||||
let a = select::pick_with(&d, &Space::Model, &ix, &[], p, ap);
|
||||
let b = select::pick_with(&d, &Space::Model, &None, &[], p, ap);
|
||||
let a = select::pick_with(&d, &Space::Model, &ix, p, ap);
|
||||
let b = select::pick_with(&d, &Space::Model, &None, p, ap);
|
||||
assert_eq!(a, b, "seed {seed} p {p:?} ap {ap}");
|
||||
hits += usize::from(a.is_some());
|
||||
}
|
||||
@@ -444,15 +444,12 @@ mod tests {
|
||||
let b = a + Vec2::new(r.r(-40.0, 40.0), r.r(-40.0, 40.0));
|
||||
let bx = Bounds2::new(a, b);
|
||||
for crossing in [false, true] {
|
||||
let x = select::select_window_with(&d, &Space::Model, &ix, &[], bx, crossing);
|
||||
let y = select::select_window_with(&d, &Space::Model, &None, &[], bx, crossing);
|
||||
let x = select::select_window_with(&d, &Space::Model, &ix, bx, crossing);
|
||||
let y = select::select_window_with(&d, &Space::Model, &None, bx, crossing);
|
||||
assert_eq!(x, y, "seed {seed} box {bx:?} crossing {crossing}");
|
||||
}
|
||||
let fence: Vec<Vec2> = (0..(2 + k % 3)).map(|_| Vec2::new(r.r(0.0, 100.0), r.r(0.0, 100.0))).collect();
|
||||
assert_eq!(
|
||||
select::select_fence_with(&d, &Space::Model, &ix, &[], &fence),
|
||||
select::select_fence_with(&d, &Space::Model, &None, &[], &fence)
|
||||
);
|
||||
assert_eq!(select::select_fence_with(&d, &Space::Model, &ix, &fence), select::select_fence_with(&d, &Space::Model, &None, &fence));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -487,13 +484,10 @@ mod tests {
|
||||
for (p, ap) in
|
||||
[(Vec2::new(f64::NAN, 1.0), 1.0), (Vec2::new(1.0, 1.0), f64::NAN), (Vec2::new(f64::INFINITY, 0.0), 1.0), (Vec2::new(50.0, 50.0), 1e300)]
|
||||
{
|
||||
assert_eq!(select::pick_with(&d, &Space::Model, &ix, &[], p, ap), select::pick_with(&d, &Space::Model, &None, &[], p, ap));
|
||||
assert_eq!(select::pick_with(&d, &Space::Model, &ix, p, ap), select::pick_with(&d, &Space::Model, &None, p, ap));
|
||||
}
|
||||
let bx = Bounds2 { min: Vec2::new(f64::NEG_INFINITY, 0.0), max: Vec2::new(f64::INFINITY, 50.0) };
|
||||
assert_eq!(
|
||||
select::select_window_with(&d, &Space::Model, &ix, &[], bx, true),
|
||||
select::select_window_with(&d, &Space::Model, &None, &[], bx, true)
|
||||
);
|
||||
assert_eq!(select::select_window_with(&d, &Space::Model, &ix, bx, true), select::select_window_with(&d, &Space::Model, &None, bx, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -166,10 +166,6 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
|
||||
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
|
||||
"DWGNAME" => json!(s.state().map(|d| d.title.clone()).unwrap_or_default()),
|
||||
"DBMOD" => json!(s.state().map(|d| i32::from(d.is_dirty())).unwrap_or(0)),
|
||||
// The next handle the drawing gives out, in hex as `$HANDSEED` (the header keeps the
|
||||
// value the file was read with, which new objects don't move): past the handles the
|
||||
// file's own objects hold, as allocation skips them.
|
||||
"HANDSEED" => json!(format!("{:X}", s.doc().ok()?.next_handle().0)),
|
||||
// The drawing's folder with a trailing separator ("" while it has no file); DWGTITLED is 1 once it has one.
|
||||
"DWGPREFIX" => json!(s.state().ok().and_then(|d| d.path.as_deref()).map(dwg_prefix).unwrap_or_default()),
|
||||
"DWGTITLED" => json!(s.state().map(|d| i32::from(d.path.is_some())).unwrap_or(0)),
|
||||
@@ -258,7 +254,6 @@ const READ_ONLY: &[&str] = &[
|
||||
"TILEMODE",
|
||||
"PLATFORM",
|
||||
"DBMOD",
|
||||
"HANDSEED",
|
||||
"BLOCKEDITOR",
|
||||
"CTAB",
|
||||
"LASTPOINT",
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
//! #1658: `attdef` takes a justification and a text style, as `text` and `mtext` do, so a
|
||||
//! title-block attribute can be built centred or right-aligned in its style without an `entmod`.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Attrib, EntityKind, HAlign, Handle, VAlign};
|
||||
use cadcraft_engine::geom::Vec3;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn h(v: &Value) -> Handle {
|
||||
v["handle"].as_str().and_then(Handle::parse_hex).unwrap()
|
||||
}
|
||||
|
||||
fn attdef(s: &Session, h: Handle) -> Attrib {
|
||||
match &s.doc().unwrap().entity(h).unwrap().kind {
|
||||
EntityKind::AttDef(a) => a.clone(),
|
||||
k => panic!("{k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `attdef` with `p` and returns the definition it made.
|
||||
fn add(s: &mut Session, p: Value) -> Attrib {
|
||||
let made = h(&s.execute("attdef", &p).unwrap());
|
||||
attdef(s, made)
|
||||
}
|
||||
|
||||
/// The issue's drawing: a text style ROMANS beside the current Standard.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({"name": "ROMANS", "font": "romans.shx"})).unwrap();
|
||||
s.execute("style.current", &json!({"name": "Standard"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justify_and_style_are_applied() {
|
||||
let mut s = session();
|
||||
let a = add(&mut s, json!({"tag": "T", "at": [10, 10], "height": 2.5, "justify": "MC", "style": "ROMANS"}));
|
||||
assert_eq!((a.text.halign, a.text.valign), (HAlign::Center, VAlign::Middle));
|
||||
assert_eq!(a.text.style, "ROMANS");
|
||||
assert_eq!(a.text.align_pt, Some(Vec3::new(10.0, 10.0, 0.0)), "justified text is placed by its alignment point");
|
||||
// Every code `text` takes, and the style name in any case (kept as the table spells it).
|
||||
for (j, want) in [
|
||||
("BR", (HAlign::Right, VAlign::Bottom)),
|
||||
("tl", (HAlign::Left, VAlign::Top)),
|
||||
("C", (HAlign::Center, VAlign::Baseline)),
|
||||
("M", (HAlign::Middle, VAlign::Baseline)),
|
||||
] {
|
||||
let a = add(&mut s, json!({"tag": "T", "at": [0, 0], "justify": j, "style": "romans"}));
|
||||
assert_eq!((a.text.halign, a.text.valign), want, "{j}");
|
||||
assert_eq!(a.text.style, "ROMANS");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_them_nothing_changes() {
|
||||
let mut s = session();
|
||||
let a = add(&mut s, json!({"tag": "T", "at": [10, 10]}));
|
||||
assert_eq!((a.text.halign, a.text.valign, a.text.align_pt), (HAlign::Left, VAlign::Baseline, None));
|
||||
assert_eq!(a.text.style, "Standard", "the current text style");
|
||||
// With another current style, that one: not always Standard.
|
||||
s.execute("style.current", &json!({"name": "ROMANS"})).unwrap();
|
||||
let a = add(&mut s, json!({"tag": "T", "at": [10, 10]}));
|
||||
assert_eq!(a.text.style, "ROMANS", "the current text style");
|
||||
let a = add(&mut s, json!({"tag": "T", "at": [10, 10], "justify": "L"}));
|
||||
assert_eq!((a.text.halign, a.text.valign, a.text.align_pt), (HAlign::Left, VAlign::Baseline, None));
|
||||
assert_eq!(a.text.style, "ROMANS", "the current text style");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_justification_or_style_is_refused() {
|
||||
let mut s = session();
|
||||
let n = s.doc().unwrap().model.len();
|
||||
assert!(s.execute("attdef", &json!({"tag": "T", "at": [0, 0], "justify": "XX"})).is_err());
|
||||
assert!(s.execute("attdef", &json!({"tag": "T", "at": [0, 0], "style": "NOPE"})).is_err());
|
||||
// Align and Fit need a second baseline point, which attdef has no way to take.
|
||||
for j in ["A", "ALIGN", "F", "fit"] {
|
||||
assert!(s.execute("attdef", &json!({"tag": "T", "at": [0, 0], "justify": j})).is_err(), "{j}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().model.len(), n, "nothing added");
|
||||
}
|
||||
|
||||
/// The issue's use: a block built from the definition gives its attributes the same placement,
|
||||
/// and a save and reopen keeps them.
|
||||
#[test]
|
||||
fn a_block_and_a_saved_file_keep_them() {
|
||||
let mut s = session();
|
||||
let ad =
|
||||
h(&s.execute("attdef", &json!({"tag": "TITLE", "default": "x", "at": [50, 10], "height": 2.5, "justify": "MC", "style": "ROMANS"})).unwrap());
|
||||
let l = s.execute("line", &json!({"points": [[0, 0], [100, 0]]})).unwrap()["handles"][0].as_str().and_then(Handle::parse_hex).unwrap();
|
||||
s.execute("block", &json!({"name": "TB", "base": [0, 0], "handles": [ad.hex(), l.hex()], "keep": "delete"})).unwrap();
|
||||
let ins = h(&s.execute("insert", &json!({"name": "TB", "at": [0, 0], "attribs": {"TITLE": "PLAN"}})).unwrap());
|
||||
let EntityKind::Insert(i) = &s.doc().unwrap().entity(ins).unwrap().kind else { panic!() };
|
||||
let att = i.attribs.first().unwrap();
|
||||
assert_eq!(
|
||||
(att.text.halign, att.text.valign, att.text.style.as_str(), att.text.value.as_str()),
|
||||
(HAlign::Center, VAlign::Middle, "ROMANS", "PLAN")
|
||||
);
|
||||
let read = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap();
|
||||
let def =
|
||||
read.block("TB").unwrap().entities.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None }).unwrap();
|
||||
assert_eq!((def.text.halign, def.text.valign, def.text.style.as_str()), (HAlign::Center, VAlign::Middle, "ROMANS"), "reopened definition");
|
||||
let att = read.model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { i.attribs.first().cloned() } else { None }).unwrap();
|
||||
assert_eq!((att.text.halign, att.text.valign, att.text.style.as_str()), (HAlign::Center, VAlign::Middle, "ROMANS"), "reopened attribute");
|
||||
}
|
||||
|
||||
/// A `justify` or `style` that is present but not a string is an error, not a silent default (#1720).
|
||||
#[test]
|
||||
fn a_non_string_justify_or_style_is_refused() {
|
||||
let mut s = session();
|
||||
let n = s.doc().unwrap().model.len();
|
||||
for (key, bad) in [("justify", json!(1)), ("justify", json!(true)), ("style", json!(2)), ("style", json!(["ROMANS"]))] {
|
||||
let mut p = json!({"tag": "T", "at": [0, 0]});
|
||||
p[key] = bad.clone();
|
||||
let err = s.execute("attdef", &p).unwrap_err().to_string();
|
||||
assert!(err.contains(key) && err.contains("string"), "{key} = {bad}: {err}");
|
||||
}
|
||||
// Null means absent.
|
||||
assert!(s.execute("attdef", &json!({"tag": "T", "at": [0, 0], "justify": null, "style": null})).is_ok());
|
||||
assert_eq!(s.doc().unwrap().model.len(), n + 1, "only the null one was added");
|
||||
}
|
||||
|
||||
/// The definition takes its text style's width factor and oblique angle (#1720).
|
||||
#[test]
|
||||
fn the_definition_takes_the_styles_width_factor_and_oblique() {
|
||||
let mut s = session();
|
||||
s.execute("style", &json!({"name": "SLANT", "font": "romans.shx", "widthFactor": 0.7, "oblique": 15, "current": false})).unwrap();
|
||||
let a = add(&mut s, json!({"tag": "T", "at": [0, 0], "style": "SLANT"}));
|
||||
assert!((a.text.width_factor - 0.7).abs() < 1e-12, "width factor {}", a.text.width_factor);
|
||||
assert!((a.text.oblique - 15f64.to_radians()).abs() < 1e-12, "oblique {}", a.text.oblique);
|
||||
// The current style, when none is named.
|
||||
s.execute("style.current", &json!({"name": "SLANT"})).unwrap();
|
||||
let a = add(&mut s, json!({"tag": "T", "at": [0, 0]}));
|
||||
assert!((a.text.width_factor - 0.7).abs() < 1e-12 && (a.text.oblique - 15f64.to_radians()).abs() < 1e-12);
|
||||
// A plain style keeps 1 and 0.
|
||||
let a = add(&mut s, json!({"tag": "T", "at": [0, 0], "style": "Standard"}));
|
||||
assert_eq!((a.text.width_factor, a.text.oblique), (1.0, 0.0));
|
||||
}
|
||||
|
||||
/// `-ATTDEF` typed at the command line: accept modes, tag, prompt and default, then the point prompt.
|
||||
fn typed_to_start_point(s: &mut Session) {
|
||||
s.cmdline("-attdef").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
for line in ["TAG", "Prompt", "Default"] {
|
||||
s.cmdline(line).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn last_attdef(s: &Session) -> Attrib {
|
||||
let e = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::AttDef(_))).last().unwrap();
|
||||
attdef(s, e.handle)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_start_point_prompt_offers_justify_and_style() {
|
||||
let mut s = session();
|
||||
typed_to_start_point(&mut s);
|
||||
assert!(s.prompt_text().contains("Specify start point of text or [Justify/Style]"), "{}", s.prompt_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_justify_then_a_point_justifies_the_definition() {
|
||||
let mut s = session();
|
||||
typed_to_start_point(&mut s);
|
||||
s.cmdline("J").unwrap();
|
||||
assert!(s.prompt_text().contains("Enter an option"), "{}", s.prompt_text());
|
||||
s.cmdline("MC").unwrap();
|
||||
assert!(s.prompt_text().contains("Specify middle point of text"), "{}", s.prompt_text());
|
||||
s.cmdline("10,10").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let a = last_attdef(&s);
|
||||
assert_eq!((a.text.halign, a.text.valign), (HAlign::Center, VAlign::Middle));
|
||||
assert_eq!(a.text.align_pt, Some(Vec3::new(10.0, 10.0, 0.0)), "stored as the JSON form does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_justify_refuses_align_fit_and_unknown_codes_and_asks_again() {
|
||||
let mut s = session();
|
||||
typed_to_start_point(&mut s);
|
||||
s.cmdline("J").unwrap();
|
||||
for bad in ["A", "Fit", "XX"] {
|
||||
s.cmdline(bad).unwrap();
|
||||
assert!(s.log.iter().any(|l| l.contains("Invalid option") || l.contains("Align and Fit")), "{bad}: {:?}", s.log);
|
||||
s.log.clear();
|
||||
assert!(s.prompt_text().contains("Enter an option"), "{bad}: {}", s.prompt_text());
|
||||
}
|
||||
s.cmdline("TR").unwrap();
|
||||
s.cmdline("0,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
let a = last_attdef(&s);
|
||||
assert_eq!((a.text.halign, a.text.valign), (HAlign::Right, VAlign::Top));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_style_then_a_point_takes_the_styles_values() {
|
||||
let mut s = session();
|
||||
s.execute("style", &json!({"name": "SLANT", "font": "romans.shx", "widthFactor": 0.7, "oblique": 15, "current": false})).unwrap();
|
||||
typed_to_start_point(&mut s);
|
||||
s.cmdline("S").unwrap();
|
||||
assert!(s.prompt_text().contains("Enter style name"), "{}", s.prompt_text());
|
||||
s.cmdline("slant").unwrap();
|
||||
s.cmdline("0,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
let a = last_attdef(&s);
|
||||
assert_eq!(a.text.style, "SLANT");
|
||||
assert!((a.text.width_factor - 0.7).abs() < 1e-12 && (a.text.oblique - 15f64.to_radians()).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_style_that_does_not_exist_asks_again() {
|
||||
let mut s = session();
|
||||
typed_to_start_point(&mut s);
|
||||
s.cmdline("S").unwrap();
|
||||
s.cmdline("NOPE").unwrap();
|
||||
assert!(s.log.iter().any(|l| l.contains("Cannot find text style \"NOPE\"")), "{:?}", s.log);
|
||||
assert!(s.prompt_text().contains("Enter style name"), "{}", s.prompt_text());
|
||||
s.cmdline("ROMANS").unwrap();
|
||||
s.cmdline("0,0").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert_eq!(last_attdef(&s).text.style, "ROMANS");
|
||||
}
|
||||
|
||||
/// The keywords a command's Justify prompt offers, from `[A/B/...]` in its prompt text.
|
||||
fn justify_options(s: &Session) -> Vec<String> {
|
||||
let p = s.prompt_text();
|
||||
let inner = p.split_once('[').and_then(|(_, r)| r.split_once(']')).map(|(i, _)| i).unwrap_or("");
|
||||
inner.split('/').map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// `-ATTDEF`'s Justify prompt doesn't list Align and Fit, which it would only refuse (they run
|
||||
/// between two points), while TEXT's still offers every option (#1720).
|
||||
#[test]
|
||||
fn attdef_justify_prompt_leaves_out_align_and_fit_but_text_keeps_them() {
|
||||
let mut s = session();
|
||||
typed_to_start_point(&mut s);
|
||||
s.cmdline("J").unwrap();
|
||||
let opts = justify_options(&s);
|
||||
assert!(opts.iter().any(|o| o == "Left") && opts.iter().any(|o| o == "MC"), "{opts:?}");
|
||||
assert!(!opts.iter().any(|o| o == "Align" || o == "Fit"), "{opts:?}");
|
||||
// A typed A or F is still refused.
|
||||
s.cmdline("A").unwrap();
|
||||
assert!(s.log.iter().any(|l| l.contains("Align and Fit")), "{:?}", s.log);
|
||||
s.cmdline("*Cancel*").ok();
|
||||
|
||||
let mut t = session();
|
||||
t.cmdline("text").unwrap();
|
||||
t.cmdline("J").unwrap();
|
||||
let opts = justify_options(&t);
|
||||
assert!(opts.iter().any(|o| o == "Align") && opts.iter().any(|o| o == "Fit"), "{opts:?}");
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
//! File and automation inputs retain CADCraft's accepted Base64 forms.
|
||||
use cadcraft_engine::cmd::file::{base64_decode, base64_encode};
|
||||
|
||||
#[test]
|
||||
fn legacy_inputs_and_standard_outputs_survive_the_shared_cutover() {
|
||||
for bytes in [&b""[..], b"f", b"fo", b"foo", b"foobar", &[0, 255, 127]] {
|
||||
assert_eq!(base64_decode(&base64_encode(bytes)).as_deref(), Some(bytes));
|
||||
}
|
||||
assert_eq!(base64_decode("+_8=").as_deref(), Some(&[251, 255][..]));
|
||||
assert_eq!(base64_decode("Z=m 9\nv\r").as_deref(), Some(&b"foo"[..]));
|
||||
assert_eq!(base64_decode("A").as_deref(), Some(&b""[..]));
|
||||
assert!(base64_decode("Zm9v\t").is_none());
|
||||
assert!(base64_decode("Zm9v!").is_none());
|
||||
}
|
||||
@@ -1,308 +0,0 @@
|
||||
//! Block libraries (the Blocks palette): BLOCKLIBRARY lists a folder of drawings or the blocks
|
||||
//! of one drawing, BLOCKLIBIMPORT defines a library block in the current drawing, and
|
||||
//! BLOCKLIBRARIES keeps the list of libraries.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use cadcraft_engine::cmd::file::{IoHooks, set_io};
|
||||
use cadcraft_engine::doc::geom::Vec3;
|
||||
use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, Handle, Layer, Line};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
/// How many times a library file was parsed.
|
||||
static READS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// Every library file reads as a drawing with blocks "Valve" (a line on layer Pipes, base point
|
||||
/// (1, 1)) and "Pump" (empty), whatever its bytes.
|
||||
fn read(_bytes: &[u8], name: &str) -> Result<Drawing, String> {
|
||||
READS.fetch_add(1, Ordering::SeqCst);
|
||||
let mut d = Drawing::new_metric();
|
||||
d.layers.push(Layer { name: "Pipes".into(), ..Layer::default() });
|
||||
d.layers.push(Layer { name: "Spare".into(), ..Layer::default() });
|
||||
let mut valve = Block::new("Valve");
|
||||
valve.description = "Gate valve".into();
|
||||
valve.annotative = true;
|
||||
valve.units = 6;
|
||||
valve.explodable = false;
|
||||
valve.base = Vec3::new(1.0, 1.0, 0.0);
|
||||
let mut line = Entity::new(Handle(0x70), EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(4.0, 0.0, 0.0) }));
|
||||
line.common.layer = "Pipes".into();
|
||||
valve.entities.push(line);
|
||||
d.blocks.insert("Valve".into(), Arc::new(valve));
|
||||
d.blocks.insert("Pump".into(), Arc::new(Block::new("Pump")));
|
||||
// "Outer" holds a reference to "Valve" and nothing else.
|
||||
let mut s = Session::new();
|
||||
*s.doc_mut().unwrap() = d;
|
||||
s.execute("insert", &json!({ "name": "Valve", "at": [2, 2] })).unwrap();
|
||||
let handles: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
|
||||
s.execute("block", &json!({ "name": "Outer", "base": [0, 0], "handles": handles, "keep": "delete" })).unwrap();
|
||||
// A dimension style nothing uses, with an arrowhead block of its own.
|
||||
if name.contains("arrow") {
|
||||
let d = s.doc_mut().unwrap();
|
||||
d.blocks.insert("TipArrow".into(), Arc::new(Block::new("TipArrow")));
|
||||
d.dim_styles.push(cadcraft_engine::doc::DimStyle { name: "Spare".into(), arrow_block: "TipArrow".into(), ..Default::default() });
|
||||
}
|
||||
// A crafted file: "Valve" holds "Outer", which holds "Valve".
|
||||
if name.contains("cycle") {
|
||||
let mut back = (**s.doc().unwrap().block("Outer").unwrap().entities.iter().next().unwrap()).clone();
|
||||
if let EntityKind::Insert(i) = &mut back.kind {
|
||||
i.block = "Outer".into();
|
||||
}
|
||||
let d = s.doc_mut().unwrap();
|
||||
let mut valve = (**d.block("Valve").unwrap()).clone();
|
||||
valve.entities.push(back);
|
||||
d.blocks.insert("Valve".into(), Arc::new(valve));
|
||||
}
|
||||
Ok(s.doc().unwrap().clone())
|
||||
}
|
||||
|
||||
/// A new folder with two drawings and a file that is not one.
|
||||
fn folder() -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-blocklibrary-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for f in ["b-pumps.dwg", "A-valves.dxf", "notes.txt"] {
|
||||
std::fs::write(dir.join(f), b"x").unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
/// Listing a drawing file and importing its blocks.
|
||||
fn lists_and_imports(s: &mut Session, file: &str) {
|
||||
// A drawing file lists its blocks.
|
||||
let r = s.execute("blocklibrary", &json!({ "path": file })).unwrap();
|
||||
assert_eq!(r["kind"], "file");
|
||||
assert_eq!(
|
||||
r["blocks"],
|
||||
json!([{ "name": "Outer", "description": "" }, { "name": "Pump", "description": "" }, { "name": "Valve", "description": "Gate valve" }])
|
||||
);
|
||||
|
||||
// Importing defines the block (and its layer) here, under another name when asked.
|
||||
let r = s.execute("blocklibimport", &json!({ "path": file, "block": "Valve", "name": "Gate" })).unwrap();
|
||||
assert_eq!(r["name"], "Gate");
|
||||
let d = s.doc().unwrap();
|
||||
let gate = d.block("Gate").unwrap();
|
||||
assert_eq!(gate.entities.iter().count(), 1);
|
||||
assert_eq!(gate.base, Vec3::new(1.0, 1.0, 0.0));
|
||||
assert_eq!((gate.description.as_str(), gate.annotative, gate.units, gate.explodable), ("Gate valve", true, 6, false));
|
||||
assert!(d.layers.iter().any(|l| l.name == "Pipes"));
|
||||
// Only what the block needs comes along: not the file's other layers or blocks.
|
||||
assert!(!d.layers.iter().any(|l| l.name == "Spare"), "an unused layer of the library stays out");
|
||||
assert!(d.block("Pump").is_none(), "an unused block of the library stays out");
|
||||
s.execute("insert", &json!({ "name": "Gate", "at": [10, 10] })).unwrap();
|
||||
// A block already here is never replaced, whatever the letter case.
|
||||
assert!(s.execute("blocklibimport", &json!({ "path": file, "block": "Pump", "name": "gate" })).is_err());
|
||||
assert_eq!(s.doc().unwrap().block("Gate").unwrap().entities.iter().count(), 1);
|
||||
assert!(s.doc().unwrap().block("Pump").is_none());
|
||||
// A block made of another block brings that one too (and its layer), not the unused ones.
|
||||
s.execute("blocklibimport", &json!({ "path": file, "block": "Outer", "name": "Assembly" })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(d.block("Assembly").is_some());
|
||||
assert!(d.block("Valve").is_some(), "the nested block stays");
|
||||
assert!(d.block("Pump").is_none());
|
||||
assert!(d.layers.iter().any(|l| l.name == "Pipes"));
|
||||
// A whole drawing is named after its file and brings its objects (here none: model space is empty).
|
||||
let r = s.execute("blocklibimport", &json!({ "path": file })).unwrap();
|
||||
assert_eq!(r["name"], "A-valves");
|
||||
assert!(!s.doc().unwrap().layers.iter().any(|l| l.name == "Spare"));
|
||||
assert!(s.execute("blocklibimport", &json!({ "path": file, "block": "Nope" })).is_err());
|
||||
assert!(s.execute("blocklibimport", &json!({ "path": file, "block": "Valve", "name": "bad/name" })).is_err());
|
||||
}
|
||||
|
||||
/// A dimension style nothing uses is left out, and its arrowhead block with it.
|
||||
fn leaves_out_an_unused_dimension_style(s: &mut Session, dir: &std::path::Path) {
|
||||
let file = dir.join("arrow-set.dxf").to_string_lossy().to_string();
|
||||
std::fs::write(&file, b"x").unwrap();
|
||||
s.execute("blocklibimport", &json!({ "path": file, "block": "Valve", "name": "Tap" })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(d.block("Tap").is_some());
|
||||
assert!(!d.dim_styles.iter().any(|t| t.name == "Spare"), "an unused dimension style stays out");
|
||||
assert!(d.block("TipArrow").is_none(), "so does its arrowhead block");
|
||||
}
|
||||
|
||||
/// Adding and removing libraries.
|
||||
fn keeps_the_list(s: &mut Session, dir: &std::path::Path, dir_s: &str, file: &str) {
|
||||
// The list: add (once), refuse what is not a library, remove.
|
||||
let l = s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).unwrap();
|
||||
assert_eq!(l["libraries"], json!([dir_s]));
|
||||
// The same path again is kept once; letter case only matters on case-sensitive file systems.
|
||||
let again = s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).unwrap();
|
||||
assert_eq!(again["libraries"], json!([dir_s]));
|
||||
if cfg!(any(windows, target_os = "macos")) {
|
||||
let upper = s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s.to_uppercase() })).unwrap();
|
||||
assert_eq!(upper["libraries"], json!([dir_s]), "the same folder in other letters is the same library");
|
||||
assert_eq!(upper["path"], json!(dir_s), "the entry keeps its first spelling");
|
||||
}
|
||||
s.execute("blocklibraries", &json!({ "op": "add", "path": file })).unwrap();
|
||||
assert_eq!(s.execute("blocklibraries", &json!({})).unwrap()["libraries"], json!([dir_s, file]));
|
||||
assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": dir.join("notes.txt").to_string_lossy() })).is_err());
|
||||
let l = s.execute("blocklibraries", &json!({ "op": "remove", "path": file })).unwrap();
|
||||
assert_eq!(l["libraries"], json!([dir_s]));
|
||||
s.execute("blocklibraries", &json!({ "op": "remove", "path": dir_s })).unwrap();
|
||||
}
|
||||
|
||||
/// Names, paths and files that try to pass for something else.
|
||||
fn refuses_hostile_input(s: &mut Session, dir: &std::path::Path, dir_s: &str) {
|
||||
// A block whose name looks like `name=path` is that block: INSERT reads no file for it.
|
||||
let reads = READS.load(Ordering::SeqCst);
|
||||
let mut odd = Session::new();
|
||||
odd.doc_mut().unwrap().blocks.insert("a=b".into(), Arc::new(Block::new("a=b")));
|
||||
odd.start("insert").unwrap();
|
||||
odd.input(Input::Text("a=b".into())).unwrap();
|
||||
assert!(odd.prompt_text().starts_with("INSERT Specify insertion point"), "{}", odd.prompt_text());
|
||||
assert_eq!(READS.load(Ordering::SeqCst), reads, "no file was read");
|
||||
odd.input(Input::Cancel).unwrap();
|
||||
|
||||
// What is not a readable drawing fails with an error.
|
||||
assert!(s.execute("blocklibimport", &json!({ "path": dir_s })).is_err(), "a folder is not a drawing");
|
||||
assert!(s.execute("blocklibrary", &json!({ "path": dir.join("missing.dxf").to_string_lossy() })).is_err());
|
||||
|
||||
// A file is a library by its name, not by its bytes: `part.bin` is refused before it is read.
|
||||
let bin = dir.join("part.bin").to_string_lossy().to_string();
|
||||
std::fs::write(&bin, b"x").unwrap();
|
||||
let reads = READS.load(Ordering::SeqCst);
|
||||
assert!(s.execute("blocklibrary", &json!({ "path": bin })).is_err());
|
||||
assert!(s.execute("blocklibimport", &json!({ "path": bin, "block": "Valve", "name": "FromBin" })).is_err());
|
||||
assert!(cadcraft_engine::cmd::read_library_file(&bin).is_err());
|
||||
assert_eq!(READS.load(Ordering::SeqCst), reads, "the file was not parsed");
|
||||
assert!(s.doc().unwrap().block("FromBin").is_none());
|
||||
|
||||
// A library whose blocks hold each other imports without hanging, and the session goes on.
|
||||
let cycle = dir.join("cycle.dxf").to_string_lossy().to_string();
|
||||
std::fs::write(&cycle, b"x").unwrap();
|
||||
let _ = s.execute("blocklibimport", &json!({ "path": cycle, "block": "Outer", "name": "Loop" }));
|
||||
s.execute("line", &json!({ "points": [[0, 0], [1, 1]] })).unwrap();
|
||||
}
|
||||
|
||||
/// The Blocks palette can open on the Start tab: listing a library and the kept list need no
|
||||
/// drawing; importing one does.
|
||||
#[test]
|
||||
fn the_library_commands_that_read_no_drawing_run_without_one() {
|
||||
let mut s = Session::empty();
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-blocklibrary-nodoc-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("pumps.dwg"), b"x").unwrap();
|
||||
let r = s.execute("blocklibrary", &json!({ "path": dir.to_string_lossy() })).unwrap();
|
||||
assert_eq!(r["files"].as_array().map(Vec::len), Some(1));
|
||||
s.execute("blocklibraries", &json!({})).unwrap();
|
||||
let err = s.execute("blocklibimport", &json!({ "path": dir.join("pumps.dwg").to_string_lossy() })).unwrap_err();
|
||||
assert!(err.to_string().contains("no drawing"), "{err}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A file with a huge block table.
|
||||
fn bounds_a_huge_table() {
|
||||
// A file with a huge block table lists a bounded part of it, and says so.
|
||||
let mut many = Session::new();
|
||||
let d = many.doc_mut().unwrap();
|
||||
for i in 0..10_001 {
|
||||
let name = format!("B{i}");
|
||||
d.blocks.insert(name.clone(), Arc::new(Block::new(&name)));
|
||||
}
|
||||
let r = many.execute("blockspalette", &json!({})).unwrap();
|
||||
let names: Vec<&str> = r["blocks"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names.len(), 10_000);
|
||||
assert_eq!(r["truncated"], true);
|
||||
// The first ones by name, sorted: B9999 comes last of all, so it is the one left out.
|
||||
assert_eq!(names.first(), Some(&"B0"));
|
||||
assert!(!names.contains(&"B9999"));
|
||||
assert!(names.windows(2).all(|w| w[0].to_ascii_lowercase() <= w[1].to_ascii_lowercase()));
|
||||
}
|
||||
|
||||
/// BLOCKSPALETTE counts every object that draws a block: references and multileader block content.
|
||||
fn counts_what_draws_each_block() {
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().blocks.insert("Tag".into(), Arc::new(Block::new("Tag")));
|
||||
s.execute("insert", &json!({ "name": "Tag", "at": [0, 0] })).unwrap();
|
||||
s.execute("mleader", &json!({ "points": [[0, 0], [10, 5]], "block": "tag" })).unwrap();
|
||||
let r = s.execute("blockspalette", &json!({})).unwrap();
|
||||
assert_eq!(r["blocks"], json!([{ "name": "Tag", "description": "", "references": 2 }]));
|
||||
}
|
||||
|
||||
/// The list file in the settings folder.
|
||||
fn checks_the_list_file(s: &mut Session, dir: &std::path::Path, dir_s: &str) {
|
||||
// The list file is checked when it is read: junk, bad entries, too many, too big.
|
||||
let list = dir.join("block-libraries.json");
|
||||
let libraries = |s: &mut Session| s.execute("blocklibraries", &json!({})).unwrap()["libraries"].as_array().unwrap().clone();
|
||||
std::fs::write(&list, "not json").unwrap();
|
||||
assert!(libraries(s).is_empty());
|
||||
// A file that is there but unreadable is never written over: the list stays as the user left it.
|
||||
assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).is_err());
|
||||
assert!(s.execute("blocklibraries", &json!({ "op": "remove", "path": dir_s })).is_err());
|
||||
assert_eq!(std::fs::read(&list).unwrap(), b"not json");
|
||||
let mut hostile: Vec<String> = (0..100).map(|i| format!("C:/lib{i}")).collect();
|
||||
hostile.insert(0, String::new());
|
||||
hostile.insert(1, "bad\nname".into());
|
||||
hostile.insert(2, "x".repeat(10_000));
|
||||
std::fs::write(&list, serde_json::to_vec(&hostile).unwrap()).unwrap();
|
||||
let kept = libraries(s);
|
||||
assert_eq!(kept.len(), 64);
|
||||
assert_eq!(kept[0], "C:/lib0");
|
||||
std::fs::write(&list, vec![b' '; 300 << 10]).unwrap();
|
||||
assert!(libraries(s).is_empty());
|
||||
// What the list file holds after an addition is the list, whole.
|
||||
std::fs::remove_file(&list).unwrap();
|
||||
s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).unwrap();
|
||||
assert_eq!(serde_json::from_slice::<Vec<String>>(&std::fs::read(&list).unwrap()).unwrap(), vec![dir_s.to_string()]);
|
||||
// Paths with control characters or of absurd length are refused.
|
||||
assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": format!("{dir_s}\nx") })).is_err());
|
||||
assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": "y".repeat(5000) })).is_err());
|
||||
}
|
||||
|
||||
/// A file named at INSERT's prompt defines its block before the insertion point is asked for, and
|
||||
/// Escape there keeps the definition and places nothing, as in AutoCAD 2027.
|
||||
fn a_cancelled_insert_keeps_the_definition_from_a_file(s: &mut Session, file: &str) {
|
||||
let placed = s.doc().unwrap().model.iter().count();
|
||||
s.start("insert").unwrap();
|
||||
s.input(Input::Text(format!("FromFile={file}"))).unwrap();
|
||||
assert!(s.prompt_text().starts_with("INSERT Specify insertion point"), "{}", s.prompt_text());
|
||||
assert!(s.doc().unwrap().block("FromFile").is_some());
|
||||
s.input(Input::Cancel).unwrap();
|
||||
assert!(s.doc().unwrap().block("FromFile").is_some());
|
||||
assert_eq!(s.doc().unwrap().model.iter().count(), placed);
|
||||
}
|
||||
|
||||
/// One test: the file hooks and the settings folder are global to the process.
|
||||
#[test]
|
||||
fn libraries_list_import_and_are_kept() {
|
||||
set_io(IoHooks { read, write: |_, _| Err("no writer in this test".into()), plot: None });
|
||||
// No settings folder: the list lives in memory, and the real one is never written.
|
||||
cadcraft_engine::settings_dir::set(None);
|
||||
let dir = folder();
|
||||
let dir_s = dir.to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
|
||||
// A folder lists its drawings by name, case-insensitively sorted; other files are not drawings.
|
||||
let r = s.execute("blocklibrary", &json!({ "path": dir_s })).unwrap();
|
||||
assert_eq!(r["kind"], "folder");
|
||||
let names: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["A-valves", "b-pumps"]);
|
||||
|
||||
let reads_before = READS.load(Ordering::SeqCst);
|
||||
let file = dir.join("A-valves.dxf").to_string_lossy().to_string();
|
||||
lists_and_imports(&mut s, &file);
|
||||
// The file was parsed once for all of that, and again only when it changes.
|
||||
assert_eq!(READS.load(Ordering::SeqCst) - reads_before, 1, "the file is parsed once, not for every block placed");
|
||||
std::fs::write(&file, b"changed contents, another size").unwrap();
|
||||
s.execute("blocklibrary", &json!({ "path": file })).unwrap();
|
||||
assert_eq!(READS.load(Ordering::SeqCst) - reads_before, 2, "a changed file is read again");
|
||||
// Refresh in the palette reads it again even when its size and time look the same.
|
||||
cadcraft_engine::cmd::clear_library_cache();
|
||||
let listed = s.execute("blocklibrary", &json!({ "path": file })).unwrap();
|
||||
assert_eq!(READS.load(Ordering::SeqCst) - reads_before, 3, "a cleared file is read again");
|
||||
// The palette's worker thread gets the same answer without a session.
|
||||
assert_eq!(cadcraft_engine::cmd::list_library(&file).unwrap(), listed);
|
||||
|
||||
leaves_out_an_unused_dimension_style(&mut s, &dir);
|
||||
a_cancelled_insert_keeps_the_definition_from_a_file(&mut s, &file);
|
||||
keeps_the_list(&mut s, &dir, &dir_s, &file);
|
||||
refuses_hostile_input(&mut s, &dir, &dir_s);
|
||||
bounds_a_huge_table();
|
||||
counts_what_draws_each_block();
|
||||
cadcraft_engine::settings_dir::set(Some(dir.clone()));
|
||||
checks_the_list_file(&mut s, &dir, &dir_s);
|
||||
cadcraft_engine::settings_dir::set(None);
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
//! A word typed with the Greek keyboard layout that is an alias of its own (ALIASEDIT) is that
|
||||
//! alias, not the Latin name its keys type. The aliases are process-wide, so this file keeps to
|
||||
//! one test at a time.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use serde_json::json;
|
||||
|
||||
/// The alias store is process-wide: each test holds this while it changes the aliases.
|
||||
static ONE_AT_A_TIME: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// A Greek word the user made an alias runs the alias's command, not the command its keys type.
|
||||
#[test]
|
||||
fn a_greek_alias_starts_its_command_not_the_latin_keys_command() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
// ΛΙΝΕ types LINE, but the user made it an alias of CIRCLE: aliases are stored as typed (only
|
||||
// ASCII is lower-cased), and the alias wins.
|
||||
s.execute("aliasedit", &json!({ "set": { "ΛΙΝΕ": "circle" } })).unwrap();
|
||||
let ran = s.script(
|
||||
"ΛΙΝΕ 0,0 5
|
||||
",
|
||||
);
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
ran.unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
let circles = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
let lines = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
|
||||
assert_eq!((circles, lines), (1, 0), "the alias drew the circle, LINE was not started");
|
||||
}
|
||||
|
||||
/// The alias is found when it is typed in lower case or with an accent too.
|
||||
#[test]
|
||||
fn a_greek_alias_starts_its_command_in_any_case_or_accent() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
s.execute("aliasedit", &json!({ "set": { "ΛΙΝΕ": "circle" } })).unwrap();
|
||||
let ran: Vec<_> = ["λινε", "λίνε"].iter().map(|typed| s.script(&format!("{typed} 0,0 5\n"))).collect();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
assert!(ran.iter().all(Result::is_ok), "{ran:?}");
|
||||
let doc = s.doc().unwrap();
|
||||
let circles = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
let lines = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
|
||||
assert_eq!((circles, lines), (2, 0), "the alias drew both circles, LINE was not started");
|
||||
}
|
||||
|
||||
/// 5 000 Greek aliases and a pasted word of a million letters that is none of them: looking it up
|
||||
/// costs the word's length once, not once for every alias.
|
||||
#[test]
|
||||
fn a_long_greek_word_is_folded_once_however_many_greek_aliases_there_are() {
|
||||
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
let set: serde_json::Map<String, serde_json::Value> = (0..5_000).map(|i| (format!("ΞΞ{i}"), json!("line"))).collect();
|
||||
s.execute("aliasedit", &json!({ "set": set })).unwrap();
|
||||
let word = "Ω".repeat(1_000_000);
|
||||
let t = std::time::Instant::now();
|
||||
let started = s.start(&word);
|
||||
let took = t.elapsed();
|
||||
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
|
||||
assert!(started.is_err(), "no command has those keys");
|
||||
assert!(took.as_secs() < 5, "{took:?}");
|
||||
}
|
||||
@@ -130,7 +130,7 @@ fn the_prompts_are_autocads() {
|
||||
// A wrong answer, or a justification not available here, is asked again.
|
||||
for typed in ["X", "_A"] {
|
||||
s.cmdline(typed).unwrap();
|
||||
assert!(s.prompt_text().contains("[Left/Center/Right/Middle/TL/"), "{typed}: {}", s.prompt_text());
|
||||
assert!(s.prompt_text().contains("[Left/Center/Right/Align/Middle/Fit/TL/"), "{typed}: {}", s.prompt_text());
|
||||
}
|
||||
s.cmdline("_MC").unwrap();
|
||||
assert!(s.prompt_text().ends_with("Specify middle point of text:"), "{}", s.prompt_text());
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! BREAK on a closed polyline removes the stretch between the two points that doesn't run
|
||||
//! through its start vertex, whichever point comes first, and leaves one open polyline from the
|
||||
//! later point round to the earlier one (#1173; AutoCAD 2024, accoreconsole).
|
||||
//! BREAK on a closed polyline removes the stretch from the first to the second point along the
|
||||
//! vertex direction and leaves one open polyline (#1173).
|
||||
|
||||
use cadcraft_doc::{EntityKind, LwPolyline};
|
||||
use cadcraft_engine::Session;
|
||||
@@ -39,15 +38,14 @@ fn break_opens_a_closed_polyline_at_the_command_line() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_json_on_a_closed_polyline_ignores_the_order_of_the_points() {
|
||||
fn break_json_on_a_closed_polyline_follows_the_order_of_the_points() {
|
||||
let mut s = Session::new();
|
||||
let r = closed_rect(&mut s);
|
||||
// Second point before the first along the vertices: the same stretch goes as with the points
|
||||
// the other way round (measured with the first point after the second, and both ways on a
|
||||
// 100 x 10 rectangle broken at (10, 0) and (10, 10), where the long stretch went).
|
||||
// Second point before the first along the vertices: the long way round goes, the short
|
||||
// stretch between them stays.
|
||||
s.execute("break", &json!({ "handle": r["handle"], "p1": [100, 30], "p2": [50, 0] })).unwrap();
|
||||
let ps = polys(&s);
|
||||
assert_eq!(ps.len(), 1);
|
||||
assert!(!ps[0].closed);
|
||||
assert_eq!(pts(&ps[0]), vec![(100.0, 30.0), (100.0, 60.0), (0.0, 60.0), (0.0, 0.0), (50.0, 0.0)]);
|
||||
assert_eq!(pts(&ps[0]), vec![(50.0, 0.0), (100.0, 0.0), (100.0, 30.0)]);
|
||||
}
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
//! BREAKATPOINT and BREAK where the result is easy to get wrong, as AutoCAD 2024 runs them
|
||||
//! (accoreconsole, `entget` of every object after the command, on these drawings):
|
||||
//!
|
||||
//! - BREAKATPOINT at either end of a line, or at the end vertex of an open polyline, leaves the
|
||||
//! object whole;
|
||||
//! - at an open polyline's middle vertex it splits it there, the original keeping the first part;
|
||||
//! - BREAK of a closed polyline at two points of one side, either way round and on the side that
|
||||
//! closes it too, opens it with its own handle;
|
||||
//! - a circle trimmed or broken becomes an arc with its own handle.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn handle(v: &Value) -> Handle {
|
||||
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The model space objects in order: handle and kind.
|
||||
fn objects(s: &Session) -> Vec<(Handle, EntityKind)> {
|
||||
s.doc().unwrap().model.iter().map(|e| (e.handle, e.kind.clone())).collect()
|
||||
}
|
||||
|
||||
/// A polyline's closed flag and vertices (rounded to 1e-9).
|
||||
fn pts(k: &EntityKind) -> (bool, Vec<(f64, f64)>) {
|
||||
let EntityKind::LwPolyline(p) = k else { panic!("not a polyline: {k:?}") };
|
||||
let r = |v: f64| (v * 1e9).round() / 1e9;
|
||||
(p.closed, p.vertices.iter().map(|v| (r(v.p.x), r(v.p.y))).collect())
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
|
||||
handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap())
|
||||
}
|
||||
|
||||
fn pline(s: &mut Session, vertices: Value, closed: bool) -> Handle {
|
||||
handle(&s.execute("pline", &json!({ "vertices": vertices, "closed": closed })).unwrap())
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, script: &str) {
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_at_an_end_leaves_the_object_whole() {
|
||||
for at in ["100,0", "0,0"] {
|
||||
let mut s = Session::new();
|
||||
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
|
||||
run(&mut s, &format!("BREAKATPOINT {at} {at}\n"));
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 1, "{at}: {objs:?}");
|
||||
let EntityKind::Line(k) = &objs[0].1 else { panic!("{objs:?}") };
|
||||
assert!(objs[0].0 == l && (k.a.x, k.a.y, k.b.x, k.b.y) == (0.0, 0.0, 100.0, 0.0), "{at}: {objs:?}");
|
||||
}
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [50, 0], [50, 30]]), false);
|
||||
run(&mut s, "BREAKATPOINT 50,30 50,30\n");
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 1, "{objs:?}");
|
||||
assert_eq!((objs[0].0, pts(&objs[0].1)), (p, (false, vec![(0.0, 0.0), (50.0, 0.0), (50.0, 30.0)])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_at_a_middle_vertex_splits_there_and_the_original_keeps_the_first_part() {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [50, 0], [50, 30]]), false);
|
||||
run(&mut s, "BREAKATPOINT 50,0 50,0\n");
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 2, "{objs:?}");
|
||||
let first = objs.iter().find(|o| o.0 == p).expect("the original stays");
|
||||
let other = objs.iter().find(|o| o.0 != p).unwrap();
|
||||
assert_eq!(pts(&first.1), (false, vec![(0.0, 0.0), (50.0, 0.0)]));
|
||||
assert_eq!(pts(&other.1), (false, vec![(50.0, 0.0), (50.0, 30.0)]));
|
||||
// One undo brings back the polyline as it was, under its handle, and nothing else.
|
||||
s.undo().unwrap();
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 1, "{objs:?}");
|
||||
assert_eq!((objs[0].0, pts(&objs[0].1)), (p, (false, vec![(0.0, 0.0), (50.0, 0.0), (50.0, 30.0)])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_at_two_points_of_one_side_opens_a_closed_polyline_with_its_handle() {
|
||||
let bottom = vec![(30.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0), (0.0, 0.0), (20.0, 0.0)];
|
||||
// The side from (0, 10) back to the start vertex closes the rectangle.
|
||||
let closing = vec![(0.0, 3.0), (0.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0), (0.0, 8.0)];
|
||||
for (script, want) in [("BREAK 20,0 30,0\n", &bottom), ("BREAK 30,0 20,0\n", &bottom), ("BREAK 0,8 0,3\n", &closing)] {
|
||||
let mut s = Session::new();
|
||||
let r = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true);
|
||||
run(&mut s, script);
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 1, "{script}: {objs:?}");
|
||||
assert_eq!((objs[0].0, pts(&objs[0].1)), (r, (false, want.clone())), "{script}");
|
||||
// Undo closes it again.
|
||||
s.undo().unwrap();
|
||||
let objs = objects(&s);
|
||||
let rect = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0)];
|
||||
assert_eq!(objs.iter().map(|o| (o.0, pts(&o.1))).collect::<Vec<_>>(), vec![(r, (true, rect))], "{script}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_trimmed_or_broken_becomes_an_arc_with_its_handle() {
|
||||
// Trimmed between the lines x = -5 and x = 5, picked at its top: the arc from 120 to 60
|
||||
// degrees, round the bottom.
|
||||
let mut s = Session::new();
|
||||
let c = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap());
|
||||
let l = line(&mut s, [-5.0, -20.0], [-5.0, 20.0]);
|
||||
let m = line(&mut s, [5.0, -20.0], [5.0, 20.0]);
|
||||
s.execute("trim", &json!({ "handle": c.hex(), "pick": [0, 10], "edges": [l.hex(), m.hex()] })).unwrap();
|
||||
// The arc's handle, and whether it is AutoCAD's: radius 10 round (0, 0), from `start` to
|
||||
// `end` degrees (to 1e-9 radians, 0 and 360 alike).
|
||||
let arc_is = |s: &Session, start: f64, end: f64| {
|
||||
let objs = objects(s);
|
||||
let (h, k) = objs.iter().find(|o| matches!(o.1, EntityKind::Arc(_))).cloned().expect("an arc");
|
||||
let EntityKind::Arc(a) = k else { panic!("not an arc") };
|
||||
let same = |got: f64, want: f64| {
|
||||
let d = (got - want.to_radians()).rem_euclid(std::f64::consts::TAU);
|
||||
d < 1e-9 || std::f64::consts::TAU - d < 1e-9
|
||||
};
|
||||
let ok = (a.radius - 10.0).abs() < 1e-9 && a.center.x.abs() < 1e-9 && a.center.y.abs() < 1e-9 && same(a.start, start) && same(a.end, end);
|
||||
(h, ok)
|
||||
};
|
||||
assert_eq!(arc_is(&s, 120.0, 60.0), (c, true));
|
||||
// Broken from (10, 0) to (0, 10): the arc from 90 degrees round to 0.
|
||||
let mut s = Session::new();
|
||||
let c = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap());
|
||||
run(&mut s, "BREAK 10,0 0,10\n");
|
||||
assert_eq!(objects(&s).len(), 1);
|
||||
assert_eq!(arc_is(&s, 90.0, 0.0), (c, true));
|
||||
// Undo gives the circle back under its handle.
|
||||
s.undo().unwrap();
|
||||
let objs = objects(&s);
|
||||
assert!(objs.len() == 1 && objs[0].0 == c && matches!(objs[0].1, EntityKind::Circle(_)), "{objs:?}");
|
||||
}
|
||||
@@ -1,647 +0,0 @@
|
||||
//! BREAK on a closed polyline and TRIM of a polyline that is one of its own cutting edges, as
|
||||
//! AutoCAD 2024 does them (measured with accoreconsole on these drawings):
|
||||
//!
|
||||
//! - BREAK between two points of a closed polyline removes the stretch between them that doesn't
|
||||
//! run through its start vertex, whichever point comes first; BREAK or BREAKATPOINT at one point
|
||||
//! splits it there into two open polylines, and at its start vertex leaves it closed.
|
||||
//! - A polyline that is one of the cutting edges (picked, or with every object, in Standard or
|
||||
//! Quick mode) is also cut at its own vertices, where it crosses itself and where a vertex of it
|
||||
//! touches another of its segments. A piece whose ends meet there is left closed. A vertex
|
||||
//! between two line segments in line (within 1e-8, straight on or doubling back) doesn't cut it.
|
||||
//! - A pick within 5e-7 of one of the polyline's own cuts, whatever its size, trims nothing; a cut
|
||||
//! by another edge that near the pick is passed over. An edge through a closed polyline's start
|
||||
//! vertex cuts it there.
|
||||
//!
|
||||
//! Quick mode was measured in AutoCAD 2024 itself, picking on screen: its scripted TRIM runs
|
||||
//! Standard mode only.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
type Vertex = (f64, f64, f64);
|
||||
|
||||
fn handle(v: &Value) -> Handle {
|
||||
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn pline(s: &mut Session, vertices: Value, closed: bool) -> Handle {
|
||||
handle(&s.execute("pline", &json!({ "vertices": vertices, "closed": closed })).unwrap())
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
|
||||
handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap())
|
||||
}
|
||||
|
||||
/// Every polyline in model space in order: its handle, closed flag and vertices with bulges.
|
||||
fn polys(s: &Session) -> Vec<(Handle, bool, Vec<Vertex>)> {
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::LwPolyline(p) => Some((e.handle, p.closed, p.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect())),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn same(got: &[Vertex], want: &[Vertex]) -> bool {
|
||||
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9 && (g.2 - w.2).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// The polylines are `want` in order, (`kept`, closed, vertices): `kept` is whether it has the
|
||||
/// handle `h`.
|
||||
fn expect(s: &Session, h: Handle, want: &[(bool, bool, &[Vertex])]) {
|
||||
let got = polys(s);
|
||||
assert_eq!(got.len(), want.len(), "{got:?}");
|
||||
for ((gh, gc, gv), (kept, closed, wv)) in got.iter().zip(want) {
|
||||
assert_eq!((*gh == h, *gc), (*kept, *closed), "{got:?}");
|
||||
assert!(same(gv, wv), "{gv:?} != {wv:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, script: &str) {
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
}
|
||||
|
||||
// ---------------- BREAK on a closed polyline ----------------
|
||||
|
||||
#[test]
|
||||
fn break_removes_the_stretch_between_the_points_that_misses_the_start_vertex() {
|
||||
// 100 x 10 rectangle broken at (10, 0) and (10, 10): the 190-unit stretch between them goes,
|
||||
// the 20 units across the start vertex stay, with the points either way round.
|
||||
for script in ["BREAK 10,0 10,10\n", "BREAK 10,10 10,0\n"] {
|
||||
let mut s = Session::new();
|
||||
let r = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true);
|
||||
run(&mut s, script);
|
||||
expect(&s, r, &[(true, false, &[(10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_with_the_first_point_after_the_second_keeps_the_run_through_the_start() {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], { "p": [40, 0], "bulge": 0.5 }, [60, 0], [60, 30], [0, 30]]), true);
|
||||
run(&mut s, "BREAK 60,20 10,0\n");
|
||||
expect(&s, p, &[(true, false, &[(60.0, 20.0, 0.0), (60.0, 30.0, 0.0), (0.0, 30.0, 0.0), (0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]);
|
||||
}
|
||||
|
||||
const SQUARE: [[f64; 2]; 4] = [[250.0, 0.0], [270.0, 0.0], [270.0, 20.0], [250.0, 20.0]];
|
||||
|
||||
#[test]
|
||||
fn break_at_one_point_splits_a_closed_polyline_in_two() {
|
||||
let first: &[Vertex] = &[(250.0, 0.0, 0.0), (260.0, 0.0, 0.0)];
|
||||
let second: &[Vertex] = &[(260.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0), (250.0, 20.0, 0.0), (250.0, 0.0, 0.0)];
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!(SQUARE), true);
|
||||
run(&mut s, "BREAK 260,0 260,0\n");
|
||||
expect(&s, p, &[(true, false, first), (false, false, second)]);
|
||||
// BREAKATPOINT does the same.
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!(SQUARE), true);
|
||||
let r = s.execute("breakatpoint", &json!({ "handle": p.hex(), "at": [260, 0] })).unwrap();
|
||||
assert_eq!(r["handles"].as_array().unwrap().len(), 2);
|
||||
expect(&s, p, &[(true, false, first), (false, false, second)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_at_a_vertex_splits_there_and_at_the_start_vertex_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!(SQUARE), true);
|
||||
run(&mut s, "BREAK 270,20 270,20\n");
|
||||
expect(
|
||||
&s,
|
||||
p,
|
||||
&[
|
||||
(true, false, &[(250.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0)]),
|
||||
(false, false, &[(270.0, 20.0, 0.0), (250.0, 20.0, 0.0), (250.0, 0.0, 0.0)]),
|
||||
],
|
||||
);
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!(SQUARE), true);
|
||||
run(&mut s, "BREAK 250,0 250,0\n");
|
||||
expect(&s, p, &[(true, true, &[(250.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0), (250.0, 20.0, 0.0)])]);
|
||||
}
|
||||
|
||||
// ---------------- TRIM of a polyline that cuts itself ----------------
|
||||
|
||||
/// A polyline with an arc, and vertical lines at x = 20 and x = 60 crossing it.
|
||||
fn arc_polyline(s: &mut Session) -> (Handle, Handle, Handle) {
|
||||
let p = pline(s, json!([[0, 0], { "p": [40, 0], "bulge": 0.4 }, [70, 0], [90, 30]]), false);
|
||||
let b = line(s, [20.0, -10.0], [20.0, 40.0]);
|
||||
let c = line(s, [60.0, -20.0], [60.0, 40.0]);
|
||||
(p, b, c)
|
||||
}
|
||||
|
||||
/// The piece from the x = 60 cut on the arc to the end, as measured.
|
||||
const FROM_C: [Vertex; 3] = [(60.0, -5.417486860749438, 0.1330399827453447), (70.0, 0.0, 0.0), (90.0, 30.0, 0.0)];
|
||||
|
||||
fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edges: Option<&[Handle]>) {
|
||||
let mut p = json!({ "handle": h.hex(), "pick": pick });
|
||||
if let Some(es) = edges {
|
||||
p["edges"] = json!(es.iter().map(|e| e.hex()).collect::<Vec<_>>());
|
||||
}
|
||||
s.execute("trim", &p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_every_object_cutting_a_polyline_trims_to_its_own_vertex() {
|
||||
let mut s = Session::new();
|
||||
let (p, ..) = arc_polyline(&mut s);
|
||||
trim(&mut s, p, [55.0, -6.0], None);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edges_that_leave_the_polyline_out_cut_only_where_they_cross_it() {
|
||||
let mut s = Session::new();
|
||||
let (p, b, c) = arc_polyline(&mut s);
|
||||
trim(&mut s, p, [55.0, -6.0], Some(&[b, c]));
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (20.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_that_is_its_only_edge_loses_the_whole_segment_picked() {
|
||||
let mut s = Session::new();
|
||||
let (p, ..) = arc_polyline(&mut s);
|
||||
trim(&mut s, p, [55.0, -6.0], Some(&[p]));
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &[(70.0, 0.0, 0.0), (90.0, 30.0, 0.0)])]);
|
||||
// The first segment: one piece left, the polyline itself.
|
||||
let mut s = Session::new();
|
||||
let (p, ..) = arc_polyline(&mut s);
|
||||
trim(&mut s, p, [10.0, 0.0], Some(&[p]));
|
||||
expect(&s, p, &[(true, false, &[(40.0, 0.0, 0.4), (70.0, 0.0, 0.0), (90.0, 30.0, 0.0)])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_polyline_that_is_its_only_edge_opens_without_the_segment_picked() {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [40, 0], [40, 30], [0, 30]]), true);
|
||||
trim(&mut s, p, [20.0, 0.0], Some(&[p]));
|
||||
expect(&s, p, &[(true, false, &[(40.0, 0.0, 0.0), (40.0, 30.0, 0.0), (0.0, 30.0, 0.0), (0.0, 0.0, 0.0)])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_crossing_itself_is_cut_at_the_crossing() {
|
||||
let x = json!([[0, 0], [40, 20], [40, 0], [0, 20]]);
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, x.clone(), false);
|
||||
trim(&mut s, p, [10.0, 5.0], Some(&[p]));
|
||||
expect(&s, p, &[(true, false, &[(20.0, 10.0, 0.0), (40.0, 20.0, 0.0), (40.0, 0.0, 0.0), (0.0, 20.0, 0.0)])]);
|
||||
// Every object (the polyline alone): cut between the crossing and the next vertex.
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, x, false);
|
||||
trim(&mut s, p, [30.0, 15.0], None);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (20.0, 10.0, 0.0)]), (false, false, &[(40.0, 20.0, 0.0), (40.0, 0.0, 0.0), (0.0, 20.0, 0.0)])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_polyline_at_survey_coordinates_trims_to_its_own_vertex() {
|
||||
let mut s = Session::new();
|
||||
let p = pline(
|
||||
&mut s,
|
||||
json!([[612345.678, 2398765.432], { "p": [612385.678, 2398765.432], "bulge": 0.4 }, [612415.678, 2398765.432], [612415.678, 2398795.432], [612345.678, 2398795.432]]),
|
||||
true,
|
||||
);
|
||||
let b = line(&mut s, [612365.678, 2398755.432], [612365.678, 2398805.432]);
|
||||
let c = line(&mut s, [612405.678, 2398745.432], [612405.678, 2398805.432]);
|
||||
trim(&mut s, p, [612400.678, 2398759.432], Some(&[p, b, c]));
|
||||
let got = polys(&s);
|
||||
assert_eq!(got.len(), 1);
|
||||
let (h, closed, vs) = &got[0];
|
||||
assert!(*h == p && !closed);
|
||||
let want: [Vertex; 6] = [
|
||||
(612405.678, 2398760.014513139, 0.1330399827461127),
|
||||
(612415.678, 2398765.432, 0.0),
|
||||
(612415.678, 2398795.432, 0.0),
|
||||
(612345.678, 2398795.432, 0.0),
|
||||
(612345.678, 2398765.432, 0.0),
|
||||
(612385.678, 2398765.432, 0.0),
|
||||
];
|
||||
// Survey coordinates: a micrometre on the points, the bulge to 1e-9.
|
||||
assert_eq!(vs.len(), want.len());
|
||||
for (g, w) in vs.iter().zip(&want) {
|
||||
assert!((g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6 && (g.2 - w.2).abs() < 1e-9, "{g:?} != {w:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standard_mode_at_the_command_line_with_every_object_cuts_at_the_polyline_vertex() {
|
||||
let mut s = Session::new();
|
||||
let (p, ..) = arc_polyline(&mut s);
|
||||
// Mode Standard, Enter: every object is a cutting edge.
|
||||
run(&mut s, "TRIM O S\n\n55,-6\n\n");
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_picked_as_an_edge_in_quick_mode_cuts_itself_too() {
|
||||
// Quick mode with the edges given (its cuTting edges option): picked is picked.
|
||||
let mut s = Session::new();
|
||||
let (p, _, c) = arc_polyline(&mut s);
|
||||
s.execute("trim", &json!({ "handle": p.hex(), "pick": [55, -6], "mode": "quick", "edges": [p.hex(), c.hex()] })).unwrap();
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_mode_with_every_object_cuts_a_polyline_at_its_own_vertex_too() {
|
||||
// As Standard mode with every object: from the vertex at (40, 0), not from the line at x = 20.
|
||||
let mut s = Session::new();
|
||||
let (p, ..) = arc_polyline(&mut s);
|
||||
s.execute("trim", &json!({ "handle": p.hex(), "pick": [55, -6], "mode": "quick" })).unwrap();
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
|
||||
}
|
||||
|
||||
/// A rectangle, then an open polyline whose last vertex (6.9, 6.2) touches its second segment
|
||||
/// inside the rectangle (reversed: whose first vertex does). The polyline's handle.
|
||||
fn touching(s: &mut Session, reversed: bool) -> Handle {
|
||||
pline(s, json!([[3.9, 3.8], [8.3, 3.8], [8.3, 6.9], [3.9, 6.9]]), true);
|
||||
let mut v = vec![[2.3, 3.3], [5.3, 8.0], [8.5, 4.4], [8.8, 7.8], [6.9, 6.2]];
|
||||
if reversed {
|
||||
v.reverse();
|
||||
}
|
||||
pline(s, json!(v), false)
|
||||
}
|
||||
|
||||
const RECT: [Vertex; 4] = [(3.9, 3.8, 0.0), (8.3, 3.8, 0.0), (8.3, 6.9, 0.0), (3.9, 6.9, 0.0)];
|
||||
/// Where the second segment crosses the rectangle's top and right sides.
|
||||
const TOP: Vertex = (6.277777777777777, 6.9, 0.0);
|
||||
const RIGHT: Vertex = (8.3, 4.625, 0.0);
|
||||
|
||||
#[test]
|
||||
fn a_polyline_is_cut_where_its_end_touches_it() {
|
||||
let start: [Vertex; 3] = [(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), TOP];
|
||||
let looped: [Vertex; 3] = [(6.9, 6.2, 0.0), (8.5, 4.4, 0.0), (8.8, 7.8, 0.0)];
|
||||
// Picked above the touch, in the rectangle: cut from the top side to the touch. What is left
|
||||
// after it ends where it starts, so it is closed. Quick mode as picked on screen, and Standard
|
||||
// mode with every object at the command line.
|
||||
let mut s = Session::new();
|
||||
let p = touching(&mut s, false);
|
||||
s.execute("trim", &json!({ "handle": p.hex(), "pick": [6.58, 6.56], "mode": "quick" })).unwrap();
|
||||
expect(&s, p, &[(false, true, &RECT), (true, false, &start), (false, true, &looped)]);
|
||||
let mut s = Session::new();
|
||||
let p = touching(&mut s, false);
|
||||
run(&mut s, "TRIM O S\n\n6.58,6.56\n\n");
|
||||
expect(&s, p, &[(false, true, &RECT), (true, false, &start), (false, true, &looped)]);
|
||||
// Below the touch: cut from the touch to the right side.
|
||||
let mut s = Session::new();
|
||||
let p = touching(&mut s, false);
|
||||
trim(&mut s, p, [7.604, 5.408], None);
|
||||
let end: [Vertex; 4] = [RIGHT, (8.5, 4.4, 0.0), (8.8, 7.8, 0.0), (6.9, 6.2, 0.0)];
|
||||
expect(&s, p, &[(false, true, &RECT), (true, false, &[(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), (6.9, 6.2, 0.0)]), (false, false, &end)]);
|
||||
// The first vertex touching: the closed loop is the piece that keeps the handle.
|
||||
let mut s = Session::new();
|
||||
let p = touching(&mut s, true);
|
||||
trim(&mut s, p, [6.58, 6.56], None);
|
||||
expect(
|
||||
&s,
|
||||
p,
|
||||
&[
|
||||
(false, true, &RECT),
|
||||
(true, true, &[(6.9, 6.2, 0.0), (8.8, 7.8, 0.0), (8.5, 4.4, 0.0)]),
|
||||
(false, false, &[TOP, (5.3, 8.0, 0.0), (2.3, 3.3, 0.0)]),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_piece_keeps_its_arcs() {
|
||||
let mut s = Session::new();
|
||||
pline(&mut s, json!([[3.9, 3.8], [8.3, 3.8], [8.3, 6.9], [3.9, 6.9]]), true);
|
||||
let p = pline(&mut s, json!([[2.3, 3.3], [5.3, 8.0], { "p": [8.5, 4.4], "bulge": 0.3 }, [8.8, 7.8], [6.9, 6.2]]), false);
|
||||
trim(&mut s, p, [6.58, 6.56], None);
|
||||
let looped: [Vertex; 3] = [(6.9, 6.2, 0.0), (8.5, 4.4, 0.3), (8.8, 7.8, 0.0)];
|
||||
expect(&s, p, &[(false, true, &RECT), (true, false, &[(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), TOP]), (false, true, &looped)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_half_a_unit_from_a_vertex_1e9_out_trims_the_segment_it_is_on() {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [1e9, 0], [1e9, 10]]), false);
|
||||
trim(&mut s, p, [1e9, 0.5], None);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (1e9, 0.0, 0.0)])]);
|
||||
}
|
||||
|
||||
// ---------------- a pick on a cut ----------------
|
||||
|
||||
type Edge = ([f64; 2], [f64; 2]);
|
||||
|
||||
/// The polyline `v`, with lines `edges`, trimmed at `pick` with every object as an edge, or only
|
||||
/// the lines when `only_lines`; the polyline's handle and whether the trim was made.
|
||||
fn attempt(v: Value, closed: bool, edges: &[Edge], only_lines: bool, pick: [f64; 2]) -> (Session, Handle, bool) {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, v, closed);
|
||||
let ls: Vec<String> = edges.iter().map(|(a, b)| line(&mut s, *a, *b).hex()).collect();
|
||||
let mut params = json!({ "handle": p.hex(), "pick": pick });
|
||||
if only_lines {
|
||||
params["edges"] = json!(ls);
|
||||
}
|
||||
let made = s.execute("trim", ¶ms).is_ok();
|
||||
(s, p, made)
|
||||
}
|
||||
|
||||
/// [`attempt`] with at most one line, which must trim.
|
||||
fn trimmed(v: Value, closed: bool, edge: Option<Edge>, only_line: bool, pick: [f64; 2]) -> (Session, Handle) {
|
||||
let (s, p, made) = attempt(v, closed, edge.as_slice(), only_line, pick);
|
||||
assert!(made, "{pick:?}");
|
||||
(s, p)
|
||||
}
|
||||
|
||||
/// A vertical line through x = `x`.
|
||||
fn at(x: f64) -> Edge {
|
||||
([x, -5.0], [x, 5.0])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_on_a_cut_trims_nothing() {
|
||||
// The vertex (10, 0) is the only cut. A pick whose nearest point is within 5e-7 of it, on it
|
||||
// or off to the side, leaves the polyline as it was; one 6e-7 from it trims the segment it is
|
||||
// on.
|
||||
let v = || json!([[0, 0], [10, 0], [10, 10]]);
|
||||
let whole: [Vertex; 3] = [(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0)];
|
||||
for pick in [[10.0, 0.0], [10.0, 4e-7], [10.5, 4e-7], [9.99999999, 0.0]] {
|
||||
let (s, p) = trimmed(v(), false, None, false, pick);
|
||||
expect(&s, p, &[(true, false, &whole)]);
|
||||
}
|
||||
let (s, p) = trimmed(v(), false, None, false, [10.0, 6e-7]);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]);
|
||||
let (s, p) = trimmed(v(), false, None, false, [9.9999994, 0.0]);
|
||||
expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_on_a_cut_is_within_the_same_distance_at_any_size() {
|
||||
// A polyline a thousandth across, and one 1e9 long with a line through its vertex: 1e-7 from
|
||||
// the vertex is on the cut, 1e-6 off it.
|
||||
let small = || json!([[0, 0], [0.001, 0], [0.001, 0.001]]);
|
||||
let (s, p) = trimmed(small(), false, None, false, [0.001, 1e-7]);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (0.001, 0.0, 0.0), (0.001, 0.001, 0.0)])]);
|
||||
let (s, p) = trimmed(small(), false, None, false, [0.001, 1e-6]);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (0.001, 0.0, 0.0)])]);
|
||||
let long = || json!([[0, 0], [10, 0], [10, 1e9]]);
|
||||
let through = Some(([0.0, -10.0], [20.0, 10.0]));
|
||||
let (s, p) = trimmed(long(), false, through, false, [10.0, 1e-7]);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 1e9, 0.0)])]);
|
||||
let (s, p) = trimmed(long(), false, through, false, [10.0, 1e-6]);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_by_another_edge_at_the_pick_is_passed_over() {
|
||||
// A pick within 5e-7 of a cut by another edge runs the piece on across it, to the next cut
|
||||
// either side; 6e-7 away the cut holds.
|
||||
let flat = || json!([[0, 0], [10, 0]]);
|
||||
let piece = |a: f64, b: f64| [(a, 0.0, 0.0), (b, 0.0, 0.0)];
|
||||
for pick in [[3.0, 0.0], [3.0000004, 0.0]] {
|
||||
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(7.0)], true, pick);
|
||||
expect(&s, p, &[(true, false, &piece(7.0, 10.0))]);
|
||||
}
|
||||
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(7.0)], true, [3.0000006, 0.0]);
|
||||
expect(&s, p, &[(true, false, &piece(0.0, 3.0)), (false, false, &piece(7.0, 10.0))]);
|
||||
// Lines at 3, 5 and 7: picked on 5, 3 to 7 goes; picked on 7, 5 to the end.
|
||||
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(5.0), at(7.0)], true, [5.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &piece(0.0, 3.0)), (false, false, &piece(7.0, 10.0))]);
|
||||
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(5.0), at(7.0)], true, [7.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &piece(0.0, 5.0))]);
|
||||
// Every object an edge: on to the polyline's own vertex (10, 0).
|
||||
let (s, p, _) = attempt(json!([[0, 0], [10, 0], [10, 10]]), false, &[at(5.0)], false, [5.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
|
||||
// A closed rectangle cut at x = 30 and 70 top and bottom, picked on the bottom at 30: round
|
||||
// its start vertex, from 30 on the top to 70 on the bottom.
|
||||
let tall = |x: f64| ([x, -5.0], [x, 15.0]);
|
||||
let (s, p, _) = attempt(json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true, &[tall(30.0), tall(70.0)], true, [30.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &[(70.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (30.0, 10.0, 0.0)])]);
|
||||
// One line only, picked on its cut or 4e-7 past it: no cut is left, and nothing is trimmed.
|
||||
for pick in [[5.0, 0.0], [5.0000004, 0.0]] {
|
||||
let (s, p, made) = attempt(json!([[0, 0], [10, 0], [10, 10]]), false, &[at(5.0)], true, pick);
|
||||
assert!(!made);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
|
||||
}
|
||||
// In Quick mode too: the polyline meets the line, so it isn't erased as one no edge crosses.
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [10, 0]]), false);
|
||||
line(&mut s, [5.0, -5.0], [5.0, 5.0]);
|
||||
assert!(s.execute("trim", &json!({ "handle": p.hex(), "pick": [5, 0], "mode": "quick" })).is_err());
|
||||
expect(&s, p, &[(true, false, &piece(0.0, 10.0))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_on_a_vertex_an_edge_runs_through_trims_nothing() {
|
||||
// The line's cut is found on the segments either side of the vertex, a rounding apart. Both
|
||||
// are passed over, so no cut is left and the polyline stays as it was, not split there.
|
||||
let cases = [
|
||||
([[5.5, 1.1], [23.3, 7.7], [30.1, 29.9]], ([23.3, 7.7], [45.7, 2.3])),
|
||||
([[5.5, 1.1], [23.3, 7.7], [30.1, 29.9]], ([2.0 * 23.3 - 45.7, 2.0 * 7.7 - 2.3], [45.7, 2.3])),
|
||||
([[1.3, 2.7], [37.9, 11.3], [55.1, 48.7]], ([4.5, 43.5], [71.3, -20.9])),
|
||||
];
|
||||
for (v, edge) in cases {
|
||||
let (s, p, made) = attempt(json!(v), false, &[edge], true, v[1]);
|
||||
let whole: Vec<Vertex> = v.iter().map(|q| (q[0], q[1], 0.0)).collect();
|
||||
assert!(!made);
|
||||
expect(&s, p, &[(true, false, &whole)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edge_through_a_closed_polylines_start_vertex_cuts_it_there() {
|
||||
// The line cuts the rectangle at (0, 0) and at (10, 10) on its top. The pick takes the piece
|
||||
// it is on, whichever vertex the rectangle starts at. 4e-7 from (0, 0) that cut is passed
|
||||
// over, which leaves one, and the trim is refused.
|
||||
let rect = || json!([[0, 0], [100, 0], [100, 10], [0, 10]]);
|
||||
let edge = Some(([-5.0, -5.0], [15.0, 15.0]));
|
||||
let left: [Vertex; 3] = [(10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0)];
|
||||
let (s, p) = trimmed(rect(), true, edge, true, [50.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &left)]);
|
||||
let (s, p) = trimmed(json!([[50, 0], [100, 0], [100, 10], [0, 10], [0, 0]]), true, edge, true, [50.0, 10.0]);
|
||||
expect(&s, p, &[(true, false, &left)]);
|
||||
let (s, p) = trimmed(rect(), true, edge, true, [0.0, 5.0]);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (10.0, 10.0, 0.0)])]);
|
||||
let whole: [Vertex; 4] = [(0.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (0.0, 10.0, 0.0)];
|
||||
let (s, p, made) = attempt(rect(), true, edge.as_slice(), true, [0.0, 4e-7]);
|
||||
assert!(!made);
|
||||
expect(&s, p, &[(true, true, &whole)]);
|
||||
// The rectangle alone, picked on its start vertex, and 4e-7 from it on its last segment.
|
||||
for pick in [[0.0, 0.0], [0.0, 4e-7]] {
|
||||
let (s, p) = trimmed(rect(), true, None, false, pick);
|
||||
expect(&s, p, &[(true, true, &whole)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_polyline_cut_at_one_point_is_left_as_it_was() {
|
||||
// A line touching the rectangle only at its start vertex, and one crossing its bottom once and
|
||||
// ending inside: AutoCAD refuses either trim, and Quick mode doesn't erase the rectangle.
|
||||
for (a, b, pick) in [([-5.0, 5.0], [5.0, -5.0], [50.0, 0.0]), ([50.0, -5.0], [50.0, 5.0], [20.0, 0.0])] {
|
||||
for mode in ["standard", "quick"] {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true);
|
||||
let l = line(&mut s, a, b);
|
||||
let before = polys(&s);
|
||||
let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": pick, "edges": [l.hex()], "mode": mode }));
|
||||
assert!(r.is_err_and(|e| e.to_string() == "Curve must intersect cutting edges at least twice."), "{a:?} {mode}");
|
||||
assert_eq!(polys(&s), before, "{a:?} {mode}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- where a polyline runs straight on ----------------
|
||||
|
||||
#[test]
|
||||
fn a_vertex_the_polyline_runs_straight_on_through_doesnt_cut_it() {
|
||||
// (5, 0) lies between two segments in line: the pick takes everything back to the cut before
|
||||
// it, the start of the polyline or the closed polyline's start vertex.
|
||||
let v = || json!([[0, 0], [5, 0], [10, 0], [10, 10]]);
|
||||
let (s, p) = trimmed(v(), false, None, false, [7.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
|
||||
let (s, p) = trimmed(v(), true, None, false, [7.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (0.0, 0.0, 0.0)])]);
|
||||
// A crossing on the segment in line before the one picked bounds the piece, as does one on the
|
||||
// segment in line after it, and one right at the vertex in line.
|
||||
let (s, p) = trimmed(json!([[0, 0], [5, 0], [10, 0], [10, 10], [2, 10], [2, -5]]), false, None, false, [7.0, 0.0]);
|
||||
expect(
|
||||
&s,
|
||||
p,
|
||||
&[
|
||||
(true, false, &[(0.0, 0.0, 0.0), (2.0, 0.0, 0.0)]),
|
||||
(false, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (2.0, 10.0, 0.0), (2.0, -5.0, 0.0)]),
|
||||
],
|
||||
);
|
||||
let (s, p) = trimmed(json!([[0, 0], [5, 0], [10, 0], [10, 10], [8, 10], [8, -5]]), false, None, false, [3.5, 0.0]);
|
||||
expect(&s, p, &[(true, false, &[(8.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (8.0, 10.0, 0.0), (8.0, -5.0, 0.0)])]);
|
||||
let at_vertex = || json!([[0, 0], [5, 0], [10, 0], [10, 10], [5, 10], [5, -5]]);
|
||||
let rest: [Vertex; 4] = [(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (5.0, 10.0, 0.0), (5.0, -5.0, 0.0)];
|
||||
let (s, p) = trimmed(at_vertex(), false, None, false, [7.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (5.0, 0.0, 0.0)]), (false, false, &rest)]);
|
||||
let (s, p) = trimmed(at_vertex(), false, None, false, [3.0, 0.0]);
|
||||
expect(&s, p, &[(true, false, &[(5.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (5.0, 10.0, 0.0), (5.0, -5.0, 0.0)])]);
|
||||
// Straight on, or doubling back over itself: no cut at all.
|
||||
for (v, pick) in [(json!([[0, 0], [5, 0], [10, 0]]), [7.0, 0.0]), (json!([[0, 0], [10, 0], [5, 0]]), [2.0, 0.0])] {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, v, false);
|
||||
let before = polys(&s);
|
||||
assert!(s.execute("trim", &json!({ "handle": p.hex(), "pick": pick })).is_err());
|
||||
assert_eq!(polys(&s), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bend_of_1e_8_cuts_a_polyline_and_a_smaller_one_doesnt() {
|
||||
// The bend at (5, 0), as the sine of its angle, whatever the segments' lengths.
|
||||
for (end, pick, cuts) in [
|
||||
([10.0, 4e-8], [7.0, 0.0], false),
|
||||
([10.0, 6e-8], [7.0, 0.0], true),
|
||||
([5005.0, 1e-6], [700.0, 0.0], false),
|
||||
([5005.0, 0.01], [700.0, 0.0], true),
|
||||
] {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [5, 0], end]), false);
|
||||
let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": pick }));
|
||||
assert_eq!((r.is_ok(), polys(&s)[0].2.len()), if cuts { (true, 2) } else { (false, 3) }, "{end:?}");
|
||||
}
|
||||
// Two arcs of one circle, or a line and an arc on from it, cut where they meet.
|
||||
let q = 0.41421356237309503;
|
||||
let (s, p) = trimmed(json!([{ "p": [0, 0], "bulge": -q }, { "p": [5, 5], "bulge": -q }, [10, 0]]), false, None, false, [8.5355339, 3.5355339]);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, -q), (5.0, 5.0, 0.0)])]);
|
||||
let (s, p) = trimmed(json!([[0, 0], { "p": [5, 0], "bulge": q }, [10, 5]]), false, None, false, [8.5355339, 1.4644661]);
|
||||
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (5.0, 0.0, 0.0)])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_of_thousands_of_segments_is_cut_where_it_crosses_itself() {
|
||||
// 3,003 segments, the last crossing the first at (50, 0): the pick on the first takes it from
|
||||
// there to the vertex (100, 0), as with a few segments.
|
||||
let mut v = vec![json!([0, 0]), json!([100, 0]), json!([100, 20])];
|
||||
v.extend((1..=3000).map(|i| json!([100.0 - f64::from(i) / 60.0, 20.0 + f64::from(i % 2)])));
|
||||
v.push(json!([50, -10]));
|
||||
let (s, p) = trimmed(json!(v), false, None, false, [75.0, 0.0]);
|
||||
let got = polys(&s);
|
||||
assert_eq!(got.len(), 2, "{:?}", got.iter().map(|g| g.2.len()).collect::<Vec<_>>());
|
||||
assert!(got[0].0 == p && same(&got[0].2, &[(0.0, 0.0, 0.0), (50.0, 0.0, 0.0)]), "{:?}", got[0]);
|
||||
assert_eq!((got[1].2.len(), got[1].2.first().copied()), (3003, Some((100.0, 0.0, 0.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_too_long_to_search_for_its_own_crossings_is_left_as_it_was() {
|
||||
// 4,100 segments in line: the run picked times those near it is past the bound searched. 300
|
||||
// segments in line over the same stretch, back and forth, crossed by 300 more: 90,000
|
||||
// crossings, past the bound kept. The trim is refused, and Quick mode doesn't erase the
|
||||
// polyline as one no edge crosses.
|
||||
let mut back_and_forth: Vec<[f64; 2]> = (0..=300).map(|i| [if i % 2 == 0 { 0.0 } else { 10.0 }, 0.0]).collect();
|
||||
back_and_forth.extend((0..300).map(|i| [0.5 + f64::from(i) * 0.03, if i % 2 == 0 { 5.0 } else { -5.0 }]));
|
||||
for (v, why) in [(json!((0..=4100).map(|i| [i, 0]).collect::<Vec<_>>()), "Too many segments"), (json!(back_and_forth), "Too many crossings")] {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, v, false);
|
||||
let before = polys(&s);
|
||||
let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": [0.2, 0], "mode": "quick" }));
|
||||
assert!(r.is_err_and(|e| e.to_string().contains(why)), "{why}");
|
||||
assert_eq!(polys(&s), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_piece_whose_ends_only_come_near_stays_open_far_from_the_origin() {
|
||||
// 1e9 out, as survey coordinates in millimetres are: the piece left runs from the line's cut
|
||||
// to the polyline's end, 0.58 away, and stays open.
|
||||
let o = 1e9;
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[o + 2.3, 3.3], [o + 5.3, 8.0], [o + 8.5, 4.4], [o + 8.8, 7.8], [o + 7.4, 6.5]]), false);
|
||||
line(&mut s, [o + 6.9, 5.0], [o + 6.9, 7.0]);
|
||||
trim(&mut s, p, [o + 6.1, 7.1], None);
|
||||
let got = polys(&s);
|
||||
assert_eq!(got.len(), 2, "{got:?}");
|
||||
let (h, closed, vs) = &got[1];
|
||||
assert!(*h != p && !closed && vs.len() == 4, "{got:?}");
|
||||
let last = vs[3];
|
||||
assert!((last.0 - (o + 7.4)).abs() < 1e-6 && (last.1 - 6.5).abs() < 1e-6, "{last:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_is_cut_where_a_vertex_of_it_touches_it() {
|
||||
// The vertex (6, 6) lies on the first segment, which is cut there.
|
||||
let v = json!([[0, 0], [10, 10], [12, 4], [6, 6], [4, 12]]);
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, v.clone(), false);
|
||||
trim(&mut s, p, [3.0, 3.0], None);
|
||||
expect(&s, p, &[(true, false, &[(6.0, 6.0, 0.0), (10.0, 10.0, 0.0), (12.0, 4.0, 0.0), (6.0, 6.0, 0.0), (4.0, 12.0, 0.0)])]);
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, v, false);
|
||||
trim(&mut s, p, [8.0, 8.0], None);
|
||||
expect(
|
||||
&s,
|
||||
p,
|
||||
&[
|
||||
(true, false, &[(0.0, 0.0, 0.0), (6.0, 6.0, 0.0)]),
|
||||
(false, false, &[(10.0, 10.0, 0.0), (12.0, 4.0, 0.0), (6.0, 6.0, 0.0), (4.0, 12.0, 0.0)]),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_run_in_line_on_a_large_polyline_is_cut_where_it_is_crossed() {
|
||||
// 1,000 segments in line along y = 0, then 20,002 more, the last crossing the run at x = 500.25:
|
||||
// only the few segments near the run are searched, and the pick takes it from the crossing to
|
||||
// the corner (1000, 0).
|
||||
let mut v: Vec<Value> = (0..=1000).map(|i| json!([i, 0])).collect();
|
||||
v.push(json!([1000, 200]));
|
||||
v.extend((1..=20000).map(|i| json!([1000.0 - f64::from(i) * 499.75 / 20000.0, 200.0 + f64::from(i % 2)])));
|
||||
v.push(json!([500.25, -10]));
|
||||
let (s, p) = trimmed(json!(v), false, None, false, [999.5, 0.0]);
|
||||
let got = polys(&s);
|
||||
assert_eq!(got.len(), 2, "{:?}", got.iter().map(|g| g.2.len()).collect::<Vec<_>>());
|
||||
assert!(got[0].0 == p && got[0].2.len() == 502 && got[0].2.last() == Some(&(500.25, 0.0, 0.0)), "{:?}", got[0].2.last());
|
||||
assert_eq!((got[1].2.first().copied(), got[1].2.last().copied()), (Some((1000.0, 0.0, 0.0)), Some((500.25, -10.0, 0.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crossing_window_whose_nearest_point_is_a_vertex_trims_the_segment_it_ends() {
|
||||
// The window's first corner is nearest the vertex (10, 0), a cut of the polyline: the segment
|
||||
// before it goes, either way round the window, as in AutoCAD.
|
||||
for (a, b) in [([10.5, -0.5], [8.0, 2.0]), ([8.0, 2.0], [10.5, -0.5])] {
|
||||
let mut s = Session::new();
|
||||
let p = pline(&mut s, json!([[0, 0], [10, 0], [10, 10]]), false);
|
||||
s.execute("trim", &json!({ "crossing": [a, b], "mode": "standard" })).unwrap();
|
||||
expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
//! BREAKATPOINT at the command line and from a script, with AutoCAD 2024's prompts ("Select
|
||||
//! object:", then "Specify break point:"); BREAK and BREAKATPOINT end the command when a circle
|
||||
//! can't be broken at one point, and refuse an object on a locked layer when it is picked. Measured
|
||||
//! in AutoCAD 2024 (accoreconsole) on these drawings.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn handle(v: &Value) -> Handle {
|
||||
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The model space objects in order: handle and kind.
|
||||
fn objects(s: &Session) -> Vec<(Handle, EntityKind)> {
|
||||
s.doc().unwrap().model.iter().map(|e| (e.handle, e.kind.clone())).collect()
|
||||
}
|
||||
|
||||
fn line_ends(k: &EntityKind) -> ((f64, f64), (f64, f64)) {
|
||||
let EntityKind::Line(l) = k else { panic!("not a line: {k:?}") };
|
||||
((l.a.x, l.a.y), (l.b.x, l.b.y))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_asks_for_the_object_then_the_point_and_splits_the_line_there() {
|
||||
let mut s = Session::new();
|
||||
let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap());
|
||||
s.cmdline("BREAKATPOINT").unwrap();
|
||||
assert!(s.prompt_text().ends_with("Select object:"), "{}", s.prompt_text());
|
||||
s.cmdline("1002,0").unwrap();
|
||||
assert!(s.prompt_text().ends_with("Specify break point:"), "{}", s.prompt_text());
|
||||
// Off the line: the point projects onto it.
|
||||
s.cmdline("1005,3").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 2);
|
||||
assert_eq!(objs[0].0, l);
|
||||
assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1005.0, 0.0)));
|
||||
assert_eq!(line_ends(&objs[1].1), ((1005.0, 0.0), (1010.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_from_a_script_splits_an_arc_and_a_closed_polyline() {
|
||||
let mut s = Session::new();
|
||||
let a = handle(&s.execute("arc", &json!({ "center": [700, 0], "radius": 10, "start": 0, "end": 90 })).unwrap());
|
||||
let p = handle(&s.execute("pline", &json!({ "vertices": [[250, 0], [270, 0], [270, 20], [250, 20]], "closed": true })).unwrap());
|
||||
s.script("BREAKATPOINT 707.0710678,7.0710678 707.0710678,7.0710678\nBREAKATPOINT 260,0 260,0\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.iter().map(|o| o.0).take(2).collect::<Vec<_>>(), [a, p]);
|
||||
let EntityKind::Arc(arc) = &objs[0].1 else { panic!("not an arc") };
|
||||
assert!((arc.start - 0.0).abs() < 1e-9 && (arc.end.to_degrees() - 45.0).abs() < 1e-6, "{arc:?}");
|
||||
let EntityKind::Arc(rest) = &objs[2].1 else { panic!("not an arc") };
|
||||
assert!((rest.start.to_degrees() - 45.0).abs() < 1e-6 && (rest.end.to_degrees() - 90.0).abs() < 1e-9, "{rest:?}");
|
||||
let pts = |k: &EntityKind| match k {
|
||||
EntityKind::LwPolyline(l) => (l.closed, l.vertices.iter().map(|v| (v.p.x, v.p.y)).collect::<Vec<_>>()),
|
||||
k => panic!("not a polyline: {k:?}"),
|
||||
};
|
||||
assert_eq!(pts(&objs[1].1), (false, vec![(250.0, 0.0), (260.0, 0.0)]));
|
||||
assert_eq!(pts(&objs[3].1), (false, vec![(260.0, 0.0), (270.0, 0.0), (270.0, 20.0), (250.0, 20.0), (250.0, 0.0)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_and_break_at_one_point_of_a_circle_report_it_and_end() {
|
||||
for script in ["BREAKATPOINT 1300,10 1300,10\n", "BREAK 1300,10 1300,10\n"] {
|
||||
let mut s = Session::new();
|
||||
let c = handle(&s.execute("circle", &json!({ "center": [1300, 0], "radius": 10 })).unwrap());
|
||||
s.script(script).unwrap();
|
||||
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
|
||||
assert!(s.log.iter().any(|l| l == "Arc cannot be full 360 degrees"), "{script}: {:?}", s.log);
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 1);
|
||||
assert!(objs[0].0 == c && matches!(objs[0].1, EntityKind::Circle(_)), "{objs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_ends_breakatpoint_and_leaves_nothing_selected() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
s.script("BREAKATPOINT\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
// Enter at the break point after picking: the line is not left selected.
|
||||
s.script("BREAKATPOINT 5,0\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(s.selection().is_empty());
|
||||
assert_eq!(objects(&s).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_on_a_locked_layer_is_refused_when_picked() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
s.execute("layer.set", &json!({ "name": "0", "locked": true })).unwrap();
|
||||
for cmd in ["BREAKATPOINT", "BREAK"] {
|
||||
s.cmdline(cmd).unwrap();
|
||||
s.cmdline("5,0").unwrap();
|
||||
assert!(s.prompt_text().ends_with("Select object:"), "{cmd}: {}", s.prompt_text());
|
||||
assert!(s.log.iter().any(|l| l == "The object is on a locked layer."), "{cmd}: {:?}", s.log);
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none(), "{cmd}: {}", s.prompt_text());
|
||||
}
|
||||
assert_eq!(objects(&s).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_from_lisp_with_a_bare_entity_name() {
|
||||
let mut s = Session::new();
|
||||
let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap());
|
||||
s.cmdline("(command \"_.BREAKATPOINT\" (entlast) '(1004.0 0.0))").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 2);
|
||||
assert_eq!(objs[0].0, l);
|
||||
assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1004.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breakatpoint_from_lisp_with_an_entity_and_point() {
|
||||
let mut s = Session::new();
|
||||
let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap());
|
||||
s.cmdline("(command \"_.BREAKATPOINT\" (list (entlast) '(1005.0 0.0)) '(1005.0 0.0))").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let objs = objects(&s);
|
||||
assert_eq!(objs.len(), 2);
|
||||
assert_eq!(objs[0].0, l);
|
||||
assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1005.0, 0.0)));
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
//! The dimension shortcut menu's style commands: Remove Style Overrides clears the selected
|
||||
//! dimensions' overrides, and Save as New Style makes a style of a dimension's settings (its
|
||||
//! overrides included) and gives it to the dimension.
|
||||
|
||||
use cadcraft_engine::doc::{Dimension, EntityKind, Handle};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
fn dimension(s: &mut Session, y: f64) -> Handle {
|
||||
s.execute("dimlinear", &json!({ "p1": [0, y], "p2": [10, y], "at": [5, y + 3.0] })).unwrap();
|
||||
s.doc().unwrap().model.last().unwrap().handle
|
||||
}
|
||||
|
||||
fn dim(s: &Session, h: Handle) -> Dimension {
|
||||
match &s.doc().unwrap().entity(h).unwrap().kind {
|
||||
EntityKind::Dimension(d) => d.clone(),
|
||||
k => panic!("not a dimension: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_style_overrides_clears_the_selected_dimensions() {
|
||||
let mut s = Session::new();
|
||||
let (a, b) = (dimension(&mut s, 0.0), dimension(&mut s, 10.0));
|
||||
s.execute("properties.set", &json!({ "handles": [a.hex(), b.hex()], "textHeight": 0.3 })).unwrap();
|
||||
s.execute("dimoverride.clear", &json!({ "handles": [a.hex()] })).unwrap();
|
||||
assert!(dim(&s, a).overrides.is_empty() && !dim(&s, b).overrides.is_empty());
|
||||
// From the menu: the selected dimensions, in one undo step.
|
||||
s.set_selection(vec![b]);
|
||||
s.start("dimoverride.clear").unwrap();
|
||||
assert!(s.running.is_none() && dim(&s, b).overrides.is_empty());
|
||||
s.undo().unwrap();
|
||||
assert_eq!(dim(&s, b).overrides.get("textHeight"), Some(&json!(0.3)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_new_style_takes_the_dimensions_settings() {
|
||||
let mut s = Session::new();
|
||||
let h = dimension(&mut s, 0.0);
|
||||
s.execute("properties.set", &json!({ "handles": [h.hex()], "textHeight": 0.3, "DIMDEC": 2 })).unwrap();
|
||||
let r = s.execute("dimstyle.saveas", &json!({ "handle": h.hex(), "name": "Detail" })).unwrap();
|
||||
assert_eq!(r["style"], "Detail");
|
||||
let d = dim(&s, h);
|
||||
assert!(d.style == "Detail" && d.overrides.is_empty(), "{d:?}");
|
||||
let st = s.execute("dimstyle.list", &json!({ "name": "Detail" })).unwrap();
|
||||
assert_eq!((st["variables"]["DIMTXT"].as_f64(), st["variables"]["DIMDEC"].as_u64()), (Some(0.3), Some(2)));
|
||||
// The dimension looks the same, and the current style is still Standard.
|
||||
let g = cadcraft_engine::render::dimension_in(s.doc().unwrap(), &d);
|
||||
assert!((g.text_height - 0.3).abs() < 1e-12 && g.value == "10.00", "{} {}", g.text_height, g.value);
|
||||
assert_eq!(s.doc().unwrap().header.str("DIMSTYLE", "Standard"), "Standard");
|
||||
// A new name that a style can have (no `~`, which -DIMSTYLE Restore reads as compare).
|
||||
for name in ["detail", " ", "a<b", "~Plan"] {
|
||||
assert!(s.execute("dimstyle.saveas", &json!({ "handle": h.hex(), "name": name })).is_err(), "{name}");
|
||||
}
|
||||
// Only dimensions.
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap();
|
||||
let c = s.doc().unwrap().model.last().unwrap().handle;
|
||||
assert!(s.execute("dimstyle.saveas", &json!({ "handle": c.hex(), "name": "Other" })).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_new_style_from_the_menu_asks_for_a_name() {
|
||||
let mut s = Session::new();
|
||||
let h = dimension(&mut s, 0.0);
|
||||
s.execute("properties.set", &json!({ "handles": [h.hex()], "textHeight": 0.3 })).unwrap();
|
||||
s.set_selection(vec![h]);
|
||||
s.start("dimstyle.saveas").unwrap();
|
||||
assert!(s.prompt_text().contains("name of new dimension style"), "{}", s.prompt_text());
|
||||
// A name already taken is refused, said why, and asked again.
|
||||
let _ = s.input(Input::Text("Standard".into()));
|
||||
assert!(s.running.is_some(), "a taken name asks again");
|
||||
assert!(s.log.iter().any(|l| l.contains("already exists")), "{:?}", s.log);
|
||||
s.input(Input::Text("Detail".into())).unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(dim(&s, h).style, "Detail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_new_style_picks_a_dimension_when_none_is_selected() {
|
||||
let mut s = Session::new();
|
||||
let h = dimension(&mut s, 0.0);
|
||||
s.start("dimstyle.saveas").unwrap();
|
||||
assert!(s.prompt_text().contains("Select a dimension"), "{}", s.prompt_text());
|
||||
// The dimension line of the dimension.
|
||||
s.input(Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 3.0))).unwrap();
|
||||
s.input(Input::Text("Picked".into())).unwrap();
|
||||
assert_eq!(dim(&s, h).style, "Picked");
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
//! A negative DIMGAP draws a frame around the dimension text: SETVAR takes the negative value, a
|
||||
//! new dimension draws the frame, and EXPLODE turns it into four lines.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use serde_json::json;
|
||||
|
||||
/// Draw a linear dimension with DIMGAP `gap`, explode it, and return the number of lines the
|
||||
/// dimension drew and the number of LINEs EXPLODE left.
|
||||
fn explode_with_gap(gap: f64) -> (usize, usize) {
|
||||
let mut s = Session::new();
|
||||
s.execute("setvar", &json!({ "name": "DIMGAP", "value": gap })).unwrap();
|
||||
let r = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [30, 0], "at": [15, 5] })).unwrap();
|
||||
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let drawn = match &s.doc().unwrap().entity(h).unwrap().kind {
|
||||
EntityKind::Dimension(dm) => cadcraft_engine::render::dimension_in(s.doc().unwrap(), dm).lines.len(),
|
||||
k => panic!("not a dimension: {k:?}"),
|
||||
};
|
||||
s.execute("explode", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
let lines = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
|
||||
(drawn, lines)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_dimgap_frame_is_drawn_and_exploded() {
|
||||
let (plain_drawn, plain_lines) = explode_with_gap(0.09);
|
||||
let (drawn, lines) = explode_with_gap(-0.09);
|
||||
assert_eq!(drawn, plain_drawn + 4);
|
||||
assert_eq!(lines, plain_lines + 4);
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
//! -DIMSTYLE at the command line and as JSON (save, annotative, restore, status, variables,
|
||||
//! apply, list), and `dimstyle.overrides`, which sets the current style's overrides.
|
||||
|
||||
use cadcraft_engine::doc::{Dimension, EntityKind, Handle};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
fn dimension(s: &mut Session) -> Handle {
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
s.doc().unwrap().model.last().unwrap().handle
|
||||
}
|
||||
|
||||
fn dim(s: &Session, h: Handle) -> Dimension {
|
||||
match &s.doc().unwrap().entity(h).unwrap().kind {
|
||||
EntityKind::Dimension(d) => d.clone(),
|
||||
k => panic!("not a dimension: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn current(s: &Session) -> String {
|
||||
s.doc().unwrap().header.str("DIMSTYLE", "")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_restore_status_and_variables_as_json() {
|
||||
let mut s = Session::new();
|
||||
// A current-style override (SETVAR) goes into the saved style.
|
||||
s.execute("setvar", &json!({ "name": "DIMTXT", "value": 0.25 })).unwrap();
|
||||
let r = s.execute("-dimstyle", &json!({ "option": "save", "name": "Plan" })).unwrap();
|
||||
assert_eq!(r["style"], "Plan");
|
||||
assert_eq!(current(&s), "Plan");
|
||||
let d = s.doc().unwrap();
|
||||
assert!(d.dim_overrides().is_empty(), "saved into the style");
|
||||
assert_eq!(d.dim_style("Plan").unwrap().text_height, 0.25);
|
||||
// A name in use is redefined only when asked to.
|
||||
assert!(s.execute("-dimstyle", &json!({ "option": "save", "name": "plan" })).is_err());
|
||||
s.execute("-dimstyle", &json!({ "option": "save", "name": "plan", "replace": true })).unwrap();
|
||||
assert_eq!(s.doc().unwrap().dim_styles.iter().filter(|st| st.name.eq_ignore_ascii_case("plan")).count(), 1);
|
||||
s.execute("-dimstyle", &json!({ "option": "restore", "name": "standard" })).unwrap();
|
||||
assert_eq!(current(&s), "Standard");
|
||||
let status = s.execute("-dimstyle", &json!({ "option": "status" })).unwrap();
|
||||
assert_eq!(status["variables"]["DIMTXT"], 0.18);
|
||||
let vars = s.execute("-dimstyle", &json!({ "option": "variables", "name": "Plan" })).unwrap();
|
||||
assert_eq!(vars["variables"]["DIMTXT"], 0.25);
|
||||
s.execute("-dimstyle", &json!({ "option": "annotative", "name": "Anno" })).unwrap();
|
||||
assert!(s.doc().unwrap().dim_style("Anno").unwrap().annotative);
|
||||
let list = s.execute("-dimstyle", &json!({ "option": "list", "pattern": "p*" })).unwrap();
|
||||
assert_eq!(list["styles"], json!(["Plan"]));
|
||||
// A dimension's style becomes current; its variables include its overrides.
|
||||
let h = dimension(&mut s);
|
||||
s.execute("properties.set", &json!({ "handles": [h.hex()], "textHeight": 0.4 })).unwrap();
|
||||
let vars = s.execute("-dimstyle", &json!({ "option": "variables", "handle": h.hex() })).unwrap();
|
||||
assert_eq!(vars["variables"]["DIMTXT"], 0.4);
|
||||
s.execute("-dimstyle", &json!({ "option": "restore", "handle": h.hex() })).unwrap();
|
||||
assert_eq!(current(&s), "Anno");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_gives_dimensions_the_current_settings() {
|
||||
let mut s = Session::new();
|
||||
let h = dimension(&mut s);
|
||||
s.execute("dimstyle", &json!({ "name": "Plan", "DIMTXT": 0.3 })).unwrap();
|
||||
s.execute("setvar", &json!({ "name": "DIMDEC", "value": 1 })).unwrap();
|
||||
let r = s.execute("-dimstyle", &json!({ "option": "apply", "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(r["changed"], 1);
|
||||
let d = dim(&s, h);
|
||||
assert_eq!(d.style, "Plan");
|
||||
assert_eq!(d.overrides.get("decimals"), Some(&json!(1)));
|
||||
let g = cadcraft_engine::render::dimension_in(s.doc().unwrap(), &d);
|
||||
assert_eq!(g.value, "10.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_line_asks_like_autocad() {
|
||||
let mut s = Session::new();
|
||||
s.cmdline("-DIMSTYLE").unwrap();
|
||||
assert!(s.prompt_text().contains("ANnotative"), "{}", s.prompt_text());
|
||||
s.cmdline("S").unwrap();
|
||||
s.cmdline("Plan").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(current(&s), "Plan");
|
||||
s.cmdline("-DIMSTYLE").unwrap();
|
||||
s.cmdline("R").unwrap();
|
||||
s.cmdline("Standard").unwrap();
|
||||
assert_eq!(current(&s), "Standard");
|
||||
let before = s.log.len();
|
||||
s.cmdline("-DIMSTYLE").unwrap();
|
||||
s.cmdline("ST").unwrap();
|
||||
assert!(s.log[before..].iter().any(|l| l.starts_with("DIMTXT") && l.contains("Text height")), "{:?}", &s.log[before..]);
|
||||
// A name in use asks to redefine it.
|
||||
s.cmdline("-DIMSTYLE").unwrap();
|
||||
s.cmdline("S").unwrap();
|
||||
s.cmdline("Plan").unwrap();
|
||||
assert!(s.prompt_text().contains("redefine"), "{}", s.prompt_text());
|
||||
s.cmdline("Y").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
// Apply: the objects to give the current settings.
|
||||
s.cmdline("-DIMSTYLE").unwrap();
|
||||
s.cmdline("R").unwrap();
|
||||
s.cmdline("Standard").unwrap();
|
||||
let h = dimension(&mut s);
|
||||
s.execute("dimstyle.current", &json!({ "name": "Plan" })).unwrap();
|
||||
s.cmdline("-DIMSTYLE").unwrap();
|
||||
s.cmdline("A").unwrap();
|
||||
s.input(Input::Pick(vec![h])).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(dim(&s, h).style, "Plan");
|
||||
// ~name compares a style with the current settings.
|
||||
s.cmdline("-DIMSTYLE").unwrap();
|
||||
s.cmdline("R").unwrap();
|
||||
let before = s.log.len();
|
||||
s.cmdline("~Standard").unwrap();
|
||||
assert!(s.log[before..].iter().any(|l| l.contains("Differences")), "{:?}", &s.log[before..]);
|
||||
s.cancel();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn style_overrides_are_set_in_one_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimstyle.overrides", &json!({ "textHeight": 0.3, "DIMCLRT": 1 })).unwrap();
|
||||
let o = s.doc().unwrap().dim_overrides();
|
||||
assert_eq!(o.get("textHeight"), Some(&json!(0.3)));
|
||||
assert!(o.contains_key("textColor"), "{o:?}");
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc().unwrap().dim_overrides().is_empty(), "one undo step");
|
||||
// Unusable values change nothing; names that aren't variables are refused.
|
||||
assert!(s.execute("dimstyle.overrides", &json!({ "textHeight": -1, "DIMDEC": 2 })).is_err());
|
||||
assert!(s.execute("dimstyle.overrides", &json!({ "nope": 1 })).is_err());
|
||||
assert!(s.doc().unwrap().dim_overrides().is_empty());
|
||||
s.execute("dimstyle.overrides", &json!({ "DIMDEC": 2 })).unwrap();
|
||||
// Clear drops them only when every value is usable.
|
||||
assert!(s.execute("dimstyle.overrides", &json!({ "clear": true, "textHeight": -1 })).is_err());
|
||||
assert!(s.execute("dimstyle.overrides", &json!({ "clear": true, "nope": 1 })).is_err());
|
||||
assert_eq!(s.doc().unwrap().dim_overrides().get("decimals"), Some(&json!(2)));
|
||||
s.execute("dimstyle.overrides", &json!({ "clear": true, "textGap": 0.05 })).unwrap();
|
||||
let o = s.doc().unwrap().dim_overrides();
|
||||
assert_eq!((o.len(), o.get("textGap")), (1, Some(&json!(0.05))));
|
||||
s.execute("dimstyle.overrides", &json!({ "clear": true })).unwrap();
|
||||
assert!(s.doc().unwrap().dim_overrides().is_empty());
|
||||
// A lineweight by name goes in as the number the header variable holds.
|
||||
s.execute("dimstyle.overrides", &json!({ "clear": true, "DIMLWD": "bylayer" })).unwrap();
|
||||
assert_eq!(s.doc().unwrap().header.i64("DIMLWD", 0), -1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_calls_leave_no_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("-dimstyle", &json!({ "option": "save", "name": "Plan" })).unwrap();
|
||||
assert!(s.execute("-dimstyle", &json!({ "option": "save", "name": "plan" })).is_err());
|
||||
assert!(s.execute("-dimstyle", &json!({ "option": "restore", "name": "Nope" })).is_err());
|
||||
// Apply to objects none of which is a dimension changes nothing, and makes no step either.
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
let line = s.doc().unwrap().model.last().unwrap().handle.hex();
|
||||
assert_eq!(s.execute("-dimstyle", &json!({ "option": "apply", "handles": [line] })).unwrap()["changed"], 0);
|
||||
// The undo steps are the line and the save: none for the refused calls or that Apply.
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc().unwrap().dim_style("Plan").is_some(), "the first undo is the line's");
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc().unwrap().dim_style("Plan").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_and_renamed_styles_take_the_names_dimstyle_takes() {
|
||||
let mut s = Session::new();
|
||||
for name in ["~Plan", "a*b", "x?"] {
|
||||
assert!(s.execute("dimstyle", &json!({ "name": name })).is_err(), "{name}");
|
||||
}
|
||||
s.execute("dimstyle", &json!({ "name": "Plan", "current": false })).unwrap();
|
||||
assert!(s.execute("dimstyle.rename", &json!({ "from": "Plan", "to": "~Plan" })).is_err());
|
||||
s.execute("dimstyle.rename", &json!({ "from": "Plan", "to": "Site" })).unwrap();
|
||||
assert!(s.doc().unwrap().dim_style("Site").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_answer_asks_the_same_question() {
|
||||
let mut s = Session::new();
|
||||
s.cmdline("-DIMSTYLE").unwrap();
|
||||
s.cmdline("R").unwrap();
|
||||
// A style to compare with that doesn't exist.
|
||||
let _ = s.cmdline("~Nope");
|
||||
assert!(s.prompt_text().contains("Enter a dimension style name"), "{}", s.prompt_text());
|
||||
// Words at "Select dimension".
|
||||
s.cmdline("").unwrap();
|
||||
let _ = s.cmdline("Standard");
|
||||
assert!(s.prompt_text().contains("Select dimension"), "{}", s.prompt_text());
|
||||
s.cancel();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_with_many_stars_takes_no_time() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimstyle", &json!({ "name": "a".repeat(200), "current": false })).unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
for pattern in ["*".repeat(255) + "x", "*a".repeat(120) + "b"] {
|
||||
let r = s.execute("-dimstyle", &json!({ "option": "list", "pattern": pattern })).unwrap();
|
||||
assert_eq!(r["styles"], json!([]));
|
||||
}
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
let r = s.execute("-dimstyle", &json!({ "option": "list", "pattern": "a*a?" })).unwrap();
|
||||
assert_eq!(r["styles"], json!(["a".repeat(200)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_requests_never_panic() {
|
||||
let mut s = Session::new();
|
||||
let h = dimension(&mut s);
|
||||
for p in [
|
||||
json!({ "option": "save", "name": "" }),
|
||||
json!({ "option": "save", "name": "a*b" }),
|
||||
json!({ "option": "restore", "handle": "zz" }),
|
||||
json!({ "option": "variables", "handle": 1e300 }),
|
||||
json!({ "option": "apply", "handles": [h.hex(), "1", 5] }),
|
||||
json!({ "option": "list", "pattern": "*".repeat(100_000) }),
|
||||
json!({ "option": 5 }),
|
||||
] {
|
||||
let r = s.execute("-dimstyle", &p);
|
||||
assert!(!matches!(r, Err(cadcraft_engine::EngineError::Internal(..))), "{p}: {r:?}");
|
||||
}
|
||||
for p in [json!({ "DIMTXT": "x" }), json!({ "DIMBLK": [1] }), json!({ "DIMCLRT": { "a": 1 } }), json!({ "clear": "yes" })] {
|
||||
let r = s.execute("dimstyle.overrides", &p);
|
||||
assert!(!matches!(r, Err(cadcraft_engine::EngineError::Internal(..))), "{p}: {r:?}");
|
||||
}
|
||||
for line in ["-DIMSTYLE", "?", "", "-DIMSTYLE", "V", "", "-DIMSTYLE", "AN", "N", "?", "Bad/Name", "Good"] {
|
||||
let _ = s.cmdline(line);
|
||||
}
|
||||
s.cancel();
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
//! Which end of an open polyline EXTEND runs on, as AutoCAD 2024 chooses it (measured with
|
||||
//! accoreconsole on these drawings): the end on the pick's side of the polyline's middle parameter.
|
||||
//! The pick's parameter is the segment it is nearest, counted from 0, plus how far along that
|
||||
//! segment it is; from half the number of segments on, the last end extends, below it the first.
|
||||
//! Neither the end vertex nearer the pick nor the length along the polyline decides.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
type Vertex = (f64, f64, f64);
|
||||
|
||||
fn handle(v: &Value) -> String {
|
||||
v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
/// The open polyline `vertices` with lines `edges`, extended at `pick` to the lines; its vertices
|
||||
/// with their bulges.
|
||||
fn extended(vertices: &[Vertex], edges: &[([f64; 2], [f64; 2])], pick: [f64; 2]) -> Vec<Vertex> {
|
||||
let mut s = Session::new();
|
||||
let vs: Vec<Value> = vertices.iter().map(|(x, y, b)| json!({ "p": [x, y], "bulge": b })).collect();
|
||||
let p = handle(&s.execute("pline", &json!({ "vertices": vs, "closed": false })).unwrap());
|
||||
let es: Vec<String> = edges.iter().map(|(a, b)| handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap())).collect();
|
||||
s.execute("extend", &json!({ "handle": p, "pick": pick, "edges": es })).unwrap();
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(&p).unwrap()).unwrap().kind {
|
||||
EntityKind::LwPolyline(l) => l.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect(),
|
||||
k => panic!("{k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn same(got: &[Vertex], want: &[Vertex]) -> bool {
|
||||
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6 && (g.2 - w.2).abs() < 1e-6)
|
||||
}
|
||||
|
||||
/// Vertical lines through x = `xs`, from `y0` to `y1`.
|
||||
fn at(xs: &[f64], y0: f64, y1: f64) -> Vec<([f64; 2], [f64; 2])> {
|
||||
xs.iter().map(|x| ([*x, y0], [*x, y1])).collect()
|
||||
}
|
||||
|
||||
fn flat(pts: &[(f64, f64)]) -> Vec<Vertex> {
|
||||
pts.iter().map(|(x, y)| (*x, *y, 0.0)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_on_the_picks_side_of_the_middle_parameter_extends() {
|
||||
// (name, vertices, edges, pick, the vertices AutoCAD leaves). Lines at both ends, so either
|
||||
// end could extend.
|
||||
let cases: Vec<(&str, Vec<Vertex>, Vec<([f64; 2], [f64; 2])>, [f64; 2], Vec<(f64, f64)>)> = vec![
|
||||
// 1.2 of 3 segments: the first end, though the pick is on a vertex of the middle one.
|
||||
(
|
||||
"1.2 of 3",
|
||||
flat(&[(0.0, 160.0), (10.0, 160.0), (10.0, 165.0), (20.0, 165.0)]),
|
||||
at(&[-5.0, 25.0], 155.0, 170.0),
|
||||
[10.0, 161.0],
|
||||
vec![(-5.0, 160.0), (10.0, 160.0), (10.0, 165.0), (20.0, 165.0)],
|
||||
),
|
||||
// 0.8: the first end, though the last vertex is nearer the pick.
|
||||
(
|
||||
"0.8, last vertex nearer",
|
||||
flat(&[(0.0, 220.0), (20.0, 220.0), (20.0, 230.0), (15.0, 221.0)]),
|
||||
vec![([-5.0, 215.0], [-5.0, 235.0]), ([0.0, 210.0], [30.0, 210.0])],
|
||||
[16.0, 220.0],
|
||||
vec![(-5.0, 220.0), (20.0, 220.0), (20.0, 230.0), (15.0, 221.0)],
|
||||
),
|
||||
(
|
||||
"0.2",
|
||||
flat(&[(0.0, 240.0), (20.0, 240.0), (20.0, 250.0), (5.0, 241.0)]),
|
||||
vec![([-5.0, 235.0], [-5.0, 255.0]), ([-10.0, 230.0], [30.0, 230.0])],
|
||||
[4.0, 240.0],
|
||||
vec![(-5.0, 240.0), (20.0, 240.0), (20.0, 250.0), (5.0, 241.0)],
|
||||
),
|
||||
(
|
||||
"1.9",
|
||||
flat(&[(0.0, 260.0), (2.0, 260.0), (2.0, 280.0), (4.0, 280.0)]),
|
||||
at(&[-5.0, 10.0], 255.0, 285.0),
|
||||
[2.0, 278.0],
|
||||
vec![(0.0, 260.0), (2.0, 260.0), (2.0, 280.0), (10.0, 280.0)],
|
||||
),
|
||||
// 0.9: the first end, though 18 of the 22 units along is nearer the last.
|
||||
(
|
||||
"0.9, length nearer the last",
|
||||
flat(&[(0.0, 300.0), (20.0, 300.0), (20.0, 301.0), (21.0, 301.0)]),
|
||||
at(&[-5.0, 25.0], 295.0, 305.0),
|
||||
[18.0, 300.0],
|
||||
vec![(-5.0, 300.0), (20.0, 300.0), (20.0, 301.0), (21.0, 301.0)],
|
||||
),
|
||||
(
|
||||
"1.1",
|
||||
flat(&[(0.0, 320.0), (2.0, 320.0), (2.0, 340.0), (4.0, 340.0)]),
|
||||
at(&[-5.0, 10.0], 315.0, 345.0),
|
||||
[2.0, 322.0],
|
||||
vec![(-5.0, 320.0), (2.0, 320.0), (2.0, 340.0), (4.0, 340.0)],
|
||||
),
|
||||
(
|
||||
"1.25",
|
||||
flat(&[(0.0, 400.0), (30.0, 400.0), (30.0, 420.0), (31.0, 420.0)]),
|
||||
at(&[-5.0, 40.0], 395.0, 425.0),
|
||||
[30.0, 405.0],
|
||||
vec![(-5.0, 400.0), (30.0, 400.0), (30.0, 420.0), (31.0, 420.0)],
|
||||
),
|
||||
(
|
||||
"1.75",
|
||||
flat(&[(0.0, 440.0), (1.0, 440.0), (1.0, 460.0), (31.0, 460.0)]),
|
||||
at(&[-5.0, 40.0], 435.0, 465.0),
|
||||
[1.0, 455.0],
|
||||
vec![(0.0, 440.0), (1.0, 440.0), (1.0, 460.0), (40.0, 460.0)],
|
||||
),
|
||||
("0.6 of 1", flat(&[(0.0, 480.0), (20.0, 480.0)]), at(&[-5.0, 25.0], 475.0, 485.0), [12.0, 480.0], vec![(0.0, 480.0), (25.0, 480.0)]),
|
||||
// 1.8 of 4, the end of the segment picked: the first end.
|
||||
(
|
||||
"1.8 of 4",
|
||||
flat(&[(0.0, 500.0), (10.0, 500.0), (10.0, 510.0), (20.0, 510.0), (20.0, 520.0)]),
|
||||
vec![([-5.0, 495.0], [-5.0, 525.0]), ([15.0, 530.0], [25.0, 530.0])],
|
||||
[10.0, 508.0],
|
||||
vec![(-5.0, 500.0), (10.0, 500.0), (10.0, 510.0), (20.0, 510.0), (20.0, 520.0)],
|
||||
),
|
||||
(
|
||||
"2.8 of 4",
|
||||
flat(&[(0.0, 540.0), (10.0, 540.0), (10.0, 550.0), (20.0, 550.0), (20.0, 560.0)]),
|
||||
vec![([-5.0, 535.0], [-5.0, 565.0]), ([15.0, 570.0], [25.0, 570.0])],
|
||||
[18.0, 550.0],
|
||||
vec![(0.0, 540.0), (10.0, 540.0), (10.0, 550.0), (20.0, 550.0), (20.0, 570.0)],
|
||||
),
|
||||
// Right on the middle parameter, 1.5 of 3: the last end.
|
||||
(
|
||||
"1.5 of 3",
|
||||
flat(&[(0.0, 600.0), (10.0, 600.0), (10.0, 610.0), (20.0, 610.0)]),
|
||||
at(&[-5.0, 25.0], 595.0, 615.0),
|
||||
[10.0, 605.0],
|
||||
vec![(0.0, 600.0), (10.0, 600.0), (10.0, 610.0), (25.0, 610.0)],
|
||||
),
|
||||
];
|
||||
for (name, vertices, edges, pick, want) in cases {
|
||||
let got = extended(&vertices, &edges, pick);
|
||||
assert!(same(&got, &flat(&want)), "{name}: {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parameter_runs_along_an_arc_segment_too() {
|
||||
// The middle segment an arc of bulge -18, swinging round to within 2 of the first vertex:
|
||||
// picked 60% along it (1.6 of 3), 3.6 from the first vertex and 18.3 from the last, the last
|
||||
// end extends.
|
||||
let got = extended(
|
||||
&[(0.0, 0.0, 0.0), (10.0, 0.0, -18.0), (10.0, 1.0, 0.0), (20.0, 1.0, 0.0)],
|
||||
&at(&[-5.0, 25.0], -10.0, 10.0),
|
||||
[1.804081304825758, 3.0714821777453793],
|
||||
);
|
||||
assert!(same(&got, &[(0.0, 0.0, 0.0), (10.0, 0.0, -18.0), (10.0, 1.0, 0.0), (25.0, 1.0, 0.0)]), "{got:?}");
|
||||
// The end segment an arc of bulge -0.5: picked on it (1.6 of 2) the last end runs on round
|
||||
// its circle to x = 14.3; the same polyline turned round, picked on its first segment (0.4),
|
||||
// the first end does.
|
||||
let got = extended(&[(0.0, 40.0, 0.0), (10.0, 40.0, -0.5), (14.0, 40.0, 0.0)], &at(&[14.3], 30.0, 50.0), [12.0, 41.0]);
|
||||
assert!(same(&got, &[(0.0, 40.0, 0.0), (10.0, 40.0, -0.5776771824075506), (14.3, 39.47979589711327, 0.0)]), "{got:?}");
|
||||
let got = extended(&[(0.0, 60.0, -0.5), (4.0, 60.0, 0.0), (14.0, 60.0, 0.0)], &at(&[-0.3], 50.0, 70.0), [2.0, 61.0]);
|
||||
assert!(same(&got, &[(-0.3, 59.47979589711327, -0.5776771824075504), (4.0, 60.0, 0.0), (14.0, 60.0, 0.0)]), "{got:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_vertex_counts_as_a_segment() {
|
||||
// (10, 0) twice: three segments, the middle one of no length. Picked on (10, 0), the end of
|
||||
// the first, 1.0 of 3: the first end extends (counting two segments it would be the last).
|
||||
// Picked 1 up the last segment, 2.1 of 3: the last end.
|
||||
let vs = flat(&[(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 10.0)]);
|
||||
let edges = vec![([-5.0, -10.0], [-5.0, 10.0]), ([-10.0, 15.0], [20.0, 15.0])];
|
||||
let got = extended(&vs, &edges, [10.0, 0.0]);
|
||||
assert!(same(&got, &flat(&[(-5.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 10.0)])), "{got:?}");
|
||||
let got = extended(&vs, &edges, [10.0, 1.0]);
|
||||
assert!(same(&got, &flat(&[(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 15.0)])), "{got:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_a_hair_outside_an_arc_end_counts_as_that_end() {
|
||||
// A single semicircle from (1, 0) to (-1, 0). Picked 1e-13 outside its sweep at the first
|
||||
// vertex, the pick is on the arc's start, not round the circle at its end: the first end runs
|
||||
// on to x = 0, three quarters of the way round.
|
||||
let b = 1.0 + 2f64.sqrt();
|
||||
let got = extended(&[(1.0, 0.0, 1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], -2.0, -0.5), [1.0, -1e-13]);
|
||||
assert!(same(&got, &[(0.0, -1.0, b), (-1.0, 0.0, 0.0)]), "{got:?}");
|
||||
// A hair past its end is the last end.
|
||||
let got = extended(&[(1.0, 0.0, 1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], -2.0, -0.5), [-1.0, -1e-13]);
|
||||
assert!(same(&got, &[(1.0, 0.0, b), (0.0, -1.0, 0.0)]), "{got:?}");
|
||||
// Turning clockwise, the arc's start angle is the polyline's last vertex: a hair outside it is
|
||||
// the last end.
|
||||
let got = extended(&[(1.0, 0.0, -1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], 0.5, 2.0), [-1.0, 1e-13]);
|
||||
assert!(same(&got, &[(1.0, 0.0, -b), (0.0, 1.0, 0.0)]), "{got:?}");
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
//! A command or keyword typed with the Greek keyboard layout active (ΛΙΝΕ for LINE, ΘΝΔΟ for
|
||||
//! Undo) works as its Latin name: the layout types each Greek letter on the Latin key it sounds
|
||||
//! like.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use serde_json::json;
|
||||
|
||||
/// How many lines the drawing's model space holds.
|
||||
fn lines(s: &Session) -> usize {
|
||||
s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count()
|
||||
}
|
||||
|
||||
/// ΛΙΝΕ draws a line like LINE, in lower case and with accents too; `;ΣΑΩΕ` starts QSAVE; a
|
||||
/// Greek word that is no command's keys is reported as typed.
|
||||
#[test]
|
||||
fn greek_layout_commands_start_like_the_latin_ones() {
|
||||
let mut s = Session::new();
|
||||
s.script("ΛΙΝΕ 0,0 10,0\n\n").unwrap();
|
||||
assert_eq!(lines(&s), 1, "{}", s.prompt_text());
|
||||
// Accents the layout's dead key adds are ignored; lower case works too.
|
||||
s.script("λίνε 0,5 10,5\n\n").unwrap();
|
||||
assert_eq!(lines(&s), 2);
|
||||
// The Q key types a semicolon: QSAVE is ";ΣΑΩΕ", which only starts the command (no file needed
|
||||
// here: it reports, it never fails as an unknown command).
|
||||
let err = s.start(";ΣΑΩΕ").map(|_| String::new()).unwrap_or_else(|e| e.to_string());
|
||||
assert!(!err.contains("unknown command"), "{err}");
|
||||
// A Greek word that is no command's keys is reported as typed, not as the Latin letters read from it.
|
||||
let err = s.start("ΧΥΖ").unwrap_err().to_string();
|
||||
assert!(err.contains("ΧΥΖ") && !err.contains("xyz"), "{err}");
|
||||
}
|
||||
|
||||
/// A LISP command with a Greek name runs as itself, not as the command its keys type.
|
||||
#[test]
|
||||
fn a_greek_lisp_command_runs_as_itself_not_as_the_latin_keys_command() {
|
||||
let mut s = Session::new();
|
||||
// ΛΙΝΕ types LINE, but the routine defines a command of that Greek name: it is the command typed.
|
||||
s.cmdline("(defun c:ΛΙΝΕ () (command \"_.CIRCLE\" '(0 0) 5) (princ))").unwrap();
|
||||
s.cmdline("ΛΙΝΕ").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let doc = s.doc().unwrap();
|
||||
let circles = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
assert_eq!((circles, lines(&s)), (1, 0), "the routine drew the circle, LINE was not started");
|
||||
}
|
||||
|
||||
/// ΑΛΛ at "Select objects" selects everything, as ALL does.
|
||||
#[test]
|
||||
fn greek_layout_selection_words_select_like_the_latin_ones() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap();
|
||||
s.execute("circle", &json!({ "center": [20, 0], "radius": 5 })).unwrap();
|
||||
// ΑΛΛ is the keys A-L-L: ALL at the "Select objects" prompt.
|
||||
s.script(
|
||||
"ERASE ΑΛΛ
|
||||
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(s.doc().unwrap().model.is_empty(), "ΑΛΛ selected nothing");
|
||||
}
|
||||
|
||||
/// Ν and Υ answer MIRROR's "Erase source objects?" as N and Y do.
|
||||
#[test]
|
||||
fn greek_layout_keywords_match_prompt_options() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap();
|
||||
s.script("ΜΙΡΡΟΡ ALL\n\n0,0 10,0\n").unwrap();
|
||||
// ... the last prompt asks whether to delete the sources: N (Greek layout: Ν) keeps them. Text
|
||||
// the prompt does not know keeps them too, so what Ν is read as is checked itself.
|
||||
let no = s.current_prompt().and_then(|p| p.match_keyword("Ν"));
|
||||
assert_eq!(no.as_deref(), Some("No"), "{}", s.prompt_text());
|
||||
s.script("Ν\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
let circles = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
assert_eq!(circles, 2, "the circle and its mirror image");
|
||||
|
||||
// Υ (the Y key) answers Yes, which erases the source: unmatched Greek text would count as No, so
|
||||
// only a recognised keyword gives this result.
|
||||
let mut yes = Session::new();
|
||||
yes.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap();
|
||||
yes.script(
|
||||
"ΜΙΡΡΟΡ ALL
|
||||
|
||||
0,0 10,0
|
||||
Υ
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(yes.running.is_none(), "{}", yes.prompt_text());
|
||||
let circles = yes.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
assert_eq!(circles, 1, "Υ answered Yes and the source was erased");
|
||||
}
|
||||
|
||||
/// A Greek block name typed at BEDIT's "block name or select" opens that block: it is not read
|
||||
/// as a selection word.
|
||||
#[test]
|
||||
fn a_greek_block_name_typed_at_a_name_or_select_prompt_reaches_the_command_as_typed() {
|
||||
let mut s = Session::new();
|
||||
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
|
||||
s.execute("block", &json!({ "name": "ΠΟΡΤΑ", "base": [0, 0], "handles": [l] })).unwrap();
|
||||
// BEDIT asks for a block name or a selected reference. ΠΟΡΤΑ is also the keys P-O-R-T-A, which a
|
||||
// selection word would be read from, but no selection word is meant here: the name is typed as it is.
|
||||
s.start("BEDIT").unwrap();
|
||||
s.cmdline("ΠΟΡΤΑ").unwrap();
|
||||
let open = s.state().unwrap().block_editor().map(str::to_string);
|
||||
assert_eq!(open.as_deref(), Some("ΠΟΡΤΑ"), "{}", s.prompt_text());
|
||||
}
|
||||
|
||||
/// Μ is the M key, Multiple at a selection prompt; once a block has that name, typing it at
|
||||
/// BEDIT opens the block.
|
||||
#[test]
|
||||
fn a_block_named_like_a_greek_selection_word_opens_at_a_name_or_select_prompt() {
|
||||
// The Greek capital Mu (U+039C) is the M key: Multiple at a selection prompt.
|
||||
let mu = "\u{39c}";
|
||||
let mut s = Session::new();
|
||||
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
|
||||
// With no block of that name it stays the selection word, which BEDIT's prompt waits through.
|
||||
s.start("BEDIT").unwrap();
|
||||
s.cmdline(mu).unwrap();
|
||||
assert!(s.running.is_some(), "Multiple keeps the prompt: {}", s.prompt_text());
|
||||
assert!(s.state().unwrap().block_editor().is_none());
|
||||
s.cancel();
|
||||
// Once a block has that name, typing it opens that block.
|
||||
s.execute("block", &json!({ "name": mu, "base": [0, 0], "handles": [l] })).unwrap();
|
||||
s.start("BEDIT").unwrap();
|
||||
s.cmdline(mu).unwrap();
|
||||
let open = s.state().unwrap().block_editor().map(str::to_string);
|
||||
assert_eq!(open.as_deref(), Some(mu), "{}", s.prompt_text());
|
||||
}
|
||||
|
||||
/// ΣΟΛΙΔ is the keys of Solid at HATCH's pattern prompt; once a loaded pattern has that name,
|
||||
/// typing it in any case or accent chooses that pattern.
|
||||
#[test]
|
||||
fn a_loaded_pattern_named_like_the_greek_keys_of_solid_is_that_pattern_at_the_pattern_prompt() {
|
||||
// ΣΟΛΙΔ is the keys S-O-L-I-D: Solid at HATCH's pattern prompt, which takes no scale or angle.
|
||||
let mut s = Session::new();
|
||||
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap();
|
||||
s.start("hatch").unwrap();
|
||||
s.input(cadcraft_engine::Input::Keyword("Pattern".into())).unwrap();
|
||||
s.cmdline("ΣΟΛΙΔ").unwrap();
|
||||
assert!(!s.prompt_text().contains("scale"), "Solid: {}", s.prompt_text());
|
||||
s.cancel();
|
||||
// A pattern file that defines a pattern of that name: typing the name chooses that pattern, which asks its scale.
|
||||
s.execute("hatch.patterns", &json!({ "text": "*ΣΟΛΙΔ, test\n0,0,0,0,1\n" })).unwrap();
|
||||
let asked = ["ΣΟΛΙΔ", "σολιδ", "σολίδ"].map(|typed| {
|
||||
s.start("hatch").unwrap();
|
||||
s.input(cadcraft_engine::Input::Keyword("Pattern".into())).unwrap();
|
||||
s.cmdline(typed).unwrap();
|
||||
let asked = s.prompt_text();
|
||||
s.cancel();
|
||||
asked
|
||||
});
|
||||
s.execute("hatch.patterns", &json!({ "clear": true })).unwrap();
|
||||
assert!(asked.iter().all(|a| a.contains("scale")), "the loaded pattern, in any spelling: {asked:?}");
|
||||
}
|
||||
|
||||
/// A LISP command with a Greek name runs when typed in upper case, lower case or with an accent.
|
||||
#[test]
|
||||
fn a_greek_lisp_command_runs_in_any_case_or_accent() {
|
||||
for typed in ["ΛΙΝΕ", "λινε", "λίνε"] {
|
||||
let mut s = Session::new();
|
||||
s.cmdline("(defun c:ΛΙΝΕ () (command \"_.CIRCLE\" '(0 0) 5) (princ))").unwrap();
|
||||
s.cmdline(typed).unwrap();
|
||||
let circles = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
|
||||
assert_eq!((circles, lines(&s)), (1, 0), "{typed}: {}", s.prompt_text());
|
||||
}
|
||||
}
|
||||
|
||||
/// A block called Μ opens at BEDIT when its name is typed in either case.
|
||||
#[test]
|
||||
fn a_block_opens_in_any_case_or_accent_at_a_prompt_that_also_takes_a_selection() {
|
||||
for typed in ["\u{39c}", "\u{3bc}"] {
|
||||
let mut s = Session::new();
|
||||
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
|
||||
s.execute("block", &json!({ "name": "\u{39c}", "base": [0, 0], "handles": [l] })).unwrap();
|
||||
s.start("BEDIT").unwrap();
|
||||
s.cmdline(typed).unwrap();
|
||||
let open = s.state().unwrap().block_editor().map(str::to_string);
|
||||
assert_eq!(open.as_deref(), Some("\u{39c}"), "{typed}: {}", s.prompt_text());
|
||||
}
|
||||
}
|
||||
|
||||
/// Σ is the S key, Select at BLOCKREPLACE; once a block has that name, typing it in either case
|
||||
/// names the block.
|
||||
#[test]
|
||||
fn a_block_named_like_the_keys_of_select_is_that_block_at_blockreplace() {
|
||||
let mut s = Session::new();
|
||||
// Σ is the S key: the Select option of BLOCKREPLACE, while no block has that name.
|
||||
s.start("BLOCKREPLACE").unwrap();
|
||||
s.cmdline("Σ").unwrap();
|
||||
assert!(s.prompt_text().contains("Select a block reference"), "{}", s.prompt_text());
|
||||
s.cancel();
|
||||
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
|
||||
s.execute("block", &json!({ "name": "Σ", "base": [0, 0], "handles": [l] })).unwrap();
|
||||
s.execute("insert", &json!({ "name": "Σ", "at": [0, 0] })).unwrap();
|
||||
for typed in ["Σ", "σ"] {
|
||||
s.start("BLOCKREPLACE").unwrap();
|
||||
s.cmdline(typed).unwrap();
|
||||
let asked = s.prompt_text();
|
||||
s.cancel();
|
||||
assert!(asked.contains("replacement block for Σ"), "{typed}: {asked}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Λ is the L key. At COUNT's "Select object to count or [List/Spaces]" the Latin L is the selection
|
||||
/// word Last, not the List option: the Greek key is read the same way, and so is the whole word.
|
||||
#[test]
|
||||
fn a_greek_selection_word_wins_over_a_keyword_on_the_same_key() {
|
||||
let answer = |typed: &str| {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap();
|
||||
s.start("COUNT").unwrap();
|
||||
let from = s.log.len();
|
||||
s.cmdline(typed).unwrap();
|
||||
s.log[from..].join("\n")
|
||||
};
|
||||
let last = answer("L");
|
||||
assert!(last.contains("like the selected one"), "L counts the objects like the last one: {last}");
|
||||
assert_ne!(last, answer("List"));
|
||||
for typed in ["Λ", "λ", "ΛΑΣΤ"] {
|
||||
assert_eq!(answer(typed), last, "{typed}");
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
//! Enter or Space at INSERT's insertion point prompt asks again, as in AutoCAD 2027; Escape ends
|
||||
//! the command (the Blocks palette's Repeat Placement stops this way).
|
||||
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn enter_at_the_insertion_point_asks_again() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
|
||||
s.execute("block", &json!({"name": "A", "base": [0, 0], "handles": hs, "keep": "delete"})).unwrap();
|
||||
|
||||
s.start("insert").unwrap();
|
||||
s.input(Input::Text("A".into())).unwrap();
|
||||
assert!(s.prompt_text().starts_with("INSERT Specify insertion point"), "{}", s.prompt_text());
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.prompt_text().starts_with("INSERT Specify insertion point"), "{}", s.prompt_text());
|
||||
s.input(Input::Cancel).unwrap();
|
||||
assert_eq!(s.prompt_text(), "Command:");
|
||||
assert_eq!(s.doc().unwrap().model.iter().count(), 0, "nothing is placed");
|
||||
assert_eq!(s.last_finished, None, "ending it this way is cancelling it");
|
||||
}
|
||||
|
||||
/// A cancelled INSERT leaves the drawing as it was: it takes no undo step, or the next undo would
|
||||
/// seem to do nothing (Repeat Placement always ends this way). A placed block keeps its name.
|
||||
#[test]
|
||||
fn a_cancelled_insert_takes_no_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
|
||||
s.execute("block", &json!({"name": "A", "base": [0, 0], "handles": hs, "keep": "delete"})).unwrap();
|
||||
let steps = s.state().unwrap().undo.len();
|
||||
|
||||
s.start("insert").unwrap();
|
||||
s.input(Input::Text("A".into())).unwrap();
|
||||
s.input(Input::Cancel).unwrap();
|
||||
assert_eq!(s.state().unwrap().undo.len(), steps);
|
||||
assert_eq!(s.doc().unwrap().header.str("INSNAME", ""), "");
|
||||
|
||||
s.start("insert").unwrap();
|
||||
s.input(Input::Text("A".into())).unwrap();
|
||||
s.input(Input::Keyword("Scale".into())).unwrap();
|
||||
s.input(Input::Text("1".into())).unwrap();
|
||||
s.input(Input::Keyword("Rotate".into())).unwrap();
|
||||
s.input(Input::Text("0".into())).unwrap();
|
||||
s.input(Input::Point(Vec2::new(1.0, 1.0))).unwrap();
|
||||
assert_eq!(s.state().unwrap().undo.len(), steps + 1);
|
||||
assert_eq!(s.doc().unwrap().header.str("INSNAME", ""), "A");
|
||||
}
|
||||
|
||||
/// How the last command ended: by itself, with what it added; a cancelled one changes nothing.
|
||||
#[test]
|
||||
fn the_last_finished_command_says_whether_it_added_objects() {
|
||||
let mut s = Session::new();
|
||||
s.start("line").unwrap();
|
||||
s.input(Input::Point(Vec2::new(0.0, 0.0))).unwrap();
|
||||
s.input(Input::Point(Vec2::new(1.0, 1.0))).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let line = (s.commands_started, true);
|
||||
assert_eq!(s.last_finished, Some(line));
|
||||
s.start("circle").unwrap();
|
||||
s.input(Input::Cancel).unwrap();
|
||||
assert_eq!(s.last_finished, Some(line));
|
||||
}
|
||||
|
||||
/// A transparent command runs inside the current one: it does not count as a new command.
|
||||
#[test]
|
||||
fn only_a_command_of_its_own_counts_as_started() {
|
||||
let mut s = Session::new();
|
||||
s.start("line").unwrap();
|
||||
let started = s.commands_started;
|
||||
s.start("'zoom").unwrap();
|
||||
assert_eq!(s.commands_started, started);
|
||||
s.start("circle").unwrap();
|
||||
assert_eq!(s.commands_started, started + 1);
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{EntityCodec, set_entity_codec, set_object_records};
|
||||
use cadcraft_engine::cmd::file::{EntityCodec, set_entity_codec};
|
||||
use cadcraft_engine::doc::Entity;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -220,8 +220,6 @@ fn run_case(dir: &Path) -> Result<(), String> {
|
||||
#[test]
|
||||
fn autolisp_corpus() {
|
||||
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
set_object_records(cadcraft_io::object_records);
|
||||
let Some(dir) = cases_dir() else {
|
||||
eprintln!("CADCRAFT_LISP_CORPUS is not set: the AutoLISP corpus is skipped");
|
||||
return;
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
//! LISP `findfile` finds folders as well as files (#2985): routines test whether an optional
|
||||
//! module is installed with `(findfile "module/.")`.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
#[path = "../support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
|
||||
/// `(findfile name)` as LISP prints it.
|
||||
fn findfile(name: &str) -> String {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("lisp", &json!({ "code": format!("(findfile \"{name}\")") })).unwrap();
|
||||
r["value"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findfile_finds_a_folder_with_and_without_a_trailing_dot() {
|
||||
let dir = TempDir::new("findfile-folder");
|
||||
std::fs::create_dir_all(dir.join("module")).unwrap();
|
||||
// Forward slashes, so the name needs no escaping in the LISP string on Windows.
|
||||
let folder = dir.join("module").to_string_lossy().replace('\\', "/");
|
||||
assert_eq!(findfile(&folder), format!("\"{folder}\""));
|
||||
assert_eq!(findfile(&format!("{folder}/.")), format!("\"{folder}/.\""));
|
||||
// A folder that isn't there is still nil.
|
||||
assert_eq!(findfile(&format!("{folder}-missing")), "nil");
|
||||
assert_eq!(findfile(&format!("{folder}-missing/.")), "nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findfile_still_finds_a_file() {
|
||||
let dir = TempDir::new("findfile-file");
|
||||
let file = dir.file("routine.lsp", "(princ)").replace('\\', "/");
|
||||
assert_eq!(findfile(&file), format!("\"{file}\""));
|
||||
}
|
||||
@@ -17,12 +17,9 @@ mod block_keep;
|
||||
mod block_redefine;
|
||||
mod blockreplace;
|
||||
mod break_closed_polyline;
|
||||
mod break_ends_and_closing_side;
|
||||
mod break_join_locked_layers;
|
||||
mod break_keeps_z;
|
||||
mod break_trim_keep_handle;
|
||||
mod break_trim_polyline_rules;
|
||||
mod breakatpoint_command_line;
|
||||
mod burst;
|
||||
mod change_command;
|
||||
mod chprop_command;
|
||||
@@ -42,10 +39,7 @@ mod dim_explode_text;
|
||||
mod dim_properties;
|
||||
mod dim_radial_inside;
|
||||
mod dim_radial_outside;
|
||||
mod dim_style_menu;
|
||||
mod dim_text_frame;
|
||||
mod dim_vars;
|
||||
mod dimstyle_cli;
|
||||
mod dimtedit_prompts;
|
||||
mod drafting_spacing;
|
||||
mod draw_prompts;
|
||||
@@ -55,11 +49,9 @@ mod dynamic_block_data;
|
||||
mod dynamic_grips;
|
||||
mod explode_stretched;
|
||||
mod extend_polyline_arc_end;
|
||||
mod extend_polyline_end_choice;
|
||||
mod fillet_chamfer;
|
||||
mod fix_holds_grips;
|
||||
mod followups_626;
|
||||
mod greek_keyboard;
|
||||
mod grip_dim_input;
|
||||
mod grip_options;
|
||||
mod grip_selection;
|
||||
@@ -75,7 +67,6 @@ mod inquiry_keywords;
|
||||
mod inquiry_variables;
|
||||
mod inquiry_z;
|
||||
mod insert_attribute_prompts;
|
||||
mod insert_enter;
|
||||
mod insert_prompts;
|
||||
mod isometric;
|
||||
mod join_close;
|
||||
@@ -87,7 +78,6 @@ mod layout_prompts;
|
||||
mod leader_command;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod lisp_corpus;
|
||||
mod lisp_findfile;
|
||||
mod lisp_undo_in_routine;
|
||||
mod malformed_handles;
|
||||
mod matchprop;
|
||||
@@ -125,9 +115,7 @@ mod polyface_explode;
|
||||
mod post_command_passes;
|
||||
mod prompt_keywords;
|
||||
mod prompt_or_once;
|
||||
mod properties_describe;
|
||||
mod properties_set_locked;
|
||||
mod properties_set_text_dims;
|
||||
mod props_bad_lineweight;
|
||||
mod props_insert_scale_attribs;
|
||||
mod purge_mlinestyles;
|
||||
@@ -174,15 +162,10 @@ mod text_left_justify;
|
||||
mod tolerance;
|
||||
mod transparent;
|
||||
mod trim_closed_polyline;
|
||||
mod trim_cut_at_the_pick;
|
||||
mod trim_cut_where_an_arc_span_starts;
|
||||
mod trim_extend_json_pick;
|
||||
mod trim_extend_options;
|
||||
mod trim_keeps_z_and_width;
|
||||
mod undo_count;
|
||||
mod undo_layout_tab;
|
||||
mod viewport_clip;
|
||||
mod viewport_frozen_selection;
|
||||
mod vplayer_prompts;
|
||||
mod vports;
|
||||
mod wipeout_grips;
|
||||
|
||||
@@ -1,228 +0,0 @@
|
||||
//! `properties.describe`: the Properties palette's rows for text, mtext and dimensions, with
|
||||
//! shared values, *VARIES*, units, and the reason a dimension's text height can't be edited.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn handle(r: &Value) -> String {
|
||||
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string()
|
||||
}
|
||||
|
||||
fn last(s: &Session) -> String {
|
||||
s.doc().unwrap().model.last().unwrap().handle.hex()
|
||||
}
|
||||
|
||||
fn describe(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("properties.describe", &p).unwrap()
|
||||
}
|
||||
|
||||
/// The row `key` in group `group`.
|
||||
fn row<'a>(desc: &'a Value, group: &str, key: &str) -> &'a Value {
|
||||
let g = desc["groups"].as_array().unwrap().iter().find(|g| g["name"] == group).unwrap_or_else(|| panic!("no group {group}: {desc}"));
|
||||
g["rows"].as_array().unwrap().iter().find(|r| r["key"] == key).unwrap_or_else(|| panic!("no row {key} in {group}: {g}"))
|
||||
}
|
||||
|
||||
fn group_names(desc: &Value) -> Vec<String> {
|
||||
desc["groups"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_rows_share_values_and_vary() {
|
||||
let mut s = Session::new();
|
||||
let a = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 2.5 })).unwrap());
|
||||
let b = handle(&s.execute("text", &json!({ "at": [0, 5], "text": "B", "height": 1, "justify": "MC" })).unwrap());
|
||||
let one = describe(&mut s, json!({ "handles": [a] }));
|
||||
assert_eq!(group_names(&one), ["General", "Text", "Geometry"]);
|
||||
let h = row(&one, "Text", "height");
|
||||
assert_eq!((h["value"].as_f64(), h["display"].as_str(), h["kind"].as_str()), (Some(2.5), Some("2.5000"), Some("distance")));
|
||||
assert_eq!(row(&one, "Text", "justify")["display"], "Left");
|
||||
assert_eq!(row(&one, "Text", "style")["value"], "Standard");
|
||||
assert!(row(&one, "Text", "style")["options"].as_array().unwrap().iter().any(|o| o["value"] == "Standard"));
|
||||
assert_eq!(row(&one, "Text", "text")["value"], "A");
|
||||
|
||||
let both = describe(&mut s, json!({ "handles": [a, b] }));
|
||||
assert_eq!(both["count"], 2);
|
||||
let h = row(&both, "Text", "height");
|
||||
assert_eq!((h["varies"].as_bool(), h["display"].as_str(), h["value"].is_null()), (Some(true), Some("*VARIES*"), true));
|
||||
// Both are rotated 0 and in the same style.
|
||||
assert_eq!(row(&both, "Text", "rotation")["varies"], false);
|
||||
assert_eq!(row(&both, "Text", "style")["display"], "Standard");
|
||||
assert_eq!(row(&both, "Text", "justify")["varies"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_selections_show_general_rows_unless_filtered() {
|
||||
let mut s = Session::new();
|
||||
let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 1 })).unwrap());
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap();
|
||||
let c = last(&s);
|
||||
let mixed = describe(&mut s, json!({ "handles": [t, c] }));
|
||||
assert_eq!(group_names(&mixed), ["General"]);
|
||||
assert_eq!(mixed["types"], json!([{ "type": "Text", "count": 1 }, { "type": "Circle", "count": 1 }]));
|
||||
assert_eq!(row(&mixed, "General", "layer")["value"], "0");
|
||||
let texts = describe(&mut s, json!({ "handles": [t, c], "type": "text" }));
|
||||
assert_eq!((texts["filter"].as_str(), texts["count"].as_u64()), (Some("Text"), Some(1)));
|
||||
assert_eq!(group_names(&texts), ["General", "Text", "Geometry"]);
|
||||
// An unknown filter describes everything.
|
||||
assert_eq!(describe(&mut s, json!({ "handles": [t, c], "type": "nope" }))["count"], 2);
|
||||
// Nothing selected, or handles that name nothing: no rows.
|
||||
assert_eq!(describe(&mut s, json!({ "handles": [] }))["groups"], json!([]));
|
||||
assert_eq!(describe(&mut s, json!({ "handles": ["FFFFFF"] }))["count"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_rows() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("mtext", &json!({ "at": [0, 0], "text": "one\\Ptwo", "height": 3, "width": 40, "justify": "MC", "lineSpacing": 1.5 })).unwrap();
|
||||
let m = handle(&r);
|
||||
let d = describe(&mut s, json!({ "handles": [m] }));
|
||||
assert_eq!(group_names(&d), ["General", "Text", "Geometry"]);
|
||||
assert_eq!(row(&d, "Text", "justify")["value"], "MC");
|
||||
assert_eq!(row(&d, "Text", "justify")["display"], "Middle center");
|
||||
assert_eq!(row(&d, "Text", "text")["kind"], "contents");
|
||||
assert_eq!(row(&d, "Text", "lineSpacing")["value"], 1.5);
|
||||
// Line space distance: factor × height × 5/3.
|
||||
let dist = row(&d, "Text", "lineSpacingDistance")["value"].as_f64().unwrap();
|
||||
assert!((dist - 1.5 * 3.0 * 5.0 / 3.0).abs() < 1e-9, "{dist}");
|
||||
assert_eq!(row(&d, "Text", "lineSpacingStyle")["value"], "atLeast");
|
||||
assert_eq!(row(&d, "Text", "width")["value"], 40.0);
|
||||
let cols = row(&d, "Text", "columns");
|
||||
assert_eq!((cols["display"].as_str(), cols["editable"].as_bool()), (Some("None"), Some(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimension_rows_come_from_the_style_and_its_overrides() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
let dm = last(&s);
|
||||
let d = describe(&mut s, json!({ "handles": [dm] }));
|
||||
assert_eq!(group_names(&d), ["General", "Misc", "Lines & Arrows", "Text", "Fit", "Primary Units", "Alternate Units", "Tolerances"]);
|
||||
let th = row(&d, "Text", "textHeight");
|
||||
assert_eq!((th["value"].as_f64(), th["editable"].as_bool(), th.get("overridden")), (Some(0.18), Some(true), None));
|
||||
assert_eq!(row(&d, "Misc", "dimStyle")["value"], "Standard");
|
||||
assert_eq!(row(&d, "Text", "textAbove")["display"], "Centered");
|
||||
assert_eq!(row(&d, "Primary Units", "decimals")["display"], "0.0000");
|
||||
assert_eq!(row(&d, "Lines & Arrows", "arrowBlock1")["display"], "Closed filled");
|
||||
assert_eq!(row(&d, "Lines & Arrows", "dimLineColor")["value"], "ByBlock");
|
||||
let m = row(&d, "Text", "measurement");
|
||||
assert_eq!((m["editable"].as_bool(), m["display"].as_str()), (Some(false), Some("10.0000")));
|
||||
assert_eq!(row(&d, "Text", "textOverride")["value"], "");
|
||||
|
||||
// A Properties edit is an override of this dimension; the row says so.
|
||||
let r = s.execute("properties.set", &json!({ "handles": [dm], "textHeight": 0.3 })).unwrap();
|
||||
assert_eq!(r["ignored"], json!([]));
|
||||
let d = describe(&mut s, json!({ "handles": [dm] }));
|
||||
let th = row(&d, "Text", "textHeight");
|
||||
assert_eq!((th["value"].as_f64(), th["overridden"].as_bool()), (Some(0.3), Some(true)));
|
||||
// The style itself is unchanged.
|
||||
let st = s.execute("dimstyle.list", &json!({ "name": "Standard" })).unwrap();
|
||||
assert_eq!(st["variables"]["DIMTXT"], 0.18);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fixed_height_text_style_decides_dimension_text_height() {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "Fixed", "height": 0.5, "current": false })).unwrap();
|
||||
s.execute("dimstyle", &json!({ "name": "FixedDims", "textStyle": "Fixed" })).unwrap();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
let dm = last(&s);
|
||||
let d = describe(&mut s, json!({ "handles": [dm] }));
|
||||
let th = row(&d, "Text", "textHeight");
|
||||
assert_eq!((th["editable"].as_bool(), th["display"].as_str()), (Some(false), Some("0.5000")));
|
||||
assert!(th["note"].as_str().unwrap().contains("Fixed"), "{th}");
|
||||
// Fixed heights that differ vary, whatever their DIMTXT says.
|
||||
s.execute("style", &json!({ "name": "Large", "height": 0.75, "current": false })).unwrap();
|
||||
s.execute("dimstyle", &json!({ "name": "LargeDims", "textStyle": "Large" })).unwrap();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 10], "p2": [10, 10], "at": [5, 13] })).unwrap();
|
||||
let large = last(&s);
|
||||
let d = describe(&mut s, json!({ "handles": [dm, large] }));
|
||||
let th = row(&d, "Text", "textHeight");
|
||||
assert_eq!((th["editable"].as_bool(), th["display"].as_str()), (Some(false), Some("*VARIES*")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measurements_read_as_each_dimension_writes_them() {
|
||||
let mut s = Session::new();
|
||||
let shown =
|
||||
|s: &mut Session, hs: Value| row(&describe(s, json!({ "handles": hs })), "Text", "measurement")["display"].as_str().unwrap().to_string();
|
||||
s.execute("dimangular", &json!({ "vertex": [0, 0], "p1": [10, 0], "p2": [0, 10], "at": [3, 3] })).unwrap();
|
||||
let angle = last(&s);
|
||||
assert_eq!(shown(&mut s, json!([angle])), "90°");
|
||||
// In the dimension's angle format.
|
||||
s.execute("properties.set", &json!({ "handles": [angle], "angularUnit": 3, "angularDecimals": 2 })).unwrap();
|
||||
assert_eq!(shown(&mut s, json!([angle])), "1.57r");
|
||||
// The same length written at two precisions varies.
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
let a = last(&s);
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 20], "p2": [10, 20], "at": [5, 23] })).unwrap();
|
||||
let b = last(&s);
|
||||
assert_eq!(shown(&mut s, json!([a, b])), "10.0000");
|
||||
s.execute("properties.set", &json!({ "handles": [b], "precision": 1 })).unwrap();
|
||||
assert_eq!(shown(&mut s, json!([a, b])), "*VARIES*");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_show_lengths_in_the_drawing_units() {
|
||||
let mut s = Session::new();
|
||||
s.execute("setvar", &json!({ "name": "LUNITS", "value": 4 })).unwrap();
|
||||
let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 18 })).unwrap());
|
||||
let d = describe(&mut s, json!({ "handles": [t] }));
|
||||
assert_eq!(row(&d, "Text", "height")["display"], "1'-6\"");
|
||||
assert_eq!(row(&d, "Text", "height")["value"], 18.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_requests_never_panic() {
|
||||
let mut s = Session::new();
|
||||
let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 1 })).unwrap());
|
||||
for p in [json!({}), json!({ "handles": "x" }), json!({ "handles": [t, t, t] }), json!({ "handles": [t], "type": 5 }), json!({ "type": "Text" })]
|
||||
{
|
||||
let _ = s.execute("properties.describe", &p);
|
||||
}
|
||||
// Duplicates count once.
|
||||
assert_eq!(describe(&mut s, json!({ "handles": [t, t] }))["count"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotations_show_as_the_drawing_measures_directions() {
|
||||
let mut s = Session::new();
|
||||
s.execute("text", &json!({ "at": [0, 0], "text": "N", "height": 1, "rotation": 2.22729505553431 })).unwrap();
|
||||
// Clockwise from north (ANGBASE 90, ANGDIR 1): AutoCAD shows the text turned 2.23° as 87.77
|
||||
// (#1275); the value stays from +X counterclockwise, as properties.set takes it.
|
||||
for (name, value) in [("ANGDIR", json!(1)), ("ANGBASE", json!(90)), ("AUPREC", json!(2))] {
|
||||
s.execute("setvar", &json!({ "name": name, "value": value })).unwrap();
|
||||
}
|
||||
let h = last(&s);
|
||||
let desc = describe(&mut s, json!({ "handles": [h] }));
|
||||
let r = row(&desc, "Text", "rotation");
|
||||
assert_eq!(r["kind"], "direction");
|
||||
assert_eq!(r["display"], "87.77");
|
||||
assert!((r["value"].as_f64().unwrap() - 2.22729505553431).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_arrowheads_read_as_the_ones_drawn() {
|
||||
use cadcraft_engine::doc::DimStyle;
|
||||
use cadcraft_engine::properties::{DIM_PROPS, dim_value};
|
||||
let st = serde_json::to_value(DimStyle { arrow_block: "_DOT".into(), ..DimStyle::default() }).unwrap();
|
||||
let p = |field: &str| DIM_PROPS.iter().find(|p| p.field == field).unwrap();
|
||||
// An empty per-end arrowhead draws DIMBLK's; an empty leader arrowhead is closed filled.
|
||||
assert_eq!(dim_value(p("arrowBlock1"), &st), json!("_DOT"));
|
||||
assert_eq!(dim_value(p("arrowBlock"), &st), json!("_DOT"));
|
||||
assert_eq!(dim_value(p("leaderArrowBlock"), &st), json!(""));
|
||||
}
|
||||
|
||||
/// Float noise is no difference between two objects' values (7 and 7.0000000000001), but values
|
||||
/// the display rounds alike still vary (7 and 7.000001 both show as 7.0000).
|
||||
#[test]
|
||||
fn float_noise_does_not_vary_but_a_real_difference_does() {
|
||||
let mut s = Session::new();
|
||||
let a = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 7.0 })).unwrap());
|
||||
let b = handle(&s.execute("text", &json!({ "at": [0, 5], "text": "B", "height": 7.0 + 1e-13 })).unwrap());
|
||||
let both = describe(&mut s, json!({ "handles": [a.clone(), b.clone()] }));
|
||||
let h = row(&both, "Text", "height");
|
||||
assert_eq!((h["varies"].as_bool(), h["display"].as_str()), (Some(false), Some("7.0000")));
|
||||
s.execute("properties.set", &json!({ "handles": [b.clone()], "height": 7.000001 })).unwrap();
|
||||
let both = describe(&mut s, json!({ "handles": [a, b] }));
|
||||
assert_eq!(row(&both, "Text", "height")["varies"], true);
|
||||
}
|
||||
@@ -1,366 +0,0 @@
|
||||
//! `properties.set` for text, mtext and dimensions: the edits the Properties palette makes, keys
|
||||
//! nobody took coming back as `ignored`, and style edits reaching dimensions read from files.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, HAlign, Handle, MText, Text};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn handle(r: &Value) -> String {
|
||||
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string()
|
||||
}
|
||||
|
||||
fn last(s: &Session) -> String {
|
||||
s.doc().unwrap().model.last().unwrap().handle.hex()
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, h: &str, p: Value) -> Value {
|
||||
let mut p = p;
|
||||
p["handles"] = json!([h]);
|
||||
s.execute("properties.set", &p).unwrap()
|
||||
}
|
||||
|
||||
fn text(s: &Session, h: &str) -> Text {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::Text(t) => t.clone(),
|
||||
k => panic!("not text: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn mtext(s: &Session, h: &str) -> MText {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::MText(t) => t.clone(),
|
||||
k => panic!("not mtext: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn dim(s: &Session, h: &str) -> cadcraft_engine::doc::Dimension {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::Dimension(d) => d.clone(),
|
||||
k => panic!("not a dimension: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_style_justify_oblique_and_position() {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "Notes", "current": false })).unwrap();
|
||||
let t = handle(&s.execute("text", &json!({ "at": [5, 5], "text": "Hello", "height": 2 })).unwrap());
|
||||
let r = set(&mut s, &t, json!({ "style": "notes", "oblique": 15, "bogus": 1 }));
|
||||
assert_eq!(r["ignored"], json!(["bogus"]));
|
||||
assert_eq!(text(&s, &t).style, "Notes");
|
||||
assert!(near(text(&s, &t).oblique.to_degrees(), 15.0));
|
||||
// A style that doesn't exist is refused; an oblique past 85 degrees is ignored.
|
||||
assert!(s.execute("properties.set", &json!({ "handles": [t], "style": "Nope" })).is_err());
|
||||
assert_eq!(set(&mut s, &t, json!({ "oblique": 90 }))["ignored"], json!(["oblique"]));
|
||||
|
||||
// Justify keeps the point the text is placed by: the text moves around it.
|
||||
set(&mut s, &t, json!({ "justify": "MC" }));
|
||||
let j = text(&s, &t);
|
||||
assert_eq!((j.halign, j.justify_point().x, j.justify_point().y), (HAlign::Center, 5.0, 5.0));
|
||||
// Position X moves the text along X only.
|
||||
set(&mut s, &t, json!({ "positionX": 20 }));
|
||||
let j = text(&s, &t);
|
||||
assert_eq!((j.justify_point().x, j.justify_point().y), (20.0, 5.0));
|
||||
// Fit puts the second point at the end of the text, along its rotation.
|
||||
set(&mut s, &t, json!({ "justify": "Fit" }));
|
||||
let f = text(&s, &t);
|
||||
let end = f.align_pt.unwrap();
|
||||
assert!(f.halign == HAlign::Fit && near(f.insert.x, 20.0) && end.x > 20.0 && near(end.y, 5.0), "{f:?}");
|
||||
// The second point alone (the text refits between them).
|
||||
set(&mut s, &t, json!({ "alignmentX": 40 }));
|
||||
assert!(near(text(&s, &t).align_pt.unwrap().x, 40.0) && near(text(&s, &t).insert.x, 20.0));
|
||||
// Back to left: one point, where the fit text started.
|
||||
set(&mut s, &t, json!({ "justify": "Left" }));
|
||||
let l = text(&s, &t);
|
||||
assert!(l.align_pt.is_none() && near(l.insert.x, 20.0));
|
||||
// Alignment points belong to aligned and fit text only.
|
||||
assert_eq!(set(&mut s, &t, json!({ "alignmentX": 1 }))["ignored"], json!(["alignmentX"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_style_justify_and_line_spacing() {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "Notes", "current": false })).unwrap();
|
||||
let m = handle(&s.execute("mtext", &json!({ "at": [0, 10], "text": "one\\Ptwo", "height": 3, "width": 40 })).unwrap());
|
||||
set(&mut s, &m, json!({ "style": "Notes", "justify": "MC", "lineSpacing": 2, "lineSpacingStyle": "Exactly" }));
|
||||
let t = mtext(&s, &m);
|
||||
assert_eq!((t.style.as_str(), t.attach, t.line_spacing, t.line_spacing_exact), ("Notes", 5, 2.0, true));
|
||||
// The attachment point stays put.
|
||||
assert!(near(t.insert.x, 0.0) && near(t.insert.y, 10.0));
|
||||
// MTEXT's factors run from 0.25 to 4.
|
||||
assert_eq!(set(&mut s, &m, json!({ "lineSpacing": 10 }))["ignored"], json!(["lineSpacing"]));
|
||||
// A distance between lines sets the factor: factor × height × 5/3.
|
||||
set(&mut s, &m, json!({ "lineSpacingDistance": 7.5 }));
|
||||
assert!(near(mtext(&s, &m).line_spacing, 1.5));
|
||||
set(&mut s, &m, json!({ "lineSpacingStyle": "atLeast", "positionX": 4, "positionY": 6 }));
|
||||
let t = mtext(&s, &m);
|
||||
assert!(!t.line_spacing_exact && near(t.insert.x, 4.0) && near(t.insert.y, 6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimension_variables_become_overrides_of_each_dimension() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
let dm = last(&s);
|
||||
set(&mut s, &dm, json!({ "textHeight": 0.3 }));
|
||||
assert_eq!(dim(&s, &dm).overrides.get("textHeight"), Some(&json!(0.3)));
|
||||
let geometry = |s: &Session| cadcraft_engine::render::dimension_in(s.doc().unwrap(), &dim(s, &dm));
|
||||
assert!(near(geometry(&s).text_height, 0.3));
|
||||
// A DIM* name replaces the override under its field name.
|
||||
set(&mut s, &dm, json!({ "DIMTXT": 0.25, "DIMGAP": 0.05 }));
|
||||
let o = dim(&s, &dm).overrides;
|
||||
assert_eq!((o.len(), o.get("textHeight"), o.get("textGap")), (2, Some(&json!(0.25)), Some(&json!(0.05))));
|
||||
// Clear one, then all.
|
||||
set(&mut s, &dm, json!({ "clear": ["DIMGAP"] }));
|
||||
assert_eq!(dim(&s, &dm).overrides.keys().collect::<Vec<_>>(), ["textHeight"]);
|
||||
set(&mut s, &dm, json!({ "clearOverrides": true }));
|
||||
assert!(dim(&s, &dm).overrides.is_empty());
|
||||
assert!(near(geometry(&s).text_height, 0.18));
|
||||
// Bad values and unknown text styles don't become overrides.
|
||||
// An unusable text height is refused (as Properties' dimension rows refuse it, #1473).
|
||||
assert!(s.execute("properties.set", &json!({ "handles": [dm], "textHeight": -1 })).is_err());
|
||||
assert!(s.execute("properties.set", &json!({ "handles": [dm], "textStyle": "Nope" })).is_err());
|
||||
assert!(dim(&s, &dm).overrides.is_empty());
|
||||
// A refused call makes no layer either.
|
||||
assert!(s.execute("properties.set", &json!({ "handles": [dm], "layer": "Notes", "dimStyle": "Nope" })).is_err());
|
||||
assert!(s.doc().unwrap().layer("Notes").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_filled_for_one_end_is_drawn_whatever_dimblk_says() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimstyle", &json!({ "name": "Ticks", "arrowBlock": "_ARCHTICK" })).unwrap();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
let dm = last(&s);
|
||||
// Closed filled is "" among the arrowheads; for one end it's named, as "" there is DIMBLK's.
|
||||
set(&mut s, &dm, json!({ "arrowBlock1": "" }));
|
||||
assert_eq!(dim(&s, &dm).overrides.get("arrowBlock1"), Some(&json!("_CLOSEDFILLED")));
|
||||
let rows = s.execute("properties.describe", &json!({ "handles": [dm] })).unwrap();
|
||||
let arrow = |key: &str| {
|
||||
rows["groups"].as_array().unwrap().iter().flat_map(|g| g["rows"].as_array().unwrap()).find(|r| r["key"] == key).unwrap()["value"].clone()
|
||||
};
|
||||
assert_eq!((arrow("arrowBlock1"), arrow("arrowBlock2")), (json!(""), json!("_ARCHTICK")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimension_text_rows() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
let dm = last(&s);
|
||||
set(&mut s, &dm, json!({ "prefix": "~", "suffix": " mm", "textRotation": 30, "textPositionX": 2 }));
|
||||
let d = dim(&s, &dm);
|
||||
assert_eq!(d.overrides.get("post"), Some(&json!("~<> mm")));
|
||||
assert!(near(d.text_rotation.to_degrees(), 30.0));
|
||||
assert!(d.user_text_pos && near(d.text_mid.x, 2.0));
|
||||
let g = cadcraft_engine::render::dimension_in(s.doc().unwrap(), &d);
|
||||
assert!(g.value.starts_with('~') && g.value.ends_with(" mm"), "{}", g.value);
|
||||
// A suffix alone keeps the prefix.
|
||||
set(&mut s, &dm, json!({ "suffix": "" }));
|
||||
assert_eq!(dim(&s, &dm).overrides.get("post"), Some(&json!("~<>")));
|
||||
// Together with other edits, the prefix goes into what those leave: here no suffix override.
|
||||
set(&mut s, &dm, json!({ "suffix": " mm" }));
|
||||
set(&mut s, &dm, json!({ "clearOverrides": true, "prefix": "=" }));
|
||||
assert_eq!(dim(&s, &dm).overrides.get("post"), Some(&json!("=<>")));
|
||||
// The prefix and suffix rows are DIMPOST's halves: overridden with it, reset with it.
|
||||
let rows = s.execute("properties.describe", &json!({ "handles": [dm] })).unwrap();
|
||||
let prefix =
|
||||
rows["groups"].as_array().unwrap().iter().flat_map(|g| g["rows"].as_array().unwrap()).find(|r| r["key"] == "prefix").unwrap().clone();
|
||||
assert_eq!(prefix["overridden"], true, "{prefix}");
|
||||
set(&mut s, &dm, json!({ "clear": ["prefix"] }));
|
||||
assert!(dim(&s, &dm).overrides.get("post").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotating_aligned_text_turns_its_baseline() {
|
||||
let mut s = Session::new();
|
||||
let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "Wide", "height": 1 })).unwrap());
|
||||
set(&mut s, &t, json!({ "justify": "Align" }));
|
||||
let long = text(&s, &t).align_pt.unwrap().x;
|
||||
assert!(long > 0.0);
|
||||
set(&mut s, &t, json!({ "rotation": 90 }));
|
||||
let end = text(&s, &t).align_pt.unwrap();
|
||||
assert!(near(end.x, 0.0) && near(end.y, long), "{end:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justify_in_one_call_with_other_edits_takes_them_in() {
|
||||
// Fit with new contents measures the new text; with a rotation, the baseline runs along it.
|
||||
let mut s = Session::new();
|
||||
let short = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 1 })).unwrap());
|
||||
let long = handle(&s.execute("text", &json!({ "at": [0, 5], "text": "Much longer", "height": 1 })).unwrap());
|
||||
set(&mut s, &long, json!({ "justify": "Fit" }));
|
||||
set(&mut s, &short, json!({ "text": "Much longer", "justify": "Fit", "rotation": 90 }));
|
||||
let (a, b) = (text(&s, &short), text(&s, &long));
|
||||
let len = |t: &Text| t.insert.xy().dist(t.align_pt.unwrap().xy());
|
||||
assert!(near(len(&a), len(&b)), "{} {}", len(&a), len(&b));
|
||||
let end = a.align_pt.unwrap();
|
||||
assert!(near(end.x, 0.0) && end.y > 0.0, "{end:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_is_no_dimension_override() {
|
||||
// `scale` is an insert's or hatch's; a dimension's overall scale is `dimScale`.
|
||||
let mut s = Session::new();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
let dm = last(&s);
|
||||
assert_eq!(set(&mut s, &dm, json!({ "scale": 2 }))["ignored"], json!(["scale"]));
|
||||
assert!(dim(&s, &dm).overrides.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn making_a_style_current_keeps_the_dimensions_read_from_a_file() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap();
|
||||
s.open_drawing(back, "dims", None);
|
||||
let dm = last(&s);
|
||||
assert!(dim(&s, &dm).block.is_some());
|
||||
// No field changes: the geometry the file stored stays.
|
||||
s.execute("dimstyle", &json!({ "name": "Standard" })).unwrap();
|
||||
s.execute("style", &json!({ "name": "Standard" })).unwrap();
|
||||
assert!(dim(&s, &dm).block.is_some());
|
||||
// A change redraws it.
|
||||
s.execute("dimstyle", &json!({ "name": "Standard", "DIMTXT": 0.3 })).unwrap();
|
||||
assert!(dim(&s, &dm).block.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_pattern_edits_go_as_hatchedits_do() {
|
||||
let mut s = Session::new();
|
||||
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap();
|
||||
s.execute("gradient", &json!({ "points": [[5, 5]], "color1": "1", "color2": "3" })).unwrap();
|
||||
let h = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle.hex();
|
||||
let hatch = |s: &Session| match &s.doc().unwrap().entity(Handle::parse_hex(&h).unwrap()).unwrap().kind {
|
||||
EntityKind::Hatch(x) => x.clone(),
|
||||
k => panic!("not a hatch: {k:?}"),
|
||||
};
|
||||
assert!(hatch(&s).gradient.is_some());
|
||||
// SOLID is a plain fill, not the gradient.
|
||||
set(&mut s, &h, json!({ "pattern": "SOLID" }));
|
||||
assert!(hatch(&s).solid && hatch(&s).gradient.is_none());
|
||||
// A blank name changes nothing.
|
||||
assert_eq!(set(&mut s, &h, json!({ "pattern": " " }))["ignored"], json!(["pattern"]));
|
||||
assert_eq!(hatch(&s).pattern, "SOLID");
|
||||
// A name no pattern has is refused, as HATCHEDIT refuses it; a defined one is taken.
|
||||
assert!(s.execute("properties.set", &json!({ "handles": [h], "pattern": "ANSI3" })).is_err());
|
||||
assert_eq!(hatch(&s).pattern, "SOLID");
|
||||
set(&mut s, &h, json!({ "pattern": "ansi31" }));
|
||||
assert_eq!(hatch(&s).pattern, "ANSI31");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_that_is_not_there_refuses_the_whole_call() {
|
||||
let mut s = Session::new();
|
||||
let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 1 })).unwrap());
|
||||
assert!(s.execute("properties.set", &json!({ "handles": [t, "FFFFF"], "height": 3, "layer": "Notes" })).is_err());
|
||||
assert_eq!(text(&s, &t).height, 1.0);
|
||||
assert!(s.doc().unwrap().layer("Notes").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_of_a_dimension_read_from_a_file_redraw_it() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
// Read back from DXF, a dimension draws the block it was saved with.
|
||||
let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap();
|
||||
s.open_drawing(back, "dims", None);
|
||||
let dm = last(&s);
|
||||
assert!(dim(&s, &dm).block.is_some());
|
||||
// Nothing changed: the block stays.
|
||||
set(&mut s, &dm, json!({ "clear": [], "color": "ByLayer" }));
|
||||
assert!(dim(&s, &dm).block.is_some());
|
||||
set(&mut s, &dm, json!({ "textHeight": 0.4 }));
|
||||
assert!(dim(&s, &dm).block.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn style_edits_redraw_dimensions_read_from_a_file() {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "DimText", "current": false })).unwrap();
|
||||
s.execute("dimstyle", &json!({ "name": "Plan", "textStyle": "DimText" })).unwrap();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
s.execute("dimstyle", &json!({ "name": "Other" })).unwrap();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 10], "p2": [10, 10], "at": [5, 13] })).unwrap();
|
||||
let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap();
|
||||
s.open_drawing(back, "dims", None);
|
||||
let dims: Vec<(String, cadcraft_engine::doc::Dimension)> = s
|
||||
.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| if let EntityKind::Dimension(d) = &e.kind { Some((e.handle.hex(), d.clone())) } else { None })
|
||||
.collect();
|
||||
let plan = dims.iter().find(|(_, d)| d.style == "Plan").unwrap().0.clone();
|
||||
let other = dims.iter().find(|(_, d)| d.style == "Other").unwrap().0.clone();
|
||||
assert!(dim(&s, &plan).block.is_some() && dim(&s, &other).block.is_some());
|
||||
// Editing a dimension style redraws the dimensions that use it, and only those.
|
||||
s.execute("dimstyle", &json!({ "name": "Plan", "DIMTXT": 0.5, "current": false })).unwrap();
|
||||
assert!(dim(&s, &plan).block.is_none() && dim(&s, &other).block.is_some());
|
||||
let g = cadcraft_engine::render::dimension_in(s.doc().unwrap(), &dim(&s, &plan));
|
||||
assert!(near(g.text_height, 0.5));
|
||||
// Editing a text style redraws the dimensions whose text uses it.
|
||||
let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap();
|
||||
s.open_drawing(back, "dims", None);
|
||||
let plan = s.doc().unwrap().model.iter().find(|e| matches!(&e.kind, EntityKind::Dimension(d) if d.style == "Plan")).unwrap().handle.hex();
|
||||
assert!(dim(&s, &plan).block.is_some());
|
||||
s.execute("style", &json!({ "name": "DimText", "widthFactor": 0.8, "current": false })).unwrap();
|
||||
assert!(dim(&s, &plan).block.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_text_style_follows_dimension_overrides() {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "Old", "current": false })).unwrap();
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
let dm = last(&s);
|
||||
set(&mut s, &dm, json!({ "textStyle": "Old" }));
|
||||
s.execute("style.rename", &json!({ "from": "Old", "to": "New" })).unwrap();
|
||||
assert_eq!(dim(&s, &dm).overrides.get("textStyle"), Some(&json!("New")));
|
||||
// A style only a dimension override names is in use: it can't be deleted.
|
||||
assert!(s.execute("style.delete", &json!({ "name": "New" })).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_values_never_panic() {
|
||||
let mut s = Session::new();
|
||||
let t = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "A", "height": 1 })).unwrap());
|
||||
let m = handle(&s.execute("mtext", &json!({ "at": [0, 5], "text": "B", "height": 1 })).unwrap());
|
||||
s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap();
|
||||
let dm = last(&s);
|
||||
for v in [json!(null), json!("x"), json!(1e308), json!(-1e308), json!([1, 2]), json!({ "a": 1 }), json!(true)] {
|
||||
let mut p = json!({ "handles": [t, m, dm] });
|
||||
for k in [
|
||||
"justify",
|
||||
"oblique",
|
||||
"positionX",
|
||||
"positionZ",
|
||||
"alignmentX",
|
||||
"lineSpacing",
|
||||
"lineSpacingDistance",
|
||||
"lineSpacingStyle",
|
||||
"textRotation",
|
||||
"textPositionX",
|
||||
"prefix",
|
||||
"suffix",
|
||||
"altPrefix",
|
||||
"clear",
|
||||
"clearOverrides",
|
||||
"DIMTXT",
|
||||
"DIMBLK1",
|
||||
"DIMCLRT",
|
||||
"DIMLWD",
|
||||
"DIMLTYPE",
|
||||
] {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
let _ = s.execute("properties.set", &p);
|
||||
let _ = s.execute("properties.describe", &json!({ "handles": [t, m, dm] }));
|
||||
}
|
||||
// Every dimension still draws.
|
||||
let g = cadcraft_engine::render::dimension_in(s.doc().unwrap(), &dim(&s, &dm));
|
||||
assert!(g.text_height.is_finite());
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Attrib, Block, Common, Entity, EntityKind, Handle, Insert, MLine, MLineElement, MLineJust, MLineStyle, Space};
|
||||
use cadcraft_engine::doc::{Block, Common, Entity, EntityKind, Handle, Insert, MLine, MLineJust, MLineStyle, Space};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -75,67 +75,3 @@ fn purge_mlinestyles_at_the_command_line() {
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(styles(&s), ["STANDARD", "Model", "InBlock", "Gone", "Current"]);
|
||||
}
|
||||
|
||||
/// A linetype is in use when only a dimension style, a dimension override, a multiline style, a
|
||||
/// multiline's copy of its style or an attribute override names it.
|
||||
#[test]
|
||||
fn linetypes_named_by_styles_and_attributes_are_kept() {
|
||||
let mut s = session();
|
||||
let d = s.doc_mut().unwrap();
|
||||
for name in ["InDimStyle", "InOverride", "InMline", "InMlineCopy", "InAttribute", "Unused"] {
|
||||
let mut lt = d.linetypes[0].clone();
|
||||
lt.name = name.into();
|
||||
d.linetypes.push(lt);
|
||||
}
|
||||
d.dim_styles[0].ext_linetype2 = "InDimStyle".into();
|
||||
let element = MLineElement { linetype: "InMline".into(), ..MLineElement::default() };
|
||||
d.mline_styles.iter_mut().for_each(|t| t.elements.push(element.clone()));
|
||||
let at = serde_json::to_value(Vec3::ZERO).unwrap();
|
||||
let mut attrib: Attrib = serde_json::from_value(json!({ "tag": "A", "text": { "insert": at, "height": 1.0, "value": "1" } })).unwrap();
|
||||
attrib.props.linetype = Some("InAttribute".into());
|
||||
let Some(EntityKind::Insert(mut ins)) = d.model.iter().find_map(|e| matches!(e.kind, EntityKind::Insert(_)).then(|| e.kind.clone())) else {
|
||||
return;
|
||||
};
|
||||
ins.attribs.push(attrib);
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||||
let copy = MLineElement { linetype: "InMlineCopy".into(), ..MLineElement::default() };
|
||||
let drawn = MLineStyle { name: "Model".into(), elements: vec![copy], ..MLineStyle::default() };
|
||||
d.add(&Space::Model, Common::default(), mline(&drawn)).unwrap();
|
||||
let dim = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap();
|
||||
let handle = dim["handle"].clone();
|
||||
s.execute("dimoverride", &json!({ "handles": [handle], "DIMLTYPE": "InOverride" })).unwrap();
|
||||
s.execute("purge", &json!({ "type": "linetypes" })).unwrap();
|
||||
let names: Vec<String> = s.doc().unwrap().linetypes.iter().map(|l| l.name.clone()).collect();
|
||||
for kept in ["InDimStyle", "InOverride", "InMline", "InMlineCopy", "InAttribute"] {
|
||||
assert!(names.iter().any(|n| n == kept), "{kept}: {names:?}");
|
||||
}
|
||||
assert!(!names.iter().any(|n| n == "Unused"), "{names:?}");
|
||||
}
|
||||
|
||||
/// A dimension override given as a number names a text style, linetype or arrowhead block all
|
||||
/// the same (DIMOVERRIDE keeps the number, the dimension is drawn with it as text): PURGE keeps
|
||||
/// them.
|
||||
#[test]
|
||||
fn numbers_in_dimension_overrides_name_what_they_use() {
|
||||
let mut s = session();
|
||||
let d = s.doc_mut().unwrap();
|
||||
for name in ["123", "Spare"] {
|
||||
let mut t = d.text_styles[0].clone();
|
||||
t.name = name.into();
|
||||
d.text_styles.push(t);
|
||||
}
|
||||
for name in ["7", "Spare"] {
|
||||
let mut lt = d.linetypes[0].clone();
|
||||
lt.name = name.into();
|
||||
d.linetypes.push(lt);
|
||||
}
|
||||
d.blocks.insert("45".into(), Arc::new(Block::new("45")));
|
||||
let h = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap()["handle"].clone();
|
||||
s.execute("dimoverride", &json!({ "handles": [h], "DIMTXSTY": 123, "DIMLTYPE": 7, "DIMBLK1": 45 })).unwrap();
|
||||
let r = s.execute("purge", &json!({ "type": "all" })).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(d.text_style("123").is_some(), "{r}");
|
||||
assert!(d.linetypes.iter().any(|l| l.name == "7"), "{r}");
|
||||
assert!(d.block("45").is_some(), "{r}");
|
||||
assert_eq!((r["purged"]["textstyles"].clone(), r["purged"]["linetypes"].clone()), (json!(["Spare"]), json!(["Spare"])), "{r}");
|
||||
}
|
||||
|
||||
@@ -88,27 +88,6 @@ fn massprop_self_check_reports_skipped_objects() {
|
||||
assert_eq!(sc["implausible"], json!([]));
|
||||
}
|
||||
|
||||
/// REGION typed with nothing selected asks for objects, as in AutoCAD, instead of reporting
|
||||
/// "0 Region(s) created."; with objects already selected it converts them at once.
|
||||
#[test]
|
||||
fn typed_region_asks_for_objects() {
|
||||
let mut s = Session::new();
|
||||
let r = h(&s.execute("rectang", &json!({"p1": [0, 0], "p2": [10, 4]})).unwrap());
|
||||
s.set_selection(Vec::new());
|
||||
s.cmdline("region").unwrap();
|
||||
assert!(s.running.is_some(), "REGION should ask for objects: {}", s.prompt_text());
|
||||
s.cmdline("l").unwrap();
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(matches!(s.doc().unwrap().entity(r).unwrap().kind, EntityKind::Region(_)));
|
||||
// Preselected objects are converted at once.
|
||||
let c = h(&s.execute("circle", &json!({"center": [20, 0], "radius": 2})).unwrap());
|
||||
s.set_selection(vec![c]);
|
||||
s.cmdline("region").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(matches!(s.doc().unwrap().entity(c).unwrap().kind, EntityKind::Region(_)));
|
||||
}
|
||||
|
||||
/// Make `hd` invisible: it no longer counts towards the drawing extents.
|
||||
fn hide(s: &mut Session, hd: Handle) {
|
||||
s.doc_mut().unwrap().modify_entity(hd, |e| e.common.visible = false).unwrap();
|
||||
|
||||
@@ -123,13 +123,11 @@ fn undo_restores_the_closed_polyline() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_cut_leaves_the_outline_as_it_was() {
|
||||
// As AutoCAD 2024 does (measured with accoreconsole on a 100 x 10 rectangle cut once on its
|
||||
// bottom): it refuses, "Curve must intersect cutting edges at least twice."
|
||||
fn a_single_cut_still_opens_the_outline_there() {
|
||||
let mut s = Session::new();
|
||||
let p = handle(s.execute("pline", &json!({ "vertices": square(), "closed": true })).unwrap());
|
||||
let cutter = handle(s.execute("line", &json!({ "points": [[2, -1], [2, 1]] })).unwrap());
|
||||
let r = s.execute("trim", &json!({ "handle": p, "pick": [0, 2], "edges": [cutter] }));
|
||||
assert!(r.is_err_and(|e| e.to_string() == "Curve must intersect cutting edges at least twice."));
|
||||
assert_eq!(polys(&s), vec![(true, vec![(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 4.0, 0.0), (0.0, 4.0, 0.0)])]);
|
||||
s.execute("trim", &json!({ "handle": p, "pick": [0, 2], "edges": [cutter] })).unwrap();
|
||||
let all = [(2.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 4.0, 0.0), (0.0, 4.0, 0.0), (0.0, 0.0, 0.0), (2.0, 0.0, 0.0)];
|
||||
assert_eq!(polys(&s), vec![(false, all.to_vec())]);
|
||||
}
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
//! TRIM of a line, an arc or a circle picked on a cut, as AutoCAD 2024 does it (measured with
|
||||
//! accoreconsole on these drawings): a cut within 5e-7 of the pick, along the object, is passed
|
||||
//! over, and the piece runs on across it to the next cut either side. With no cut left, nothing is
|
||||
//! trimmed.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn handle(v: &Value) -> Handle {
|
||||
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// Vertical lines through x = `xs`, from y = -15 to 15; their handles.
|
||||
fn edges(s: &mut Session, xs: &[f64]) -> Vec<String> {
|
||||
xs.iter().map(|x| handle(&s.execute("line", &json!({ "points": [[x, -15], [x, 15]] })).unwrap()).hex()).collect()
|
||||
}
|
||||
|
||||
/// Every object but the edges: lines as their ends, arcs and circles as their angles in degrees.
|
||||
fn shapes(s: &Session, edges: &[String]) -> Vec<(Handle, Vec<f64>)> {
|
||||
let r = |v: f64| (v * 1e9).round() / 1e9;
|
||||
s.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter(|e| !edges.contains(&e.handle.hex()))
|
||||
.map(|e| {
|
||||
let v = match &e.kind {
|
||||
EntityKind::Line(l) => vec![l.a.x, l.a.y, l.b.x, l.b.y],
|
||||
EntityKind::Arc(a) => vec![a.start.to_degrees(), a.end.to_degrees()],
|
||||
EntityKind::Circle(_) => Vec::new(),
|
||||
k => panic!("{k:?}"),
|
||||
};
|
||||
(e.handle, v.into_iter().map(r).collect())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Trim `h` at `pick` with `edges`: whether the trim was made.
|
||||
fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edges: &[String]) -> bool {
|
||||
s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "edges": edges })).is_ok()
|
||||
}
|
||||
|
||||
/// A line from (0, 0) to (10, 0) with vertical lines through `xs`, trimmed at `pick`.
|
||||
fn line_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec<f64>)>, Handle) {
|
||||
let mut s = Session::new();
|
||||
let h = handle(&s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap());
|
||||
let es = edges(&mut s, xs);
|
||||
let made = trim(&mut s, h, pick, &es);
|
||||
(made, shapes(&s, &es), h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_picked_on_its_only_cut_is_left_as_it_was() {
|
||||
for pick in [[5.0, 0.0], [5.0000004, 0.0], [4.9999996, 0.0]] {
|
||||
let (made, got, h) = line_trimmed(&[5.0], pick);
|
||||
assert!(!made, "{pick:?}");
|
||||
assert_eq!(got, vec![(h, vec![0.0, 0.0, 10.0, 0.0])], "{pick:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_picked_on_one_of_two_cuts_loses_the_pieces_both_sides() {
|
||||
// Cuts at x = 3 and 7: on 3, 0 to 7 goes; 4e-7 past 7, 3 to the end; between them, 3 to 7.
|
||||
let (_, got, h) = line_trimmed(&[3.0, 7.0], [3.0, 0.0]);
|
||||
assert_eq!(got, vec![(h, vec![7.0, 0.0, 10.0, 0.0])]);
|
||||
let (_, got, h) = line_trimmed(&[3.0, 7.0], [7.0000004, 0.0]);
|
||||
assert_eq!(got, vec![(h, vec![0.0, 0.0, 3.0, 0.0])]);
|
||||
let (_, got, h) = line_trimmed(&[3.0, 7.0], [5.0, 0.0]);
|
||||
assert_eq!(got.len(), 2);
|
||||
assert_eq!(got[0], (h, vec![0.0, 0.0, 3.0, 0.0]));
|
||||
assert_eq!(got[1].1, vec![7.0, 0.0, 10.0, 0.0]);
|
||||
}
|
||||
|
||||
/// An arc of radius 10 about the origin from 0 to 180 degrees, with vertical lines through `xs`,
|
||||
/// trimmed at `pick`.
|
||||
fn arc_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec<f64>)>, Handle) {
|
||||
let mut s = Session::new();
|
||||
let h = handle(&s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 180 })).unwrap());
|
||||
let es = edges(&mut s, xs);
|
||||
let made = trim(&mut s, h, pick, &es);
|
||||
(made, shapes(&s, &es), h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arc_picked_on_its_only_cut_is_left_as_it_was() {
|
||||
// The line x = 0 cuts it at 90 degrees: on the cut and 4e-7 along from it nothing is trimmed,
|
||||
// 6e-7 along the arc from 90 to 180 goes.
|
||||
for pick in [[0.0, 10.0], [-4e-7, 10.0]] {
|
||||
let (made, got, h) = arc_trimmed(&[0.0], pick);
|
||||
assert!(!made, "{pick:?}");
|
||||
assert_eq!(got, vec![(h, vec![0.0, 180.0])], "{pick:?}");
|
||||
}
|
||||
let (_, got, h) = arc_trimmed(&[0.0], [-6e-7, 10.0]);
|
||||
assert_eq!(got, vec![(h, vec![0.0, 90.0])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arc_picked_on_its_last_cut_loses_the_rest() {
|
||||
// Cuts at 60 and 120 degrees, picked on 120: from 60 to the end goes.
|
||||
let (_, got, h) = arc_trimmed(&[5.0, -5.0], [-5.0, 75f64.sqrt()]);
|
||||
assert_eq!(got, vec![(h, vec![0.0, 60.0])]);
|
||||
}
|
||||
|
||||
/// A circle of radius 10 about the origin, with vertical lines through `xs`, trimmed at `pick`.
|
||||
fn circle_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec<f64>)>, Handle) {
|
||||
let mut s = Session::new();
|
||||
let h = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap());
|
||||
let es = edges(&mut s, xs);
|
||||
let made = trim(&mut s, h, pick, &es);
|
||||
(made, shapes(&s, &es), h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_picked_on_a_cut_loses_the_arcs_both_sides() {
|
||||
// Lines at x = 5 and -5 cut it at 60, 120, 240 and 300 degrees. Picked on 60, and 4e-7 along
|
||||
// from it, the arc from 300 round to 120 goes; picked at 90, the arc from 60 to 120.
|
||||
let y = 75f64.sqrt();
|
||||
for pick in [[5.0, y], [4.9999998, y + 2e-7 * 5.0 / y]] {
|
||||
let (_, got, h) = circle_trimmed(&[5.0, -5.0], pick);
|
||||
assert_eq!(got, vec![(h, vec![120.0, 300.0])], "{pick:?}");
|
||||
}
|
||||
let (_, got, h) = circle_trimmed(&[5.0, -5.0], [0.0, 10.0]);
|
||||
assert_eq!(got, vec![(h, vec![120.0, 60.0])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_picked_on_one_of_two_cuts_is_left_as_it_was() {
|
||||
// One line, cutting it at 60 and 300 degrees: picked on 60, one cut is left and the trim is
|
||||
// refused.
|
||||
let (made, got, h) = circle_trimmed(&[5.0], [5.0, 75f64.sqrt()]);
|
||||
assert!(!made);
|
||||
assert_eq!(got, vec![(h, Vec::new())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_mode_leaves_an_object_picked_on_its_only_cut() {
|
||||
// The line, the arc and the circle each meet the edges, at the pick, so Quick mode doesn't
|
||||
// erase them as objects no edge crosses.
|
||||
let y = 75f64.sqrt();
|
||||
let cases = [
|
||||
("line", json!({ "points": [[0, 0], [10, 0]] }), 5.0, [5.0, 0.0]),
|
||||
("arc", json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 180 }), 0.0, [0.0, 10.0]),
|
||||
("circle", json!({ "center": [0, 0], "radius": 10 }), 5.0, [5.0, y]),
|
||||
];
|
||||
for (cmd, shape, x, pick) in cases {
|
||||
let mut s = Session::new();
|
||||
let h = handle(&s.execute(cmd, &shape).unwrap());
|
||||
let es = edges(&mut s, &[x]);
|
||||
let r = s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "mode": "quick" }));
|
||||
assert!(r.is_err(), "{cmd}");
|
||||
assert!(s.doc().unwrap().entity(h).is_some(), "{cmd} was erased");
|
||||
assert_eq!(shapes(&s, &es).len(), 1, "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arc_picked_just_off_one_end_loses_the_piece_at_that_end() {
|
||||
// From 0 to 90 degrees, cut at 45: picked just before its start the piece from 0 goes, just
|
||||
// past its end the piece to 90.
|
||||
let x = 10.0 * std::f64::consts::FRAC_PI_4.cos();
|
||||
let trimmed = |pick: [f64; 2]| {
|
||||
let mut s = Session::new();
|
||||
let h = handle(&s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap());
|
||||
let es = edges(&mut s, &[x]);
|
||||
assert!(trim(&mut s, h, pick, &es));
|
||||
shapes(&s, &es)
|
||||
};
|
||||
assert_eq!(trimmed([10.0, -0.01])[0].1, vec![45.0, 90.0]);
|
||||
assert_eq!(trimmed([-0.01, 10.0])[0].1, vec![0.0, 45.0]);
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
//! TRIM on a polyline cut through the vertex where an arc span starts: the cut is at that vertex
|
||||
//! only. Where the crossing came out a hair before the arc's start angle it was also put at the
|
||||
//! arc's far end, round the circle, and TRIM took out the arc alone.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use serde_json::json;
|
||||
|
||||
fn handle(v: serde_json::Value) -> String {
|
||||
v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cut_is_at_the_arc_spans_start_vertex_only() {
|
||||
// (0, 0) to (10, 0), a semicircle round (15, 5) to (10, 10), then on to (0, 10). A line
|
||||
// through (10, 0) running up to the left crosses the top span at x = 10 + 10 cot(angle);
|
||||
// picked on the arc, the polyline goes from (10, 0) to there.
|
||||
for k in 0..172 {
|
||||
let th = (91.0 + f64::from(k) * 0.25).to_radians();
|
||||
let d = [th.cos() * 30.0, th.sin() * 30.0];
|
||||
let mut s = Session::new();
|
||||
let p = handle(s.execute("pline", &json!({ "vertices": [[0, 0], { "p": [10, 0], "bulge": 1 }, [10, 10], [0, 10]] })).unwrap());
|
||||
let e = handle(s.execute("line", &json!({ "points": [[10.0 - d[0], -d[1]], [10.0 + d[0], d[1]]] })).unwrap());
|
||||
s.execute("trim", &json!({ "handle": p, "pick": [15, 5], "edges": [e] })).unwrap();
|
||||
let pieces: Vec<Vec<(f64, f64)>> = s
|
||||
.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::LwPolyline(l) => Some(l.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let x = 10.0 + 10.0 / th.tan();
|
||||
let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6;
|
||||
let ok = pieces.len() == 2
|
||||
&& pieces.iter().any(|v| v.len() == 2 && near(v[0], (0.0, 0.0)) && near(v[1], (10.0, 0.0)))
|
||||
&& pieces.iter().any(|v| v.len() == 2 && near(v[0], (x, 10.0)) && near(v[1], (0.0, 10.0)));
|
||||
assert!(ok, "{:.2} degrees: {pieces:?}", th.to_degrees());
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
//! JSON execute pick roles and diagnostic-only refusals (#2750).
|
||||
|
||||
use cadcraft_doc::{Common, EntityKind, Handle, Line, Space};
|
||||
use cadcraft_engine::{Session, find_command};
|
||||
use cadcraft_geom::Vec3;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
type TestResult<T = ()> = Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
fn fixture(end: f64, edge_x: f64) -> TestResult<(Session, Handle, Handle)> {
|
||||
let mut s = Session::new();
|
||||
let a = s.doc_mut()?.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(end, 0.0, 0.0) }))?;
|
||||
let b = s.doc_mut()?.add(
|
||||
&Space::Model,
|
||||
Common::default(),
|
||||
EntityKind::Line(Line { a: Vec3::new(edge_x, -20.0, 0.0), b: Vec3::new(edge_x, 20.0, 0.0) }),
|
||||
)?;
|
||||
Ok((s, a, b))
|
||||
}
|
||||
|
||||
fn assert_line(s: &Session, h: Handle, start: f64, end: f64) -> TestResult {
|
||||
let e = s.doc()?.entity(h).ok_or("line missing")?;
|
||||
let EntityKind::Line(l) = &e.kind else { return Err("expected line".into()) };
|
||||
assert_eq!((l.a, l.b), (Vec3::new(start, 0.0, 0.0), Vec3::new(end, 0.0, 0.0)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn failure(s: &mut Session, cmd: &str, params: Value, message: &str) -> TestResult {
|
||||
let before = s.doc()?.clone();
|
||||
let selection = s.state()?.selection.clone();
|
||||
let error = s.execute(cmd, ¶ms).err().ok_or("expected refusal")?;
|
||||
assert_eq!(error.to_string(), message);
|
||||
assert_eq!(s.doc()?, &before, "a failed JSON call must leave the whole drawing unchanged");
|
||||
assert_eq!(s.state()?.selection, selection);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_execute_pick_selects_the_portion_to_remove() -> TestResult {
|
||||
// Off-object picks that already succeed by projection remain accepted.
|
||||
for (pick, start, end) in [([5, 0], 25.0, 50.0), ([40, 0], 0.0, 25.0), ([5, 3], 25.0, 50.0)] {
|
||||
let (mut s, a, b) = fixture(50.0, 25.0)?;
|
||||
let boundary = s.doc()?.entity(b).cloned().ok_or("boundary missing")?;
|
||||
let result = s.execute("trim", &json!({"handle": a.hex(), "edges": [b.hex()], "pick": pick}))?;
|
||||
let handles = result["handles"].as_array().ok_or("expected handles")?;
|
||||
assert_eq!(handles.len(), 1);
|
||||
let h = handles.first().and_then(Value::as_str).and_then(Handle::parse_hex).ok_or("expected trimmed handle")?;
|
||||
assert_eq!(h, a, "TRIM keeps the original handle on the surviving piece");
|
||||
assert_line(&s, h, start, end)?;
|
||||
assert_eq!(s.doc()?.entity(b), Some(&boundary));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_execute_pick_selects_the_end_toward_the_boundary() -> TestResult {
|
||||
for pick in [[25, 10], [25, -15], [19, 0], [40, 0]] {
|
||||
let (mut s, a, b) = fixture(20.0, 25.0)?;
|
||||
let boundary = s.doc()?.entity(b).cloned().ok_or("boundary missing")?;
|
||||
let result = s.execute("extend", &json!({"handle": a.hex(), "edges": [b.hex()], "pick": pick}))?;
|
||||
assert_eq!(result, Value::Null);
|
||||
assert_line(&s, a, 0.0, 25.0)?;
|
||||
assert_eq!(s.doc()?.entity(b), Some(&boundary));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_execute_distinguishes_picks_at_or_projecting_onto_a_cut_from_no_cut() -> TestResult {
|
||||
let (mut s, a, b) = fixture(50.0, 25.0)?;
|
||||
for (pick, message) in [
|
||||
([25, 10], "The `pick` point is off the line and projects onto a cutting intersection; pick away from that intersection."),
|
||||
([25, 0], "The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection."),
|
||||
] {
|
||||
failure(&mut s, "trim", json!({"handle": a.hex(), "edges": [b.hex()], "pick": pick, "mode": "standard"}), message)?;
|
||||
}
|
||||
let (mut s, a, b) = fixture(50.0, 75.0)?;
|
||||
failure(
|
||||
&mut s,
|
||||
"trim",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [5, 0]}),
|
||||
"No usable cutting-edge intersection in the interior of the object to trim.",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_execute_distinguishes_the_wrong_end_from_no_boundary_hit() -> TestResult {
|
||||
let (mut s, a, b) = fixture(20.0, 25.0)?;
|
||||
failure(
|
||||
&mut s,
|
||||
"extend",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [10, 0]}),
|
||||
"The `pick` point selects an end with no boundary ahead; choose `pick` toward the boundary to extend to.",
|
||||
)?;
|
||||
s.doc_mut()?.modify_entity(b, |e| {
|
||||
e.kind = EntityKind::Line(Line { a: Vec3::new(0.0, 20.0, 0.0), b: Vec3::new(25.0, 20.0, 0.0) });
|
||||
})?;
|
||||
failure(
|
||||
&mut s,
|
||||
"extend",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [25, 20]}),
|
||||
"No usable boundary intersection was found for either end of the object to extend.",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_erasure_and_unrelated_errors_keep_their_behavior() -> TestResult {
|
||||
let (mut s, a, b) = fixture(50.0, 25.0)?;
|
||||
// Quick mode leaves a line picked on its only cut in place (#2648), and the JSON form explains
|
||||
// the refusal as Standard mode does.
|
||||
failure(
|
||||
&mut s,
|
||||
"trim",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [25, 0], "mode": "quick"}),
|
||||
"The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection.",
|
||||
)?;
|
||||
assert!(s.doc()?.entity(a).is_some());
|
||||
assert!(s.doc()?.entity(b).is_some());
|
||||
failure(&mut s, "trim", json!({"handle": "DEAD", "pick": [5, 0]}), "no such object")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_contracts_and_missing_pick_errors_explain_the_roles() -> TestResult {
|
||||
let trim = find_command("trim").ok_or("trim not registered")?;
|
||||
assert!(trim.params.contains("pick selects the portion of that object to remove"));
|
||||
assert!(trim.params.contains("edges are the cutting edges"));
|
||||
let extend = find_command("extend").ok_or("extend not registered")?;
|
||||
assert!(extend.params.contains("pick points toward the boundary to extend to"));
|
||||
assert!(extend.params.contains("selecting the nearer end"));
|
||||
assert!(extend.params.contains("edges are the boundary edges"));
|
||||
let (mut s, a, b) = fixture(20.0, 25.0)?;
|
||||
failure(
|
||||
&mut s,
|
||||
"trim",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()]}),
|
||||
"invalid parameters for `trim`: `pick` ([x, y]) is required: select the portion of the object to trim away",
|
||||
)?;
|
||||
failure(
|
||||
&mut s,
|
||||
"extend",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()]}),
|
||||
"invalid parameters for `extend`: `pick` ([x, y]) is required: point toward the boundary to extend to, selecting the nearer end",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_on_the_line_far_from_the_origin_is_not_called_off_the_line() -> TestResult {
|
||||
// Survey coordinates: rounding there is far above 1e-9 (the pick below is 3.7e-9 off the line
|
||||
// after rounding), so a pick on the line still reads as on it.
|
||||
let (x0, y0, k) = (123_456_789.1, 9_876_543.3, 33.3333);
|
||||
let mut s = Session::new();
|
||||
let a = s.doc_mut()?.add(
|
||||
&Space::Model,
|
||||
Common::default(),
|
||||
EntityKind::Line(Line { a: Vec3::new(x0, y0, 0.0), b: Vec3::new(x0 + 50.0, y0 + 30.0, 0.0) }),
|
||||
)?;
|
||||
let b = s.doc_mut()?.add(
|
||||
&Space::Model,
|
||||
Common::default(),
|
||||
EntityKind::Line(Line { a: Vec3::new(x0 + k, y0 - 20.0, 0.0), b: Vec3::new(x0 + k, y0 + 50.0, 0.0) }),
|
||||
)?;
|
||||
failure(
|
||||
&mut s,
|
||||
"trim",
|
||||
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [x0 + k, y0 + k * 0.6]}),
|
||||
"The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection.",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_extend_contract_names_the_polyline_end_rule() -> TestResult {
|
||||
// An open polyline extends the end on the pick's side of its middle parameter (#2693), not
|
||||
// the nearer end.
|
||||
let extend = find_command("extend").ok_or("extend not registered")?;
|
||||
assert!(extend.params.contains("middle"), "{}", extend.params);
|
||||
Ok(())
|
||||
}
|
||||
@@ -112,33 +112,10 @@ fn crossing_window_trims_what_it_touches() {
|
||||
s.script("TRIM C 4,-1 6,1\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (15.0, 2.0)), ((10.0, 0.0), (15.0, 0.0))]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_in_empty_space_starts_a_fence_in_quick_mode_and_a_window_in_standard_mode() {
|
||||
// #1594: Quick mode's two-point fence trims what it crosses and returns to the first prompt.
|
||||
for cmd in ["TRIM", "EXTEND"] {
|
||||
let mut s = ladder();
|
||||
s.cmdline(cmd).unwrap();
|
||||
s.cmdline("4,-4").unwrap();
|
||||
assert!(s.prompt_text().contains("Specify next fence point"), "{cmd}: {}", s.prompt_text());
|
||||
}
|
||||
// A pick in empty space opens a crossing window too.
|
||||
let mut s = ladder();
|
||||
s.script("TRIM 4,-4 6,1\n").unwrap();
|
||||
assert!(s.prompt_text().contains("Select object to trim"), "{}", s.prompt_text());
|
||||
s.cmdline("").unwrap();
|
||||
s.script("TRIM 4,-4 6,1\n\n").unwrap();
|
||||
assert_eq!(lines(&s), with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (15.0, 2.0)), ((10.0, 0.0), (15.0, 0.0))]));
|
||||
// EXTEND's fence extends both lines it crosses to the boundary at x = 10.
|
||||
let mut s = session(&["10,-5 10,5", "0,0 4,0", "0,2 4,2"]);
|
||||
s.script("EXTEND 3,-1 3,3\n").unwrap();
|
||||
assert!(s.prompt_text().contains("Select object to extend"), "{}", s.prompt_text());
|
||||
s.cmdline("").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), vec![((0.0, 0.0), (10.0, 0.0)), ((0.0, 2.0), (10.0, 2.0)), ((10.0, -5.0), (10.0, 5.0))]);
|
||||
// Standard mode keeps the crossing window.
|
||||
let mut s = ladder();
|
||||
s.script("TRIM O S\n\n4,-4\n").unwrap();
|
||||
assert!(s.prompt_text().contains("Specify opposite corner"), "{}", s.prompt_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
//! TRIM keeps what the object has beyond its outline, as BREAK does: a line's Z, an arc's centre
|
||||
//! Z (a circle trimmed into an arc), a polyline's elevation, and a polyline's constant width on
|
||||
//! every piece. The Z cases and the width on BREAK were measured in AutoCAD 2024 (accoreconsole)
|
||||
//! on these drawings.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Circle, Common, Entity, EntityKind, Handle, Line, LwPolyline};
|
||||
use cadcraft_engine::geom::{PolyVertex, Vec2, Vec3};
|
||||
use serde_json::json;
|
||||
|
||||
fn add(s: &mut Session, kind: EntityKind, thickness: f64) -> Handle {
|
||||
let space = s.space();
|
||||
let d = s.doc_mut().unwrap();
|
||||
let handle = d.new_handle();
|
||||
d.space_mut(&space).unwrap().push(Entity { handle, common: Common { thickness, ..Common::default() }, kind });
|
||||
handle
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
|
||||
let v = s.execute("line", &json!({ "points": [a, b] })).unwrap();
|
||||
Handle::parse_hex(v["handles"][0].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edge: Handle) {
|
||||
s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "edges": [edge.hex()] })).unwrap();
|
||||
}
|
||||
|
||||
fn kind(s: &Session, h: Handle) -> EntityKind {
|
||||
s.doc().unwrap().entity(h).unwrap().kind.clone()
|
||||
}
|
||||
|
||||
fn polyline(vertices: &[(f64, f64, f64)], const_width: f64, elevation: f64, plinegen: bool) -> EntityKind {
|
||||
let vertices = vertices.iter().map(|&(x, y, bulge)| PolyVertex { bulge, ..PolyVertex::new(Vec2::new(x, y)) }).collect();
|
||||
EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width, elevation, plinegen })
|
||||
}
|
||||
|
||||
fn near(a: Vec3, b: Vec3, tol: f64) -> bool {
|
||||
(a.x - b.x).abs() < tol && (a.y - b.y).abs() < tol && (a.z - b.z).abs() < tol
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_keeps_a_lines_z() {
|
||||
let mut s = Session::new();
|
||||
let a = add(&mut s, EntityKind::Line(Line { a: Vec3::new(0.5, 0.25, 0.007), b: Vec3::new(0.54, 0.25, 0.007) }), 0.0);
|
||||
let b = line(&mut s, [0.52, 0.24], [0.52, 0.26]);
|
||||
trim(&mut s, a, [0.53, 0.25], b);
|
||||
let EntityKind::Line(l) = kind(&s, a) else { panic!("not a line") };
|
||||
assert!(near(l.a, Vec3::new(0.5, 0.25, 0.007), 1e-12) && near(l.b, Vec3::new(0.52, 0.25, 0.007), 1e-12), "{l:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_keeps_the_centre_z_of_a_circle_made_an_arc() {
|
||||
// At survey coordinates, with a thickness of 2.
|
||||
let mut s = Session::new();
|
||||
let c = add(&mut s, EntityKind::Circle(Circle { center: Vec3::new(612345.678, 2398765.432, 5.0), radius: 10.0 }), 2.0);
|
||||
let b = line(&mut s, [612350.678, 2398745.432], [612350.678, 2398785.432]);
|
||||
trim(&mut s, c, [612335.678, 2398765.432], b);
|
||||
let e = s.doc().unwrap().entity(c).unwrap().clone();
|
||||
let EntityKind::Arc(a) = &e.kind else { panic!("not an arc: {:?}", e.kind) };
|
||||
assert!(near(a.center, Vec3::new(612345.678, 2398765.432, 5.0), 1e-9), "{a:?}");
|
||||
assert!((a.start - 5.235987755978257).abs() < 1e-9 && (a.end - 1.047197551201328).abs() < 1e-9, "{a:?}");
|
||||
assert_eq!(e.common.thickness, 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_keeps_a_polylines_elevation() {
|
||||
let mut s = Session::new();
|
||||
let p = add(&mut s, polyline(&[(0.0, 0.0, 0.0), (20.0, 0.0, 0.4), (30.0, 15.0, 0.0), (5.0, 20.0, 0.0)], 0.0, 12.5, false), 1.0);
|
||||
let b = line(&mut s, [10.0, -10.0], [10.0, 30.0]);
|
||||
trim(&mut s, p, [5.0, 0.0], b);
|
||||
let EntityKind::LwPolyline(l) = kind(&s, p) else { panic!("not a polyline") };
|
||||
assert_eq!(l.elevation, 12.5);
|
||||
let want = [(10.0, 0.0, 0.0), (20.0, 0.0, 0.4), (30.0, 15.0, 0.0), (5.0, 20.0, 0.0)];
|
||||
assert_eq!(l.vertices.len(), want.len());
|
||||
for (v, w) in l.vertices.iter().zip(want) {
|
||||
assert!(near(Vec3::new(v.p.x, v.p.y, v.bulge), Vec3::new(w.0, w.1, w.2), 1e-12), "{v:?} != {w:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_and_trim_keep_a_polylines_constant_width_on_every_piece() {
|
||||
// Measured for BREAK: a width-2 polyline broken from (705, 0) to (735, 0) leaves two width-2
|
||||
// pieces. TRIM leaves its pieces the same way. Linetype generation is the polyline's setting
|
||||
// too, so the pieces keep it (not measured).
|
||||
let shape = [(700.0, 0.0, 0.0), (720.0, 0.0, 0.0), (740.0, 0.0, 0.0)];
|
||||
let mut s = Session::new();
|
||||
let p = add(&mut s, polyline(&shape, 2.0, 0.0, true), 0.0);
|
||||
let r = s.execute("break", &json!({ "handle": p.hex(), "p1": [705, 0], "p2": [735, 0] })).unwrap();
|
||||
let mut s2 = Session::new();
|
||||
let q = add(&mut s2, polyline(&shape, 2.0, 0.0, true), 0.0);
|
||||
let k1 = line(&mut s2, [705.0, -5.0], [705.0, 5.0]);
|
||||
let k2 = line(&mut s2, [735.0, -5.0], [735.0, 5.0]);
|
||||
let t = s2.execute("trim", &json!({ "handle": q.hex(), "pick": [720, 0], "edges": [k1.hex(), k2.hex()] })).unwrap();
|
||||
for (s, r) in [(&s, &r), (&s2, &t)] {
|
||||
let hs = r["handles"].as_array().unwrap();
|
||||
assert_eq!(hs.len(), 2);
|
||||
for h in hs {
|
||||
let EntityKind::LwPolyline(l) = kind(s, Handle::parse_hex(h.as_str().unwrap()).unwrap()) else { panic!("not a polyline") };
|
||||
assert_eq!((l.const_width, l.plinegen), (2.0, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user