mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-23 14:25:22 -06:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e4c350dd2 |
@@ -60,4 +60,3 @@ jobs:
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
|
||||
+1
-3
@@ -19,9 +19,7 @@ Generated-in-code assets are original and have no file to list:
|
||||
- the standard linetype and hatch-pattern libraries (`crates/doc/src/library.rs`; industry-common
|
||||
names, our own dash/spacing values);
|
||||
- the colour index palette, generated from its structure (`crates/color/src/lib.rs`);
|
||||
- the sample drawings (`crates/engine/src/sample.rs`);
|
||||
- the synthetic two-hexagon hatch logo (`crates/io/tests/it/hatch_loop_flags.rs`, `logo`):
|
||||
original contributor geometry, generated in code from invented points, under MIT OR Apache-2.0.
|
||||
- the sample drawings (`crates/engine/src/sample.rs`).
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
|
||||
Generated
+102
-97
@@ -648,7 +648,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"cadcraft-engine",
|
||||
"cadcraft-io",
|
||||
@@ -661,7 +661,6 @@ dependencies = [
|
||||
"craft-window",
|
||||
"eframe",
|
||||
"egui",
|
||||
"fmv-macos-events",
|
||||
"hidapi",
|
||||
"log",
|
||||
"muda",
|
||||
@@ -682,7 +681,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-cli"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"cadcraft-engine",
|
||||
"cadcraft-io",
|
||||
@@ -698,14 +697,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-color"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-constraints"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"cadcraft-doc",
|
||||
"cadcraft-geom",
|
||||
@@ -715,7 +714,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-doc"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"cadcraft-color",
|
||||
"cadcraft-geom",
|
||||
@@ -727,7 +726,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-engine"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"cadcraft-color",
|
||||
"cadcraft-constraints",
|
||||
@@ -749,7 +748,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-fonts"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"cadcraft-geom",
|
||||
"craft-dxf",
|
||||
@@ -764,14 +763,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-geom"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-io"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"cadcraft-color",
|
||||
@@ -781,7 +780,7 @@ dependencies = [
|
||||
"cadcraft-render",
|
||||
"craft-dwg",
|
||||
"craft-dxf",
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-pdf",
|
||||
"craft-svg",
|
||||
"image",
|
||||
@@ -795,7 +794,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-mcp"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"cadcraft-engine",
|
||||
"cadcraft-io",
|
||||
@@ -812,13 +811,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-render"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"cadcraft-color",
|
||||
"cadcraft-doc",
|
||||
"cadcraft-fonts",
|
||||
"cadcraft-geom",
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"lyon_tessellation",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
@@ -827,7 +826,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-ui-egui"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"cadcraft-color",
|
||||
"cadcraft-doc",
|
||||
@@ -837,7 +836,7 @@ dependencies = [
|
||||
"cadcraft-io",
|
||||
"cadcraft-render",
|
||||
"chrono",
|
||||
"craft-image-codecs",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"craft-window",
|
||||
@@ -856,7 +855,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cadcraft-web"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"cadcraft-engine",
|
||||
"cadcraft-fonts",
|
||||
@@ -1181,30 +1180,22 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
|
||||
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=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-dwg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf#7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"log",
|
||||
@@ -1225,26 +1216,22 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c07e38090879ffa994f893df9956c6d5b96c049c#c07e38090879ffa994f893df9956c6d5b96c049c"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"kurbo",
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
"unicode-segmentation",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -1267,12 +1254,35 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
"craft-metadata",
|
||||
"craft-tiff",
|
||||
"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",
|
||||
@@ -1294,7 +1304,15 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
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",
|
||||
]
|
||||
@@ -1302,7 +1320,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jsonrpc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1310,7 +1328,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mcp"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c"
|
||||
dependencies = [
|
||||
"craft-jsonrpc",
|
||||
"serde_json",
|
||||
@@ -1319,11 +1337,23 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"chrono",
|
||||
"craft-tiff",
|
||||
"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",
|
||||
]
|
||||
@@ -1331,17 +1361,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
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=453b0da782ccef39be9a6dac8d27c80b553ef1cc)",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db)",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
dependencies = [
|
||||
"hayro-syntax",
|
||||
"krilla",
|
||||
@@ -1351,13 +1381,14 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-shx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
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=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
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",
|
||||
@@ -1371,7 +1402,16 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
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",
|
||||
@@ -1380,7 +1420,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1401,7 +1441,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1428,7 +1468,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -1439,7 +1479,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
|
||||
dependencies = [
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
@@ -1448,7 +1488,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
@@ -1459,7 +1499,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2057,17 +2097,6 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
|
||||
|
||||
[[package]]
|
||||
name = "fmv-macos-events"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.1.5"
|
||||
@@ -2417,19 +2446,6 @@ dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "harfrust"
|
||||
version = "0.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "948d0741125ba89cd3e1c23e5642415b6ade7e1d29d67ba25fb925b533e989d6"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"once_cell",
|
||||
"read-fonts 0.43.3",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "harfrust"
|
||||
version = "0.14.0"
|
||||
@@ -2489,7 +2505,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
dependencies = [
|
||||
"hayro-ccitt",
|
||||
]
|
||||
@@ -2506,7 +2522,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
dependencies = [
|
||||
"hayro-jbig2",
|
||||
"hayro-jpeg2000",
|
||||
@@ -3006,7 +3022,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4268,17 +4284,6 @@ dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.43.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "005c8acf251756c478b0bf402885bfd88a1476020c4c7e6060edc1aa68da38ea"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.44.0"
|
||||
@@ -6362,7 +6367,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"serde_json",
|
||||
|
||||
+17
-17
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
# default-members
|
||||
|
||||
[workspace.package]
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -15,10 +15,10 @@ repository = "https://github.com/storytold/cadcraft"
|
||||
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 = "219c1d0b14177af6f291395d6587f61a5e09043a" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
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 +28,17 @@ 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 = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
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 = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
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 = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
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 = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
|
||||
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 = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
|
||||
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"] }
|
||||
@@ -70,8 +70,8 @@ encoding_rs = "0.8.35"
|
||||
quick-xml = "0.42"
|
||||
|
||||
# ui
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
|
||||
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
@@ -81,7 +81,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 = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
@@ -113,9 +113,9 @@ debug = 0
|
||||
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
|
||||
# (Cargo ignores dependency-local patches).
|
||||
[patch.crates-io]
|
||||
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -184,34 +184,6 @@ in the text style or set `FONTFALLBACK` (`CADCRAFT_FONTFALLBACK="Vazirmatn"`). F
|
||||
inside a word (an MTEXT colour change in the middle of a Persian word) break the joining at that
|
||||
point.
|
||||
|
||||
### Portable Windows ZIP
|
||||
|
||||
The Windows portable ZIP includes `portable.txt` beside `cadcraft.exe`. With that
|
||||
marker present, the desktop app's settings, logs, autosaves, workspace data,
|
||||
plotter files, and eframe preferences/window state stay in `CADCraftData` beside
|
||||
the executable. eframe saves its preferences and window state in `CADCraftData/app.ron`.
|
||||
Keep that directory when replacing the binaries. The MSI does not include the
|
||||
marker and continues to use the normal user profile.
|
||||
|
||||
`CADCRAFT_CONFIG_DIR` takes precedence over the marker, including an empty or
|
||||
blank value that disables the settings folder. If `CADCraftData` cannot be
|
||||
created or written, CADCraft warns and uses the normal profile. Existing profile
|
||||
settings are not automatically copied into the portable directory.
|
||||
|
||||
Before switching an existing Windows installation to portable mode, close CADCraft,
|
||||
back up `%APPDATA%\CADCraft`, and copy the settings you want to retain into
|
||||
`CADCraftData`. Include the `autosave` folder if you need to recover unsaved drawings. The
|
||||
preferences and window state are kept apart, in `%APPDATA%\ai.storyteller.cadcraft\data\app.ron`:
|
||||
copy that file to `CADCraftData\app.ron` to keep them.
|
||||
Updating a portable ZIP, including through the updater, can restore `portable.txt`;
|
||||
set `CADCRAFT_CONFIG_DIR` to your existing profile folder to keep using it across updates.
|
||||
|
||||
`cadcraft-cli.exe` does not detect the marker. To share the desktop app's portable
|
||||
settings, pass `--config-dir` with the full path to `CADCraftData`, or set
|
||||
`CADCRAFT_CONFIG_DIR` to that path. The marker is also recognized on other desktop
|
||||
platforms, but is intended for a standalone writable installation, not inside a
|
||||
signed macOS application bundle.
|
||||
|
||||
### Logs
|
||||
|
||||
The desktop app writes its `log` records to standard error and to `logs/cadcraft.log` in the
|
||||
|
||||
+10
-15
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: pre-alpha** · next: alpha, when the six rows of the [alpha gate](docs/roadmap.md#alpha-gate) pass (five fail today; the gate was revised on 2026-11-19 and its hours are not re-estimated yet)
|
||||
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-20 · **Change:** minor (Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-19 · **Change:** major (alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
|
||||
CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and
|
||||
plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a
|
||||
@@ -115,23 +115,21 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
|
||||
- The open findings of the security audit (#1919–#1935): check each against the input limits that
|
||||
landed on 2026-11-11, close what is fixed and fix the rest. A crafted handle that makes new entities
|
||||
overwrite existing ones (#1921) is fixed by #1276.
|
||||
- A saved file that crashes AutoCAD 2021 (#3303) and dimension text lost on save (#3299).
|
||||
- Hostile-input fixes waiting in pull requests (#2820, #2821, #2765).
|
||||
- Crashes and hangs with a reproduction: the web build on a large DXF (#1603), a DWG with 3D content
|
||||
(#2174), startup on older graphics hardware (#1724, #1631, #3222).
|
||||
|
||||
**2. Parity with AutoCAD: the alpha gate rows, then the beta checklist (apart from its items named under tier 3).**
|
||||
- It starts on common hardware: an automatic fallback renderer (`CADCRAFT_STENCIL=0` is the manual
|
||||
switch since #3336).
|
||||
- It starts on common hardware (#1596, then an automatic fallback renderer).
|
||||
- It opens the DWG and DXF files people already have: large files (#3102, #2633, #1088), layouts and
|
||||
paper units (#1672, #2836), and a corpus of real files run in CI.
|
||||
- Saving loses nothing and other CAD programs open the result (#2904, #1687, #3234, #2632).
|
||||
- Input feels like AutoCAD for Windows: the fixes for clicks while the mouse moves, right-click and
|
||||
Space as Enter, and double-click text editing landed (#3307, #3345); waiting for the reporters to
|
||||
confirm, and table cells are left (#842).
|
||||
- The prompt options that still say "not available yet" (gaps F1).
|
||||
- Layouts print at scale on a system printer (#3216); the menu bar and panels can be restored since
|
||||
#3308.
|
||||
- 661 pull requests are open (2026-11-20; 714 the day before). About 230 were mergeable, passed CI and were small; they are
|
||||
- Input feels like AutoCAD for Windows: clicks while the mouse moves (#1001, #2092), right-click and
|
||||
Space as Enter (#1387), double-click to edit text (#842).
|
||||
- The prompt options that still say "not available yet", and TRIM/EXTEND depth.
|
||||
- Layouts print at scale on a system printer, and the menu bar and panels can always be restored
|
||||
(#3216, #1240).
|
||||
- 714 pull requests are open (2026-11-19). About 230 are mergeable, pass CI and are small; they are
|
||||
reviewed and landed in this order, the longest-waiting authors first within a row.
|
||||
|
||||
**3. Lower priority: affects fewer people and nothing breaks without it.**
|
||||
@@ -141,9 +139,7 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
|
||||
but a file with 3D content must open safely (tier 1).
|
||||
- Menu breadth against AutoCAD for Mac as a headline number.
|
||||
|
||||
Done on 2026-11-19 and 2026-11-20: the hostile-input fixes #1276, #2820, #2821 and #2765 (#3304, #3305), clicks while the mouse moves and right-click or Space as Enter (#3307), the interface reset (#3308), paper units (#3309), the UCS command (#3310), -ATTEDIT, -RENAME and -LAYER options (#3311), TRIM/EXTEND depth (#3312), dimension values kept on save (#3335), the stencil switch (#3336), a typed OPEN path (#3343) and double-click text editing (#3345).
|
||||
|
||||
Done before that: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
|
||||
Done since the last ranking: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
|
||||
OFFSET, ROTATE, PLINE, SPLINE, MTEXT and MLEADER (#397, #408, #547), autosave, recovery, AUDIT and
|
||||
RECOVER on the desktop (#406, #416), xrefs (#525), groups (#417), the Block Editor (#824, #833, #885),
|
||||
REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the Dimension Style Manager
|
||||
@@ -170,7 +166,6 @@ REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the D
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | minor | Upcoming updated for the merges of 2026-11-19 and 2026-11-20 (security stacks, input, interface reset, paper units, UCS, prompt options, TRIM/EXTEND, text editing in place); pull-request count 714 → 661; percentages and hours not re-scored |
|
||||
| 2026-11-19 | major | Alpha gate revised from user reports (six rows, Windows first; block authoring, xref editing in place and exact curve geometry moved to beta); Upcoming re-ranked into three tiers: urgent (security, leaks, crashes, lost work), parity, lower priority; percentages and hours not re-scored |
|
||||
| 2026-10-24 | minor | Re-audit against main 41d9b5e95: language table, CI gate and open-PR count re-checked against main 41d9b5e95 |
|
||||
| 2026-10-21 | trivial | Progress log: proxy objects keep their class through a save (#1812) |
|
||||
|
||||
@@ -56,9 +56,6 @@ fn install_io() {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
}
|
||||
|
||||
/// `path` as text, for the engine and io calls that take a file name as a string.
|
||||
@@ -79,11 +76,6 @@ pub fn command() -> clap::Command {
|
||||
/// Run the CLI on its arguments (without the program name). Returns the process exit code (0 ok,
|
||||
/// 1 failure, 2 usage). clap reads the arguments as they are: a value that is not valid Unicode
|
||||
/// is a usage error, never a panic as with `std::env::args()`.
|
||||
///
|
||||
/// Reading or writing DWG needs a conversion worker, which this function does not set up: the
|
||||
/// binary calls `cadcraft_io::dwg_worker::use_own_worker()` first. A caller that converts only its
|
||||
/// own, trusted files can call `cadcraft_io::dwg_worker::allow_in_process()` instead. With
|
||||
/// neither, a DWG file gets "no worker is configured" and exit code 1.
|
||||
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
@@ -96,7 +88,7 @@ where
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
|
||||
return match write!(to, "{}", e.render()).and_then(|()| to.flush()) {
|
||||
return match write!(to, "{}", e.render()) {
|
||||
Err(w) if w.kind() != std::io::ErrorKind::BrokenPipe => {
|
||||
let _ = writeln!(err, "error: can't write the output: {w}");
|
||||
1
|
||||
@@ -166,25 +158,6 @@ mod tests {
|
||||
assert_eq!(run(["--help"], &mut FailingWriter(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
|
||||
}
|
||||
|
||||
struct FailingFlush(std::io::ErrorKind);
|
||||
|
||||
impl Write for FailingFlush {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_flush_of_help_exits_1_unless_the_pipe_is_closed() {
|
||||
let mut err = Vec::new();
|
||||
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::StorageFull), &mut err), 1);
|
||||
assert!(String::from_utf8_lossy(&err).starts_with("error: "));
|
||||
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_atomic_replaces_file_and_leaves_no_staging_files() {
|
||||
let dir = scratch_dir("replace");
|
||||
|
||||
@@ -58,7 +58,7 @@ pub(crate) fn roundtrip(a: &RoundtripArgs, io: &mut Streams) -> Result {
|
||||
if a.keep_saved {
|
||||
opts.keep_saved = Some(out.join("saved"));
|
||||
}
|
||||
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| io.errln(format_args!("[{}/{n}] {rel}", i + 1)));
|
||||
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| eprintln!("[{}/{n}] {rel}", i + 1));
|
||||
for f in &report.files {
|
||||
let routes: Vec<String> = f
|
||||
.routes
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::args::{CmdStep, Drawing, RunArgs, Step};
|
||||
use super::error::Result;
|
||||
use super::open;
|
||||
use super::output::{Streams, export, export_framed, export_window, model_views, undrawn_message};
|
||||
use super::output::{Streams, export, export_framed, export_window, model_views};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Handle;
|
||||
use serde_json::Value;
|
||||
@@ -216,15 +216,7 @@ pub(crate) fn run_cmds(a: &RunArgs, io: &mut Streams) -> Result {
|
||||
export(&s, p, io)?;
|
||||
}
|
||||
if let Some(p) = export_to {
|
||||
let window = if cadcraft_io::is_image(p) {
|
||||
let window = export_window(&s, framing, Some(&before))?;
|
||||
if let Some(message) = undrawn_message(s.doc()?, &p.to_string_lossy()) {
|
||||
io.errln(format_args!("{message}"));
|
||||
}
|
||||
window
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let window = if cadcraft_io::is_image(p) { export_window(&s, framing, Some(&before))? } else { None };
|
||||
export_framed(&s, p, window, io)?;
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -8,7 +8,6 @@ use cadcraft_io::dwg_worker;
|
||||
#[test]
|
||||
fn a_real_worker_reads_and_writes_and_its_death_is_an_error_here() {
|
||||
let drawing = cadcraft_engine::sample::bracket();
|
||||
dwg_worker::allow_in_process();
|
||||
let in_process = cadcraft_io::write(&drawing, "a.dwg").unwrap();
|
||||
|
||||
dwg_worker::use_worker(env!("CARGO_BIN_EXE_cadcraft-cli").into(), vec![dwg_worker::WORKER_ARG.into()]);
|
||||
@@ -35,8 +34,7 @@ fn a_real_worker_reads_and_writes_and_its_death_is_an_error_here() {
|
||||
assert!(e.contains("worker stopped"), "{e}");
|
||||
assert!(cadcraft_io::read(&written, "a.dwg").is_ok(), "the next file gets a new worker");
|
||||
|
||||
// A worker that cannot start is an error, even where in-process conversion is allowed.
|
||||
// No worker to start: the work happens here, as without one.
|
||||
dwg_worker::use_worker("no-such-program-here".into(), Vec::new());
|
||||
let e = cadcraft_io::read(&written, "a.dwg").unwrap_err().to_string();
|
||||
assert!(e.contains("could not start"), "{e}");
|
||||
assert!(cadcraft_io::read(&written, "a.dwg").is_ok());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Image exports report how many model-space entities they can't draw, by type. The exit code
|
||||
//! stays 0 (#1208).
|
||||
//! `convert` to an image says how many model-space entities it can't draw, by type, instead of
|
||||
//! leaving them out silently (#1208). The exit code stays 0.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
@@ -70,28 +70,6 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() {
|
||||
assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_image_export_warns_about_undrawn_entities() {
|
||||
let scratch = Scratch::new("run-undrawn");
|
||||
let input = scratch.0.join("proxies.dxf");
|
||||
std::fs::write(&input, PROXIES).unwrap();
|
||||
let image = scratch.0.join("out.svg");
|
||||
let out = cli(&["run", input.to_str().unwrap(), "--export", image.to_str().unwrap()]);
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{:?}: {err}", out.status);
|
||||
assert!(image.is_file());
|
||||
assert!(out.stdout.is_empty(), "the warning belongs on stderr");
|
||||
let warnings: Vec<&str> = err.lines().filter(|l| l.contains("not drawn")).collect();
|
||||
assert_eq!(warnings, [format!("{}: 3 entities not drawn (PDFUNDERLAY: 1, REGION: 2)", image.display())], "{err}");
|
||||
|
||||
let copy = scratch.0.join("copy.dxf");
|
||||
let out = cli(&["run", input.to_str().unwrap(), "--export", copy.to_str().unwrap()]);
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{:?}: {err}", out.status);
|
||||
assert!(copy.is_file());
|
||||
assert!(!err.contains("not drawn"), "{err}");
|
||||
}
|
||||
|
||||
/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it an undrawn entity (#2422); it
|
||||
/// says once that the OLE content inside the frame is not drawn (review on #2587).
|
||||
#[test]
|
||||
|
||||
@@ -824,7 +824,6 @@ fn non_unicode_arguments() {
|
||||
fn non_unicode_output_names() {
|
||||
use std::ffi::OsString;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let s = Scratch::new("nonunicode-out");
|
||||
let latin1 = |ext: &str| {
|
||||
let mut n = b"caf\xe9.".to_vec();
|
||||
@@ -949,11 +948,3 @@ fn json_output_is_pretty_unless_compact() {
|
||||
assert_eq!(r.stdout.lines().count(), 2, "one line per --cmd result: {}", r.stdout);
|
||||
assert_eq!(invoke(&["run", "--sample", "--compact"]).code, 2, "run takes no --compact");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_progress_uses_the_requested_stderr() {
|
||||
run_cases(
|
||||
"roundtrip-progress",
|
||||
&[case("roundtrip progress", &["roundtrip", "{b}", "--same-format", "--no-census"], 0, Starts("b.dxf: opened;"), Line("[1/1] b.dxf"))],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ fn cli(args: &[&str]) -> Output {
|
||||
/// A DWG of 200 lines, and a copy damaged so that the reader skips some of its records (found the
|
||||
/// way the reader's own test finds one: flipping a few bytes at a time across the objects area).
|
||||
fn dwg_and_damaged_copy() -> (Vec<u8>, Vec<u8>) {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut dxf = String::from("0\nSECTION\n2\nENTITIES\n");
|
||||
for i in 0..200 {
|
||||
dxf += &format!("0\nLINE\n8\n0\n10\n{i}\n20\n0\n11\n{i}\n21\n10\n");
|
||||
|
||||
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
|
||||
cadcraft-fonts = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -130,9 +130,6 @@ mod web {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
let Some(canvas) = app_canvas() else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
|
||||
@@ -62,11 +62,6 @@ winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
|
||||
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
|
||||
# in Cargo.lock through eframe.
|
||||
pollster = "1"
|
||||
# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C
|
||||
# handler behind a safe API, without relaxing the workspace's unsafe-code lint.
|
||||
# Pinned exactly: review the implementation before bumping.
|
||||
fmv-macos-events = "=0.1.0"
|
||||
|
||||
# Rust HID backends: no proprietary SDK or C HID library.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
//! macOS open-documents and quit Apple events (#158).
|
||||
//!
|
||||
//! A Finder double-click, Open With, a drop on the Dock icon and `open -a CADCraft plan.dxf` don't
|
||||
//! put the path in argv: LaunchServices sends the running (or just-launched) app a
|
||||
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
|
||||
//! `NSApplicationDelegate`, so AppKit answered "CADCraft cannot open files in the Drawing Exchange
|
||||
//! Format format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which
|
||||
//! this workspace forbids. The pinned `fmv-macos-events` crate wraps exactly that, an
|
||||
//! `NSAppleEventManager` handler registered before Finder's
|
||||
//! launch event that leaves winit's delegate alone, behind a safe main-thread API.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use cadcraft_ui_egui::CadApp;
|
||||
#[cfg(target_os = "macos")]
|
||||
use fmv_macos_events::{Event, Inbox, Registration};
|
||||
|
||||
/// The shape of `fmv_macos_events::Event`, so [`dispatch`] and its tests also build and run where
|
||||
/// that crate is not compiled (PR CI runs on Linux). On macOS the crate's own type is used.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
enum Event {
|
||||
Open(Vec<PathBuf>),
|
||||
Quit,
|
||||
}
|
||||
|
||||
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub struct AppleEvents {
|
||||
_registration: Registration,
|
||||
inbox: Inbox,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl AppleEvents {
|
||||
/// Register the handlers. Call on the main thread before the event loop starts, so the event
|
||||
/// that launched the app (a Finder double-click) is caught too.
|
||||
pub fn install() -> Self {
|
||||
let (registration, inbox) = Registration::install();
|
||||
Self { _registration: registration, inbox }
|
||||
}
|
||||
|
||||
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
|
||||
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
|
||||
let ctx = ctx.clone();
|
||||
self.inbox.set_wake(move || ctx.request_repaint());
|
||||
self.inbox.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths to hand to OPEN: UTF-8 and non-empty, each once, in the order they arrived. A second
|
||||
/// copy of the same path (Finder sends one per selected item, and a drop can repeat) would open
|
||||
/// the drawing twice.
|
||||
fn openable(paths: impl IntoIterator<Item = PathBuf>) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for p in paths {
|
||||
if let Some(s) = p.to_str().filter(|s| !s.is_empty())
|
||||
&& !out.iter().any(|o| o == s)
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Dispatch a batch through the regular opening and unsaved-changes paths. Returns whether the
|
||||
/// window may close now; a queued quit must not bypass the Save / Don't Save / Cancel prompt.
|
||||
fn dispatch(events: impl IntoIterator<Item = Event>, app: &mut CadApp) -> bool {
|
||||
let mut quit = false;
|
||||
for e in events {
|
||||
match e {
|
||||
Event::Open(paths) => {
|
||||
for p in openable(paths) {
|
||||
app.open_path(std::path::Path::new(&p));
|
||||
}
|
||||
}
|
||||
Event::Quit => quit = true,
|
||||
}
|
||||
}
|
||||
quit && !app.request_quit()
|
||||
}
|
||||
|
||||
/// Drain the inbox each frame; a quit closes the window like Cmd+Q, prompting for unsaved drawings.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn poll(inbox: &Inbox, app: &mut CadApp, ctx: &egui::Context) {
|
||||
if dispatch(inbox.drain(), app) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Event, dispatch, openable};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::closing::Choice;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct TestDir(PathBuf);
|
||||
|
||||
impl TestDir {
|
||||
fn new() -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-apple-events-{}-{}", std::process::id(), NEXT_DIR.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn app() -> CadApp {
|
||||
crate::install_io();
|
||||
// The DWG written and read here is the test's own synthetic file; the app starts its DWG
|
||||
// worker in `main`, which a test does not run.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
CadApp::new(Session::new(), Services::default())
|
||||
}
|
||||
|
||||
fn settle(app: &mut CadApp) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while app.opening.busy() && Instant::now() < deadline {
|
||||
app.finish_opening();
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
app.finish_opening();
|
||||
assert!(!app.opening.busy(), "background opening completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_order_and_drops_duplicates_and_empty_paths() {
|
||||
let paths = ["/a/plan.dxf", "", "/b/site.dwg", "/a/plan.dxf"].map(PathBuf::from);
|
||||
assert_eq!(openable(paths), ["/a/plan.dxf", "/b/site.dwg"]);
|
||||
assert!(openable(Vec::new()).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn skips_paths_that_are_not_utf8() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let bad = PathBuf::from(std::ffi::OsString::from_vec(vec![b'/', 0xff, b'.', b'd', b'x', b'f']));
|
||||
assert_eq!(openable([bad, PathBuf::from("/ok.dxf")]), ["/ok.dxf"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_dwg_and_dxf_without_replacing_an_unsaved_drawing() {
|
||||
// Writing and opening the DWG here needs the converter in this process: each test is its own.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let dir = TestDir::new();
|
||||
let dxf = dir.0.join("planta com espaços.dxf");
|
||||
let dwg = dir.0.join("Documentac\u{327}a\u{303}o.dwg");
|
||||
let bytes = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n10\n0\nENDSEC\n0\nEOF\n";
|
||||
let drawing = cadcraft_io::read(bytes, "synthetic.dxf").unwrap();
|
||||
std::fs::write(&dxf, bytes).unwrap();
|
||||
std::fs::write(&dwg, cadcraft_io::write(&drawing, "synthetic.dwg").unwrap()).unwrap();
|
||||
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!dispatch([Event::Open(vec![dxf.clone(), dwg.clone(), dxf.clone(), PathBuf::new()])], &mut app));
|
||||
settle(&mut app);
|
||||
|
||||
assert_eq!(app.session.docs.len(), 3, "each file is opened once alongside the unsaved drawing");
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
for path in [&dxf, &dwg] {
|
||||
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == path.to_str()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_open_reports_the_path_and_keeps_existing_drawings() {
|
||||
let dir = TestDir::new();
|
||||
let missing = dir.0.join("missing drawing.dwg");
|
||||
let mut app = app();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(!dispatch([Event::Open(vec![missing.clone()])], &mut app));
|
||||
settle(&mut app);
|
||||
assert_eq!(app.session.docs.len(), 1);
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.log.iter().any(|line| line.contains(missing.to_str().unwrap())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_asks_before_closing_unsaved_work_and_can_be_cancelled() {
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
assert!(!dispatch([Event::Quit], &mut app), "must not issue a window close before the answer");
|
||||
assert!(app.close_prompt().is_some());
|
||||
assert!(!app.quit_confirmed);
|
||||
assert!(!app.quit_requested);
|
||||
app.answer_close(Choice::Cancel);
|
||||
assert!(app.close_prompt().is_none());
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!app.quit_requested);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_can_close_a_clean_session() {
|
||||
let mut app = app();
|
||||
assert!(dispatch([Event::Quit], &mut app));
|
||||
assert!(app.close_prompt().is_none());
|
||||
}
|
||||
}
|
||||
@@ -35,10 +35,8 @@ pub(crate) const VARS: &[(&str, &str)] = &[
|
||||
/// `CADCRAFT_CONFIG_DIR`.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(crate) struct Env {
|
||||
/// Portable eframe storage file, kept with the other settings instead of the user profile.
|
||||
pub(crate) portable_storage_file: Option<PathBuf>,
|
||||
/// The settings folder (logs, autosave, workspace, plotters): `CADCRAFT_CONFIG_DIR`; else, when
|
||||
/// that is unset, the portable directory or the platform's (`cadcraft_engine::settings_dir::platform`). `None`: no
|
||||
/// that is unset, the platform's (`cadcraft_engine::settings_dir::platform`). `None`: no
|
||||
/// folder, because the variable is empty or blank (the way to run without one) or the
|
||||
/// platform has none.
|
||||
pub(crate) config_dir: Option<PathBuf>,
|
||||
@@ -65,26 +63,7 @@ pub(crate) struct Env {
|
||||
|
||||
impl Env {
|
||||
pub(crate) fn read() -> Env {
|
||||
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(PathBuf::from));
|
||||
Self::from_vars_and_exe(|k| std::env::var_os(k), exe_dir.as_deref())
|
||||
}
|
||||
|
||||
fn from_vars_and_exe(var: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&std::path::Path>) -> Env {
|
||||
let mut vars = Env::from_vars(&var);
|
||||
// An explicit override (including blank, which disables settings) takes precedence.
|
||||
if var(CONFIG_DIR).is_none()
|
||||
&& let Some(exe) = exe_dir
|
||||
{
|
||||
match crate::portable::directory_in(exe) {
|
||||
Ok(Some(data)) => {
|
||||
vars.config_dir = Some(data.clone());
|
||||
vars.portable_storage_file = Some(data.join("app.ron"));
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => log::warn!("portable settings cannot be written ({error}); using the user profile"),
|
||||
}
|
||||
}
|
||||
vars
|
||||
Env::from_vars(|k| std::env::var_os(k))
|
||||
}
|
||||
|
||||
/// [`Env::read`] with `var` looking a variable up.
|
||||
@@ -92,7 +71,6 @@ impl Env {
|
||||
let text = |k: &str| var(k).and_then(|v| v.into_string().ok()).filter(|v| !v.trim().is_empty());
|
||||
let switch = |k: &str| Switch::parse(k, var(k).map(|v| v.to_string_lossy().into_owned()).as_deref());
|
||||
Env {
|
||||
portable_storage_file: None,
|
||||
config_dir: match var(CONFIG_DIR) {
|
||||
Some(dir) if dir.to_str().is_some_and(|d| d.trim().is_empty()) => None,
|
||||
Some(dir) => Some(PathBuf::from(dir)),
|
||||
@@ -124,37 +102,6 @@ mod tests {
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
|
||||
#[test]
|
||||
fn portable_eframe_storage_is_a_file_inside_the_settings_directory() {
|
||||
let exe = std::env::temp_dir().join(format!("cadcraft-env-portable-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join("portable.txt"), "").unwrap();
|
||||
let vars = Env::from_vars_and_exe(env(&[("APPDATA", "/profile")]), Some(&exe));
|
||||
assert_eq!(vars.config_dir, Some(exe.join("CADCraftData")));
|
||||
let storage_file = vars.portable_storage_file.unwrap();
|
||||
assert_eq!(storage_file, exe.join("CADCraftData").join("app.ron"));
|
||||
assert_eq!(storage_file.parent(), vars.config_dir.as_deref());
|
||||
std::fs::write(&storage_file, r#"{"window":"saved window state"}"#).unwrap();
|
||||
let restarted = Env::from_vars_and_exe(env(&[("APPDATA", "/profile")]), Some(&exe));
|
||||
assert_eq!(restarted.portable_storage_file.as_ref(), Some(&storage_file));
|
||||
assert_eq!(std::fs::read_to_string(restarted.portable_storage_file.unwrap()).unwrap(), r#"{"window":"saved window state"}"#);
|
||||
std::fs::remove_dir_all(exe).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_override_skips_portable_probe() {
|
||||
let exe = std::env::temp_dir().join(format!("cadcraft-env-override-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join("portable.txt"), "").unwrap();
|
||||
for value in ["/custom", "", " "] {
|
||||
let vars = Env::from_vars_and_exe(env(&[(CONFIG_DIR, value)]), Some(&exe));
|
||||
assert_eq!(vars.config_dir, (!value.trim().is_empty()).then(|| PathBuf::from(value)));
|
||||
assert_eq!(vars.portable_storage_file, None);
|
||||
assert!(!exe.join("CADCraftData").exists());
|
||||
}
|
||||
std::fs::remove_dir_all(exe).unwrap();
|
||||
}
|
||||
|
||||
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
|
||||
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
|
||||
}
|
||||
@@ -199,7 +146,6 @@ mod tests {
|
||||
assert_eq!(
|
||||
read,
|
||||
Env {
|
||||
portable_storage_file: None,
|
||||
config_dir: Some(PathBuf::from("/private/cc")),
|
||||
locale: Some("cs-CZ".into()),
|
||||
vsync: Switch::On,
|
||||
|
||||
@@ -14,8 +14,6 @@
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
mod apple_events;
|
||||
mod control_server;
|
||||
mod desktop_theme;
|
||||
mod env;
|
||||
@@ -25,7 +23,6 @@ mod launch_args;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod portable;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod sheet;
|
||||
mod single_instance;
|
||||
@@ -56,9 +53,6 @@ struct App {
|
||||
/// The `movable` flag last set on the main window.
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: Option<bool>,
|
||||
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events: fmv_macos_events::Inbox,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -107,9 +101,6 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Drawings and quit requests from Finder, the Dock and `open -a` (macOS).
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events::poll(&self.apple_events, &mut self.cad, ctx);
|
||||
// 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
|
||||
@@ -182,9 +173,6 @@ pub fn install_io() {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
@@ -247,12 +235,9 @@ fn saved_window(app_ron: &str) -> bool {
|
||||
|
||||
/// The window state from the last session is saved and will be restored (#2595). A saved size
|
||||
/// below the minimum (seen on Windows: 64×64 points, which eframe restores un-maximized and
|
||||
/// unusable) is dropped first, so the window opens at its default size. `portable_file`: the
|
||||
/// portable copy's settings file, read instead of the user profile's.
|
||||
fn restores_window(portable_file: Option<&std::path::Path>) -> bool {
|
||||
let Some(path) = portable_file.map(std::path::PathBuf::from).or_else(|| eframe::storage_dir(APP_ID).map(|dir| dir.join("app.ron"))) else {
|
||||
return false;
|
||||
};
|
||||
/// unusable) is dropped first, so the window opens at its default size.
|
||||
fn restores_window() -> bool {
|
||||
let Some(path) = eframe::storage_dir(APP_ID).map(|dir| dir.join("app.ron")) else { return false };
|
||||
let Ok(mut ron) = std::fs::read_to_string(&path) else { return false };
|
||||
// Through a temporary file: a failed write (a full disk) keeps the other saved settings.
|
||||
if let Some(fixed) = without_tiny_window(&ron)
|
||||
@@ -406,8 +391,7 @@ fn main() -> eframe::Result {
|
||||
// The crosshair is drawn by the app: present without a queue on Linux/BSD, where X11
|
||||
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
|
||||
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
|
||||
persistence_path: vars.portable_storage_file.clone(),
|
||||
..window_options(restores_window(vars.portable_storage_file.as_deref()), stencil)
|
||||
..window_options(restores_window(), stencil)
|
||||
};
|
||||
if let Some(icon) = app_icon() {
|
||||
options.viewport = options.viewport.with_icon(icon);
|
||||
@@ -446,12 +430,6 @@ fn main() -> eframe::Result {
|
||||
b.with_close_requested_on_terminate(true);
|
||||
}));
|
||||
}
|
||||
// Registered before the event loop starts, so it catches the Finder event that launched us as
|
||||
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = apple_events::AppleEvents::install();
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = &apple_events;
|
||||
eframe::run_native(
|
||||
"CADCraft",
|
||||
options,
|
||||
@@ -515,14 +493,6 @@ fn main() -> eframe::Result {
|
||||
for f in &files {
|
||||
app.open_path(f);
|
||||
}
|
||||
// Start reading any launch-time documents before the first frame. Later events use
|
||||
// this same inbox, including the normal unsaved-changes handling for quit requests.
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events = {
|
||||
let inbox = apple_events.connect(&cc.egui_ctx);
|
||||
apple_events::poll(&inbox, &mut app, &cc.egui_ctx);
|
||||
inbox
|
||||
};
|
||||
if app.session.docs.is_empty() {
|
||||
// In the units the profile asks for (MEASUREINIT, restored above).
|
||||
let metric = app.session.settings.measureinit;
|
||||
@@ -550,8 +520,6 @@ fn main() -> eframe::Result {
|
||||
menus_in_window: vars.no_native_menu == Switch::On,
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: None,
|
||||
#[cfg(target_os = "macos")]
|
||||
apple_events,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -144,10 +144,6 @@ impl NativeMenu {
|
||||
self.last_refresh = now;
|
||||
let typing = menus::text_field_window(ctx).is_some();
|
||||
for (cmd, _, item) in self.items.values() {
|
||||
// Open Recent rebuilds this item with the correct enabled state.
|
||||
if cmd == menus::RECENT_CLEAR {
|
||||
continue;
|
||||
}
|
||||
let en = (typing && menus::edits_text(cmd)) || cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
|
||||
item.set_enabled(en);
|
||||
}
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
//! Windows portable ZIP settings, selected by a marker beside the executable.
|
||||
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// A marker must be a file. Prove the data folder is writable before selecting it.
|
||||
pub(crate) fn directory_in(exe_dir: &Path) -> std::io::Result<Option<PathBuf>> {
|
||||
if !exe_dir.join("portable.txt").is_file() {
|
||||
return Ok(None);
|
||||
}
|
||||
let data = exe_dir.join("CADCraftData");
|
||||
std::fs::create_dir_all(&data)?;
|
||||
let probe = data.join(format!(".portable-write-test-{}", std::process::id()));
|
||||
// A byte, not just an empty file: a full drive can still make the file and refuse its data.
|
||||
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
let written = file.write_all(&[0]).and_then(|()| file.sync_all());
|
||||
drop(file);
|
||||
let removed = std::fs::remove_file(&probe);
|
||||
written?;
|
||||
removed?;
|
||||
Ok(Some(data))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct Temp(PathBuf);
|
||||
|
||||
impl Temp {
|
||||
fn new(name: &str) -> Self {
|
||||
let root = std::env::temp_dir().join(format!("cadcraft-portable-{}-{name}", std::process::id()));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
Self(root)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Temp {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absent_marker_and_directory_named_marker_do_not_enable_portable_mode() {
|
||||
let temp = Temp::new("no-marker");
|
||||
assert_eq!(directory_in(&temp.0).unwrap(), None);
|
||||
std::fs::create_dir(temp.0.join("portable.txt")).unwrap();
|
||||
assert_eq!(directory_in(&temp.0).unwrap(), None);
|
||||
assert!(!temp.0.join("CADCraftData").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marker_selects_adjacent_data_and_preserves_existing_settings() {
|
||||
let temp = Temp::new("settings-é");
|
||||
std::fs::write(temp.0.join("portable.txt"), "").unwrap();
|
||||
let data = directory_in(&temp.0).unwrap().unwrap();
|
||||
assert_eq!(data, temp.0.join("CADCraftData"));
|
||||
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 0);
|
||||
std::fs::write(data.join("workspace.json"), "existing settings").unwrap();
|
||||
assert_eq!(directory_in(&temp.0).unwrap(), Some(data.clone()));
|
||||
assert_eq!(std::fs::read_to_string(data.join("workspace.json")).unwrap(), "existing settings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_data_folder_is_an_error() {
|
||||
let temp = Temp::new("blocked");
|
||||
std::fs::write(temp.0.join("portable.txt"), "").unwrap();
|
||||
std::fs::write(temp.0.join("CADCraftData"), "a file blocks the directory").unwrap();
|
||||
assert!(directory_in(&temp.0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn independent_copies_have_independent_settings() {
|
||||
let a = Temp::new("copy-a");
|
||||
let b = Temp::new("copy-b");
|
||||
for temp in [&a, &b] {
|
||||
std::fs::write(temp.0.join("portable.txt"), "").unwrap();
|
||||
}
|
||||
assert_ne!(directory_in(&a.0).unwrap(), directory_in(&b.0).unwrap());
|
||||
}
|
||||
}
|
||||
@@ -331,43 +331,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for one test, and its socket path. Both names stay short: a Windows socket path
|
||||
/// holds at most 107 bytes, and a long `%TEMP%` already uses most of them.
|
||||
/// 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!("cc-si-{}-{test}", std::process::id()));
|
||||
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("t.sock");
|
||||
let path = dir.join("instance-test.sock");
|
||||
(Cleanup(dir), path)
|
||||
}
|
||||
|
||||
/// Whether a socket can be bound at `path` here. It can't when `%TEMP%` is too long or lives
|
||||
/// under a redirected `%LOCALAPPDATA%`; the socket tests then skip instead of failing.
|
||||
#[cfg(windows)]
|
||||
fn can_bind(path: &std::path::Path) -> bool {
|
||||
let bound = uds_windows::UnixListener::bind(path)
|
||||
.map(drop)
|
||||
.map_err(|e| {
|
||||
// Straight to stderr: the test harness hides `eprintln!` from a test that passes.
|
||||
use std::io::Write;
|
||||
let _ = writeln!(std::io::stderr(), "skipping: no AF_UNIX socket at {}: {e}", path.display());
|
||||
})
|
||||
.is_ok();
|
||||
let _ = std::fs::remove_file(path);
|
||||
bound
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_test_socket_path_stays_far_below_the_limit() {
|
||||
// Its own folder, with a name as long as the longest one used here: `socket_dir` empties the
|
||||
// folder, and the launches test may be using "together" at the same moment.
|
||||
let (_dir, path) = socket_dir("lengthck");
|
||||
let added = path.as_os_str().len() - std::env::temp_dir().as_os_str().len();
|
||||
assert!(added <= 40, "{added} bytes on top of %TEMP%");
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -375,9 +348,6 @@ mod tests {
|
||||
#[test]
|
||||
fn a_later_launch_hands_its_files_to_the_first() {
|
||||
let (dir, path) = socket_dir("handoff");
|
||||
if !can_bind(&path) {
|
||||
return;
|
||||
}
|
||||
drop(uds_windows::UnixListener::bind(&path).unwrap());
|
||||
assert!(path.exists(), "the stale socket file stays behind");
|
||||
|
||||
@@ -399,9 +369,6 @@ mod tests {
|
||||
fn launches_at_once_open_one_window() {
|
||||
const LAUNCHES: usize = 6;
|
||||
let (dir, path) = socket_dir("together");
|
||||
if !can_bind(&path) {
|
||||
return;
|
||||
}
|
||||
let start = Arc::new(std::sync::Barrier::new(LAUNCHES));
|
||||
let launches: Vec<_> = (0..LAUNCHES)
|
||||
.map(|i| {
|
||||
|
||||
+47
-246
@@ -22,7 +22,7 @@ use crate::{Drawing, Handle, RawTag};
|
||||
mod apply;
|
||||
mod grips;
|
||||
mod reference;
|
||||
pub use apply::{align_grip, drag_grip, grip_stops, set_property};
|
||||
pub use apply::{drag_grip, set_property};
|
||||
pub use grips::{DynGrip, GripPart, GripShape, grips};
|
||||
pub use reference::{CustomProperty, Reference, Value, custom_properties, reference};
|
||||
|
||||
@@ -52,13 +52,6 @@ pub struct DynamicBlock {
|
||||
/// the grips shown in them by object).
|
||||
#[serde(skip)]
|
||||
pub grip_objects: Vec<(i32, Handle)>,
|
||||
/// Where each grip object is in the dynamic block, by graph id (a flip grip's place along its
|
||||
/// reflection line).
|
||||
#[serde(skip)]
|
||||
pub grip_points: Vec<(i32, Vec3)>,
|
||||
/// The block's base point (where a base point parameter is in the block).
|
||||
#[serde(skip)]
|
||||
pub base: Vec3,
|
||||
}
|
||||
|
||||
/// One parameter: a property a reference to the block can change.
|
||||
@@ -94,41 +87,16 @@ pub enum ParameterKind {
|
||||
/// The value changes the end point (`false`) or both points from the midpoint (`true`).
|
||||
from_midpoint: bool,
|
||||
},
|
||||
/// A distance and an angle from a base point (Distance1, Angle1): the end point's distance
|
||||
/// from the base and its direction (counterclockwise from the X axis of the block).
|
||||
Polar {
|
||||
base: Vec3,
|
||||
end: Vec3,
|
||||
label: String,
|
||||
description: String,
|
||||
angle_label: String,
|
||||
angle_description: String,
|
||||
values: ValueSet,
|
||||
angle_values: ValueSet,
|
||||
},
|
||||
/// Horizontal and vertical distances from a base point (X Distance1, Y Distance1): how far
|
||||
/// the end point is from the base along the block's X and Y axes.
|
||||
Xy {
|
||||
base: Vec3,
|
||||
end: Vec3,
|
||||
x_label: String,
|
||||
y_label: String,
|
||||
x_description: String,
|
||||
y_description: String,
|
||||
x_values: ValueSet,
|
||||
y_values: ValueSet,
|
||||
},
|
||||
/// An angle about a base point (Angle1): the end point turns about the base. The angle is
|
||||
/// measured from the direction the dynamic block has from base to end.
|
||||
Rotation { base: Vec3, end: Vec3, label: String, description: String, values: ValueSet },
|
||||
/// Aligns the reference with nearby geometry: dragged next to an object, its base point lands
|
||||
/// on the object and the direction from base to end runs along it. `perpendicular` is the
|
||||
/// parameter's type (perpendicular, else tangent); AutoCAD aligned both types the same way in
|
||||
/// every case measured.
|
||||
Alignment { base: Vec3, end: Vec3, perpendicular: bool },
|
||||
/// Mirrors the objects about the reflection line from base to end (Flip state1); the names
|
||||
/// of its two states, not flipped and flipped.
|
||||
Flip { base: Vec3, end: Vec3, label: String, description: String, states: [String; 2] },
|
||||
/// A distance and an angle from a base point.
|
||||
Polar { base: Vec3, end: Vec3 },
|
||||
/// Horizontal and vertical distances from a base point.
|
||||
Xy { base: Vec3, end: Vec3 },
|
||||
/// An angle about a base point.
|
||||
Rotation { base: Vec3, end: Vec3 },
|
||||
/// Aligns the reference with nearby geometry.
|
||||
Alignment { base: Vec3, end: Vec3 },
|
||||
/// Mirrors the objects about a reflection line.
|
||||
Flip { base: Vec3, end: Vec3 },
|
||||
/// A position (Position1).
|
||||
Point { at: Vec3, label: String, description: String },
|
||||
/// Named sets of visible objects.
|
||||
@@ -142,9 +110,7 @@ pub enum ParameterKind {
|
||||
},
|
||||
/// A named value chosen from a lookup table.
|
||||
Lookup { at: Vec3, label: String, description: String },
|
||||
/// The block's base point: the reference's insertion point is here, and an action that moves
|
||||
/// it moves the reference's insertion point. `at` is where the block editor showed it; the
|
||||
/// block itself has it at its base point (AutoCAD moves the block's objects to put it there).
|
||||
/// Moves the block's base point.
|
||||
BasePoint { at: Vec3 },
|
||||
/// A parameter type not modelled yet.
|
||||
Other { dxf_type: String },
|
||||
@@ -156,23 +122,11 @@ impl ParameterKind {
|
||||
match self {
|
||||
ParameterKind::Linear { label, .. }
|
||||
| ParameterKind::Point { label, .. }
|
||||
| ParameterKind::Rotation { label, .. }
|
||||
| ParameterKind::Flip { label, .. }
|
||||
| ParameterKind::Visibility { label, .. }
|
||||
| ParameterKind::Lookup { label, .. } => Some(label),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every property name a reference shows for the parameter: a polar parameter's distance
|
||||
/// and angle, an XY parameter's two distances, else its one label.
|
||||
pub fn labels(&self) -> Vec<&str> {
|
||||
match self {
|
||||
ParameterKind::Polar { label, angle_label, .. } => vec![label, angle_label],
|
||||
ParameterKind::Xy { x_label, y_label, .. } => vec![x_label, y_label],
|
||||
other => other.label().into_iter().collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One visibility state: its name and the objects shown in it (the parameter's other controlled
|
||||
@@ -251,46 +205,24 @@ pub enum ActionKind {
|
||||
angle_offset: f64,
|
||||
},
|
||||
/// A table: each row sets the listed parameter values together.
|
||||
Lookup { columns: Vec<LookupColumn>, rows: Vec<Vec<String>> },
|
||||
Lookup {
|
||||
columns: Vec<LookupColumn>,
|
||||
rows: Vec<Vec<String>>,
|
||||
},
|
||||
/// Moves the objects by the change of the parameter values it follows.
|
||||
Move { multiplier: f64, angle_offset: f64 },
|
||||
/// Scales the objects about its base point by how much the distance it follows grew (a linear
|
||||
/// or polar parameter's distance, an XY parameter's diagonal). Its connections name what each
|
||||
/// reads ("Scale", "XScale", "YScale").
|
||||
Scale { base: ActionBase },
|
||||
/// Turns the objects about its base point by the change of a rotation parameter's angle.
|
||||
Rotate { base: ActionBase },
|
||||
/// Mirrors the objects across a flip parameter's reflection line when its state changes.
|
||||
Flip,
|
||||
/// Repeats the objects as far as the parameter it follows reaches: along a distance (linear
|
||||
/// or polar parameter) every `column` units, or in a grid of columns and rows across an XY
|
||||
/// parameter's distances. The objects follow the parameter's base point.
|
||||
Array { column: f64, row: f64 },
|
||||
/// Follows a polar parameter: turns its objects about the parameter's base point by the change
|
||||
/// of its angle, and moves the vertices inside `frame` of the objects listed (all of an object
|
||||
/// not listed) along the parameter's new direction by the change of its distance. The
|
||||
/// `rotate_only` objects (outside the selection) only turn.
|
||||
PolarStretch {
|
||||
frame: Vec<Vec2>,
|
||||
#[serde(serialize_with = "hex_vertices")]
|
||||
vertices: Vec<(Handle, Vec<i32>)>,
|
||||
#[serde(serialize_with = "hexes")]
|
||||
rotate_only: Vec<Handle>,
|
||||
Move {
|
||||
multiplier: f64,
|
||||
angle_offset: f64,
|
||||
},
|
||||
Scale,
|
||||
Rotate,
|
||||
Flip,
|
||||
Array,
|
||||
PolarStretch,
|
||||
/// An action type not modelled yet.
|
||||
Other { dxf_type: String },
|
||||
}
|
||||
|
||||
/// Where an action that turns or scales its objects has its base point.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ActionBase {
|
||||
/// It follows the parameter's base point, at `offset` from it; else it stays at `at`.
|
||||
pub dependent: bool,
|
||||
pub offset: Vec3,
|
||||
pub at: Vec3,
|
||||
Other {
|
||||
dxf_type: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// A lookup table column: the parameter value it reads or sets.
|
||||
@@ -451,7 +383,7 @@ pub fn is_dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -
|
||||
/// [`dynamic_block`] with the drawing's [`ObjectIndex`] already built.
|
||||
pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> Option<DynamicBlock> {
|
||||
let xdict = block_xdict(d, name)?;
|
||||
let mut out = DynamicBlock { base: d.block(name.trim()).map(|b| b.base).unwrap_or_default(), ..Default::default() };
|
||||
let mut out = DynamicBlock::default();
|
||||
for o in graph_members(&objects.0, xdict)? {
|
||||
let secs = sections(&o.tags);
|
||||
let node = Cursor::new(section(&secs, "AcDbEvalExpr")).int(90);
|
||||
@@ -466,7 +398,6 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
|
||||
} else {
|
||||
if kind.ends_with("GRIP") {
|
||||
out.grip_objects.push((node, o.handle));
|
||||
out.grip_points.push((node, Cursor::new(section(&secs, "AcDbBlockGrip")).point(1010)));
|
||||
}
|
||||
out.other.push(o.kind.clone());
|
||||
}
|
||||
@@ -475,21 +406,15 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
|
||||
}
|
||||
|
||||
/// A parameter's grip ids: after a two-point parameter's points, the grip count (170) and the
|
||||
/// base and end grips (91), then an XY parameter's corner grips (base X and end Y, base Y and end
|
||||
/// X); after a one-point parameter's point, its grip (93).
|
||||
/// base and end grips (91); after a one-point parameter's point, its grip (93).
|
||||
fn grip_ids(secs: &[(&str, &[RawTag])]) -> Vec<i32> {
|
||||
let two = section(secs, "AcDbBlock2PtParameter");
|
||||
if !two.is_empty() {
|
||||
let mut c = Cursor::new(two);
|
||||
c.point(1010);
|
||||
c.point(1011);
|
||||
let n = c.count(170).min(4);
|
||||
let mut ids: Vec<i32> = (0..n).map(|_| c.int(91)).collect();
|
||||
// Corner grips only an XY parameter has (the others write 0 for them).
|
||||
while ids.len() > 2 && ids.last() == Some(&0) {
|
||||
ids.pop();
|
||||
}
|
||||
return ids;
|
||||
let n = c.count(170).min(2);
|
||||
return (0..n).map(|_| c.int(91)).collect();
|
||||
}
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlock1PtParameter"));
|
||||
c.point(1010);
|
||||
@@ -521,49 +446,15 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
|
||||
ParameterKind::Lookup { at: one(), label: c.string(303), description: c.string(304) }
|
||||
}
|
||||
"BLOCKBASEPOINTPARAMETER" => ParameterKind::BasePoint { at: one() },
|
||||
// Its name and description (305, 306), the base angle point (1011) and angle (140), then
|
||||
// the value set.
|
||||
"BLOCKROTATIONPARAMETER" => {
|
||||
"BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKROTATIONPARAMETER" | "BLOCKALIGNMENTPARAMETER" | "BLOCKFLIPPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockRotationParameter"));
|
||||
let (label, description) = (c.string(305), c.string(306));
|
||||
ParameterKind::Rotation { base, end, label, description, values: value_set(&mut c) }
|
||||
}
|
||||
// Its name and description (305, 306) and its states' names (307 not flipped, 308 flipped).
|
||||
"BLOCKFLIPPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockFlipParameter"));
|
||||
let (label, description) = (c.string(305), c.string(306));
|
||||
let states = [c.string(307), c.string(308)];
|
||||
ParameterKind::Flip { base, end, label, description, states }
|
||||
}
|
||||
// The distance's name and description (305, 306), the angle's (307, 308), the label
|
||||
// offset (140), then the distance's value set (309, 96, 141–144, 175) and the angle's
|
||||
// (410, 97, 145–148, 176).
|
||||
"BLOCKPOLARPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockPolarParameter"));
|
||||
let (label, description, angle_label, angle_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
|
||||
let values = value_set_at(&mut c, [309, 96, 141, 175]);
|
||||
let angle_values = value_set_at(&mut c, [410, 97, 145, 176]);
|
||||
ParameterKind::Polar { base, end, label, description, angle_label, angle_description, values, angle_values }
|
||||
}
|
||||
// The vertical distance's name (305) before the horizontal's (306), then their
|
||||
// descriptions (307, 308), label offsets (141, 140), the vertical value set (309, 97,
|
||||
// 146–149, 176) and the horizontal one (410, 96, 142–145, 175).
|
||||
"BLOCKXYPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockXYParameter"));
|
||||
let (y_label, x_label, y_description, x_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
|
||||
let y_values = value_set_at(&mut c, [309, 97, 146, 176]);
|
||||
let x_values = value_set_at(&mut c, [410, 96, 142, 175]);
|
||||
ParameterKind::Xy { base, end, x_label, y_label, x_description, y_description, x_values, y_values }
|
||||
}
|
||||
// Its type (280): 1 perpendicular, 0 tangent.
|
||||
"BLOCKALIGNMENTPARAMETER" => {
|
||||
let (base, end) = two();
|
||||
let perpendicular = Cursor::new(section(secs, "AcDbBlockAlignmentParameter")).int(280) != 0;
|
||||
ParameterKind::Alignment { base, end, perpendicular }
|
||||
match kind {
|
||||
"BLOCKPOLARPARAMETER" => ParameterKind::Polar { base, end },
|
||||
"BLOCKXYPARAMETER" => ParameterKind::Xy { base, end },
|
||||
"BLOCKROTATIONPARAMETER" => ParameterKind::Rotation { base, end },
|
||||
"BLOCKALIGNMENTPARAMETER" => ParameterKind::Alignment { base, end },
|
||||
_ => ParameterKind::Flip { base, end },
|
||||
}
|
||||
}
|
||||
other => ParameterKind::Other { dxf_type: other.to_string() },
|
||||
}
|
||||
@@ -572,17 +463,11 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
|
||||
/// A value set after a parameter's name and description: description (307), flags (96),
|
||||
/// minimum, maximum and increment (141–143), then the listed values (175 count, 144 each).
|
||||
fn value_set(c: &mut Cursor) -> ValueSet {
|
||||
value_set_at(c, [307, 96, 141, 175])
|
||||
}
|
||||
|
||||
/// A value set written with codes `[description, flags, minimum, count]`: the maximum and
|
||||
/// increment follow the minimum's code, each listed value is the code after the increment's.
|
||||
fn value_set_at(c: &mut Cursor, [description, flags, min, count]: [i32; 4]) -> ValueSet {
|
||||
c.next(description);
|
||||
let flags = c.int(flags);
|
||||
let (minimum, maximum, increment) = (c.real(min), c.real(min + 1), c.real(min + 2));
|
||||
let n = c.count(count);
|
||||
let list = (0..n).filter_map(|_| c.next(min + 3).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
|
||||
c.next(307);
|
||||
let flags = c.int(96);
|
||||
let (minimum, maximum, increment) = (c.real(141), c.real(142), c.real(143));
|
||||
let n = c.count(175);
|
||||
let list = (0..n).filter_map(|_| c.next(144).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
|
||||
ValueSet { flags, minimum, maximum, increment, list }
|
||||
}
|
||||
|
||||
@@ -622,56 +507,16 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[
|
||||
let (multiplier, angle_offset) = (c.real(140), c.real(141));
|
||||
(two_connections(tags), ActionKind::Move { multiplier, angle_offset })
|
||||
}
|
||||
// The base point's two connections (as a rotate action's), then the scale's three: the
|
||||
// parameters (94-96) and what each reads (303-305, "Scale", "XScale", "YScale").
|
||||
"BLOCKSCALEACTION" => {
|
||||
let with_base = section(secs, "AcDbBlockActionWithBasePt");
|
||||
let mut connections = two_connections(with_base);
|
||||
let tags = section(secs, "AcDbBlockScaleAction");
|
||||
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
|
||||
connections.extend((0..3).map(|i| (first(94 + i).trim().parse().unwrap_or(0), first(303 + i))));
|
||||
(connections, ActionKind::Scale { base: action_base(with_base) })
|
||||
}
|
||||
"BLOCKROTATEACTION" => {
|
||||
let mut connections = two_connections(section(secs, "AcDbBlockActionWithBasePt"));
|
||||
let mut c = Cursor::new(section(secs, "AcDbBlockRotationAction"));
|
||||
connections.push((c.int(94), c.string(303)));
|
||||
(connections, ActionKind::Rotate { base: action_base(section(secs, "AcDbBlockActionWithBasePt")) })
|
||||
}
|
||||
// Its four connections: the parameter (92-95) and the values it reads (301-304).
|
||||
"BLOCKFLIPACTION" => {
|
||||
let tags = section(secs, "AcDbBlockFlipAction");
|
||||
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
|
||||
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
|
||||
(connections, ActionKind::Flip)
|
||||
}
|
||||
// Its four connections (92-95 with 301-304, as a flip action's), then the row (140) and
|
||||
// column (141) offsets.
|
||||
"BLOCKARRAYACTION" => {
|
||||
let tags = section(secs, "AcDbBlockArrayAction");
|
||||
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
|
||||
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
|
||||
let mut c = Cursor::new(tags);
|
||||
let (row, column) = (c.real(140), c.real(141));
|
||||
(connections, ActionKind::Array { column, row })
|
||||
}
|
||||
"BLOCKPOLARSTRETCHACTION" => polar_stretch(section(secs, "AcDbBlockPolarStretchAction")),
|
||||
"BLOCKSCALEACTION" => (Vec::new(), ActionKind::Scale),
|
||||
"BLOCKROTATEACTION" => (Vec::new(), ActionKind::Rotate),
|
||||
"BLOCKFLIPACTION" => (Vec::new(), ActionKind::Flip),
|
||||
"BLOCKARRAYACTION" => (Vec::new(), ActionKind::Array),
|
||||
"BLOCKPOLARSTRETCHACTION" => (Vec::new(), ActionKind::PolarStretch),
|
||||
other => (Vec::new(), ActionKind::Other { dxf_type: other.to_string() }),
|
||||
};
|
||||
Action { node, handle, name, at, selection, connections, kind }
|
||||
}
|
||||
|
||||
/// The base point of an action that has one: after its two connections (92/93, 301/302), the
|
||||
/// offset from the parameter's base point (1011), whether it follows that point (280), and the
|
||||
/// point it stays at when it doesn't (1012).
|
||||
fn action_base(tags: &[RawTag]) -> ActionBase {
|
||||
let mut c = Cursor::new(tags);
|
||||
c.next(302);
|
||||
let offset = c.point(1011);
|
||||
let dependent = c.int(280) != 0;
|
||||
ActionBase { dependent, offset, at: c.point(1012) }
|
||||
}
|
||||
|
||||
/// Two connections: parameter ids (92, 93) and the values they read (301, 302). Writers order
|
||||
/// these groups differently (92 93 301 302, or 92 301 93 302), so each is read on its own.
|
||||
fn two_connections(tags: &[RawTag]) -> Vec<(i32, String)> {
|
||||
@@ -706,42 +551,6 @@ fn stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
|
||||
(connections, ActionKind::Stretch { frame, vertices, multiplier, angle_offset })
|
||||
}
|
||||
|
||||
/// A polar stretch action: its six connections (92-97 with 301-306), the frame (73 count,
|
||||
/// 1011/1021 points), the objects it only turns (72 count, 331 each), the objects whose vertices it
|
||||
/// moves (74 count; each a 332 handle, a 75 count and 76 vertex indices), more vertex lists (78
|
||||
/// count; each a 98 code, a 79 count and 76 indices), then the distance multiplier (141) and angle
|
||||
/// offset (140).
|
||||
fn polar_stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
|
||||
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
|
||||
let connections = (0..6).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
|
||||
let mut c = Cursor::new(tags);
|
||||
let n = c.count(73);
|
||||
let frame = (0..n)
|
||||
.map(|_| {
|
||||
let x = c.real(1011);
|
||||
Vec2::new(x, c.real(1021))
|
||||
})
|
||||
.collect();
|
||||
let n = c.count(72);
|
||||
let rotate_only = c.handles(331, n);
|
||||
let objects = c.count(74);
|
||||
let vertices = (0..objects)
|
||||
.filter_map(|_| {
|
||||
let h = c.handle(332)?;
|
||||
let n = c.count(75);
|
||||
Some((h, (0..n).map(|_| c.int(76)).collect()))
|
||||
})
|
||||
.collect();
|
||||
for _ in 0..c.count(78) {
|
||||
c.next(98);
|
||||
for _ in 0..c.count(79) {
|
||||
c.next(76);
|
||||
}
|
||||
}
|
||||
let (multiplier, angle_offset) = (c.real(141), c.real(140));
|
||||
(connections, ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, angle_offset })
|
||||
}
|
||||
|
||||
/// A lookup table: rows (92) and columns (93), the cells row by row (302, after a 301 header),
|
||||
/// then each column: unmatched name (303 then 305), parameter id (94), lookup flag (282) and the
|
||||
/// parameter value it stands for (304).
|
||||
@@ -789,13 +598,5 @@ mod tests {
|
||||
let (_, ActionKind::Stretch { vertices, .. }) = stretch(&tags) else { panic!("a stretch action") };
|
||||
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
|
||||
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
|
||||
|
||||
let mut tags = vec![tag(74, &n.to_string())];
|
||||
tags.extend((0..n).flat_map(|_| [tag(332, "1F"), tag(75, &n.to_string())]));
|
||||
tags.push(tag(78, &n.to_string()));
|
||||
tags.extend((0..n).map(|_| tag(79, &n.to_string())));
|
||||
let (_, ActionKind::PolarStretch { vertices, .. }) = polar_stretch(&tags) else { panic!("a polar stretch action") };
|
||||
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
|
||||
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
|
||||
}
|
||||
}
|
||||
|
||||
+161
-1081
File diff suppressed because it is too large
Load Diff
@@ -1,11 +1,7 @@
|
||||
//! The grips of a dynamic block reference, as AutoCAD shows them on a selected reference: an
|
||||
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter),
|
||||
//! a circle at the end of an angle (rotation parameter), a flip arrow across a reflection line
|
||||
//! (flip parameter), a down-pointing triangle for a list (visibility states, lookup values) and a
|
||||
//! pentagon pointing across the alignment direction at an alignment's base point (alignment
|
||||
//! parameter; dragged next to an object it aligns the reference with it, [`super::align_grip`]).
|
||||
//! Dragging an arrow, square or circle is [`super::drag_grip`]; a flip grip flips at a click; a
|
||||
//! list grip offers its property's choices.
|
||||
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter)
|
||||
//! and a down-pointing triangle for a list (visibility states, lookup values). Dragging an arrow
|
||||
//! or square is [`super::drag_grip`]; a list grip offers its property's choices.
|
||||
//!
|
||||
//! With a visibility parameter, a state lists the grips shown in it; the others are hidden.
|
||||
|
||||
@@ -30,13 +26,6 @@ pub enum GripPart {
|
||||
End,
|
||||
/// A one-point parameter's point (a position, a visibility or lookup grip).
|
||||
At,
|
||||
/// An XY parameter's corner at the base's X and the end's Y (listed as `blocks.reference.grip`
|
||||
/// takes it, as [`GripPart::name`] names it).
|
||||
#[serde(rename = "basex-endy")]
|
||||
BaseXEndY,
|
||||
/// An XY parameter's corner at the end's X and the base's Y.
|
||||
#[serde(rename = "basey-endx")]
|
||||
BaseYEndX,
|
||||
}
|
||||
|
||||
impl GripPart {
|
||||
@@ -45,8 +34,6 @@ impl GripPart {
|
||||
GripPart::Base => "base",
|
||||
GripPart::End => "end",
|
||||
GripPart::At => "at",
|
||||
GripPart::BaseXEndY => "basex-endy",
|
||||
GripPart::BaseYEndX => "basey-endx",
|
||||
}
|
||||
}
|
||||
pub fn from_name(s: &str) -> Option<GripPart> {
|
||||
@@ -54,28 +41,11 @@ impl GripPart {
|
||||
"base" => Some(GripPart::Base),
|
||||
"end" => Some(GripPart::End),
|
||||
"at" => Some(GripPart::At),
|
||||
"basex-endy" => Some(GripPart::BaseXEndY),
|
||||
"basey-endx" => Some(GripPart::BaseYEndX),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::GripPart;
|
||||
|
||||
/// A grip is listed with the part name `blocks.reference.grip` takes back.
|
||||
#[test]
|
||||
fn listed_part_names_are_the_names_a_drag_takes() {
|
||||
for p in [GripPart::Base, GripPart::End, GripPart::At, GripPart::BaseXEndY, GripPart::BaseYEndX] {
|
||||
let listed = serde_json::to_value(p).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
|
||||
assert_eq!(listed, p.name());
|
||||
assert_eq!(GripPart::from_name(&listed), Some(p));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a grip looks and what it does.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -86,13 +56,6 @@ pub enum GripShape {
|
||||
Point,
|
||||
/// A down-pointing triangle: click it for the property's choices.
|
||||
List,
|
||||
/// A circle at the end of an angle: drag it to turn the angle.
|
||||
Rotation,
|
||||
/// An arrow across a reflection line: click it to flip (its choices are the two states).
|
||||
Flip,
|
||||
/// A pentagon pointing to the left of an alignment's direction: drag it next to an object to
|
||||
/// align the reference with it.
|
||||
Alignment,
|
||||
}
|
||||
|
||||
/// One grip of a dynamic block reference.
|
||||
@@ -139,15 +102,6 @@ fn ends_used(m: &DynamicBlock, node: i32) -> Option<(bool, bool)> {
|
||||
used
|
||||
}
|
||||
|
||||
/// Where a grip object at `g` (from its parameter's base, in the dynamic block) is when the
|
||||
/// parameter's line `home` (base to end, in the block) is now `now` from `base`: kept along and
|
||||
/// across the line as it turns, moves or stretches. `home` and `now` aren't zero.
|
||||
fn carried(g: Vec2, home: Vec2, base: Vec2, now: Vec2) -> Vec2 {
|
||||
let (u0, u) = (home * (1.0 / home.len()), now * (1.0 / now.len()));
|
||||
let (along, across) = (g.dot(u0) / home.len(), u0.x * g.y - u0.y * g.x);
|
||||
base + now * along + u.perp() * across
|
||||
}
|
||||
|
||||
fn point<S: serde::Serializer>(p: &Vec2, s: S) -> Result<S::Ok, S::Error> {
|
||||
[p.x, p.y].serialize(s)
|
||||
}
|
||||
@@ -166,7 +120,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
|
||||
};
|
||||
// The grips the current visibility state shows (all of them without visibility states).
|
||||
let objects: HashMap<i32, Handle> = m.grip_objects.iter().copied().collect();
|
||||
let points: HashMap<i32, Vec3> = m.grip_points.iter().copied().collect();
|
||||
let mut shown_in_state: Option<HashSet<Handle>> = None;
|
||||
let mut visibility_node = None;
|
||||
for p in &m.parameters {
|
||||
@@ -218,87 +171,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
|
||||
}
|
||||
}
|
||||
}
|
||||
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
|
||||
let (b, e) = match r.values.get(&p.node) {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*hb, *he),
|
||||
};
|
||||
let id = grip(1);
|
||||
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
|
||||
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
|
||||
// The grip object's place (AutoCAD draws the circle there, not at the radius'
|
||||
// end), turned and moved with the radius.
|
||||
let at = carried(points.get(&id).copied().unwrap_or(*he).xy() - hb.xy(), home, b.xy(), now);
|
||||
let at = Vec3::new(at.x, at.y, b.z);
|
||||
let u = at - b;
|
||||
let u = if u.len() > 1e-12 { u * (1.0 / u.len()) } else { Vec3::new(1.0, 0.0, 0.0) };
|
||||
let (at, dir) = (world(at), toward(at, u));
|
||||
out.push(DynGrip {
|
||||
node: p.node,
|
||||
part: GripPart::End,
|
||||
shape: GripShape::Rotation,
|
||||
at,
|
||||
dir,
|
||||
property: label.clone(),
|
||||
choices: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
ParameterKind::Flip { base: hb, end: he, label, states, .. } => {
|
||||
let (b, e, flipped) = match r.values.get(&p.node) {
|
||||
Some(Value::Flip { base, end, flipped }) => (*base, *end, *flipped),
|
||||
_ => (*hb, *he, false),
|
||||
};
|
||||
let id = grip(0);
|
||||
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
|
||||
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
|
||||
// The grip object's place, kept along and across the reflection line as the
|
||||
// line turns or moves with other actions.
|
||||
let g = points.get(&id).copied().unwrap_or(*hb).xy() - hb.xy();
|
||||
let at = carried(g, home, b.xy(), now);
|
||||
let u = now * (1.0 / now.len());
|
||||
let across_dir = if flipped { -u.perp() } else { u.perp() };
|
||||
let (at3, dir) = (Vec3::new(at.x, at.y, b.z), toward(Vec3::new(at.x, at.y, b.z), across_dir.to3(0.0)));
|
||||
out.push(DynGrip {
|
||||
node: p.node,
|
||||
part: GripPart::Base,
|
||||
shape: GripShape::Flip,
|
||||
at: world(at3),
|
||||
dir,
|
||||
property: label.clone(),
|
||||
choices: states.to_vec(),
|
||||
});
|
||||
}
|
||||
}
|
||||
// Squares at the base and the end (a polar parameter), and at the two other corners of
|
||||
// the rectangle they span (an XY parameter), for the grips the parameter has; an end
|
||||
// no action follows has none.
|
||||
ParameterKind::Polar { base, end, label, .. } | ParameterKind::Xy { base, end, x_label: label, .. } => {
|
||||
let (b, e) = match r.values.get(&p.node) {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*base, *end),
|
||||
};
|
||||
let used = ends_used(&m, p.node).map_or([true, true], |(base, end)| [base, end]);
|
||||
let mut corners = vec![(0, GripPart::Base, b, used[0]), (1, GripPart::End, e, used[1])];
|
||||
if matches!(p.kind, ParameterKind::Xy { .. }) {
|
||||
let both = used[0] && used[1];
|
||||
corners.push((2, GripPart::BaseXEndY, Vec3::new(b.x, e.y, b.z), both));
|
||||
corners.push((3, GripPart::BaseYEndX, Vec3::new(e.x, b.y, b.z), both));
|
||||
}
|
||||
for (i, part, at, used) in corners {
|
||||
if used && shown(p.node, grip(i)) {
|
||||
out.push(DynGrip {
|
||||
node: p.node,
|
||||
part,
|
||||
shape: GripShape::Point,
|
||||
at: world(at),
|
||||
dir: Vec2::ZERO,
|
||||
property: label.clone(),
|
||||
choices: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
ParameterKind::Point { at, label, .. } => {
|
||||
let at = match r.values.get(&p.node) {
|
||||
Some(Value::Point { at }) => *at,
|
||||
@@ -317,26 +189,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
|
||||
});
|
||||
}
|
||||
}
|
||||
// At the base point, pointing to the left of the direction (as AutoCAD draws it).
|
||||
ParameterKind::Alignment { base, end, .. } => {
|
||||
let (b, e) = match r.values.get(&p.node) {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*base, *end),
|
||||
};
|
||||
let u = (e - b).xy();
|
||||
if shown(p.node, grip(0)) && u.len() > 1e-12 {
|
||||
let (at, dir) = (world(b), toward(b, u.perp().to3(0.0)));
|
||||
out.push(DynGrip {
|
||||
node: p.node,
|
||||
part: GripPart::Base,
|
||||
shape: GripShape::Alignment,
|
||||
at,
|
||||
dir,
|
||||
property: String::new(),
|
||||
choices: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
ParameterKind::Visibility { at, label, .. } | ParameterKind::Lookup { at, label, .. } => {
|
||||
let Some(list) = choices.get(&label.to_ascii_uppercase()).filter(|c| !c.is_empty()) else { continue };
|
||||
if shown(p.node, grip(0)) {
|
||||
|
||||
@@ -29,8 +29,6 @@ pub enum Value {
|
||||
Point { at: Vec3 },
|
||||
/// A two-point parameter's points.
|
||||
Points { base: Vec3, end: Vec3 },
|
||||
/// A flip parameter's reflection line and whether it is flipped.
|
||||
Flip { base: Vec3, end: Vec3, flipped: bool },
|
||||
}
|
||||
|
||||
/// A dynamic block reference.
|
||||
@@ -53,8 +51,8 @@ pub struct CustomProperty {
|
||||
/// The values it may be set to, when it is a choice (visibility states, lookup values, a
|
||||
/// distance's list).
|
||||
pub choices: Vec<String>,
|
||||
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, an angle,
|
||||
/// a position, a flip state, or a lookup whose tables set only those.
|
||||
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, a
|
||||
/// position, or a lookup whose tables set only those.
|
||||
pub editable: bool,
|
||||
}
|
||||
|
||||
@@ -93,9 +91,7 @@ fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(Stri
|
||||
out
|
||||
}
|
||||
|
||||
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip
|
||||
/// parameter's also has its state, a group 70 after its points (the header's `70 25`, `70 104`
|
||||
/// come before them).
|
||||
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30).
|
||||
fn value(o: &ForeignObject) -> Option<Value> {
|
||||
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
|
||||
return Some(Value::Text { value: t.value.clone() });
|
||||
@@ -104,10 +100,7 @@ fn value(o: &ForeignObject) -> Option<Value> {
|
||||
o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
|
||||
};
|
||||
let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0)));
|
||||
let first_point = o.tags.iter().position(|t| t.code == 10).unwrap_or(o.tags.len());
|
||||
let state = o.tags.get(first_point..).unwrap_or_default().iter().rev().find(|t| t.code == 70).map(|t| t.value.trim() == "1");
|
||||
match (point(0), point(1)) {
|
||||
(Some(base), Some(end)) if state.is_some() => Some(Value::Flip { base, end, flipped: state == Some(true) }),
|
||||
(Some(base), Some(end)) => Some(Value::Points { base, end }),
|
||||
(Some(at), None) => Some(Value::Point { at }),
|
||||
_ => None,
|
||||
@@ -129,52 +122,17 @@ pub fn reference(d: &Drawing, insert: Handle) -> Option<Reference> {
|
||||
let target = data.tags.iter().find(|t| t.code == 340).and_then(|t| Handle::parse_hex(&t.value))?;
|
||||
let (kind, name) = d.foreign.targets.get(&target)?;
|
||||
let definition = d.block(name).filter(|_| kind == "BLOCK_RECORD")?.name.clone();
|
||||
let m = dynamic_block(d, &definition)?;
|
||||
dynamic_block(d, &definition)?;
|
||||
let mut values = BTreeMap::new();
|
||||
let cache = entry(&objects, rep, "AppDataCache").and_then(|c| entry(&objects, c, "ACAD_ENHANCEDBLOCKDATA"));
|
||||
for (key, h) in cache.map(|c| entries(&objects, c)).unwrap_or_default().into_iter().take(MAX_VALUES) {
|
||||
if let (Ok(node), Some(v)) = (key.trim().parse::<i32>(), objects.get(&h).and_then(|o| value(o))) {
|
||||
// The record's groups alone can't tell a flip from another two-point parameter (a stray
|
||||
// 70, or a flip without its state): the parameter it belongs to decides.
|
||||
let flip = m.parameters.iter().any(|p| p.node == node && matches!(p.kind, ParameterKind::Flip { .. }));
|
||||
let v = match (flip, v) {
|
||||
(false, Value::Flip { base, end, .. }) => Value::Points { base, end },
|
||||
(true, Value::Points { base, end }) => Value::Flip { base, end, flipped: false },
|
||||
(_, v) => v,
|
||||
};
|
||||
values.insert(node, v);
|
||||
}
|
||||
}
|
||||
Some(Reference { definition, values })
|
||||
}
|
||||
|
||||
/// An angle (radians) as Properties shows it: degrees with AUPREC decimals.
|
||||
/// An angle parameter's value `a` (radians, counterclockwise) as the drawing shows angles: from
|
||||
/// ANGBASE, clockwise when ANGDIR is 1 (AutoCAD shows a 0 angle as 90 in a drawing measured
|
||||
/// clockwise from north, and 0.5 rad as 61.35).
|
||||
pub(super) fn angle_shown(d: &Drawing, a: f64) -> f64 {
|
||||
let base = d.header.f64("ANGBASE", 0.0);
|
||||
let shown = if d.header.i64("ANGDIR", 0) == 1 { base - a } else { a - base };
|
||||
shown.rem_euclid(std::f64::consts::TAU)
|
||||
}
|
||||
|
||||
/// The value of an angle parameter shown (or typed) as `v` (radians): the inverse of
|
||||
/// [`angle_shown`].
|
||||
pub(super) fn angle_from_shown(d: &Drawing, v: f64) -> f64 {
|
||||
let base = d.header.f64("ANGBASE", 0.0);
|
||||
let a = if d.header.i64("ANGDIR", 0) == 1 { base - v } else { v + base };
|
||||
a.rem_euclid(std::f64::consts::TAU)
|
||||
}
|
||||
|
||||
fn angle_text(d: &Drawing, a: f64) -> String {
|
||||
let prec = usize::try_from(d.header.i64("AUPREC", 0).clamp(0, 8)).unwrap_or(0);
|
||||
// Rounded to the shown decimals first: an angle just short of a full turn shows as 0, not 360.
|
||||
let step = 10f64.powi(i32::try_from(prec).unwrap_or(0));
|
||||
let shown = (angle_shown(d, a).to_degrees() * step).round() / step;
|
||||
let shown = if shown >= 360.0 { shown - 360.0 } else { shown };
|
||||
format!("{:.prec$}", shown + 0.0)
|
||||
}
|
||||
|
||||
/// A number as the drawing shows lengths (LUPREC decimals).
|
||||
fn number(d: &Drawing, v: f64) -> String {
|
||||
let prec = usize::try_from(d.header.i64("LUPREC", 4).clamp(0, 8)).unwrap_or(4);
|
||||
@@ -198,7 +156,26 @@ struct Current<'a> {
|
||||
impl Current<'_> {
|
||||
/// Parameter `node`'s value of property `property`, as table cells write it.
|
||||
fn property(&self, node: i32, property: &str) -> Option<String> {
|
||||
super::apply::property_text(self.m, self.values, node, property)
|
||||
let p = self.m.parameters.iter().find(|p| p.node == node)?;
|
||||
let v = self.values.get(&node);
|
||||
match (&p.kind, property.to_ascii_lowercase().as_str()) {
|
||||
(ParameterKind::Visibility { states, .. }, "visibilitystate") => match v {
|
||||
Some(Value::Text { value }) => Some(value.clone()),
|
||||
_ => states.first().map(|s| s.name.clone()),
|
||||
},
|
||||
(ParameterKind::Linear { base, end, .. }, "updateddistance" | "distance") => {
|
||||
let (b, e) = match v {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*base, *end),
|
||||
};
|
||||
Some(format!("{}", (e - b).len()))
|
||||
}
|
||||
(ParameterKind::Lookup { .. }, "lookupstring") => match v {
|
||||
Some(Value::Text { value }) => Some(value.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Lookup parameter `node`'s value: the value every lookup table that sets it gives for the
|
||||
@@ -262,27 +239,6 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
|
||||
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
|
||||
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
|
||||
}
|
||||
// The distance from the base to the end, and the end's direction (AutoCAD measures it
|
||||
// from the block's X axis, not from where the dynamic block has it).
|
||||
ParameterKind::Polar { base: b, end: e, label, angle_label, values, .. } => {
|
||||
let (b, e) = match v {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*b, *e),
|
||||
};
|
||||
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
|
||||
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
|
||||
let a = (e - b).xy().angle().rem_euclid(std::f64::consts::TAU);
|
||||
out.push(CustomProperty { name: angle_label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
|
||||
}
|
||||
// How far the end is from the base along X and along Y.
|
||||
ParameterKind::Xy { base: b, end: e, x_label, y_label, .. } => {
|
||||
let (b, e) = match v {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*b, *e),
|
||||
};
|
||||
out.push(CustomProperty { name: x_label.clone(), value: number(d, (e.x - b.x) * sx), choices: Vec::new(), editable: true });
|
||||
out.push(CustomProperty { name: y_label.clone(), value: number(d, (e.y - b.y) * sy), choices: Vec::new(), editable: true });
|
||||
}
|
||||
ParameterKind::Point { at, label, .. } => {
|
||||
let at = match v {
|
||||
Some(Value::Point { at }) => *at,
|
||||
@@ -291,21 +247,6 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
|
||||
out.push(CustomProperty { name: format!("{label} X"), value: number(d, (at.x - base.x) * sx), choices: Vec::new(), editable: true });
|
||||
out.push(CustomProperty { name: format!("{label} Y"), value: number(d, (at.y - base.y) * sy), choices: Vec::new(), editable: true });
|
||||
}
|
||||
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
|
||||
let (b, e) = match v {
|
||||
Some(Value::Points { base, end }) => (*base, *end),
|
||||
_ => (*hb, *he),
|
||||
};
|
||||
let now = (e - b).xy();
|
||||
let zero = (*he - *hb).xy();
|
||||
let a = (now.y.atan2(now.x) - zero.y.atan2(zero.x)).rem_euclid(std::f64::consts::TAU);
|
||||
out.push(CustomProperty { name: label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
|
||||
}
|
||||
ParameterKind::Flip { label, states, .. } => {
|
||||
let flipped = matches!(v, Some(Value::Flip { flipped: true, .. }));
|
||||
let value = states[usize::from(flipped)].clone();
|
||||
out.push(CustomProperty { name: label.clone(), value, choices: states.to_vec(), editable: true });
|
||||
}
|
||||
ParameterKind::Visibility { label, states, .. } => {
|
||||
let value = cur.property(p.node, "VisibilityState").unwrap_or_default();
|
||||
out.push(CustomProperty { name: label.clone(), value, choices: states.iter().map(|s| s.name.clone()).collect(), editable: true });
|
||||
@@ -322,8 +263,7 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
|
||||
}
|
||||
|
||||
/// Whether every lookup table that sets lookup parameter `node` sets only what
|
||||
/// [`super::set_property`] can apply with it: visibility states, distances, angles, positions and
|
||||
/// flip states.
|
||||
/// [`super::set_property`] can apply with it: visibility states and distances.
|
||||
fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
|
||||
let mut any = false;
|
||||
for a in &m.actions {
|
||||
@@ -332,29 +272,12 @@ fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
let settable = |c: &super::LookupColumn| {
|
||||
m.parameters.iter().find(|p| p.node == c.node).is_some_and(|p| super::apply::column(&p.kind, &c.property).is_some())
|
||||
};
|
||||
if !columns.iter().all(settable) {
|
||||
if !columns
|
||||
.iter()
|
||||
.all(|c| matches!(c.property.to_ascii_lowercase().as_str(), "lookupstring" | "visibilitystate" | "updateddistance" | "distance"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::angle_text;
|
||||
use crate::Drawing;
|
||||
|
||||
#[test]
|
||||
fn an_angle_just_short_of_a_full_turn_shows_as_zero() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_i64("AUPREC", 0);
|
||||
assert_eq!(angle_text(&d, 359.7f64.to_radians()), "0");
|
||||
assert_eq!(angle_text(&d, 359.4f64.to_radians()), "359");
|
||||
d.header.set_i64("AUPREC", 2);
|
||||
assert_eq!(angle_text(&d, 359.996f64.to_radians()), "0.00");
|
||||
assert_eq!(angle_text(&d, 90f64.to_radians()), "90.00");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -617,7 +617,7 @@ impl EntityKind {
|
||||
EntityKind::Text(t) => vec![t.justify_point()],
|
||||
EntityKind::MText(t) => vec![t.insert.xy()],
|
||||
EntityKind::AttDef(a) => vec![a.text.justify_point()],
|
||||
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.grip_attribs().map(|(_, a)| a.text.justify_point())).collect(),
|
||||
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.attribs.iter().map(|a| a.text.justify_point())).collect(),
|
||||
EntityKind::Dimension(d) => vec![d.p13.xy(), d.p14.xy(), d.defpt.xy(), d.text_mid.xy()],
|
||||
EntityKind::MLine(m) => m.points(),
|
||||
EntityKind::Leader(l) => l.vertices.iter().map(|v| v.xy()).collect(),
|
||||
|
||||
@@ -191,12 +191,6 @@ fn one_u() -> u32 {
|
||||
}
|
||||
|
||||
impl Insert {
|
||||
/// The attributes that have a grip of their own (grips 1, 2… after the insertion point), with
|
||||
/// their index in `attribs`: those shown and not locked in position, as AutoCAD offers them.
|
||||
pub fn grip_attribs(&self) -> impl Iterator<Item = (usize, &Attrib)> {
|
||||
self.attribs.iter().enumerate().filter(|(_, a)| !a.invisible && !a.modes.lock_position)
|
||||
}
|
||||
|
||||
/// Block-to-world transform (2D part).
|
||||
pub fn transform(&self, base: Vec2) -> Mat3 {
|
||||
Mat3::translate(self.insert.xy())
|
||||
|
||||
@@ -7,11 +7,6 @@ pub struct HatchLoop {
|
||||
pub vertices: Vec<PolyVertex>,
|
||||
#[serde(default)]
|
||||
pub outer: bool,
|
||||
/// Original DXF group 92 bits. Writing keeps only Derived (4), Textbox (8) and
|
||||
/// Outermost (16), derives External (1) from `outer`, and sets Polyline (2).
|
||||
/// None uses the flags of a locally created loop.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub boundary_flags: Option<i64>,
|
||||
/// The objects the loop was made from (DXF group 97 count, 330 handles): an associative
|
||||
/// hatch re-fills the loop from them when they change.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
|
||||
@@ -37,7 +37,7 @@ pub struct RegionProps {
|
||||
impl Region {
|
||||
/// A region bounded by one closed loop.
|
||||
pub fn from_loop(vertices: Vec<PolyVertex>) -> Region {
|
||||
Region { loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }] }
|
||||
Region { loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }] }
|
||||
}
|
||||
|
||||
pub fn polylines(&self) -> Vec<Polyline> {
|
||||
@@ -170,7 +170,7 @@ mod tests {
|
||||
let mut vertices: Vec<PolyVertex> =
|
||||
(0..n).map(|k| PolyVertex::new(Vec2::new(c - half + 2.0 * half * k as f64 / n as f64, c - half))).collect();
|
||||
vertices.extend([Vec2::new(c + half, c - half), Vec2::new(c + half, c + half), Vec2::new(c - half, c + half)].map(PolyVertex::new));
|
||||
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
|
||||
HatchLoop { vertices, outer, sources: Vec::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -53,10 +53,6 @@ impl ForeignExtra {
|
||||
/// Everything of a file CADCraft keeps without modelling it.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Foreign {
|
||||
/// Original two-point text and style, by entity handle and attribute position.
|
||||
/// Kept with imported metadata so new entities never inherit another entity's fitting.
|
||||
pub text_fits: BTreeMap<Handle, Vec<(crate::Text, crate::TextStyle)>>,
|
||||
|
||||
/// CLASS records (groups after `0 CLASS`) of the kept objects' and entities' types.
|
||||
pub classes: Vec<Vec<RawTag>>,
|
||||
/// Classes retain every source position, including duplicate names.
|
||||
@@ -89,9 +85,6 @@ pub struct Foreign {
|
||||
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
|
||||
/// later save must not take it for this one (#2471).
|
||||
pub version: Option<String>,
|
||||
/// The file's registered applications (APPID names as read, in file order). Saving writes
|
||||
/// them all back, whether or not any xdata still names them.
|
||||
pub appids: Vec<String>,
|
||||
}
|
||||
|
||||
impl Foreign {
|
||||
@@ -110,7 +103,6 @@ impl Foreign {
|
||||
&& self.targets.is_empty()
|
||||
&& self.class_order.is_empty()
|
||||
&& self.data_store.is_empty()
|
||||
&& self.appids.is_empty()
|
||||
}
|
||||
|
||||
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
|
||||
@@ -134,89 +126,22 @@ pub fn sat_text_acis(u: &crate::Unknown, handle: Handle, stored: &std::collectio
|
||||
["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && !stored.contains(&handle) && has_sat_text(&u.tags)
|
||||
}
|
||||
|
||||
/// Whether a solid modeler entity can't be written to a DXF of 2013 and later (`modern`: SAT text
|
||||
/// with no data store record, [`sat_text_acis`]) or of 2010 and earlier (geometry only in the data
|
||||
/// store, which those files don't have, and no SAT text to write instead) (#2334).
|
||||
pub fn acis_left_out(u: &crate::Unknown, handle: Handle, stored: &std::collections::BTreeSet<Handle>, modern: bool) -> bool {
|
||||
if modern {
|
||||
return sat_text_acis(u, handle, stored);
|
||||
}
|
||||
["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && stored.contains(&handle) && !has_sat_text(&u.tags)
|
||||
}
|
||||
|
||||
/// The entities a DXF of 2013 or later leaves out because they hold SAT-text ACIS data
|
||||
/// ([`sat_text_acis`]), counted by DXF type, across model space, layouts and block definitions.
|
||||
pub fn sat_text_dropped(d: &crate::Drawing) -> BTreeMap<String, usize> {
|
||||
acis_dropped(d, true)
|
||||
}
|
||||
|
||||
/// The entities a DXF leaves out by [`acis_left_out`], counted like [`sat_text_dropped`].
|
||||
pub fn acis_dropped(d: &crate::Drawing, modern: bool) -> BTreeMap<String, usize> {
|
||||
let stored = d.foreign.data_store_entities();
|
||||
let mut out = BTreeMap::new();
|
||||
for e in saved_entities(d) {
|
||||
if let crate::EntityKind::Unknown(u) = &e.kind
|
||||
&& acis_left_out(u, e.handle, &stored, modern)
|
||||
{
|
||||
count(&mut out, &u.dxf_type);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The entities a DXF file holds: model space, layouts and block definitions. The writer saves
|
||||
/// xrefs as references: their blocks (and `xref|` ones) hold nothing in the file.
|
||||
fn saved_entities(d: &crate::Drawing) -> impl Iterator<Item = &std::sync::Arc<crate::Entity>> {
|
||||
// The writer saves xrefs as references: their blocks (and `xref|` ones) hold nothing in the file.
|
||||
let own_blocks = d.blocks.values().filter(|b| b.xref_path.is_none() && !xref_dependent(&b.name));
|
||||
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(own_blocks.map(|b| &b.entities));
|
||||
stores.flat_map(|s| s.iter())
|
||||
}
|
||||
|
||||
/// Add one record of DXF type `kind` to `out`.
|
||||
fn count(out: &mut BTreeMap<String, usize>, kind: &str) {
|
||||
let n: &mut usize = out.entry(kind.to_ascii_uppercase()).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
|
||||
/// Whether a DXF type is a proxy (ACAD_PROXY_OBJECT, ACAD_PROXY_ENTITY).
|
||||
pub fn is_proxy(kind: &str) -> bool {
|
||||
let k = kind.trim();
|
||||
k.eq_ignore_ascii_case("ACAD_PROXY_OBJECT") || k.eq_ignore_ascii_case("ACAD_PROXY_ENTITY")
|
||||
}
|
||||
|
||||
/// Whether a proxy's groups (after its type) give it a separate string stream: a size above 0 in
|
||||
/// group 96 (2007) or 162 (2010 and later) after the `AcDbProxy…` marker. Before 2007 a proxy's
|
||||
/// strings are part of its data, so a file of an earlier version has no form for one that keeps
|
||||
/// them apart (#3229).
|
||||
pub fn proxy_has_string_stream<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)>) -> bool {
|
||||
let mut own = false;
|
||||
for (code, value) in groups {
|
||||
let v = value.as_ref().trim();
|
||||
match code {
|
||||
100 => own = own || v.to_ascii_lowercase().starts_with("acdbproxy"),
|
||||
96 | 162 if own && v.parse::<i64>().is_ok_and(|n| n > 0) => return true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The proxies a DXF earlier than 2007 leaves out because they have a separate string stream
|
||||
/// ([`proxy_has_string_stream`]), counted by DXF type.
|
||||
pub fn proxies_dropped_before_2007(d: &crate::Drawing) -> BTreeMap<String, usize> {
|
||||
let mut out = BTreeMap::new();
|
||||
let has_strings = |tags: &[RawTag]| proxy_has_string_stream(tags.iter().map(|t| (t.code, t.value.as_str())));
|
||||
for e in saved_entities(d) {
|
||||
for e in stores.flat_map(|s| s.iter()) {
|
||||
if let crate::EntityKind::Unknown(u) = &e.kind
|
||||
&& is_proxy(&u.dxf_type)
|
||||
&& has_strings(&u.tags)
|
||||
&& sat_text_acis(u, e.handle, &stored)
|
||||
{
|
||||
count(&mut out, &u.dxf_type);
|
||||
let n: &mut usize = out.entry(u.dxf_type.to_ascii_uppercase()).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
}
|
||||
for o in d.foreign.objects.iter().filter(|o| is_proxy(&o.kind) && has_strings(&o.tags)) {
|
||||
count(&mut out, &o.kind);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -239,23 +164,6 @@ pub fn data_store_records(tags: &[RawTag]) -> Vec<&[RawTag]> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The ACIS version a modeler entity's SAT text declares (the first number of its first line:
|
||||
/// 400, 700, 21800…), if it has SAT text.
|
||||
pub fn sat_version(tags: &[RawTag]) -> Option<u32> {
|
||||
let marked = tags.iter().take_while(|r| r.code < 1000).any(|r| r.code == 100);
|
||||
let mut in_modeler = !marked;
|
||||
for r in tags.iter().take_while(|r| r.code < 1000) {
|
||||
if r.code == 100 {
|
||||
in_modeler = r.value.trim().eq_ignore_ascii_case("AcDbModelerGeometry");
|
||||
} else if in_modeler && r.code == 1 {
|
||||
let first = r.value.split_whitespace().next()?;
|
||||
// DXF before 2013 encodes SAT text: each character but a space is 159 minus it ("hoo" is 700).
|
||||
return first.parse().ok().or_else(|| first.bytes().map(|b| char::from(159u8.wrapping_sub(b))).collect::<String>().parse().ok());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether an entity's groups hold SAT text: groups 1 and 3 inside its `AcDbModelerGeometry`
|
||||
/// subclass. A file of a version before the subclass markers has no `100` groups: all of its
|
||||
/// groups (before the extended data) are the entity's.
|
||||
|
||||
@@ -821,18 +821,6 @@ pub struct PageSetup {
|
||||
/// save keeps where the sheet sits; `None` for a page CADCraft made, written as 0,0 (#2109).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub image_origin: Option<Vec2>,
|
||||
/// The plot layout flags (DXF group 70 of AcDbPlotSettings) as the file had them. Saving keeps
|
||||
/// the bits CADCraft doesn't model (plot paper space last, plot with plot styles, standard
|
||||
/// scale and the rest) as read instead of forcing its defaults (#3227); `None` for page setups
|
||||
/// made in CADCraft.
|
||||
#[serde(skip)]
|
||||
pub file_plot_flags: Option<i64>,
|
||||
/// The standard scale the file chose (DXF group 75, such as 25 for 1:50) and the plot scale it
|
||||
/// was read with. While the scale is unchanged, saving keeps that choice and the standard scale
|
||||
/// flag instead of writing the scale as a custom one; `None` for a custom scale, scaled to
|
||||
/// fit, or a page setup made in CADCraft.
|
||||
#[serde(skip)]
|
||||
pub file_standard_scale: Option<(i64, f64)>,
|
||||
}
|
||||
|
||||
impl Default for PageSetup {
|
||||
@@ -856,8 +844,6 @@ impl Default for PageSetup {
|
||||
paper_mm: None,
|
||||
file_paper: None,
|
||||
image_origin: None,
|
||||
file_plot_flags: None,
|
||||
file_standard_scale: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,14 +70,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.enabled(has_doc)
|
||||
.noundo(),
|
||||
CommandSpec::new("blocks.reference.set", "Set Dynamic Property", run_reference_set)
|
||||
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance, \"Position1 X\", an angle or a flip state), value (lengths in drawing units, angles in degrees; a flip state by name or 0/1)} → {properties}")
|
||||
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance or \"Position1 X\"), value (lengths in drawing units)} → {properties}")
|
||||
.enabled(has_doc),
|
||||
CommandSpec::new("blocks.reference.grips", "Dynamic Block Grips", dyngrip::run_grips)
|
||||
.params("{handle} → [{node, part: base|end|at|basex-endy|basey-endx, shape: linear|point|list|rotation|flip, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
|
||||
.params("{handle} → [{node, part: base|end|at, shape: linear|point|list, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
|
||||
.enabled(has_doc)
|
||||
.noundo(),
|
||||
CommandSpec::new("blocks.reference.grip", "Drag Dynamic Grip", dyngrip::run_grip)
|
||||
.params("{handle, node (the parameter's graph id), part: base|end|at|basex-endy|basey-endx, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it, a rotation's circle turns its angle, a polar or XY parameter's squares move its base, end or corners")
|
||||
.params("{handle, node (the parameter's graph id), part: base|end|at, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it")
|
||||
.enabled(has_doc),
|
||||
CommandSpec::new("purge", "Purge", purge::run)
|
||||
.alias(&["pu", "-purge"])
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Grips of dynamic block references: `blocks.reference.grips` lists them, `blocks.reference.grip`
|
||||
//! drags one (one undo step), and [`Session::start_dyn_grip`] starts the drag the UI's click on a
|
||||
//! grip begins, with the reference re-evaluated under the cursor as its preview. Typing a number
|
||||
//! at a distance's grip sets the distance, at a rotation grip the angle (degrees).
|
||||
//! at a distance's grip sets the distance.
|
||||
|
||||
use cadcraft_doc::color::Color;
|
||||
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
|
||||
@@ -30,8 +30,7 @@ pub(super) fn run_grip(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.and_then(Value::as_i64)
|
||||
.and_then(|n| i32::try_from(n).ok())
|
||||
.ok_or_else(|| bad(cmd, "`node` (a parameter's graph id) is required"))?;
|
||||
let part =
|
||||
str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end, at, basex-endy or basey-endx"))?;
|
||||
let part = str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end or at"))?;
|
||||
let to = point_param(p, "to").ok_or_else(|| bad(cmd, "`to` [x, y] is required"))?;
|
||||
drag(s, h, node, part, to).map_err(|e| bad(cmd, e))?;
|
||||
let properties = dynblock::custom_properties(s.doc()?, h).map(|(_, p)| p).unwrap_or_default();
|
||||
@@ -47,25 +46,11 @@ fn drag(s: &mut Session, h: Handle, node: i32, part: GripPart, to: Vec2) -> std:
|
||||
return Err("the reference is on a locked layer".into());
|
||||
}
|
||||
let mut d = s.doc().map_err(|e| e.to_string())?.clone();
|
||||
drag_in(s, &mut d, h, node, part, to)?;
|
||||
dynblock::drag_grip(&mut d, h, node, part, to)?;
|
||||
*s.doc_mut().map_err(|e| e.to_string())? = d;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drag grip (`node`, `part`) of reference `h` to `to` in drawing `d`; an alignment grip aligns
|
||||
/// the reference with the object at the cursor (within the aperture), as AutoCAD does.
|
||||
fn drag_in(s: &Session, d: &mut Drawing, h: Handle, node: i32, part: GripPart, to: Vec2) -> std::result::Result<(), String> {
|
||||
let alignment = dynblock::reference(d, h)
|
||||
.and_then(|r| dynblock::dynamic_block(d, &r.definition))
|
||||
.is_some_and(|m| m.parameters.iter().any(|p| p.node == node && matches!(p.kind, dynblock::ParameterKind::Alignment { .. })));
|
||||
if !alignment {
|
||||
return dynblock::drag_grip(d, h, node, part, to);
|
||||
}
|
||||
let aperture = s.pixel_size() * s.settings.aperture.max(1.0);
|
||||
let near = crate::snap::nearest_with_direction(d, &s.space(), to, aperture, h);
|
||||
dynblock::align_grip(d, h, node, to, near)
|
||||
}
|
||||
|
||||
/// The properties an object of a block draws with in reference `r`: on layer 0 it is on the
|
||||
/// reference's layer, and its ByBlock colour, linetype, lineweight and transparency are the
|
||||
/// reference's (as the renderer draws a block's contents).
|
||||
@@ -117,11 +102,7 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
|
||||
_ => None,
|
||||
});
|
||||
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
|
||||
let kind = match a.multiline_text() {
|
||||
Some(m) => EntityKind::MText(m),
|
||||
None => EntityKind::Text(a.text.clone()),
|
||||
};
|
||||
Entity { handle: Handle(0), common, kind }
|
||||
Entity { handle: Handle(0), common, kind: EntityKind::Text(a.text.clone()) }
|
||||
}));
|
||||
out
|
||||
}
|
||||
@@ -133,16 +114,11 @@ struct DynGripEdit {
|
||||
part: GripPart,
|
||||
/// Where the grip is (the rubber band's start).
|
||||
from: Vec2,
|
||||
/// The property it changes, and the grip's shape (a typed number sets a distance or angle).
|
||||
/// The property it changes, and whether it is a distance (a typed number sets it).
|
||||
property: String,
|
||||
shape: GripShape,
|
||||
/// Where the grip can stop (a value list or increments): tick marks across its travel.
|
||||
stops: Vec<(Vec2, Vec2)>,
|
||||
distance: bool,
|
||||
}
|
||||
|
||||
/// Half a tick mark's length, in pixels.
|
||||
const TICK_PX: f64 = 6.0;
|
||||
|
||||
impl Interactive for DynGripEdit {
|
||||
fn name(&self) -> &'static str {
|
||||
"GRIP"
|
||||
@@ -153,22 +129,19 @@ impl Interactive for DynGripEdit {
|
||||
}
|
||||
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
let (msg, accept) = match self.shape {
|
||||
GripShape::Linear => ("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER),
|
||||
GripShape::Rotation => ("** ROTATE ** Specify rotation point or angle", Accept::POINT_OR_NUMBER),
|
||||
GripShape::Alignment => ("Specify point location", Accept::POINT),
|
||||
_ => ("** STRETCH ** Specify stretch point", Accept::POINT),
|
||||
let (msg, accept) = if self.distance {
|
||||
("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER)
|
||||
} else {
|
||||
("** STRETCH ** Specify stretch point", Accept::POINT)
|
||||
};
|
||||
let p = Prompt::new(msg, accept).kw(&["eXit"]).base(self.from);
|
||||
// A rotation grip asks for an angle: Dynamic Input shows one angle box.
|
||||
if self.shape == GripShape::Rotation { p.angle() } else { p }
|
||||
Prompt::new(msg, accept).kw(&["eXit"]).base(self.from)
|
||||
}
|
||||
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
let to = match i {
|
||||
Input::Point(p) => p,
|
||||
Input::Deferred(d) => d.at,
|
||||
Input::Text(t) if matches!(self.shape, GripShape::Linear | GripShape::Rotation) => {
|
||||
Input::Text(t) if self.distance => {
|
||||
let mut d = s.doc()?.clone();
|
||||
dynblock::set_property(&mut d, self.handle, &self.property, t.trim()).map_err(EngineError::Other)?;
|
||||
*s.doc_mut()? = d;
|
||||
@@ -182,30 +155,9 @@ impl Interactive for DynGripEdit {
|
||||
Ok(Step::Done)
|
||||
}
|
||||
|
||||
/// The rubber band from the grip, and ticks at the stops of a value list or increments.
|
||||
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
let half = TICK_PX * s.pixel_size();
|
||||
let mut out: Vec<EntityKind> = self
|
||||
.stops
|
||||
.iter()
|
||||
.map(|(at, way)| {
|
||||
let n = way.perp() * half;
|
||||
crate::cmd::helpers::line(*at - n, *at + n)
|
||||
})
|
||||
.collect();
|
||||
out.push(crate::cmd::helpers::line(self.from, c));
|
||||
out
|
||||
}
|
||||
|
||||
/// A rotation grip's angle at the cursor, as Properties will show it.
|
||||
fn live_value(&self, s: &Session, c: Vec2) -> Option<String> {
|
||||
if self.shape != GripShape::Rotation {
|
||||
return None;
|
||||
}
|
||||
let mut d = s.doc().ok()?.clone();
|
||||
dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c).ok()?;
|
||||
let (_, props) = dynblock::custom_properties(&d, self.handle)?;
|
||||
props.into_iter().find(|p| p.name.eq_ignore_ascii_case(&self.property)).map(|p| format!("{}°", p.value))
|
||||
/// The rubber band from the grip.
|
||||
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
|
||||
vec![crate::cmd::helpers::line(self.from, c)]
|
||||
}
|
||||
|
||||
/// The reference re-evaluated at the cursor, drawn as it will look (its own colours, so
|
||||
@@ -213,7 +165,7 @@ impl Interactive for DynGripEdit {
|
||||
fn preview_objects(&self, s: &Session, c: Vec2) -> Vec<Entity> {
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
let mut d = d.clone();
|
||||
match drag_in(s, &mut d, self.handle, self.node, self.part, c) {
|
||||
match dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c) {
|
||||
Ok(()) => drawn(&d, self.handle),
|
||||
Err(_) => Vec::new(),
|
||||
}
|
||||
@@ -222,8 +174,8 @@ impl Interactive for DynGripEdit {
|
||||
|
||||
impl Session {
|
||||
/// Start dragging grip `part` of parameter `node` of dynamic block reference `handle` (the
|
||||
/// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no
|
||||
/// drag: the UI offers the choices, or flips, with `blocks.reference.set`.
|
||||
/// UI's click on a dynamic grip). A list grip (visibility, lookup) has no drag: the UI offers
|
||||
/// its choices and sets them with `blocks.reference.set`.
|
||||
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
|
||||
if self.running.is_some() {
|
||||
self.cancel();
|
||||
@@ -232,19 +184,17 @@ impl Session {
|
||||
.into_iter()
|
||||
.find(|g| g.node == node && g.part == part)
|
||||
.ok_or_else(|| EngineError::Other("no such grip".into()))?;
|
||||
if matches!(g.shape, GripShape::List | GripShape::Flip) {
|
||||
return Err(EngineError::Other("a list or flip grip is clicked, not dragged".into()));
|
||||
if g.shape == GripShape::List {
|
||||
return Err(EngineError::Other("a list grip is chosen from, not dragged".into()));
|
||||
}
|
||||
let label = if g.shape == GripShape::Rotation { "** ROTATE **" } else { "** STRETCH **" };
|
||||
let stops = dynblock::grip_stops(self.doc()?, handle, node, part);
|
||||
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, shape: g.shape, stops };
|
||||
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, distance: g.shape == GripShape::Linear };
|
||||
let machine = crate::guard::Guarded::wrap(Box::new(edit));
|
||||
let st = self.state()?;
|
||||
let (before, selection_before) = (st.doc.clone(), st.selection.clone());
|
||||
self.running = Some(Running { id: "grip".into(), machine, before, selection_before });
|
||||
self.pending_window = None;
|
||||
self.point_mods.clear();
|
||||
self.echo(label);
|
||||
self.echo("** STRETCH **");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::curves::KW;
|
||||
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
|
||||
use super::super::file::{drops_unknown, new_folder, not_saved, not_saved_message, report_new_folder, report_not_saved};
|
||||
use super::super::machines::{SelOutcome, SelectPhase};
|
||||
use super::super::modify::erase_kept;
|
||||
use super::super::{CommandSpec, bad, point_param, str_param, targets};
|
||||
@@ -44,13 +44,13 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost) = match str_param(p, "name") {
|
||||
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
|
||||
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
|
||||
};
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost) = match str_param(p, "name") {
|
||||
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
|
||||
None => {
|
||||
let hs = targets(s, p)?;
|
||||
@@ -76,17 +76,16 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
|
||||
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
|
||||
/// the version it was written at, for the caller to report as a save does. The
|
||||
/// Write `what` to `path` through the io hooks; the objects written, the file's size and what a
|
||||
/// DWG file left out, for the caller to report as a save does. The
|
||||
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
|
||||
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
|
||||
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>)> {
|
||||
let src = s.doc()?;
|
||||
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
|
||||
// block's base point for a block.
|
||||
@@ -109,15 +108,13 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
|
||||
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
// The written drawing's own version: the writer is given no other.
|
||||
let version = own_version(&d, path);
|
||||
let lost = lost_writing(&d, path, version);
|
||||
Ok((d.model.len(), bytes.len(), lost, version))
|
||||
let lost = if drops_unknown(path) { not_saved(&d) } else { BTreeMap::new() };
|
||||
Ok((d.model.len(), bytes.len(), lost))
|
||||
}
|
||||
|
||||
/// Say on the command line what the file written at `path` and `version` left out.
|
||||
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
|
||||
if let Some(msg) = lost_message(path, version, lost) {
|
||||
/// Say on the command line what the written DWG file left out.
|
||||
fn echo_not_saved(s: &mut Session, lost: &BTreeMap<String, usize>) {
|
||||
if let Some(msg) = not_saved_message(lost) {
|
||||
s.echo(msg);
|
||||
}
|
||||
}
|
||||
@@ -338,7 +335,7 @@ impl DashWblockM {
|
||||
|
||||
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
|
||||
match write(s, "-wblock", &self.path, what) {
|
||||
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
|
||||
Ok((.., lost)) => echo_not_saved(s, &lost),
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
}
|
||||
Ok(Step::Done)
|
||||
@@ -349,8 +346,8 @@ impl DashWblockM {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
|
||||
Ok((.., lost, version)) => {
|
||||
echo_not_saved(s, &self.path, version, &lost);
|
||||
Ok((.., lost)) => {
|
||||
echo_not_saved(s, &lost);
|
||||
erase(s, hs)?;
|
||||
}
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
|
||||
@@ -39,10 +39,6 @@ fn vertex_value(v: &Value) -> Option<PolyVertex> {
|
||||
Some(PolyVertex { p, bulge: f64_or(v, "bulge", 0.0), start_width: f64_or(v, "startWidth", 0.0), end_width: f64_or(v, "endWidth", 0.0) })
|
||||
}
|
||||
|
||||
fn current_elevation(s: &Session) -> Result<f64> {
|
||||
Ok(s.doc()?.header.f64("ELEVATION", 0.0))
|
||||
}
|
||||
|
||||
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
|
||||
for v in raw.into_iter().flatten() {
|
||||
@@ -57,7 +53,6 @@ pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut k = lwpoly(vs, bool_or(p, "closed", false));
|
||||
if let EntityKind::LwPolyline(pl) = &mut k {
|
||||
pl.const_width = width;
|
||||
pl.elevation = current_elevation(s)?;
|
||||
}
|
||||
added(s.add_entity(k)?)
|
||||
}
|
||||
@@ -179,7 +174,6 @@ impl Interactive for LineM {
|
||||
#[derive(Default)]
|
||||
pub(super) struct PlineM {
|
||||
verts: Vec<PolyVertex>,
|
||||
elevation: f64,
|
||||
arc_mode: bool,
|
||||
/// Total width at the start and end of the next segment (Width / Halfwidth answers).
|
||||
start_w: f64,
|
||||
@@ -197,7 +191,6 @@ impl PlineM {
|
||||
fn entity(&self, closed: bool) -> EntityKind {
|
||||
let mut k = lwpoly(self.verts.clone(), closed);
|
||||
if let EntityKind::LwPolyline(pl) = &mut k {
|
||||
pl.elevation = self.elevation;
|
||||
// Every segment the same uniform width: store it as the constant width, as before.
|
||||
let segs = if closed { pl.vertices.len() } else { pl.vertices.len().saturating_sub(1) };
|
||||
let w = pl.vertices.first().map_or(0.0, |v| v.start_width);
|
||||
@@ -266,10 +259,6 @@ impl Interactive for PlineM {
|
||||
fn name(&self) -> &'static str {
|
||||
"PLINE"
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.elevation = current_elevation(s)?;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
if self.asking_width > 0 {
|
||||
let unit = if self.half { "half-width" } else { "width" };
|
||||
|
||||
@@ -232,7 +232,7 @@ impl Interactive for MTextM {
|
||||
None => Prompt::new("Specify first corner", Accept::POINT),
|
||||
Some(a) if !self.boxed() => Prompt::new("Specify opposite corner", Accept::POINT)
|
||||
.kw(&["Height", "Justify", "Line spacing", "Rotation", "Style", "Width", "Columns"])
|
||||
.corner(a),
|
||||
.base(a),
|
||||
_ if self.lines.is_empty() => Prompt::new("Enter text (use \\P for new paragraphs)", Accept::TEXT),
|
||||
_ => Prompt::new("Enter next line of text (empty line to finish)", Accept::TEXT),
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ use super::{
|
||||
Accept, Chain, Circle, Ellipse, EntityKind, Handle, Input, Interactive, Line, MAX_GEN, PolyVertex, Polyline, Prompt, Result, Session, Step,
|
||||
Value, Vec2, added, bad, bool_or, curves, lwpoly, number, other, point_param, points_param, rect_vertices, shoelace, str_param,
|
||||
};
|
||||
use cadcraft_doc::RawTag;
|
||||
|
||||
// =====================================================================================
|
||||
// REVCLOUD
|
||||
@@ -21,11 +20,6 @@ fn default_arc_len(s: &Session) -> f64 {
|
||||
d.map(|d| d.header.f64("REVCLOUDARCLEN", if metric { 15.0 } else { 0.5 })).unwrap_or(0.5).max(1e-6)
|
||||
}
|
||||
|
||||
/// Maximum arc length remembered between REVCLOUD runs (CADCraft-only state, not an AutoCAD variable); never below `min`.
|
||||
fn default_max_arc_len(s: &Session, min: f64) -> f64 {
|
||||
s.doc().ok().map_or(min, |d| d.header.f64("CADCRAFT_REVCLOUDMAXARCLEN", min)).max(min)
|
||||
}
|
||||
|
||||
/// Bulged closed polyline vertices for a revision cloud around `boundary`.
|
||||
pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, reverse: bool) -> Option<Vec<PolyVertex>> {
|
||||
let mut pts: Vec<Vec2> = Vec::new();
|
||||
@@ -100,38 +94,6 @@ fn cloud_entity(vs: Vec<PolyVertex>, calligraphy: bool, arc_len: f64) -> EntityK
|
||||
lwpoly(vs, true)
|
||||
}
|
||||
|
||||
/// The application name of the xdata that marks a closed polyline as a revision cloud.
|
||||
const REVCLOUD_APP: &str = "RevcloudProps";
|
||||
|
||||
/// Adds a revision cloud with its `RevcloudProps` xdata (how AutoCAD and other readers tell a
|
||||
/// revision cloud from a polyline). Made from object `src`, the cloud takes the object's place
|
||||
/// and properties.
|
||||
fn add_cloud(s: &mut Session, vs: Vec<PolyVertex>, calligraphy: bool, arc_len: f64, src: Option<Handle>) -> Result<Handle> {
|
||||
let h = s.add_entity(cloud_entity(vs, calligraphy, arc_len))?;
|
||||
let mut common = match src {
|
||||
Some(src) => curves::entity(s, src)?.common,
|
||||
None => curves::entity(s, h)?.common,
|
||||
};
|
||||
let mut keep = true;
|
||||
common.xdata.retain(|t| {
|
||||
if t.code == 1001 {
|
||||
keep = !t.value.trim().eq_ignore_ascii_case(REVCLOUD_APP);
|
||||
}
|
||||
keep
|
||||
});
|
||||
common.xdata.extend([
|
||||
RawTag { code: 1001, value: REVCLOUD_APP.into() },
|
||||
RawTag { code: 1070, value: "0".into() },
|
||||
RawTag { code: 1040, value: arc_len.to_string() },
|
||||
]);
|
||||
let d = s.doc_mut()?;
|
||||
d.modify_entity(h, |e| e.common = common)?;
|
||||
if let Some(src) = src {
|
||||
d.remove_entity(src);
|
||||
}
|
||||
Ok(h)
|
||||
}
|
||||
|
||||
pub(super) fn run_revcloud(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let arc_len = p.get("arcLength").and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0).unwrap_or_else(|| default_arc_len(s));
|
||||
let reverse = bool_or(p, "reverse", false);
|
||||
@@ -151,7 +113,13 @@ pub(super) fn run_revcloud(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad("revcloud", "too many points"));
|
||||
}
|
||||
let vs = cloud_vertices(&pts, arc_len, per_edge, reverse).ok_or_else(|| bad("revcloud", "the boundary needs an area"))?;
|
||||
let h = add_cloud(s, vs, calligraphy, arc_len, src)?;
|
||||
let h = s.add_entity(cloud_entity(vs, calligraphy, arc_len))?;
|
||||
if let Some(src) = src {
|
||||
let common = curves::entity(s, src)?.common;
|
||||
let d = s.doc_mut()?;
|
||||
d.modify_entity(h, |e| e.common = common)?;
|
||||
d.remove_entity(src);
|
||||
}
|
||||
added(h)
|
||||
}
|
||||
|
||||
@@ -159,31 +127,15 @@ pub(super) struct RevcloudM {
|
||||
kind: CloudKind,
|
||||
pts: Vec<Vec2>,
|
||||
arc_len: f64,
|
||||
max_arc_len: f64,
|
||||
asking_arc: bool,
|
||||
asking_max: bool,
|
||||
object: bool,
|
||||
/// Outline of the picked object while "Reverse direction" is being asked.
|
||||
picked: Option<(Handle, Vec<Vec2>)>,
|
||||
calligraphy: bool,
|
||||
asking_style: bool,
|
||||
}
|
||||
|
||||
impl RevcloudM {
|
||||
pub(super) fn new(s: &Session, kind: CloudKind) -> Self {
|
||||
let arc_len = default_arc_len(s);
|
||||
RevcloudM {
|
||||
kind,
|
||||
pts: Vec::new(),
|
||||
arc_len,
|
||||
max_arc_len: default_max_arc_len(s, arc_len),
|
||||
asking_arc: false,
|
||||
asking_max: false,
|
||||
object: false,
|
||||
picked: None,
|
||||
calligraphy: false,
|
||||
asking_style: false,
|
||||
}
|
||||
RevcloudM { kind, pts: Vec::new(), arc_len: default_arc_len(s), asking_arc: false, object: false, calligraphy: false, asking_style: false }
|
||||
}
|
||||
fn boundary(&self, extra: Option<Vec2>) -> Vec<Vec2> {
|
||||
let mut pts = self.pts.clone();
|
||||
@@ -199,7 +151,7 @@ impl RevcloudM {
|
||||
let b = self.boundary(None);
|
||||
match cloud_vertices(&b, self.arc_len, self.kind != CloudKind::Free, false) {
|
||||
Some(vs) => {
|
||||
add_cloud(s, vs, self.calligraphy, self.arc_len, None)?;
|
||||
s.add_entity(cloud_entity(vs, self.calligraphy, self.arc_len))?;
|
||||
s.echo("Revision cloud finished.");
|
||||
Ok(Step::Done)
|
||||
}
|
||||
@@ -218,19 +170,13 @@ impl Interactive for RevcloudM {
|
||||
CloudKind::Poly => "Polygonal",
|
||||
CloudKind::Free => "Freehand",
|
||||
};
|
||||
s.echo(format!("Minimum arc length: {0:.4} Maximum arc length: {1:.4} Style: Normal Type: {t}", self.arc_len, self.max_arc_len));
|
||||
s.echo(format!("Minimum arc length: {0:.4} Maximum arc length: {0:.4} Style: Normal Type: {t}", self.arc_len));
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
if self.picked.is_some() {
|
||||
return Prompt::new("Reverse direction", curves::KW).kw(&["Yes", "No"]).default("No");
|
||||
}
|
||||
if self.asking_arc {
|
||||
return Prompt::new("Specify minimum length of arc", Accept::NUMBER).default(format!("{:.4}", self.arc_len));
|
||||
}
|
||||
if self.asking_max {
|
||||
return Prompt::new("Specify maximum length of arc", Accept::NUMBER).default(format!("{:.4}", self.max_arc_len));
|
||||
}
|
||||
if self.asking_style {
|
||||
return Prompt::new("Select arc style", curves::KW).kw(&["Normal", "Calligraphy"]).default("Normal");
|
||||
}
|
||||
@@ -251,34 +197,13 @@ impl Interactive for RevcloudM {
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
if let Some((h, pts)) = self.picked.take() {
|
||||
let reverse = matches!(&i, Input::Keyword(k) | Input::Text(k) if k.to_ascii_lowercase().starts_with('y'));
|
||||
let vs = cloud_vertices(&pts, self.arc_len, false, reverse).ok_or_else(|| other("The object has no area."))?;
|
||||
add_cloud(s, vs, self.calligraphy, self.arc_len, Some(h))?;
|
||||
s.echo("Revision cloud finished.");
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
if self.asking_arc {
|
||||
if let Input::Text(t) = &i {
|
||||
let v = number(t).filter(|v| *v > 0.0).ok_or_else(|| other("Requires a positive value."))?;
|
||||
self.arc_len = v;
|
||||
self.max_arc_len = self.max_arc_len.max(v);
|
||||
let max = self.max_arc_len;
|
||||
let d = s.doc_mut()?;
|
||||
d.header.set_f64("REVCLOUDARCLEN", v);
|
||||
d.header.set_f64("CADCRAFT_REVCLOUDMAXARCLEN", max);
|
||||
s.doc_mut()?.header.set_f64("REVCLOUDARCLEN", v);
|
||||
}
|
||||
self.asking_arc = false;
|
||||
self.asking_max = true;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.asking_max {
|
||||
if let Input::Text(t) = &i {
|
||||
let v = number(t).filter(|v| *v >= self.arc_len).ok_or_else(|| other("Requires a value not less than the minimum arc length."))?;
|
||||
self.max_arc_len = v;
|
||||
s.doc_mut()?.header.set_f64("CADCRAFT_REVCLOUDMAXARCLEN", v);
|
||||
}
|
||||
self.asking_max = false;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.asking_style {
|
||||
@@ -289,19 +214,17 @@ impl Interactive for RevcloudM {
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.object {
|
||||
let h = match i {
|
||||
Input::Point(p) => curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?,
|
||||
Input::Pick(hs) => hs.first().copied().ok_or_else(|| other("*Invalid selection*"))?,
|
||||
Input::Enter => return Ok(Step::Cancel),
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
let Input::Point(p) = i else { return if i == Input::Enter { Ok(Step::Cancel) } else { Ok(Step::Continue) } };
|
||||
let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?;
|
||||
let pts = object_outline(s, h)?;
|
||||
if cloud_vertices(&pts, self.arc_len, false, false).is_none() {
|
||||
return Err(other("The object has no area."));
|
||||
}
|
||||
self.object = false;
|
||||
self.picked = Some((h, pts));
|
||||
return Ok(Step::Continue);
|
||||
let vs = cloud_vertices(&pts, self.arc_len, false, false).ok_or_else(|| other("The object has no area."))?;
|
||||
let nh = s.add_entity(cloud_entity(vs, self.calligraphy, self.arc_len))?;
|
||||
let common = curves::entity(s, h)?.common;
|
||||
let d = s.doc_mut()?;
|
||||
d.modify_entity(nh, |e| e.common = common)?;
|
||||
d.remove_entity(h);
|
||||
s.echo("Revision cloud finished.");
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
match i {
|
||||
Input::Keyword(k) => {
|
||||
|
||||
@@ -755,44 +755,10 @@ fn revcloud_json() {
|
||||
assert!(s.execute("revcloud", &json!({"p1": [0, 0], "p2": [1e300, 1e300], "arcLength": 1e-300})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcloud_saves_revcloudprops_xdata() {
|
||||
let mut s = Session::new();
|
||||
let props = |s: &Session| {
|
||||
let xd = s.doc().unwrap().model.last().unwrap().common.xdata.clone();
|
||||
xd.iter().map(|t| (t.code, t.value.clone())).collect::<Vec<_>>()
|
||||
};
|
||||
let want = vec![(1001, "RevcloudProps".to_string()), (1070, "0".to_string()), (1040, "2".to_string())];
|
||||
s.execute("revcloud", &json!({"p1": [0, 0], "p2": [100, 50], "arcLength": 2})).unwrap();
|
||||
assert_eq!(props(&s), want);
|
||||
let dxf = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
let groups: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect();
|
||||
assert!(groups.contains(&("1001", "RevcloudProps")), "no RevcloudProps xdata in the DXF");
|
||||
let appid = groups
|
||||
.iter()
|
||||
.enumerate()
|
||||
.any(|(i, g)| *g == ("0", "APPID") && groups[i + 1..].iter().take_while(|g| g.0 != "0").any(|g| *g == ("2", "RevcloudProps")));
|
||||
assert!(appid, "no RevcloudProps APPID record");
|
||||
// Made from an object: the object's properties are kept, the cloud is still a revision cloud.
|
||||
let c = h(&s.execute("circle", &json!({"center": [10, 10], "radius": 1})).unwrap());
|
||||
s.execute("revcloud", &json!({"handle": c, "arcLength": 2})).unwrap();
|
||||
assert_eq!(props(&s), want);
|
||||
// Interactive (the arc length takes a minimum and a maximum, #1714).
|
||||
s.cmdline("revcloud a 2 2").unwrap();
|
||||
s.cmdline("0,0 4,2").unwrap();
|
||||
assert_eq!(props(&s), want);
|
||||
// Interactive Object, after the "Reverse direction" prompt.
|
||||
s.execute("rectang", &json!({"p1": [20, 20], "p2": [24, 22]})).unwrap();
|
||||
s.cmdline("revcloud o 20,21 n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(props(&s), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcloud_command_line() {
|
||||
let mut s = Session::new();
|
||||
s.cmdline("revcloud a 1 1").unwrap();
|
||||
s.cmdline("revcloud a 1").unwrap();
|
||||
s.cmdline("0,0 4,2").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(matches!(last(&s), EntityKind::LwPolyline(p) if p.vertices.len() == 12));
|
||||
@@ -805,50 +771,11 @@ fn revcloud_command_line() {
|
||||
assert_eq!(kinds(&s).len(), 3);
|
||||
// Object option converts a closed polyline.
|
||||
s.execute("rectang", &json!({"p1": [10, 10], "p2": [12, 12]})).unwrap();
|
||||
s.cmdline("revcloud o 10,11 n").unwrap();
|
||||
s.cmdline("revcloud o 10,11").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(kinds(&s).len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcloud_object_accepts_entity_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("rectang", &json!({"p1": [0, 0], "p2": [4, 4]})).unwrap();
|
||||
let h = s.doc().unwrap().model.last().unwrap().handle;
|
||||
s.cmdline("revcloud o").unwrap();
|
||||
s.input(Input::Pick(vec![h])).unwrap();
|
||||
// Object asks "Reverse direction" next (#1714); Enter keeps it.
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(kinds(&s).len(), 1);
|
||||
assert!(matches!(last(&s), EntityKind::LwPolyline(p) if p.vertices.len() > 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcloud_arc_length_asks_max_and_object_asks_reverse() {
|
||||
let mut s = Session::new();
|
||||
s.execute("rectang", &json!({"p1": [10, 10], "p2": [12, 12]})).unwrap();
|
||||
s.cmdline("revcloud a 200 800").unwrap();
|
||||
assert!(s.prompt_text().contains("first corner"), "{}", s.prompt_text());
|
||||
s.cmdline("0,0 2000,1000").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
s.cmdline("revcloud").unwrap();
|
||||
assert!(s.log.iter().any(|l| l.contains("Minimum arc length: 200.0000 Maximum arc length: 800.0000")), "{:?}", s.log);
|
||||
s.cmdline("o").unwrap();
|
||||
s.cmdline("10,11").unwrap();
|
||||
assert!(s.running.is_some() && s.prompt_text().contains("Reverse direction"), "{}", s.prompt_text());
|
||||
s.cmdline("n").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
// Yes reverses the arcs (negative bulges).
|
||||
s.execute("rectang", &json!({"p1": [30, 30], "p2": [32, 32]})).unwrap();
|
||||
s.cmdline("revcloud o 30,31 y").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
match last(&s) {
|
||||
EntityKind::LwPolyline(p) => assert!(p.vertices.iter().all(|v| v.bulge < 0.0)),
|
||||
k => panic!("{k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- BREAKLINE ----------------
|
||||
|
||||
fn breakline_points(s: &Session) -> Vec<(f64, f64)> {
|
||||
|
||||
+42
-144
@@ -83,40 +83,6 @@ pub fn object_records() -> Option<ObjectRecords> {
|
||||
OBJECT_RECORDS.get().copied()
|
||||
}
|
||||
|
||||
/// What a DXF of a version before 2007 leaves out of a drawing because it has no form for a
|
||||
/// proxy's separate string stream, counted by DXF type (installed by the app with the DXF writer,
|
||||
/// a lower layer, which finds it by writing; see `cadcraft_io::proxies_lost`). Without it the
|
||||
/// proxies themselves are counted ([`cadcraft_doc::foreign::proxies_dropped_before_2007`]).
|
||||
pub type ProxiesLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
|
||||
|
||||
static PROXIES_LOST: OnceLock<ProxiesLost> = OnceLock::new();
|
||||
|
||||
pub fn set_proxies_lost(f: ProxiesLost) {
|
||||
let _ = PROXIES_LOST.set(f);
|
||||
}
|
||||
|
||||
/// Version-specific DWG compatibility omissions, counted by the host's actual writer.
|
||||
pub type DwgCompatLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
|
||||
|
||||
static DWG_COMPAT_LOST: OnceLock<DwgCompatLost> = OnceLock::new();
|
||||
|
||||
pub fn set_dwg_compat_lost(f: DwgCompatLost) {
|
||||
let _ = DWG_COMPAT_LOST.set(f);
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
|
||||
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
|
||||
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
if version >= Version::R2007 {
|
||||
return Default::default();
|
||||
}
|
||||
let d = d.committed();
|
||||
match PROXIES_LOST.get() {
|
||||
Some(f) => f(&d, version),
|
||||
None => cadcraft_doc::foreign::proxies_dropped_before_2007(&d),
|
||||
}
|
||||
}
|
||||
|
||||
/// COMPARE (drawing comparison).
|
||||
pub mod compare;
|
||||
|
||||
@@ -826,23 +792,15 @@ fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The version a drawing is saved in at `path` when none is asked for: its `$ACADVER` (2018 by
|
||||
/// default), and for DWG at least 2004 (the io layer's rule: R2000 DWG has no true colours).
|
||||
pub fn drawing_version(s: &Session, path: &str) -> Version {
|
||||
let v = s.state().ok().and_then(|st| acadver(st.drawing())).unwrap_or_default();
|
||||
fn drawing_version(s: &Session, path: &str) -> Version {
|
||||
let v = s
|
||||
.state()
|
||||
.ok()
|
||||
.and_then(|st| st.drawing().header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver))
|
||||
.unwrap_or_default();
|
||||
if is_dxf(path) { v } else { v.max(Version::R2004) }
|
||||
}
|
||||
|
||||
/// The version `d` is saved in at `path` when none is asked for, as [`drawing_version`] says for
|
||||
/// the active drawing.
|
||||
pub(crate) fn own_version(d: &Drawing, path: &str) -> Version {
|
||||
let v = acadver(d).unwrap_or_default();
|
||||
if is_dxf(path) { v } else { v.max(Version::R2004) }
|
||||
}
|
||||
|
||||
/// The version `d`'s `$ACADVER` names.
|
||||
fn acadver(d: &Drawing) -> Option<Version> {
|
||||
d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver)
|
||||
}
|
||||
|
||||
/// `document.switch index`: require the index, cancel the running command, activate that drawing and bump the epoch even if it was already active (screenshot identity).
|
||||
fn run_switch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("document.switch", "`index` is required"))? as usize;
|
||||
@@ -868,9 +826,8 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
|
||||
if drops_unknown(format!("drawing.{fmt}")) {
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
} else if is_dxf_file(format!("drawing.{fmt}")) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
} else if version >= Version::R2013 && is_dxf_file(format!("drawing.{fmt}")) {
|
||||
report_sat_text_dropped(s, &mut r);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
@@ -905,12 +862,10 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
|
||||
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities));
|
||||
for e in stores.flat_map(|s| s.iter()) {
|
||||
if let cadcraft_doc::EntityKind::Unknown(u) = &e.kind {
|
||||
// A DWG before 2013 keeps a solid's SAT text of ACIS 7.0 and later; from 2013 the geometry
|
||||
// has to be in the data store, and SAT text alone is lost. Older SAT (ACIS 4.0, as ZWCAD
|
||||
// writes to DXF 2000) reaches the DWG without usable geometry: ZWCAD 2025 opens such a
|
||||
// solid as a proxy or an empty body (#2334).
|
||||
// A DWG before 2013 writes a solid's SAT text as it is; from 2013 the geometry has to be
|
||||
// in the data store, and SAT text alone is lost (#2334).
|
||||
if MODELER_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t))
|
||||
&& (stored.contains(&e.handle) || (version < Version::R2013 && cadcraft_doc::foreign::sat_version(&u.tags).is_some_and(|v| v >= 700)))
|
||||
&& (stored.contains(&e.handle) || (version < Version::R2013 && cadcraft_doc::foreign::has_sat_text(&u.tags)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -932,12 +887,6 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
}
|
||||
if let Some(compatibility) = DWG_COMPAT_LOST.get() {
|
||||
for (kind, count) in compatibility(d, version) {
|
||||
let total = out.entry(kind).or_default();
|
||||
*total = total.saturating_add(count);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -958,8 +907,9 @@ pub fn not_saved_message(lost: &std::collections::BTreeMap<String, usize>) -> Op
|
||||
/// reports the same list afterwards to callers that never get a dialog.
|
||||
pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap<String, usize> {
|
||||
let version = drawing_version(s, path);
|
||||
if is_dxf_file(path) {
|
||||
return host_dxf_lost(s, version);
|
||||
if is_dxf_file(path) && version >= Version::R2013 {
|
||||
// The drawing a file holds: the host while the Block Editor is open.
|
||||
return s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default();
|
||||
}
|
||||
if !drops_unknown(path) {
|
||||
return Default::default();
|
||||
@@ -967,85 +917,16 @@ pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap<Strin
|
||||
s.doc().map(|d| not_saved_as(d, version)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of the drawing a save writes: the host while the Block
|
||||
/// Editor is open ([`dxf_lost`]).
|
||||
fn host_dxf_lost(s: &Session, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
s.state().map(|st| dxf_lost(st.drawing(), version)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of `d`: solid modeler entities whose ACIS geometry that
|
||||
/// version has no place for (#2334: SAT text alone from 2013, data store geometry alone before),
|
||||
/// and before 2007 proxies whose strings it can't hold, with the objects that go with them
|
||||
/// (#3229). The two never name the same record: a solid lost before 2013 is lost in 2007 too.
|
||||
fn dxf_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
let mut lost = cadcraft_doc::foreign::acis_dropped(d, version >= Version::R2013);
|
||||
for (kind, n) in proxies_lost(d, version) {
|
||||
let m = lost.entry(kind).or_insert(0);
|
||||
*m = m.saturating_add(n);
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
/// What a file at `path` leaves out of `d`, written at `version`: empty when it keeps everything.
|
||||
pub(crate) fn lost_writing(d: &Drawing, path: &str, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
if !is_dxf_file(path) {
|
||||
return if drops_unknown(path) { not_saved_as(d, version) } else { Default::default() };
|
||||
}
|
||||
dxf_lost(d, version)
|
||||
}
|
||||
|
||||
/// Report what the file `path`, just written from the active document (what EXPORT writes: the
|
||||
/// block while the Block Editor is open) at its own version, left out.
|
||||
/// Report what the file `path`, just written at the drawing's own version, left out.
|
||||
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
|
||||
let Ok(d) = s.doc() else { return };
|
||||
let version = own_version(d, path);
|
||||
let lost = lost_writing(d, path, version);
|
||||
report_lost(s, r, path, version, &lost);
|
||||
}
|
||||
|
||||
/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`),
|
||||
/// in the words for that kind of file, and list it in the result's `notSaved`.
|
||||
pub(crate) fn report_lost(s: &mut Session, r: &mut Value, path: &str, version: Version, lost: &std::collections::BTreeMap<String, usize>) {
|
||||
match lost_message(path, version, lost) {
|
||||
Some(msg) => s.echo(msg),
|
||||
None => return,
|
||||
if is_dxf_file(path) {
|
||||
if drawing_version(s, path) >= Version::R2013 {
|
||||
report_sat_text_dropped(s, r);
|
||||
}
|
||||
} else {
|
||||
let lost = loss_on_save(s, path);
|
||||
report_not_saved(s, r, &lost);
|
||||
}
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("notSaved".into(), json!(lost));
|
||||
}
|
||||
}
|
||||
|
||||
/// The command-line warning for what a file at `path` written at `version` left out, or `None`
|
||||
/// when it kept everything.
|
||||
pub(crate) fn lost_message(path: &str, version: Version, lost: &std::collections::BTreeMap<String, usize>) -> Option<String> {
|
||||
if !is_dxf_file(path) {
|
||||
return not_saved_message(lost);
|
||||
}
|
||||
if lost.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Solids (#2334) and, before 2007, proxies and what goes with them (#3229), each with its reason.
|
||||
let list = |solids: bool| -> Vec<String> {
|
||||
lost.iter().filter(|(t, _)| MODELER_TYPES.iter().any(|m| t.eq_ignore_ascii_case(m)) == solids).map(|(t, n)| format!("{n} {t}")).collect()
|
||||
};
|
||||
let mut parts = Vec::new();
|
||||
let solids = list(true);
|
||||
if !solids.is_empty() {
|
||||
let why = if version >= Version::R2013 {
|
||||
"2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them"
|
||||
} else {
|
||||
"2010 and earlier have no data store, where these entities keep their ACIS geometry; save as 2013 or later to keep them"
|
||||
};
|
||||
parts.push(format!("Not saved in the DXF file ({why}): {}", solids.join(", ")));
|
||||
}
|
||||
let others = list(false);
|
||||
if !others.is_empty() {
|
||||
parts.push(format!(
|
||||
"Not saved in the DXF file (proxies that keep their strings apart from their data, which DXF before 2007 can't hold, and the objects that go with them; save as 2007 or later to keep them): {}",
|
||||
others.join(", ")
|
||||
));
|
||||
}
|
||||
Some(parts.join(" "))
|
||||
}
|
||||
|
||||
/// Whether saving to `path` leaves out the entities [`not_saved`] counts: DWG does (the DWG
|
||||
@@ -1064,6 +945,24 @@ fn is_dxf_file(path: impl AsRef<std::path::Path>) -> bool {
|
||||
Format::from_path(path) == Some(Format::Dxf)
|
||||
}
|
||||
|
||||
/// Say on the command line which solid modeler entities a DXF of 2013 or later left out because
|
||||
/// they hold SAT-text ACIS data, which such files keep in a data store instead (#2334).
|
||||
fn report_sat_text_dropped(s: &mut Session, r: &mut Value) {
|
||||
// The drawing a file holds: the host while the Block Editor is open.
|
||||
let lost = s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default();
|
||||
if lost.is_empty() {
|
||||
return;
|
||||
}
|
||||
let list: Vec<String> = lost.iter().map(|(t, n)| format!("{n} {t}")).collect();
|
||||
s.echo(format!(
|
||||
"Not saved in the DXF file (2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them): {}",
|
||||
list.join(", ")
|
||||
));
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("notSaved".into(), json!(lost));
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder a write to `path` has to create, asked before writing so it can be reported after.
|
||||
/// The web has no folders.
|
||||
pub(super) fn new_folder(path: &str) -> Option<String> {
|
||||
@@ -1107,9 +1006,8 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R
|
||||
report_new_folder(s, &mut r, folder);
|
||||
if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) {
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
} else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
} else if version >= Version::R2013 && r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
|
||||
report_sat_text_dropped(s, &mut r);
|
||||
}
|
||||
if r.get("path").and_then(Value::as_str).is_some_and(is_drawing_file) {
|
||||
report_fonts(s, &mut r);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
|
||||
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
|
||||
|
||||
mod patfile;
|
||||
pub(super) use edit::{set_pattern, takes_pattern};
|
||||
@@ -37,9 +36,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// 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("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("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
|
||||
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
|
||||
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
|
||||
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
|
||||
.enabled(has_doc)
|
||||
@@ -232,7 +228,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
let outer = found.outer;
|
||||
let ob = Bounds2::from_points(outer.iter().copied());
|
||||
let sources = handles_of(&owners, &found.outer_sources);
|
||||
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, sources }];
|
||||
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, sources }];
|
||||
// Islands: closed objects entirely inside the outer loop that don't contain the pick point.
|
||||
if let Some(store) = d.space(&space) {
|
||||
for e in store.iter() {
|
||||
@@ -248,7 +244,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
let inside = pts.iter().all(|q| point_in_polygon(&outer, *q) || outer.iter().any(|o| o.near(*q, tol * 10.0)));
|
||||
let same_as_outer = (cadcraft_geom::shoelace(&pts).abs() - cadcraft_geom::shoelace(&outer).abs()).abs() < tol.max(1e-6) * 1000.0;
|
||||
if inside && !same_as_outer && !point_in_polygon(&pts, p) {
|
||||
loops.push(HatchLoop { vertices: vs, outer: false, boundary_flags: None, sources: vec![e.handle] });
|
||||
loops.push(HatchLoop { vertices: vs, outer: false, sources: vec![e.handle] });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,12 +256,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
&& island.sources.iter().all(|&i| owners.get(i).and_then(|h| d.entity(*h)).is_some_and(|e| island_curve(d, e)));
|
||||
if open_curves {
|
||||
let sources = handles_of(&owners, &island.sources);
|
||||
loops.push(HatchLoop {
|
||||
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
|
||||
outer: false,
|
||||
boundary_flags: None,
|
||||
sources,
|
||||
});
|
||||
loops.push(HatchLoop { vertices: island.outline.into_iter().map(PolyVertex::new).collect(), outer: false, sources });
|
||||
}
|
||||
}
|
||||
Ok(loops)
|
||||
@@ -276,7 +267,7 @@ pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result<Vec<Hatch
|
||||
let mut loops = Vec::new();
|
||||
for h in hs {
|
||||
if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) {
|
||||
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, sources: vec![*h] });
|
||||
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), sources: vec![*h] });
|
||||
}
|
||||
}
|
||||
if loops.is_empty() {
|
||||
|
||||
@@ -197,7 +197,7 @@ fn follow(before: &Drawing, after: &Drawing, handle: Handle, h: &Hatch, checked:
|
||||
match refill(from, after, l) {
|
||||
Refill::Loop(vertices) => {
|
||||
let sources = l.sources.iter().copied().filter(|s| exists(after, *s)).take(MAX_SOURCES).collect();
|
||||
loops.push(HatchLoop { vertices, outer: l.outer, boundary_flags: l.boundary_flags, sources });
|
||||
loops.push(HatchLoop { vertices, outer: l.outer, sources });
|
||||
}
|
||||
// An erased island: the hatch fills its area.
|
||||
Refill::Erased if !l.outer => {}
|
||||
|
||||
@@ -29,59 +29,6 @@ fn hatches(s: &Session, p: &Value) -> Result<Vec<Handle>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Most polylines one HATCHGENERATEBOUNDARY call creates.
|
||||
const MAX_GENERATED: usize = 10_000;
|
||||
|
||||
/// HATCHGENERATEBOUNDARY: a closed polyline around every boundary loop (outer and islands) of
|
||||
/// the selected hatches, at each hatch's height. The hatches are not changed: an associative
|
||||
/// hatch stays linked to its own boundary objects and is not linked to the new polylines.
|
||||
pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let selected = targets(s, p)?;
|
||||
// The polylines go to the current space, so every hatch must be there too.
|
||||
let space = s.space();
|
||||
let mut loops = Vec::new();
|
||||
let mut found = false;
|
||||
// A hatch named twice gets its boundary once.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
{
|
||||
let d = s.doc()?;
|
||||
for h in selected {
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let EntityKind::Hatch(x) = &e.kind else { continue };
|
||||
if !seen.insert(h) {
|
||||
continue;
|
||||
}
|
||||
found = true;
|
||||
if d.space_of(h).as_ref() != Some(&space) {
|
||||
return Err(bad("hatchgenerateboundary", format!("hatch {} is not in the current space; switch to its layout first", h.hex())));
|
||||
}
|
||||
// Every selected hatch counts: none is left out of a call that succeeds. Compared
|
||||
// against the room left, so a hostile loop count can't overflow the sum.
|
||||
if x.loops.len() > MAX_GENERATED.saturating_sub(loops.len()) {
|
||||
return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches")));
|
||||
}
|
||||
// The elevation runs along the hatch's normal: one facing down Z (mirrored) lies at its
|
||||
// negative, where the polyline, facing up, goes.
|
||||
let z = if e.common.extrusion.z < 0.0 { -x.elevation } else { x.elevation };
|
||||
loops.extend(x.loops.iter().map(|l| (l.vertices.clone(), z)));
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return Err(bad("hatchgenerateboundary", "select one or more hatches"));
|
||||
}
|
||||
// Everything is checked before anything is added, so a refused call leaves nothing behind.
|
||||
let mut created = Vec::new();
|
||||
for (vs, elevation) in loops {
|
||||
let mut kind = lwpoly(vs, true);
|
||||
if let EntityKind::LwPolyline(pl) = &mut kind {
|
||||
pl.elevation = elevation;
|
||||
}
|
||||
created.push(s.add_entity(kind)?.hex());
|
||||
}
|
||||
let n = created.len();
|
||||
Ok(json!({ "handles": created, "message": format!("{n} boundary polyline(s) created.") }))
|
||||
}
|
||||
|
||||
fn outline(l: &HatchLoop) -> Vec<Vec2> {
|
||||
Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(1e-3)
|
||||
}
|
||||
|
||||
@@ -18,90 +18,6 @@ fn text_of(k: &EntityKind) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A box for the in-place editor showing one line of text where `t` sits.
|
||||
pub(crate) fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText {
|
||||
use cadcraft_doc::{HAlign, VAlign};
|
||||
let col = match t.halign {
|
||||
HAlign::Left => 0u8,
|
||||
HAlign::Right => 2,
|
||||
_ => 1,
|
||||
};
|
||||
let row = match t.valign {
|
||||
VAlign::Top => 0u8,
|
||||
VAlign::Middle => 1,
|
||||
_ if t.halign == HAlign::Middle => 1,
|
||||
_ => 2,
|
||||
};
|
||||
// Aligned and fit text is centred between its two points.
|
||||
let at = match t.halign {
|
||||
HAlign::Aligned | HAlign::Fit => t.align_pt.map_or(t.insert, |b| (t.insert + b) * 0.5),
|
||||
_ => t.justify_point().to3(t.insert.z),
|
||||
};
|
||||
cadcraft_doc::MText {
|
||||
insert: at,
|
||||
height: t.height,
|
||||
width: 0.0,
|
||||
attach: row * 3 + col + 1,
|
||||
rotation: t.rotation,
|
||||
style: t.style.clone(),
|
||||
contents: t.value.clone(),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The extents of one line of text as drawn (`value` in `t`'s place, style and justification);
|
||||
/// `None` for empty or unusable extents.
|
||||
fn drawn(d: &cadcraft_doc::Drawing, t: &cadcraft_doc::Text, value: &str) -> Option<cadcraft_geom::Bounds2> {
|
||||
let (_, b) = cadcraft_render::place_text_entity(d, t, value);
|
||||
let ok = [b.min.x, b.min.y, b.max.x, b.max.y].iter().all(|v| v.is_finite()) && b.min.x <= b.max.x && b.min.y <= b.max.y;
|
||||
ok.then_some(b)
|
||||
}
|
||||
|
||||
/// What the in-place editor edits for object `h`: an MTEXT or multileader text as multiline
|
||||
/// text, a TEXT or attribute definition as one line, a dimension's text with `<>` for its value.
|
||||
pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
|
||||
use crate::{EditorKind, TextEditor};
|
||||
let d = s.doc().ok()?;
|
||||
let key = h.hex();
|
||||
let e: &cadcraft_doc::Entity = d.entity(h)?;
|
||||
// Annotative text and dimensions are drawn scaled to the current annotation scale: the box
|
||||
// follows what is drawn. Multiline text keeps its stored height (it is written back from it).
|
||||
let scaled = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
|
||||
Some(cadcraft_doc::anno_scaled(e, f))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match &scaled.as_ref().unwrap_or(e).kind {
|
||||
EntityKind::MText(t) => Some(TextEditor { mtext: t.clone(), kind: EditorKind::MText, key, extents: None }),
|
||||
// A multileader's text opens in the same editor (#1081).
|
||||
EntityKind::MLeader(m) => m.text.clone().map(|mtext| TextEditor { mtext, kind: EditorKind::MText, key, extents: None }),
|
||||
// The box covers the text as drawn: its value, or a definition's tag.
|
||||
EntityKind::Text(t) => Some(TextEditor { mtext: line_box(t), kind: EditorKind::Line, key, extents: drawn(d, t, &t.value) }),
|
||||
EntityKind::AttDef(a) => Some(TextEditor { mtext: line_box(&a.text), kind: EditorKind::Line, key, extents: drawn(d, &a.text, &a.tag) }),
|
||||
EntityKind::Dimension(dm) => {
|
||||
let g = cadcraft_render::dimension_in(d, dm);
|
||||
let measured = cadcraft_render::dimension_in(d, &cadcraft_doc::Dimension { text: String::new(), block: None, ..dm.clone() }).value;
|
||||
let mtext = cadcraft_doc::MText {
|
||||
insert: g.text_pos.to3(0.0),
|
||||
height: if g.text_height > 0.0 && g.text_height.is_finite() { g.text_height } else { 0.18 },
|
||||
width: 0.0,
|
||||
attach: 5,
|
||||
rotation: if g.text_angle.is_finite() { g.text_angle } else { 0.0 },
|
||||
style: d.dim_style(&dm.style).map_or_else(|| "Standard".to_string(), |st| st.text_style.clone()),
|
||||
contents: if dm.text.is_empty() { "<>".into() } else { dm.text.clone() },
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
};
|
||||
Some(TextEditor { mtext, kind: EditorKind::Dimension { measured }, key, extents: None })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> {
|
||||
if curves::is_locked(s, h) {
|
||||
return Err(other("The object is on a locked layer."));
|
||||
@@ -144,8 +60,8 @@ pub(super) struct TextEditM {
|
||||
single: bool,
|
||||
/// Asking for the edit mode.
|
||||
mode: bool,
|
||||
/// What the in-place editor shows for the picked object (#842).
|
||||
editor: Option<crate::TextEditor>,
|
||||
/// The MTEXT being edited, for the in-place editor (#842).
|
||||
mtext: Option<cadcraft_doc::MText>,
|
||||
}
|
||||
|
||||
impl Interactive for TextEditM {
|
||||
@@ -154,12 +70,7 @@ impl Interactive for TextEditM {
|
||||
}
|
||||
/// An MTEXT asking for its new text opens in the in-place editor with its contents.
|
||||
fn editing_mtext(&self) -> Option<cadcraft_doc::MText> {
|
||||
self.h.as_ref().and(self.editor.as_ref().filter(|e| e.kind == crate::EditorKind::MText).map(|e| e.mtext.clone()))
|
||||
}
|
||||
/// TEXT, an attribute definition or a dimension asking for its new text opens in the one-line
|
||||
/// in-place editor; MTEXT and multileader text in the MTEXT editor.
|
||||
fn text_editor(&self) -> Option<crate::TextEditor> {
|
||||
if self.mode || self.h.is_none() { None } else { self.editor.clone() }
|
||||
self.h.as_ref().and(self.mtext.clone())
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
if self.mode {
|
||||
@@ -189,13 +100,18 @@ impl Interactive for TextEditM {
|
||||
if curves::is_locked(s, h) {
|
||||
return Err(other("The object is on a locked layer."));
|
||||
}
|
||||
let old = text_of(&curves::entity(s, h)?.kind)
|
||||
.ok_or_else(|| other("Select a text, mtext, multileader, attribute definition or dimension."))?;
|
||||
self.editor = editor_for(s, h);
|
||||
let kind = curves::entity(s, h)?.kind;
|
||||
let old = text_of(&kind).ok_or_else(|| other("Select a text, mtext, multileader, attribute definition or dimension."))?;
|
||||
self.mtext = match kind {
|
||||
EntityKind::MText(m) => Some(m),
|
||||
// A multileader's text opens in the same editor (#1081).
|
||||
EntityKind::MLeader(m) => m.text,
|
||||
_ => None,
|
||||
};
|
||||
// The editor would drop part of a text this long, and saving would lose it: the
|
||||
// command line asks for it instead.
|
||||
if self.editor.as_ref().is_some_and(|e| !crate::mtext_edit::Formatted::fits(&e.mtext.contents)) {
|
||||
self.editor = None;
|
||||
if self.mtext.as_ref().is_some_and(|m| !crate::mtext_edit::Formatted::fits(&m.contents)) {
|
||||
self.mtext = None;
|
||||
s.echo("This text is too long for the editor; enter the new text at the command line.");
|
||||
}
|
||||
self.h = Some((h, old));
|
||||
@@ -207,12 +123,12 @@ impl Interactive for TextEditM {
|
||||
set_text(s, h, &t)?;
|
||||
self.edits.push((h, before));
|
||||
self.h = None;
|
||||
self.editor = None;
|
||||
self.mtext = None;
|
||||
Ok(if self.single { Step::Done } else { Step::Continue })
|
||||
}
|
||||
(Some(_), Input::Enter) => {
|
||||
self.h = None;
|
||||
self.editor = None;
|
||||
self.mtext = None;
|
||||
Ok(if self.single { Step::Done } else { Step::Continue })
|
||||
}
|
||||
(None, Input::Enter) => Ok(Step::Done),
|
||||
|
||||
@@ -67,12 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params("{delta: [dx,dy]} | {from, to} | {center}")
|
||||
.noundo()
|
||||
.transparent()
|
||||
.interactive(|_| Ok(Box::new(PanM))),
|
||||
CommandSpec::new("-pan", "Pan", run_pan)
|
||||
.params("{delta: [dx,dy]} | {from, to} | {center}")
|
||||
.noundo()
|
||||
.transparent()
|
||||
.interactive(|_| Ok(Box::new(PanPointsM::default()))),
|
||||
.interactive(|_| Ok(Box::new(PanM::default()))),
|
||||
CommandSpec::new("pan.left", "Pan Left", |s, _| pan_frac(s, Vec2::new(-0.25, 0.0))).menu(&["View", "Pan", "Left"]).noundo().transparent(),
|
||||
CommandSpec::new("pan.right", "Pan Right", |s, _| pan_frac(s, Vec2::new(0.25, 0.0))).menu(&["View", "Pan", "Right"]).noundo().transparent(),
|
||||
CommandSpec::new("pan.up", "Pan Up", |s, _| pan_frac(s, Vec2::new(0.0, 0.25))).menu(&["View", "Pan", "Up"]).noundo().transparent(),
|
||||
@@ -606,26 +601,6 @@ impl Session {
|
||||
self.touch();
|
||||
Ok(())
|
||||
}
|
||||
/// PAN is in its realtime mode: the UI turns left-button drags into [`Session::realtime_pan`].
|
||||
pub fn realtime_pan_active(&self) -> bool {
|
||||
self.running.as_ref().is_some_and(|r| r.id == "pan") && self.current_prompt().is_some_and(|p| p.message == REALTIME_PAN_PROMPT)
|
||||
}
|
||||
/// One step of a realtime pan drag of `dx`, `dy` screen pixels (y down): the drawing follows
|
||||
/// the cursor. Does nothing outside realtime PAN.
|
||||
pub fn realtime_pan(&mut self, dx: f64, dy: f64) -> Result<()> {
|
||||
if !self.realtime_pan_active() || !dx.is_finite() || !dy.is_finite() {
|
||||
return Ok(());
|
||||
}
|
||||
let px = self.viewport_px.1.max(1.0);
|
||||
let st = self.state_mut()?;
|
||||
let v = st.view();
|
||||
let scale = px / v.height;
|
||||
// A twisted view (DVIEW TWist) turns the screen drag into the drawing's axes.
|
||||
// Only the view moves, as with a middle-button drag: no new revision, so the canvas keeps
|
||||
// its display list and does not rebuild the drawing's geometry on every frame.
|
||||
st.set_view_quiet(View { center: v.center - Vec2::new(dx / scale, -dy / scale).rotate(-v.twist), ..v });
|
||||
Ok(())
|
||||
}
|
||||
/// The zoom of a mouse wheel scroll by `delta` points (up zooms in): ZOOMFACTOR scales it
|
||||
/// (60, the default, zooms about 18% per wheel step).
|
||||
pub fn wheel_zoom_factor(&self, delta: f64) -> f64 {
|
||||
@@ -637,47 +612,15 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The prompt of realtime PAN; [`Session::realtime_pan_active`] recognises the mode by it.
|
||||
const REALTIME_PAN_PROMPT: &str = "Drag to pan; press Esc or Enter to exit";
|
||||
|
||||
/// PAN: realtime. Dragging with the left button moves the drawing with the cursor until Esc or
|
||||
/// Enter; the whole session is one Zoom Previous entry.
|
||||
struct PanM;
|
||||
#[derive(Default)]
|
||||
struct PanM {
|
||||
first: Option<Vec2>,
|
||||
}
|
||||
|
||||
impl Interactive for PanM {
|
||||
fn name(&self) -> &'static str {
|
||||
"PAN"
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
let st = s.state_mut()?;
|
||||
let v = st.view();
|
||||
st.view_history.push(v);
|
||||
if st.view_history.len() > 50 {
|
||||
st.view_history.remove(0);
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
Prompt::new(REALTIME_PAN_PROMPT, Accept { enter: true, ..Accept::default() })
|
||||
}
|
||||
fn input(&mut self, _s: &mut Session, i: Input) -> Result<Step> {
|
||||
match i {
|
||||
Input::Enter => Ok(Step::Done),
|
||||
_ => Ok(Step::Continue),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// -PAN: a base point and a second point, or a displacement (a point, then Enter).
|
||||
#[derive(Default)]
|
||||
struct PanPointsM {
|
||||
first: Option<Vec2>,
|
||||
}
|
||||
|
||||
impl Interactive for PanPointsM {
|
||||
fn name(&self) -> &'static str {
|
||||
"-PAN"
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
match self.first {
|
||||
None => Prompt::new("Specify base point or displacement (drag with the middle mouse button for realtime pan)", Accept::POINT),
|
||||
@@ -694,15 +637,7 @@ impl Interactive for PanPointsM {
|
||||
run_pan(s, &json!({ "from": [a.x, a.y], "to": [b.x, b.y] }))?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
// Enter at the second point: the first point is the displacement, as typed in the
|
||||
// current UCS. The point arrives in world coordinates, so take the UCS origin off
|
||||
// (0,0 in a moved UCS does not pan).
|
||||
(Some(p), Input::Enter) => {
|
||||
let d = p - s.input_ucs().origin.xy();
|
||||
run_pan(s, &json!({ "delta": [d.x, d.y] }))?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(None, Input::Enter) => Ok(Step::Done),
|
||||
(_, Input::Enter) => Ok(Step::Done),
|
||||
_ => Ok(Step::Continue),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,7 +123,6 @@ pub const NO_FILES: &[&str] = &[
|
||||
"zoom.extents",
|
||||
"zoom.object",
|
||||
"pan",
|
||||
"-pan",
|
||||
"pan.left",
|
||||
"pan.right",
|
||||
"pan.up",
|
||||
@@ -235,7 +234,6 @@ pub const NO_FILES: &[&str] = &[
|
||||
"boundary",
|
||||
"region",
|
||||
"hatchedit",
|
||||
"hatchgenerateboundary",
|
||||
"hatchpick",
|
||||
"overkill",
|
||||
"block",
|
||||
|
||||
@@ -170,16 +170,13 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option<EntityK
|
||||
if index == 0 {
|
||||
return Some(translated(kind, delta));
|
||||
}
|
||||
let k = i.grip_attribs().nth(index - 1).map(|(k, _)| k)?;
|
||||
let a = i.attribs.get_mut(k)?;
|
||||
let a = i.attribs.get_mut(index - 1)?;
|
||||
let ip = a.text.insert.xy() + delta;
|
||||
set_xy(&mut a.text.insert, ip);
|
||||
if let Some(al) = &mut a.text.align_pt {
|
||||
let q = al.xy() + delta;
|
||||
set_xy(al, q);
|
||||
}
|
||||
// A multiline attribute is drawn from its multiline text: it moves too.
|
||||
a.transform_multiline(&Mat3::translate(delta));
|
||||
}
|
||||
EntityKind::Dimension(d) => {
|
||||
match index {
|
||||
|
||||
@@ -92,15 +92,6 @@ impl Interactive for Guarded {
|
||||
Vec::new()
|
||||
})
|
||||
}
|
||||
fn live_value(&self, s: &Session, cursor: Vec2) -> Option<String> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
}
|
||||
catch_unwind(AssertUnwindSafe(|| self.inner.live_value(s, cursor))).unwrap_or_else(|_| {
|
||||
self.broken.set(Some("panic in preview"));
|
||||
None
|
||||
})
|
||||
}
|
||||
fn drag(&self, s: &Session, cursor: Vec2) -> Option<crate::prompt::Drag> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
@@ -119,15 +110,6 @@ impl Interactive for Guarded {
|
||||
None
|
||||
})
|
||||
}
|
||||
fn text_editor(&self) -> Option<crate::TextEditor> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
}
|
||||
catch_unwind(AssertUnwindSafe(|| self.inner.text_editor())).unwrap_or_else(|_| {
|
||||
self.broken.set(Some("panic in prompt"));
|
||||
None
|
||||
})
|
||||
}
|
||||
fn display_only(&self, s: &Session) -> Option<crate::prompt::DisplayOnly> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
|
||||
@@ -54,7 +54,7 @@ pub use cadcraft_geom as geom;
|
||||
pub use cadcraft_render as render;
|
||||
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
|
||||
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
|
||||
pub use prompt::{Accept, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
|
||||
pub use prompt::{Accept, DisplayOnly, Drag, Input, Interactive, Picker, Prompt, Step};
|
||||
|
||||
mod doc_state;
|
||||
mod error;
|
||||
|
||||
@@ -454,19 +454,6 @@ fn printing_many_lines_is_linear() {
|
||||
assert_eq!(s.log.last().map(String::as_str), Some("a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lisp_pline_keeps_current_elevation() {
|
||||
let mut s = session();
|
||||
ok(&mut s, r#"(setvar "ELEVATION" 800.0)"#);
|
||||
ok(&mut s, r#"(command "_PLINE" '(0 0) '(1000 0) '(1000 100) "")"#);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "800.0");
|
||||
|
||||
ok(&mut s, r#"(setvar "ELEVATION" -2.5)"#);
|
||||
s.execute("pline", &serde_json::json!({"vertices": [[0, 0], [10, 0]], "width": 2})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "-2.5");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 43 (entget (entlast))))"), "2.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_draws_and_one_routine_is_one_undo_step() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -126,14 +126,23 @@ pub fn snap_name(m: u32) -> &'static str {
|
||||
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
|
||||
}
|
||||
|
||||
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
|
||||
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
|
||||
/// first, then deferred snaps, then Nearest), without repeats.
|
||||
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
|
||||
/// first, then the closest snap of each other mode in `osmode`, nearest first, without repeats.
|
||||
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
|
||||
let osnap = |m: u32| crate::snap::osnap(d, space, cursor, aperture, m, base, deferred);
|
||||
let extra = osmode & mode::HATCH;
|
||||
let mut per_mode: Vec<SnapHit> = mode::ALL.iter().filter(|(b, _)| osmode & b != 0).filter_map(|(b, _)| osnap(*b | extra)).collect();
|
||||
per_mode.sort_by(|a, b| a.point.dist(cursor).total_cmp(&b.point.dist(cursor)));
|
||||
let mut out: Vec<SnapHit> = osnap(osmode).into_iter().collect();
|
||||
for h in per_mode {
|
||||
if !out.iter().any(|o| o.mode == h.mode && o.point.near(h.point, aperture * 1e-6)) {
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
|
||||
|
||||
@@ -79,7 +79,7 @@ pub struct Prompt {
|
||||
/// pick arrives as the plain point it was picked at.
|
||||
pub deferred: bool,
|
||||
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
|
||||
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
||||
/// cell): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub corner: bool,
|
||||
/// The grip this prompt stretches (one hot grip at the STRETCH prompt), as (object, grip
|
||||
@@ -103,10 +103,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 value asked for is an angle about the base (a rotation grip): Dynamic Input shows one
|
||||
/// angle box, with the command's live value ([`Interactive::live_value`]).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub angle: 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")]
|
||||
@@ -158,11 +154,6 @@ impl Prompt {
|
||||
self.grip = Some(g);
|
||||
self
|
||||
}
|
||||
/// An angle about the base is asked for (the `angle` field).
|
||||
pub fn angle(mut self) -> Self {
|
||||
self.angle = true;
|
||||
self
|
||||
}
|
||||
/// The visual chooser the UI can show (the `picker` field).
|
||||
pub fn picker(mut self, p: Picker) -> Self {
|
||||
self.picker = Some(p);
|
||||
@@ -335,11 +326,6 @@ pub trait Interactive: Send {
|
||||
fn preview_objects(&self, _s: &Session, _cursor: Vec2) -> Vec<cadcraft_doc::Entity> {
|
||||
Vec::new()
|
||||
}
|
||||
/// The value the cursor would give, as the prompt asks for it (an angle as the drawing
|
||||
/// shows angles): what Dynamic Input shows in its box before anything is typed.
|
||||
fn live_value(&self, _s: &Session, _cursor: Vec2) -> Option<String> {
|
||||
None
|
||||
}
|
||||
/// The preview as existing objects under one transform, when it is that (MOVE, COPY,
|
||||
/// ROTATE, SCALE). The UI then draws them from geometry uploaded once instead of rebuilding
|
||||
/// the transformed copies every frame; `None` falls back to [`Interactive::preview`].
|
||||
@@ -352,11 +338,6 @@ pub trait Interactive: Send {
|
||||
fn editing_mtext(&self) -> Option<cadcraft_doc::MText> {
|
||||
None
|
||||
}
|
||||
/// The text the in-place editor edits: where, how, its current contents and what kind of
|
||||
/// object holds it. By default the new multiline text of [`Interactive::editing_mtext`].
|
||||
fn text_editor(&self) -> Option<TextEditor> {
|
||||
self.editing_mtext().map(|mtext| TextEditor { mtext, kind: EditorKind::NewMText, key: String::new(), extents: None })
|
||||
}
|
||||
/// What the drawing area shows in place of the drawing while the command runs (DVIEW draws
|
||||
/// only its preview set); `None` shows the drawing.
|
||||
fn display_only(&self, _s: &Session) -> Option<DisplayOnly> {
|
||||
@@ -375,34 +356,6 @@ pub struct DisplayOnly {
|
||||
pub extra: Vec<cadcraft_doc::Entity>,
|
||||
}
|
||||
|
||||
/// What the in-place text editor edits ([`Interactive::text_editor`]). The editor answers the
|
||||
/// command's text prompt with the new contents (`Input::Text`), or Enter to keep the old text.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TextEditor {
|
||||
/// Where the box sits (insertion point, attachment, rotation), its width (0: grows with the
|
||||
/// text), text height and style; `contents` is the text to start from.
|
||||
pub mtext: cadcraft_doc::MText,
|
||||
pub kind: EditorKind,
|
||||
/// Which object is being edited: a new key means a new text to load.
|
||||
pub key: String,
|
||||
/// The drawn text's extents in drawing units, when known (one line of text): the box covers
|
||||
/// them, whatever the justification.
|
||||
pub extents: Option<cadcraft_geom::Bounds2>,
|
||||
}
|
||||
|
||||
/// The kind of text the in-place editor edits.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EditorKind {
|
||||
/// Multiline text being created (MTEXT).
|
||||
NewMText,
|
||||
/// Existing multiline text: an MTEXT, a multileader's text.
|
||||
MText,
|
||||
/// One line of plain text (TEXT, attribute definition): no formatting, Enter finishes.
|
||||
Line,
|
||||
/// A dimension's text: `<>` stands for the measured value, shown as `measured`.
|
||||
Dimension { measured: String },
|
||||
}
|
||||
|
||||
/// See [`Interactive::drag`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Drag {
|
||||
|
||||
@@ -139,7 +139,7 @@ pub fn bracket() -> Drawing {
|
||||
EntityKind::Hatch(Hatch {
|
||||
pattern: "ANSI31".into(),
|
||||
solid: false,
|
||||
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, boundary_flags: None, sources: Vec::new() }],
|
||||
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, sources: Vec::new() }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: false,
|
||||
|
||||
@@ -722,7 +722,7 @@ mod hatch_pattern_pick_tests {
|
||||
|
||||
fn square(lo: f64, hi: f64, outer: bool) -> HatchLoop {
|
||||
let vertices = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
|
||||
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
|
||||
HatchLoop { vertices, outer, sources: Vec::new() }
|
||||
}
|
||||
|
||||
fn ansi31_hatch(loops: Vec<HatchLoop>) -> Drawing {
|
||||
@@ -788,7 +788,6 @@ mod hatch_pattern_pick_tests {
|
||||
let tri = HatchLoop {
|
||||
vertices: [(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(),
|
||||
outer: true,
|
||||
boundary_flags: None,
|
||||
sources: Vec::new(),
|
||||
};
|
||||
let d = solid_hatch(vec![tri], 0);
|
||||
|
||||
@@ -192,7 +192,6 @@ impl Session {
|
||||
}
|
||||
|
||||
fn script_lines(&mut self, text: &str) -> Result<()> {
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
|
||||
for line in text.lines() {
|
||||
// Trailing spaces are inputs (Enter); other trailing whitespace (`\r`) is not.
|
||||
let line = line.trim_end_matches(|c: char| c.is_whitespace() && c != ' ');
|
||||
|
||||
@@ -536,11 +536,6 @@ impl Session {
|
||||
self.running.as_ref().and_then(|r| r.machine.editing_mtext())
|
||||
}
|
||||
|
||||
/// The text the running command edits in place ([`Interactive::text_editor`]).
|
||||
pub fn text_editor(&self) -> Option<crate::TextEditor> {
|
||||
self.running.as_ref().and_then(|r| r.machine.text_editor())
|
||||
}
|
||||
|
||||
pub fn current_prompt(&self) -> Option<Prompt> {
|
||||
if let Some(p) = self.lisp_prompt() {
|
||||
return Some(p);
|
||||
@@ -608,12 +603,6 @@ impl Session {
|
||||
out
|
||||
}
|
||||
|
||||
/// The value the cursor would give at the active command's prompt (see
|
||||
/// [`Interactive::live_value`]).
|
||||
pub fn live_value(&self, cursor: Vec2) -> Option<String> {
|
||||
self.running.as_ref()?.machine.live_value(self, cursor)
|
||||
}
|
||||
|
||||
/// What the drawing area shows in place of the drawing while a command runs (DVIEW's preview
|
||||
/// set, see [`Interactive::display_only`]), also while a transparent command interrupts it.
|
||||
/// `None`: the drawing.
|
||||
|
||||
+64
-190
@@ -7,7 +7,7 @@ mod viewport;
|
||||
|
||||
pub use viewport::ViewportPoint;
|
||||
|
||||
use cadcraft_doc::{Drawing, EntityKind, Handle, Insert, MAX_BLOCK_DEPTH, Prim, Space};
|
||||
use cadcraft_doc::{Drawing, EntityKind, Insert, MAX_BLOCK_DEPTH, Prim, Space};
|
||||
use cadcraft_geom::{Bounds2, Circle, EPS, Ellipse, Mat3, PI, Segment, Vec2, intersect_ext};
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -72,33 +72,6 @@ impl SnapHit {
|
||||
None => crate::Input::Point(self.point),
|
||||
}
|
||||
}
|
||||
|
||||
fn plain(mode: u32, point: Vec2) -> SnapHit {
|
||||
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
|
||||
}
|
||||
|
||||
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
|
||||
/// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest.
|
||||
fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) {
|
||||
let class = if self.deferred.is_some() {
|
||||
1
|
||||
} else if self.mode == mode::NEA {
|
||||
2
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(class, snap_score(self.mode, self.point, cursor, aperture))
|
||||
}
|
||||
|
||||
/// The same snap as `o`: mode and point, from the same source (paper space, or one
|
||||
/// viewport). Overlapping viewports can show different model points at one paper point;
|
||||
/// each stays a candidate, since DIST measures in the model units of the viewport picked.
|
||||
fn same(&self, o: &SnapHit) -> bool {
|
||||
self.mode == o.mode
|
||||
&& self.deferred.is_some() == o.deferred.is_some()
|
||||
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
|
||||
&& self.point.near(o.point, 1e-9 * (1.0 + self.point.len()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The curve a deferred snap refers to.
|
||||
@@ -238,14 +211,6 @@ pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u3
|
||||
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
|
||||
}
|
||||
|
||||
/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest
|
||||
/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest.
|
||||
/// Snaps seen through layout viewports are included.
|
||||
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn osnap_with(
|
||||
d: &Drawing,
|
||||
@@ -272,39 +237,19 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
|
||||
let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred);
|
||||
(all.into_iter().next(), prims)
|
||||
}
|
||||
|
||||
/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_all_with_neighborhood(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> (Vec<SnapHit>, Option<Vec<Prim>>) {
|
||||
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
|
||||
return (Vec::new(), None);
|
||||
return (None, None);
|
||||
}
|
||||
let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
||||
Some((hits, prims)) => (hits, Some(prims)),
|
||||
None => (Vec::new(), None),
|
||||
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
||||
Some((hit, prims)) => (hit, Some(prims)),
|
||||
None => (None, None),
|
||||
};
|
||||
let views = viewport::near(d, space, cursor, aperture);
|
||||
if views.is_empty() {
|
||||
return (all, near_prims);
|
||||
return (best, near_prims);
|
||||
}
|
||||
let model = Space::Model;
|
||||
let model_ix = crate::spatial::index(d, &model);
|
||||
// What a click picks across spaces stays as it was: each space's best snap, and a viewport's
|
||||
// replaces the best so far only when it scores closer. A paper-space Nearest can therefore
|
||||
// beat an Endpoint seen through a viewport, which `ranked` alone would put first.
|
||||
let mut pick = all.first().copied();
|
||||
for view in views {
|
||||
let model_cursor = view.to_model(cursor);
|
||||
let model_aperture = aperture / view.scale;
|
||||
@@ -312,7 +257,7 @@ fn osnap_all_with_neighborhood(
|
||||
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let hits = osnap_in(
|
||||
let hit = osnap_in(
|
||||
d,
|
||||
&model,
|
||||
&model_ix,
|
||||
@@ -323,36 +268,15 @@ fn osnap_all_with_neighborhood(
|
||||
deferred,
|
||||
&view.viewport.frozen_layers,
|
||||
Some(view.model_clip),
|
||||
);
|
||||
if let Some(hit) = hits.first().and_then(|h| view.hit(*h))
|
||||
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
|
||||
)
|
||||
.and_then(|h| view.hit(h));
|
||||
if let Some(hit) = hit
|
||||
&& best.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
|
||||
{
|
||||
pick = Some(hit);
|
||||
}
|
||||
all.extend(hits.into_iter().filter_map(|h| view.hit(h)));
|
||||
}
|
||||
let mut out = ranked(all, cursor, aperture);
|
||||
if let Some(pick) = pick {
|
||||
out.retain(|h| !h.same(&pick));
|
||||
out.insert(0, pick);
|
||||
}
|
||||
(out, near_prims)
|
||||
}
|
||||
|
||||
/// `hits` best first ([`SnapHit::rank`]), without repeats.
|
||||
fn ranked(mut hits: Vec<SnapHit>, cursor: Vec2, aperture: f64) -> Vec<SnapHit> {
|
||||
hits.sort_by(|a, b| {
|
||||
let (ca, sa) = a.rank(cursor, aperture);
|
||||
let (cb, sb) = b.rank(cursor, aperture);
|
||||
ca.cmp(&cb).then(sa.total_cmp(&sb))
|
||||
});
|
||||
let mut out: Vec<SnapHit> = Vec::with_capacity(hits.len());
|
||||
for h in hits {
|
||||
if !out.iter().any(|o| o.same(&h)) {
|
||||
out.push(h);
|
||||
best = Some(hit);
|
||||
}
|
||||
}
|
||||
out
|
||||
(best, near_prims)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -367,11 +291,10 @@ fn osnap_in(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Vec<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
|
||||
) -> Option<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit)
|
||||
}
|
||||
|
||||
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_in_with_prims(
|
||||
d: &Drawing,
|
||||
@@ -384,8 +307,8 @@ fn osnap_in_with_prims(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
|
||||
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
|
||||
) -> Option<(Option<SnapHit>, Vec<Prim>)> {
|
||||
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
|
||||
// Intersections between nearby primitives; Apparent Intersection also where their extensions
|
||||
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
|
||||
// that don't reach each other).
|
||||
@@ -422,8 +345,8 @@ fn osnap_in_with_prims(
|
||||
}
|
||||
}
|
||||
}
|
||||
let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hits, near_prims))
|
||||
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hit, near_prims))
|
||||
}
|
||||
|
||||
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
|
||||
@@ -475,50 +398,9 @@ pub(crate) fn gather(
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
|
||||
gather_in(d, space, ix, cursor, aperture, osmode, &[], None)
|
||||
gather_in(d, space, ix, cursor, aperture, osmode, &[])
|
||||
}
|
||||
|
||||
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
|
||||
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
|
||||
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
|
||||
/// block reference with.
|
||||
pub(crate) fn nearest_with_direction(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, skip: Handle) -> Option<(Vec2, Vec2)> {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
let (_, prims) = gather_in(d, space, &ix, cursor, aperture, 0, &[], Some(skip))?;
|
||||
let mut best: Option<(f64, Vec2, Vec2)> = None;
|
||||
let mut consider = |at: Vec2, dir: Vec2| {
|
||||
let dd = at.dist(cursor);
|
||||
if at.is_finite() && dir.len() > 1e-12 && dir.is_finite() && dd <= aperture && best.is_none_or(|(bd, _, _)| dd < bd) {
|
||||
best = Some((dd, at, dir * (1.0 / dir.len())));
|
||||
}
|
||||
};
|
||||
for p in prims.iter().take(2000) {
|
||||
if let Prim::Circle(c) = p {
|
||||
let at = c.closest(cursor);
|
||||
consider(at, (at - c.center).perp());
|
||||
continue;
|
||||
}
|
||||
if let Prim::Infinite { base, dir, .. } = p {
|
||||
let len = dir.len();
|
||||
if len > 1e-12 {
|
||||
let u = *dir * (1.0 / len);
|
||||
consider(*base + u * (cursor - *base).dot(u), u);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for seg in prim_segments(p) {
|
||||
let seg = fix_circle(&seg);
|
||||
let at = seg.closest(cursor);
|
||||
match seg {
|
||||
Segment::Line(l) => consider(at, l.b - l.a),
|
||||
Segment::Arc { arc, .. } => consider(at, (at - arc.center).perp()),
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(_, at, dir)| (at, dir))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn gather_in(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
@@ -527,7 +409,6 @@ fn gather_in(
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
frozen: &[String],
|
||||
skip: Option<Handle>,
|
||||
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
|
||||
let probe = Bounds2::new(cursor, cursor).expand(aperture);
|
||||
let mut cands: Vec<(u32, Vec2)> = Vec::new();
|
||||
@@ -535,7 +416,7 @@ fn gather_in(
|
||||
let mut count = 0usize;
|
||||
let mut budget = MAX_BLOCK_LEAVES;
|
||||
for (e, known) in crate::select::candidates(d, space, ix, &probe.expand(aperture), true, false)? {
|
||||
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) || Some(e.handle) == skip {
|
||||
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) {
|
||||
continue;
|
||||
}
|
||||
let inf = crate::select::is_infinite(e);
|
||||
@@ -577,8 +458,7 @@ fn gather_in(
|
||||
Some((cands, near_prims))
|
||||
}
|
||||
|
||||
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
|
||||
/// snaps, the deferred snaps and Nearest.
|
||||
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish(
|
||||
mut cands: Vec<(u32, Vec2)>,
|
||||
@@ -589,7 +469,7 @@ fn finish(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
clip: Option<Bounds2>,
|
||||
) -> Vec<SnapHit> {
|
||||
) -> Option<SnapHit> {
|
||||
// Perpendicular / tangent from the base point.
|
||||
if let Some(bp) = base {
|
||||
for p in near_prims {
|
||||
@@ -627,10 +507,20 @@ fn finish(
|
||||
}
|
||||
}
|
||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||
let mut hits: Vec<SnapHit> =
|
||||
cands.into_iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).map(|(m, p)| SnapHit::plain(m, p)).collect();
|
||||
if base.is_none() && deferred {
|
||||
hits.extend(deferred_hits(near_prims, cursor, aperture, osmode, clip));
|
||||
let best = cands.iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).min_by(|a, b| {
|
||||
// Prefer more specific modes when nearly equidistant.
|
||||
let da = snap_score(a.0, a.1, cursor, aperture);
|
||||
let db = snap_score(b.0, b.1, cursor, aperture);
|
||||
da.total_cmp(&db)
|
||||
});
|
||||
if let Some((m, p)) = best {
|
||||
return Some(SnapHit { point: *p, mode: *m, name: name_of(*m), viewport: None, deferred: None });
|
||||
}
|
||||
if base.is_none()
|
||||
&& deferred
|
||||
&& let Some(h) = deferred_hit(near_prims, cursor, aperture, osmode, clip)
|
||||
{
|
||||
return Some(h);
|
||||
}
|
||||
if osmode & mode::NEA != 0 {
|
||||
// The closest point of all nearby objects, whatever their drawing order.
|
||||
@@ -650,13 +540,12 @@ fn finish(
|
||||
}
|
||||
}
|
||||
if let Some((_, p)) = nb {
|
||||
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
|
||||
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
|
||||
}
|
||||
}
|
||||
ranked(hits, cursor, aperture)
|
||||
None
|
||||
}
|
||||
|
||||
/// Prefer more specific modes when nearly equidistant.
|
||||
fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
|
||||
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
|
||||
}
|
||||
@@ -959,11 +848,9 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
|
||||
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
|
||||
/// perpendicular on the same circle.
|
||||
fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
|
||||
let mut hits = Vec::new();
|
||||
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
|
||||
fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
|
||||
let mut best: Option<(f64, SnapHit)> = None;
|
||||
for p in prims {
|
||||
let curve = match p {
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||
@@ -972,28 +859,32 @@ fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip:
|
||||
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
|
||||
_ => continue,
|
||||
};
|
||||
// Where the curve was picked: a circle's, an arc's or a segment's own span, an xline/ray
|
||||
// anywhere.
|
||||
let at = match curve {
|
||||
SnapCurve::Circle { center, radius } => Circle::new(center, radius).closest(cursor),
|
||||
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor),
|
||||
SnapCurve::Line { a, b } => {
|
||||
let l = cadcraft_geom::Line::new(a, b);
|
||||
if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) }
|
||||
let (m, name, at) = match curve {
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
|
||||
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
|
||||
let l = cadcraft_geom::Line::new(a, b);
|
||||
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
if !(at.is_finite() && clip.is_none_or(|c| c.contains(at)) && at.dist(cursor) <= aperture) {
|
||||
continue;
|
||||
}
|
||||
let modes: &[(u32, &'static str)] = match curve {
|
||||
SnapCurve::Circle { .. } | SnapCurve::Arc { .. } => &[(mode::TAN, "Deferred Tangent"), (mode::PER, "Deferred Perpendicular")],
|
||||
SnapCurve::Line { .. } => &[(mode::PER, "Deferred Perpendicular")],
|
||||
};
|
||||
for &(m, name) in modes.iter().filter(|(m, _)| osmode & m != 0) {
|
||||
hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) });
|
||||
let dd = at.dist(cursor);
|
||||
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
|
||||
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) }));
|
||||
}
|
||||
}
|
||||
hits
|
||||
best.map(|(_, h)| h)
|
||||
}
|
||||
|
||||
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
|
||||
@@ -1230,23 +1121,6 @@ mod tests {
|
||||
assert_eq!(h.name, "Intersection");
|
||||
}
|
||||
|
||||
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection
|
||||
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap`
|
||||
/// picks.
|
||||
#[test]
|
||||
fn osnap_all_ranks_every_candidate() {
|
||||
let d = drawing();
|
||||
let modes = mode::END | mode::MID | mode::INT | mode::NEA;
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false);
|
||||
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}");
|
||||
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point);
|
||||
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot.
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
|
||||
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
|
||||
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
|
||||
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, modes, None, false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn center_quadrant_tangent() {
|
||||
let d = drawing();
|
||||
|
||||
@@ -60,8 +60,6 @@ const HEADER: &[(&str, Kind, Def)] = &[
|
||||
("HPNAME", Kind::Pattern, Def::Str("ANSI31")),
|
||||
("HPSCALE", Kind::Real { min: 0.0, strict: true }, Def::Real(1.0)),
|
||||
("INSNAME", Kind::Name, Def::Str("")),
|
||||
// Percent that objects on locked layers fade on screen; 0 or negative: no fade.
|
||||
("LAYLOCKFADECTL", Kind::Int(-90, 90), Def::Int(50)),
|
||||
("LWDEFAULT", Kind::Choice(&LINEWEIGHTS), Def::Int(25)),
|
||||
// Negative: Through (OFFSET picks a point).
|
||||
("OFFSETDIST", Kind::AnyReal, Def::Real(-1.0)),
|
||||
|
||||
@@ -746,15 +746,6 @@ fn script_runs_commands() {
|
||||
assert!(matches!(&t.kind, EntityKind::Text(t) if t.value == "Hello world"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripts_allow_one_leading_utf8_bom() {
|
||||
for text in ["\u{feff}LINE 0,0 10,10\n\n", "\u{feff}; first comment\r\nLINE 0,0 10,10\r\n\r\n"] {
|
||||
let mut s = Session::new();
|
||||
s.script(text).unwrap();
|
||||
assert_eq!(kinds(&s), vec!["Line"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_splits_line_at_keyword_prompt() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -336,24 +336,3 @@ fn annotative_mtext_columns_follow_the_scale() {
|
||||
assert_eq!((t.height, t.width, c.count, c.gutter, c.height, c.heights), (2.0, 20.0, 2, 2.0, 40.0, vec![6.0, 10.0]));
|
||||
}
|
||||
}
|
||||
|
||||
/// TEXTEDIT's in-place box for annotative text at a non-unit annotation scale has the height and
|
||||
/// extents of the text as drawn (scaled), not as stored (#842 review).
|
||||
#[test]
|
||||
fn the_text_edit_box_of_annotative_text_is_as_drawn() {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
let r = s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap();
|
||||
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let drawn = drawn_height(s.doc().unwrap(), h).unwrap();
|
||||
assert!(drawn > 5.0, "drawn {drawn}");
|
||||
s.cmdline("TEXTEDIT").unwrap();
|
||||
s.input(cadcraft_engine::Input::Point(cadcraft_engine::geom::Vec2::new(0.0, 0.0))).unwrap();
|
||||
let ed = s.text_editor().expect("the editor opens on the text");
|
||||
assert!((ed.mtext.height - 12.5).abs() < 1e-9, "box height {}", ed.mtext.height);
|
||||
let b = ed.extents.unwrap();
|
||||
// The text's layout box (cell height), so a little taller than the strokes, never the
|
||||
// stored 0.25-high text's.
|
||||
assert!(b.height() >= drawn * 0.95 && b.height() <= drawn * 2.0, "box extents {} vs drawn {drawn}", b.height());
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, MText, MultilineAttrib, Text};
|
||||
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, Text};
|
||||
use cadcraft_engine::geom::Vec3;
|
||||
use serde_json::json;
|
||||
|
||||
@@ -45,66 +45,3 @@ fn references_take_lock_position_from_the_definition() {
|
||||
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
|
||||
assert_eq!(i.attribs[0].modes, AttribModes { verify: false, preset: false, lock_position: true });
|
||||
}
|
||||
|
||||
/// A definition at `x` with `modes`, invisible or not, multiline or not.
|
||||
fn definition(tag: &str, x: f64, modes: AttribModes, invisible: bool, multiline: bool) -> Attrib {
|
||||
let text = Text {
|
||||
insert: Vec3::new(x, 0.0, 0.0),
|
||||
align_pt: None,
|
||||
height: 2.0,
|
||||
value: tag.into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: Default::default(),
|
||||
valign: Default::default(),
|
||||
};
|
||||
let multiline = multiline.then(|| {
|
||||
let mtext = MText {
|
||||
insert: Vec3::new(x, 0.0, 0.0),
|
||||
height: 2.0,
|
||||
width: 0.0,
|
||||
attach: 7,
|
||||
rotation: 0.0,
|
||||
style: "Standard".into(),
|
||||
contents: format!("{tag}\\PTWO"),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
};
|
||||
MultilineAttrib { mtext, read_as: format!("{tag}\nTWO") }
|
||||
});
|
||||
Attrib { tag: tag.into(), text, invisible, constant: false, prompt: tag.into(), props: Default::default(), multiline, modes }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_shown_unlocked_attributes_have_grips_and_a_multiline_one_moves_its_text() {
|
||||
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
|
||||
let locked = AttribModes { lock_position: true, ..AttribModes::default() };
|
||||
let mut b = Block::new("TAG");
|
||||
for a in [
|
||||
definition("FREE", 0.0, AttribModes::default(), false, false),
|
||||
definition("LOCKED", 10.0, locked, false, false),
|
||||
definition("HIDDEN", 20.0, AttribModes::default(), true, false),
|
||||
definition("NOTE", 30.0, AttribModes::default(), false, true),
|
||||
] {
|
||||
let h = d.new_handle();
|
||||
b.entities.push(Entity::new(h, EntityKind::AttDef(a)));
|
||||
}
|
||||
d.blocks.insert("TAG".into(), Arc::new(b));
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "tags", None);
|
||||
let r = s.execute("insert", &json!({ "name": "TAG", "at": [100, 0] })).unwrap();
|
||||
let h = cadcraft_engine::doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
// The insertion point, FREE and NOTE: no grip for the locked or the invisible attribute.
|
||||
let g = s.grips_of(h).unwrap();
|
||||
assert_eq!(g.iter().map(|p| p.x).collect::<Vec<_>>(), [100.0, 100.0, 130.0]);
|
||||
// NOTE's grip (index 2) dragged up 5: its multiline text moves with it.
|
||||
s.execute("grip.stretch", &json!({ "handle": h.hex(), "index": 2, "to": [130, 5] })).unwrap();
|
||||
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
|
||||
let note = i.attribs.iter().find(|a| a.tag == "NOTE").unwrap();
|
||||
assert_eq!((note.text.insert.y, note.multiline.as_ref().unwrap().mtext.insert.y), (5.0, 5.0));
|
||||
let free = i.attribs.iter().find(|a| a.tag == "FREE").unwrap();
|
||||
assert_eq!(free.text.insert.y, 0.0, "the others stay");
|
||||
}
|
||||
|
||||
@@ -65,7 +65,6 @@ fn baseline(d: &Drawing, t: &Text) -> cadcraft_geom::Vec2 {
|
||||
|
||||
#[test]
|
||||
fn all_attribute_value_paths_refresh_small_justified_export_changes() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
for path in ["json", "interactive", "global-json", "global-interactive"] {
|
||||
let (mut s, a, b) = fixture();
|
||||
let before = attributes(s.doc().unwrap(), a);
|
||||
@@ -148,7 +147,6 @@ fn equal_attribute_values_preserve_an_imported_font_baseline() {
|
||||
/// Recomputing a justified baseline must not replace its independent insertion elevation.
|
||||
#[test]
|
||||
fn value_edits_preserve_distinct_insertion_and_alignment_elevations_on_export() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let (mut s, a, _) = fixture();
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
|
||||
@@ -102,8 +102,6 @@ fn new_variables_are_style_overrides_and_read_back() {
|
||||
|
||||
#[test]
|
||||
fn setvar_dimension_variables_are_saved_with_the_drawing() {
|
||||
// The drawing is the test's own, so it is converted in this process.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
// DIMSCALE was kept and DIMTIH, DIMDEC and DIMTAD were not (#3100).
|
||||
let mut s = Session::new();
|
||||
for (name, v) in [("DIMSCALE", json!(2.5)), ("DIMTIH", json!(0)), ("DIMDEC", json!(2)), ("DIMTAD", json!(1))] {
|
||||
@@ -317,23 +315,6 @@ fn tolerance_justification_angular_zeros_and_arc_symbol() {
|
||||
assert_eq!(dim_lines(&g1).len(), dim_lines(&g2).len() + 1, "the symbol drawn over the text");
|
||||
}
|
||||
|
||||
/// DIMPOST frames the angle too, as AutoCAD 2026 does to its own angular dimensions (#1653).
|
||||
#[test]
|
||||
fn dimpost_applies_to_angular_dimensions() {
|
||||
let mut s = Session::new();
|
||||
set(&mut s, "DIMPOST", json!("<> m"));
|
||||
set(&mut s, "DIMADEC", json!(1));
|
||||
// Vertex and two points.
|
||||
s.execute("dimangular", &json!({ "vertex": [0, 0], "p1": [10, 0], "p2": [0, 10], "at": [3, 3] })).unwrap();
|
||||
assert_eq!(last_dim(&s).1.value, "90.0° m");
|
||||
// Two lines picked: the same suffix.
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [5, 8.660254037844387]] })).unwrap();
|
||||
let h: Vec<String> = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).map(|e| e.handle.hex()).collect();
|
||||
s.execute("dimangular", &json!({ "lines": h, "at": [4, 1] })).unwrap();
|
||||
assert_eq!(last_dim(&s).1.value, "60.0° m");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linetypes_and_lineweights_of_dimension_and_extension_lines() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -145,56 +145,3 @@ fn a_grip_drag_previews_the_reference_in_its_own_colours() {
|
||||
let blue = cadcraft_engine::doc::color::Color::True(cadcraft_engine::doc::color::Rgb(0x2f, 0x6b, 0xff));
|
||||
assert!(preview[n..].iter().all(|e| e.common.color == blue));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grip_with_a_value_list_marks_its_stops_while_dragged() {
|
||||
let (mut s, h) = session();
|
||||
// Width is a list (30, 32, 36) from (0, -4): its end can stop 30, 32 or 36 along it.
|
||||
let stops = cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 2, GripPart::End);
|
||||
let at: Vec<(f64, f64)> = stops.iter().map(|(p, _)| (p.x, p.y)).collect();
|
||||
assert_eq!(at, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
|
||||
assert!(stops.iter().all(|(_, way)| (way.x - 1.0).abs() < 1e-12 && way.y.abs() < 1e-12));
|
||||
// A grip that isn't on a list or increments has none; nor a list grip.
|
||||
assert!(cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 1, GripPart::At).is_empty());
|
||||
|
||||
// The preview marks each stop with a tick across the travel, a few pixels long.
|
||||
s.start_dyn_grip(h, 2, GripPart::End).unwrap();
|
||||
let half = 6.0 * s.pixel_size();
|
||||
let ticks: Vec<(f64, f64)> = s
|
||||
.preview(Vec2::new(133.0, 0.0))
|
||||
.into_iter()
|
||||
.filter_map(|e| match e.kind {
|
||||
cadcraft_engine::doc::EntityKind::Line(l) if (l.a.x - l.b.x).abs() < 1e-9 && ((l.b.y - l.a.y).abs() - 2.0 * half).abs() < 1e-9 => {
|
||||
Some((l.a.x, (l.a.y + l.b.y) / 2.0))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(ticks, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
|
||||
}
|
||||
|
||||
/// An alignment grip dragged onto a line (the synthetic Align block of the io tests, a line at
|
||||
/// 30° from (120, 100)): the reference moves onto the line and turns along it, as AutoCAD does;
|
||||
/// away from objects it only moves.
|
||||
#[test]
|
||||
fn an_alignment_grip_aligns_with_the_line_at_the_cursor() {
|
||||
let src = include_str!("../../../io/tests/data/dynblock_params.txt").replace("\r\n", "\n");
|
||||
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "params", None);
|
||||
let r = s.execute("insert", &json!({ "name": "Align", "at": [100, 100] })).unwrap();
|
||||
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let g = s.execute("blocks.reference.grips", &json!({ "handle": h.hex() })).unwrap();
|
||||
assert_eq!(g[0]["shape"], "alignment");
|
||||
// A point on the line, a little below it.
|
||||
let (c, sn) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
|
||||
let to = [120.0 + 10.0 * c + 0.01 * sn, 100.0 + 10.0 * sn - 0.01 * c];
|
||||
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": to })).unwrap();
|
||||
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
|
||||
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6, "{}", i.rotation.to_degrees());
|
||||
assert!((i.insert.x - (120.0 + 10.0 * c)).abs() < 1e-6 && (i.insert.y - (100.0 + 10.0 * sn)).abs() < 1e-6, "{:?}", i.insert);
|
||||
// Far from anything: it only moves.
|
||||
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": [0, -50] })).unwrap();
|
||||
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
|
||||
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6 && i.insert.x.abs() < 1e-9 && (i.insert.y + 50.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
@@ -144,26 +144,6 @@ fn moving_or_copying_the_hatch_alone_ends_the_link() {
|
||||
assert!(!hatch(&s, &h).associative);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_boundary_flags_survive_refill_and_copy() {
|
||||
let mut session = Session::new();
|
||||
let boundary = handle(&session.execute("rectang", &json!({ "p1": [0, 0], "p2": [4, 2] })).unwrap());
|
||||
let hatch_handle = handle(&session.execute("hatch", &json!({ "handles": [boundary.clone()] })).unwrap());
|
||||
session.doc_mut().unwrap().model.modify(Handle::parse_hex(&hatch_handle).unwrap(), |entity| {
|
||||
if let EntityKind::Hatch(hatch) = &mut entity.kind {
|
||||
hatch.loops[0].boundary_flags = Some(7);
|
||||
}
|
||||
});
|
||||
let expected = hatch(&session, &hatch_handle).loops[0].boundary_flags;
|
||||
session.execute("move", &json!({ "handles": [boundary], "delta": [10, 0] })).unwrap();
|
||||
assert_eq!(hatch(&session, &hatch_handle).loops[0].boundary_flags, expected);
|
||||
let count = session.doc().unwrap().model.len();
|
||||
session.execute("copy", &json!({ "handles": [hatch_handle], "delta": [30, 0] })).unwrap();
|
||||
let copy = session.doc().unwrap().model.iter().skip(count).find(|entity| matches!(entity.kind, EntityKind::Hatch(_))).unwrap();
|
||||
let EntityKind::Hatch(copied) = ©.kind else { panic!("not a hatch") };
|
||||
assert_eq!(copied.loops[0].boundary_flags, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_associative_hatch_keeps_no_sources() {
|
||||
let mut s = Session::new();
|
||||
@@ -186,10 +166,7 @@ fn hostile_sources_never_panic() {
|
||||
let k = EntityKind::Hatch(Hatch {
|
||||
pattern: "ANSI31".into(),
|
||||
solid: false,
|
||||
loops: vec![
|
||||
HatchLoop { vertices: sq, outer: true, boundary_flags: None, sources: sources.clone() },
|
||||
HatchLoop { vertices: nan, outer: false, boundary_flags: None, sources },
|
||||
],
|
||||
loops: vec![HatchLoop { vertices: sq, outer: true, sources: sources.clone() }, HatchLoop { vertices: nan, outer: false, sources }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: true,
|
||||
|
||||
@@ -1,205 +0,0 @@
|
||||
//! HATCHGENERATEBOUNDARY (#2801): closed polylines around existing hatches, which stay as they are.
|
||||
|
||||
use cadcraft_engine::doc::{EntityKind, Handle, Hatch, LwPolyline};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn hatch(s: &Session, h: &str) -> Hatch {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::Hatch(x) => x.clone(),
|
||||
k => panic!("not a hatch: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn poly(s: &Session, h: &str) -> LwPolyline {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::LwPolyline(p) => p.clone(),
|
||||
k => panic!("not a polyline: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(v: &Value) -> String {
|
||||
v["handle"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn handles(v: &Value) -> Vec<String> {
|
||||
v["handles"].as_array().unwrap().iter().map(|h| h.as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String {
|
||||
handle(&s.execute("rectang", &json!({ "p1": a, "p2": b })).unwrap())
|
||||
}
|
||||
|
||||
fn count(s: &Session) -> usize {
|
||||
s.doc().unwrap().model.iter().count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generates_a_closed_polyline_around_a_hatch_without_its_outline() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()] })).unwrap());
|
||||
s.execute("erase", &json!({ "handles": [r] })).unwrap();
|
||||
let before = hatch(&s, &h);
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
|
||||
let new = handles(&v);
|
||||
assert_eq!(new.len(), 1);
|
||||
let p = poly(&s, &new[0]);
|
||||
assert!(p.closed);
|
||||
assert_eq!(p.vertices, before.loops[0].vertices);
|
||||
assert_eq!(hatch(&s, &h), before, "the hatch is not changed");
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
assert_eq!(count(&s), 1, "one undo step removes what was generated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn islands_get_their_own_polylines() {
|
||||
let mut s = Session::new();
|
||||
rect(&mut s, [0.0, 0.0], [20.0, 20.0]);
|
||||
rect(&mut s, [5.0, 5.0], [10.0, 10.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "points": [[2, 2]] })).unwrap());
|
||||
assert_eq!(hatch(&s, &h).loops.len(), 2);
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_selected_hatch_gets_its_boundary() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let b = rect(&mut s, [10.0, 0.0], [14.0, 2.0]);
|
||||
let ha = handle(&s.execute("hatch", &json!({ "handles": [a] })).unwrap());
|
||||
let hb = handle(&s.execute("hatch", &json!({ "handles": [b] })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [ha, hb] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hatch_named_twice_gets_one_boundary() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone(), h] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_associative_hatch_stays_linked_to_its_own_boundary() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()], "associative": true })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
|
||||
let p = handles(&v)[0].clone();
|
||||
// Moving the generated polyline leaves the hatch where it is.
|
||||
s.execute("move", &json!({ "handles": [p], "delta": [0, 10] })).unwrap();
|
||||
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.y, 0.0);
|
||||
// Moving the original rectangle still moves the hatch.
|
||||
s.execute("move", &json!({ "handles": [r], "delta": [10, 0] })).unwrap();
|
||||
assert!(hatch(&s, &h).associative);
|
||||
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.x, 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boundaries_keep_the_hatch_elevation() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
x.elevation = 300.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
assert_eq!(poly(&s, &handles(&v)[0]).elevation, 300.0);
|
||||
}
|
||||
|
||||
/// A mirrored hatch (normal 0,0,-1, as exploding a mirrored block makes) at elevation 300 lies at
|
||||
/// world Z -300; its boundary, facing up, goes there too, not to +300.
|
||||
#[test]
|
||||
fn a_mirrored_hatchs_boundary_keeps_its_world_height() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
e.common.extrusion = cadcraft_engine::geom::Vec3::new(0.0, 0.0, -1.0);
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
x.elevation = 300.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
let new = Handle::parse_hex(&handles(&v)[0]).unwrap();
|
||||
let e = s.doc().unwrap().entity(new).unwrap().clone();
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
|
||||
assert_eq!(e.common.extrusion.z.signum() * p.elevation, -300.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_hatch_in_another_space_and_adds_nothing() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
|
||||
let before = s.doc().unwrap().entity_count();
|
||||
let e = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap_err();
|
||||
assert!(e.to_string().contains("not in the current space"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().entity_count(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_more_boundaries_than_the_limit_and_adds_nothing() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
// One hatch with more loops than one call may turn into polylines.
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
let l = x.loops[0].clone();
|
||||
x.loops = vec![l; 10_001];
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let before = count(&s);
|
||||
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).is_err());
|
||||
assert_eq!(count(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_a_hatch() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [r] })).is_err());
|
||||
assert_eq!(count(&s), 1, "nothing is added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_at_once_on_selected_hatches() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.set_selection(vec![Handle::parse_hex(&h).unwrap()]);
|
||||
s.start("hatchgenerateboundary").unwrap();
|
||||
assert!(s.current_prompt().is_none(), "a pickfirst selection needs no prompt");
|
||||
assert_eq!(count(&s), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asks_for_hatches_without_a_selection() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.set_selection(Vec::new());
|
||||
s.start("hatchgenerateboundary").unwrap();
|
||||
assert!(s.current_prompt().is_some());
|
||||
s.input(Input::Pick(vec![Handle::parse_hex(&h).unwrap()])).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert_eq!(count(&s), 3);
|
||||
}
|
||||
@@ -68,7 +68,6 @@ mod group_selection;
|
||||
mod groups;
|
||||
mod hatch_assoc;
|
||||
mod hatch_dialog_helpers;
|
||||
mod hatch_generate_boundary;
|
||||
mod hatch_numeric_validation;
|
||||
mod hatch_options;
|
||||
mod helix;
|
||||
@@ -106,7 +105,6 @@ mod mocoro;
|
||||
mod modify_curves;
|
||||
mod mtext_columns;
|
||||
mod mtext_options;
|
||||
mod mtext_ortho;
|
||||
mod multiline_attributes;
|
||||
mod named_viewports;
|
||||
mod named_views;
|
||||
@@ -147,7 +145,6 @@ mod refedit;
|
||||
mod region;
|
||||
mod rename_cmdline;
|
||||
mod rotate_reference;
|
||||
mod rotation_grip_input;
|
||||
mod scale_offset_z;
|
||||
mod select_keywords;
|
||||
mod select_similar;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -278,46 +278,6 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
|
||||
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
|
||||
}
|
||||
|
||||
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap
|
||||
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
|
||||
#[test]
|
||||
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
|
||||
let (mut d, paper) = drawing();
|
||||
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
|
||||
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
|
||||
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
|
||||
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
|
||||
assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
|
||||
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
|
||||
let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false);
|
||||
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
|
||||
assert!(
|
||||
all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
|
||||
"Tab reaches the viewport's endpoint: {all:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Overlapping viewports can show different model points at one paper point; Tab offers each,
|
||||
/// since DIST measures in the model units of the viewport picked.
|
||||
#[test]
|
||||
fn overlapping_viewports_each_offer_their_model_point() {
|
||||
let (mut d, paper) = drawing();
|
||||
// This viewport shows the model endpoint (20, 0) at paper (100, 50), a second one over it (0, 0).
|
||||
edit_viewport(&mut d, &paper, |vp| vp.view_center = Vec2::new(20.0, 0.0));
|
||||
let mut vp = match &d.entity(viewport(&d, &paper)).unwrap().kind {
|
||||
EntityKind::Viewport(vp) => vp.clone(),
|
||||
_ => panic!("viewport fixture"),
|
||||
};
|
||||
vp.view_center = Vec2::new(0.0, 0.0);
|
||||
vp.id = 3;
|
||||
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||||
let all = osnap_all(&d, &paper, Vec2::new(100.05, 50.04), 0.5, mode::END, None, false);
|
||||
let mut models: Vec<Vec2> =
|
||||
all.iter().filter(|h| h.point.near(Vec2::new(100.0, 50.0), 1e-9)).filter_map(|h| h.viewport).map(|v| v.point).collect();
|
||||
models.sort_by(|a, b| a.x.total_cmp(&b.x));
|
||||
assert_eq!(models, [Vec2::new(0.0, 0.0), Vec2::new(20.0, 0.0)], "{all:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewport_frozen_layers_do_not_hide_paper_space_geometry() {
|
||||
let (mut d, paper) = drawing();
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
//! MTEXT's opposite corner ignores ortho: the text box keeps its width and proportion (#3388).
|
||||
|
||||
use cadcraft_doc::{EntityKind, MText};
|
||||
use cadcraft_engine::snap::tracking::CursorQuery;
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use cadcraft_geom::{Bounds2, Vec2};
|
||||
use serde_json::json;
|
||||
|
||||
/// Move the cursor to `raw` at the current prompt, as the canvas does.
|
||||
fn hover(s: &mut Session, raw: Vec2) -> Vec2 {
|
||||
let p = s.current_prompt().unwrap();
|
||||
let q = CursorQuery { base: p.base, deferred: p.deferred, corner: p.corner, aperture: 1e-6, tol: 1e-6, now: 0.0, shift: false };
|
||||
let c = s.snap_cursor(raw, &q).point;
|
||||
s.cursor = c;
|
||||
c
|
||||
}
|
||||
|
||||
fn session(ortho: bool) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("setvar", &json!({ "name": "OSMODE", "value": 0 })).unwrap();
|
||||
s.execute("setvar", &json!({ "name": "ORTHOMODE", "value": i32::from(ortho) })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn last_mtext(s: &Session) -> MText {
|
||||
match s.doc().unwrap().model.last().map(|e| e.kind.clone()) {
|
||||
Some(EntityKind::MText(t)) => t,
|
||||
k => panic!("no mtext: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Place an MTEXT from `first` to a cursor click at `second`, returning the preview bounds,
|
||||
/// in-place editor box `(insert, width)` and created entity `(insert, width)`.
|
||||
fn click_mtext(ortho: bool, first: Vec2, second: Vec2) -> ((Vec2, Vec2), (Vec2, f64), (Vec2, f64)) {
|
||||
let mut s = session(ortho);
|
||||
s.cmdline(&format!("mtext {},{}", first.x, first.y)).unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert_eq!(p.message, "Specify opposite corner");
|
||||
assert!(p.corner, "MTEXT opposite corner ignores ortho");
|
||||
let c = hover(&mut s, second);
|
||||
assert!(c.near(second, 1e-9), "opposite corner stays under the cursor: {c:?}");
|
||||
let mut pv = Bounds2::EMPTY;
|
||||
for e in s.preview(c) {
|
||||
pv = pv.union(&cadcraft_doc::entity_bounds(s.doc().unwrap(), &e, 0));
|
||||
}
|
||||
s.input(Input::Point(c)).unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
s.input(Input::Text("Hello".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.current_prompt().is_none(), "MTEXT is done, still at {:?}", s.current_prompt().map(|p| p.message));
|
||||
let t = last_mtext(&s);
|
||||
assert_eq!(t.contents, "Hello");
|
||||
((pv.min, pv.max), (ed.insert.xy(), ed.width), (t.insert.xy(), t.width))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_opposite_corner_ignores_ortho() {
|
||||
let cases = [
|
||||
// Wide box (dx > dy)
|
||||
(Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::new(0.0, 3.0), 10.0),
|
||||
// Tall box (dy > dx)
|
||||
(Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::new(0.0, 10.0), 3.0),
|
||||
// Opposite quadrant (negative dx and dy)
|
||||
(Vec2::new(10.0, 10.0), Vec2::new(2.0, 4.0), Vec2::new(2.0, 4.0), Vec2::new(10.0, 10.0), Vec2::new(2.0, 10.0), 8.0),
|
||||
];
|
||||
for (first, second, min, max, insert, width) in cases {
|
||||
let on = click_mtext(true, first, second);
|
||||
assert!(on.0.0.near(min, 1e-9) && on.0.1.near(max, 1e-9), "preview bounds with ortho on: {:?}", on.0);
|
||||
assert!(on.1.0.near(insert, 1e-9) && (on.1.1 - width).abs() < 1e-9, "editor box with ortho on: {:?}", on.1);
|
||||
assert!(on.2.0.near(insert, 1e-9) && (on.2.1 - width).abs() < 1e-9, "entity box with ortho on: {:?}", on.2);
|
||||
let off = click_mtext(false, first, second);
|
||||
assert_eq!(off, on, "ortho changes nothing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_coordinate_and_direct_distance_input_with_ortho() {
|
||||
let mut s = session(true);
|
||||
// Absolute coordinate input for the opposite corner.
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
s.cmdline("10,3").unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
assert!(ed.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
|
||||
assert!((ed.width - 10.0).abs() < 1e-9);
|
||||
s.input(Input::Text("Abs".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let t = last_mtext(&s);
|
||||
assert!(t.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
|
||||
assert!((t.width - 10.0).abs() < 1e-9);
|
||||
|
||||
// Relative coordinate input for the opposite corner.
|
||||
s.cmdline("mtext 2,3").unwrap();
|
||||
s.cmdline("@4,9").unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
assert!(ed.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
|
||||
assert!((ed.width - 4.0).abs() < 1e-9);
|
||||
s.input(Input::Text("Rel".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let t = last_mtext(&s);
|
||||
assert!(t.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
|
||||
assert!((t.width - 4.0).abs() < 1e-9);
|
||||
|
||||
// Direct distance entry goes toward the cursor rather than along an axis.
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
let c = hover(&mut s, Vec2::new(3.0, 4.0));
|
||||
assert!(c.near(Vec2::new(3.0, 4.0), 1e-9));
|
||||
s.cmdline("5").unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
assert!(ed.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
|
||||
assert!((ed.width - 3.0).abs() < 1e-9);
|
||||
s.input(Input::Text("Dir".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let t = last_mtext(&s);
|
||||
assert!(t.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
|
||||
assert!((t.width - 3.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_escape_cancels_cleanly_with_ortho() {
|
||||
let mut s = session(true);
|
||||
// Cancel at the opposite-corner prompt.
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
let c = hover(&mut s, Vec2::new(10.0, 3.0));
|
||||
assert!(c.near(Vec2::new(10.0, 3.0), 1e-9));
|
||||
s.cancel();
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert!(s.editing_mtext().is_none());
|
||||
assert!(s.doc().unwrap().model.is_empty());
|
||||
|
||||
// Cancel after picking the opposite corner (at the text prompt).
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
let c = hover(&mut s, Vec2::new(10.0, 3.0));
|
||||
s.input(Input::Point(c)).unwrap();
|
||||
assert!(s.editing_mtext().is_some());
|
||||
s.cancel();
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert!(s.editing_mtext().is_none());
|
||||
assert!(s.doc().unwrap().model.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_and_pline_still_obey_ortho() {
|
||||
let mut s = session(true);
|
||||
s.cmdline("line 0,0").unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert!(!p.corner, "LINE next point is constrained by ortho");
|
||||
let c = hover(&mut s, Vec2::new(10.0, 3.0));
|
||||
assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps LINE horizontal: {c:?}");
|
||||
s.cancel();
|
||||
|
||||
s.cmdline("pline 0,0").unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert!(!p.corner, "PLINE next point is constrained by ortho");
|
||||
let c = hover(&mut s, Vec2::new(3.0, 10.0));
|
||||
assert!(c.near(Vec2::new(0.0, 10.0), 1e-9), "ortho keeps PLINE vertical: {c:?}");
|
||||
s.cancel();
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Named views (#463): VIEW / -VIEW Save, Window, Restore, Delete, ? and the layer snapshot
|
||||
//! setting; Zoom Realtime and Dynamic; realtime PAN and -PAN; ZOOMFACTOR. (The DXF round trip of views is tested in
|
||||
//! setting; Zoom Realtime and Dynamic; ZOOMFACTOR. (The DXF round trip of views is tested in
|
||||
//! `cadcraft-io`'s `view_tables_roundtrip`.)
|
||||
|
||||
use cadcraft_engine::doc::Space;
|
||||
@@ -155,85 +155,6 @@ fn zoom_realtime_drags_and_enter_ends() {
|
||||
assert_eq!(view(&s), View { center: Vec2::ZERO, height: 25.0, twist: 0.0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pan_realtime_drags_and_enter_ends() {
|
||||
for start in ["pan", "p"] {
|
||||
let mut s = session();
|
||||
set_view(&mut s, 0.0, 0.0, 100.0);
|
||||
s.state_mut().unwrap().view_history.clear();
|
||||
typed(&mut s, &[start]);
|
||||
assert!(s.realtime_pan_active(), "{}", s.prompt_text());
|
||||
// 800 px show 100 units: right 80 px and up 40 px move the drawing with the cursor.
|
||||
s.realtime_pan(80.0, -40.0).unwrap();
|
||||
assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0), "{:?}", view(&s));
|
||||
s.realtime_pan(f64::NAN, 3.0).unwrap();
|
||||
assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0), "{:?}", view(&s));
|
||||
typed(&mut s, &[""]);
|
||||
assert!(s.running.is_none() && !s.realtime_pan_active());
|
||||
// Outside realtime PAN a drag does nothing; Zoom Previous returns to the view before it.
|
||||
s.realtime_pan(80.0, -40.0).unwrap();
|
||||
assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0));
|
||||
s.execute("zoom.previous", &json!({})).unwrap();
|
||||
assert_eq!(view(&s), View { center: Vec2::ZERO, height: 100.0, twist: 0.0 });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pan_realtime_moves_only_the_view() {
|
||||
// A drag frame is not a change of the drawing: the revision stays, so the canvas does not
|
||||
// rebuild the drawing's geometry on every frame (as with a middle-button drag).
|
||||
let mut s = session();
|
||||
set_view(&mut s, 0.0, 0.0, 100.0);
|
||||
typed(&mut s, &["pan"]);
|
||||
let revision = s.state().unwrap().revision;
|
||||
s.realtime_pan(80.0, -40.0).unwrap();
|
||||
assert!(close(view(&s).center.x, -10.0), "{:?}", view(&s));
|
||||
assert_eq!(s.state().unwrap().revision, revision);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pan_realtime_in_a_twisted_view_moves_the_drawing_with_the_cursor() {
|
||||
// A view twisted a quarter turn (DVIEW TWist) shows the drawing's -Y to the right: a drag
|
||||
// 80 px right moves the drawing with it, so the centre moves 10 units up the drawing's Y.
|
||||
let mut s = session();
|
||||
set_view(&mut s, 0.0, 0.0, 100.0);
|
||||
s.state_mut().unwrap().set_view_quiet(View { center: Vec2::ZERO, height: 100.0, twist: std::f64::consts::FRAC_PI_2 });
|
||||
typed(&mut s, &["pan"]);
|
||||
assert!(s.realtime_pan_active(), "{}", s.prompt_text());
|
||||
s.realtime_pan(80.0, 0.0).unwrap();
|
||||
let v = view(&s);
|
||||
assert!(close(v.center.x, 0.0) && close(v.center.y, 10.0), "{v:?}");
|
||||
assert!(close(v.twist, std::f64::consts::FRAC_PI_2), "the pan kept the twist: {v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_pan_takes_two_points_or_a_displacement() {
|
||||
let mut s = session();
|
||||
set_view(&mut s, 0.0, 0.0, 100.0);
|
||||
typed(&mut s, &["-pan", "0,0", "10,5"]);
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(view(&s).center, Vec2::new(-10.0, -5.0));
|
||||
typed(&mut s, &["-pan", "3,4", ""]);
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(view(&s).center, Vec2::new(-13.0, -9.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_pan_displacement_is_measured_in_the_ucs() {
|
||||
// A UCS moved to 100,50: the displacement 0,0 does not pan, and 3,4 pans by 3,4.
|
||||
let mut s = session();
|
||||
set_view(&mut s, 0.0, 0.0, 100.0);
|
||||
s.execute("ucs", &json!({ "origin": [100.0, 50.0] })).unwrap();
|
||||
typed(&mut s, &["-pan", "0,0", ""]);
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(view(&s).center, Vec2::ZERO);
|
||||
typed(&mut s, &["-pan", "3,4", ""]);
|
||||
assert_eq!(view(&s).center, Vec2::new(-3.0, -4.0));
|
||||
// Two points: the difference, which the UCS origin does not change.
|
||||
typed(&mut s, &["-pan", "0,0", "10,5"]);
|
||||
assert_eq!(view(&s).center, Vec2::new(-13.0, -9.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zoom_dynamic_places_and_sizes_the_view_box() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
//! OFFSET Erase/Layer/Multiple/Undo and the MOVE/COPY Displacement option at the command line.
|
||||
|
||||
use cadcraft_engine::Input;
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use serde_json::json;
|
||||
|
||||
/// Every line as ((ax, ay), (bx, by), layer), sorted by the first y.
|
||||
@@ -64,27 +62,6 @@ fn offset_multiple_and_undo() {
|
||||
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.0), (10.0, 2.0), "0"), l((0.0, 4.0), (10.0, 4.0), "0")]);
|
||||
}
|
||||
|
||||
// Regression test for #618: OFFSET's distance prompt took only a typed number; clicking two points
|
||||
// (the distance between them) was rejected, and the second click had no distance guide.
|
||||
#[test]
|
||||
fn offset_distance_from_two_clicked_points() {
|
||||
let mut s = one_line();
|
||||
s.start("offset").unwrap();
|
||||
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert!(p.message.contains("second point"), "{}", s.prompt_text());
|
||||
assert!(p.base.is_some_and(|b| b.near(Vec2::new(20.0, 20.0), 1e-9)), "the second click is measured from the first");
|
||||
// The guide from the first click to the cursor is the previewed distance.
|
||||
let guide = s.preview(Vec2::new(20.0, 22.5));
|
||||
assert!(matches!(guide.first().map(|e| &e.kind), Some(EntityKind::Line(g)) if g.a.xy().near(Vec2::new(20.0, 20.0), 1e-9)), "{guide:?}");
|
||||
s.input(Input::Point(Vec2::new(20.0, 22.5))).unwrap();
|
||||
assert!(s.current_prompt().unwrap().message.contains("Select object"), "{}", s.prompt_text());
|
||||
assert_eq!(s.doc().unwrap().header.f64("OFFSETDIST", -1.0), 2.5);
|
||||
s.script("5,0 5,1\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.5), (10.0, 2.5), "0")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_json_erase_and_layer() {
|
||||
let mut s = one_line();
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
//! The rotation grip of a dynamic block asks for an angle: Dynamic Input shows one angle box,
|
||||
//! holding the angle the cursor would give as Properties will show it. The drawing is the
|
||||
//! synthetic Symbol block of the io tests (Angle1 about its base, its grip at the radius' end).
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Handle;
|
||||
use cadcraft_engine::doc::dynblock::GripPart;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use serde_json::json;
|
||||
|
||||
fn dxf(src: &str) -> String {
|
||||
src.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(|l| {
|
||||
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
|
||||
format!("{code}\n{value}\n")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A session with Symbol and a reference to it at (100, 100).
|
||||
fn session() -> (Session, Handle) {
|
||||
let src = include_str!("../../../io/tests/data/dynblock_symbol.txt").replace("\r\n", "\n");
|
||||
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "symbol", None);
|
||||
let r = s.execute("insert", &json!({ "name": "Symbol", "at": [100, 100] })).unwrap();
|
||||
(s, Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rotation_grip_asks_for_an_angle_and_shows_it_live() {
|
||||
let (mut s, h) = session();
|
||||
s.start_dyn_grip(h, 15, GripPart::End).unwrap();
|
||||
assert!(s.current_prompt().is_some_and(|p| p.angle), "{:?}", s.current_prompt());
|
||||
// The grip is at (102, 100); straight above the base is a quarter turn.
|
||||
assert_eq!(s.live_value(Vec2::new(100.0, 102.0)).as_deref(), Some("90°"));
|
||||
assert_eq!(s.live_value(Vec2::new(98.0, 100.0)).as_deref(), Some("180°"));
|
||||
// Nothing is changed by looking.
|
||||
let props = s.execute("blocks.reference", &json!({ "handle": h.hex() })).unwrap();
|
||||
let angle = props["properties"].as_array().unwrap().iter().find(|p| p["name"] == "Angle1").unwrap()["value"].clone();
|
||||
assert_eq!(angle, json!("0"));
|
||||
}
|
||||
@@ -29,7 +29,6 @@ fn defaults_are_the_ones_the_commands_use() {
|
||||
("DONUTOD", json!(1.0)),
|
||||
("WIPEOUTFRAME", json!(1)),
|
||||
("LWDEFAULT", json!(25)),
|
||||
("LAYLOCKFADECTL", json!(50)),
|
||||
("DIMASSOC", json!(2)),
|
||||
("CPLOTSTYLE", json!("ByLayer")),
|
||||
("TRANSPARENCYDISPLAY", json!(1)),
|
||||
@@ -62,9 +61,6 @@ fn values_reach_the_commands() {
|
||||
assert!(!s.settings.transparency_display);
|
||||
s.cmdline("setvar plottransparencyoverride 2").unwrap();
|
||||
assert_eq!(s.settings.plot_transparency_override, 2);
|
||||
for v in [-90, 0, 90] {
|
||||
assert!(setvar(&mut s, "LAYLOCKFADECTL", json!(v)), "LAYLOCKFADECTL {v}");
|
||||
}
|
||||
assert!(setvar(&mut s, "INSNAME", json!("Valve")));
|
||||
assert!(setvar(&mut s, "INSNAME", json!(".")));
|
||||
assert_eq!(getvar(&mut s, "INSNAME"), json!(""));
|
||||
@@ -78,8 +74,6 @@ fn bad_values_and_unknown_names_are_refused() {
|
||||
("POLYSIDES", json!(5000)),
|
||||
("TRIMMODE", json!(3)),
|
||||
("LWDEFAULT", json!(26)),
|
||||
("LAYLOCKFADECTL", json!(91)),
|
||||
("LAYLOCKFADECTL", json!(-91)),
|
||||
("HPSCALE", json!(0)),
|
||||
("HPNAME", json!("NO-SUCH-PATTERN")),
|
||||
("DONUTOD", json!(0)),
|
||||
|
||||
@@ -30,7 +30,7 @@ fn transparent_zoom_resumes_the_running_command() {
|
||||
s.cmdline("").unwrap();
|
||||
s.cancel();
|
||||
// Scripts nest the same way.
|
||||
s.script("LINE 0,0 '-PAN 0,0 1,1 5,0\n\n").unwrap();
|
||||
s.script("LINE 0,0 'PAN 0,0 1,1 5,0\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), 2);
|
||||
// Enter ends the nested command; Esc and a new command cancel both levels.
|
||||
|
||||
@@ -72,7 +72,6 @@ fn edit(drawing: Drawing, handle: Handle, points: &[Vec2], explicit: bool, index
|
||||
}
|
||||
|
||||
fn check(format: &str, interactive: bool) {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
for explicit in [false, true] {
|
||||
for reversed in [false, true] {
|
||||
let (drawing, handle, points) = fixture(explicit, reversed);
|
||||
@@ -167,7 +166,6 @@ fn polyline_closedness_is_not_inferred_from_coincident_endpoints() {
|
||||
|
||||
#[test]
|
||||
fn coincident_endpoints_remain_separately_editable_after_save() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let original = [Vec2::ZERO, Vec2::new(8.0, 0.0), Vec2::new(8.0, 6.0), Vec2::new(0.0, 6.0)];
|
||||
for explicit in [false, true] {
|
||||
for interactive in [false, true] {
|
||||
|
||||
@@ -1,179 +0,0 @@
|
||||
//! What a DXF before 2007 leaves out for its proxies' string streams, counted by the real DXF
|
||||
//! writer (#3229): only what 2007 would keep, from the drawing the command writes. In its own
|
||||
//! test binary because it installs the real io hooks for the whole process.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, SaveAs, set_io, set_proxies_lost, set_write_as};
|
||||
use cadcraft_engine::doc::Drawing;
|
||||
use serde_json::{Value, json};
|
||||
#[path = "support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
|
||||
/// The real reader and writer, and the real proxy-loss count.
|
||||
fn install() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
set_write_as(|d, name, o: &SaveAs| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
}
|
||||
|
||||
/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes.
|
||||
fn proxy(handle: &str, owner: &str, strings: &str, class: &str) -> Vec<(String, String)> {
|
||||
let p = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
vec![
|
||||
p("0", "ACAD_PROXY_ENTITY"),
|
||||
p("5", handle),
|
||||
p("330", owner),
|
||||
p("100", "AcDbEntity"),
|
||||
p("8", "0"),
|
||||
p("100", "AcDbProxyEntity"),
|
||||
p("90", "498"),
|
||||
p("91", class),
|
||||
p("95", "393245"),
|
||||
p("70", "0"),
|
||||
p("162", strings),
|
||||
p("161", "16"),
|
||||
p("310", "AABB"),
|
||||
]
|
||||
}
|
||||
|
||||
fn pairs(text: &str) -> Vec<(String, String)> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
lines.chunks(2).map(|c| (c[0].trim().to_string(), c.get(1).map_or(String::new(), |v| v.trim().to_string()))).collect()
|
||||
}
|
||||
|
||||
/// A drawing with `$ACADVER` `acadver` read from a DXF holding the class WIDGETX and, in model
|
||||
/// space, the proxies `entities` gives (each from the model space block record's handle).
|
||||
fn drawing(acadver: &str, entities: impl Fn(&str) -> Vec<Vec<(String, String)>>) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", "AC1024");
|
||||
let text = String::from_utf8(cadcraft_io::write(&d, "p.dxf").unwrap()).unwrap();
|
||||
let mut p = pairs(&text);
|
||||
let g = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
let classes = p.iter().position(|q| q.0 == "2" && q.1 == "CLASSES").unwrap() + 1;
|
||||
let class =
|
||||
[g("0", "CLASS"), g("1", "WIDGETX"), g("2", "AcDbWidgetX"), g("3", "ObjectDBX Classes"), g("90", "4095"), g("280", "0"), g("281", "1")];
|
||||
p.splice(classes..classes, class);
|
||||
// The model space block record: the owner of model space entities.
|
||||
let record_end = |i: usize| i + 1 + p[i + 1..].iter().position(|q| q.0 == "0").unwrap_or(p.len() - i - 1);
|
||||
let ms = (0..p.len())
|
||||
.filter(|&i| p[i].0 == "0" && p[i].1 == "BLOCK_RECORD")
|
||||
.find(|&i| p[i..record_end(i)].iter().any(|q| q.0 == "2" && q.1.eq_ignore_ascii_case("*Model_Space")))
|
||||
.unwrap();
|
||||
let owner = p[ms..].iter().find(|q| q.0 == "5").unwrap().1.clone();
|
||||
let ents = p.iter().position(|q| q.0 == "2" && q.1 == "ENTITIES").unwrap();
|
||||
let end = ents + p[ents..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap();
|
||||
p.splice(end..end, entities(&owner).into_iter().flatten());
|
||||
let bytes: String = p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect();
|
||||
let mut d = cadcraft_io::read(bytes.as_bytes(), "p.dxf").unwrap();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d
|
||||
}
|
||||
|
||||
/// Two proxies with string streams, one whose class number names no class (no version writes
|
||||
/// it), and one without: before 2007 only the first one is lost to the string stream.
|
||||
fn three_proxies(owner: &str) -> Vec<Vec<(String, String)>> {
|
||||
vec![proxy("AAA1", owner, "8", "500"), proxy("AAA2", owner, "8", "777"), proxy("AAA3", owner, "0", "500")]
|
||||
}
|
||||
|
||||
fn not_saved(r: &Value) -> Value {
|
||||
r.get("notSaved").cloned().unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
fn legacy_visualstyles_warn_only_for_2007_dwg() {
|
||||
install();
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let source = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1021\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic\n350\n21\n\
|
||||
0\nVISUALSTYLE\n5\n21\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic\n70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\
|
||||
74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n\
|
||||
170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n0\nENDSEC\n0\nEOF\n";
|
||||
let drawing = cadcraft_io::read_dxf(source.as_bytes()).unwrap();
|
||||
let mut session = Session::empty();
|
||||
session.open_drawing(drawing, "styles.dxf", None);
|
||||
assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&session, "styles.dwg").get("VISUALSTYLE"), Some(&1));
|
||||
for (format, version) in [("dwg", 2007), ("dwg", 2013), ("dxf", 2007)] {
|
||||
let start = session.log.len();
|
||||
let result = session.execute("document.bytes", &json!({"format": format, "version": version})).unwrap();
|
||||
if format == "dwg" && version == 2007 {
|
||||
assert_eq!(not_saved(&result), json!({"VISUALSTYLE": 1}));
|
||||
assert!(session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
|
||||
} else {
|
||||
assert_eq!(not_saved(&result), Value::Null);
|
||||
assert!(!session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_no_version_writes_is_not_reported() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let path = dir.path_str("out.dxf");
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "{:?}", s.log);
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2007 })).unwrap();
|
||||
assert_eq!(not_saved(&r), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_reports_the_drawing_it_writes() {
|
||||
// In the Block Editor EXPORT writes the block, which holds no proxy: nothing is lost.
|
||||
install();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }));
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
let line = s.execute("entities", &json!({ "type": "LINE" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string();
|
||||
s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [line], "keep": "convert" })).unwrap();
|
||||
s.execute("bedit", &json!({ "name": "B" })).unwrap();
|
||||
let n = s.log.len();
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(not_saved(&r), Value::Null, "{:?}", &s.log[n..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reference_edit_working_copy_is_not_counted_twice() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", |o| vec![proxy("AAA1", o, "8", "500")]), "proxy.dxf", None);
|
||||
s.execute("block", &json!({ "name": "W", "base": [0, 0], "handles": ["AAA1"], "keep": "convert" })).unwrap();
|
||||
let ins = s.execute("entities", &json!({ "type": "INSERT" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string();
|
||||
let path = dir.path_str("before.dxf");
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "in the block");
|
||||
s.execute("refedit", &json!({ "handle": ins })).unwrap();
|
||||
// Saves wait for REFCLOSE; the QSAVE question and `document.bytes` count the committed drawing.
|
||||
let r = s.execute("document.bytes", &json!({ "format": "dxf", "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "the working copy isn't written");
|
||||
assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&s, "during.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_wblock_of_the_whole_drawing_reports_a_pre_2007_dxf() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let path = dir.path_str("whole.dxf").replace('\\', "/");
|
||||
s.cmdline(&format!("(command \"_.-WBLOCK\" \"{path}\" \"\" \"*\")")).unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(std::path::Path::new(&path).exists());
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.ends_with("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
//! Kept render settings are in the form of the file they were read from, whatever the drawing's
|
||||
//! `$ACADVER` says after a SAVEAS to another version: saving a 2018 drawing down to 2000 and back
|
||||
//! up to 2018 writes the class version the 2018 file had, not one higher (which BricsCAD refuses,
|
||||
//! #907).
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, set_io, set_write_as};
|
||||
use serde_json::json;
|
||||
|
||||
/// A 2018 DXF with one mental ray render settings object, stored as `90 2` (class version 1 in the
|
||||
/// 2013+ form).
|
||||
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n\
|
||||
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\
|
||||
0\nMENTALRAYRENDERSETTINGS\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n\
|
||||
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nENDSEC\n0\nEOF\n";
|
||||
|
||||
/// The `AcDbRenderSettings` class version in a written DXF.
|
||||
fn class_version(path: &std::path::Path) -> Option<i64> {
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
let l: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = l.windows(2).position(|w| w == ["0", "MENTALRAYRENDERSETTINGS"])?;
|
||||
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
|
||||
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saveas_down_and_back_up_keeps_the_render_settings_class_version() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
set_write_as(|d, name, o| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-render-settings-saveas-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "render.dxf", None);
|
||||
let save = |s: &mut Session, name: &str, version: &str| {
|
||||
let path = dir.join(name);
|
||||
s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": version })).unwrap();
|
||||
class_version(&path)
|
||||
};
|
||||
|
||||
assert_eq!(save(&mut s, "2018.dxf", "2018"), Some(2), "same version: as read");
|
||||
assert_eq!(save(&mut s, "2000.dxf", "2000"), Some(1), "the 2000 form is one lower");
|
||||
s.execute("qsave", &json!({})).unwrap();
|
||||
assert_eq!(class_version(&dir.join("2000.dxf")), Some(1), "QSAVE keeps the 2000 form");
|
||||
assert_eq!(save(&mut s, "back.dxf", "2018"), Some(2), "back to 2018: the 2018 file's value, not one higher");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -212,7 +212,6 @@ fn whole_drawings_are_told_from_cut_off_ones() {
|
||||
/// in a 2018 and a 2000 file, it doesn't replace the good backup; whole, it does.
|
||||
#[test]
|
||||
fn a_dwg_cut_off_anywhere_keeps_the_good_backup() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let _saving = saving();
|
||||
hooks();
|
||||
for version in [2018, 2000] {
|
||||
|
||||
@@ -268,27 +268,19 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
|
||||
assert_eq!(r["notSaved"], json!({ "REGION": 1 }));
|
||||
}
|
||||
|
||||
/// A DWG before 2013 writes a solid's SAT text of ACIS 7.0 and later, so a save there doesn't list
|
||||
/// a solid that holds it; from 2013 the geometry must be in the data store and SAT text alone is
|
||||
/// lost, so the save lists it. Older SAT (ACIS 4.0) and a solid with neither are always listed
|
||||
/// (#2334).
|
||||
/// A DWG before 2013 writes a solid's SAT text as it is, so a save there doesn't list a solid that
|
||||
/// holds it; from 2013 the geometry must be in the data store and SAT text alone is lost, so the
|
||||
/// save lists it. A solid with neither is always listed (#2334).
|
||||
#[test]
|
||||
fn a_dwg_keeps_sat_text_solids_only_before_2013() {
|
||||
use cadcraft_engine::cmd::file::{Version, not_saved_as};
|
||||
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
|
||||
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags });
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "700 0 1 0")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 1 1 0")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 1)].into_iter().collect(), "2010 keeps the SAT-text solid");
|
||||
assert_eq!(not_saved_as(&d, Version::R2018), [("3DSOLID".to_string(), 2)].into_iter().collect(), "2018 loses it");
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 85 1 0")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2)].into_iter().collect(), "ACIS 4.0 SAT is listed");
|
||||
// The same versions encoded, as a DXF before 2013 holds them: 700 is kept, 400 is listed.
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "hoo o n o")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2)].into_iter().collect(), "encoded ACIS 7.0 SAT is kept");
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "koo gj n o")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 3)].into_iter().collect(), "encoded ACIS 4.0 SAT is listed");
|
||||
}
|
||||
|
||||
/// The DWG bridge writes OLE objects (`ole2frame_roundtrip` in the io tests), so saving one as
|
||||
@@ -310,109 +302,3 @@ fn ole_objects_are_not_reported() {
|
||||
assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1), ("ole2frame".to_string(), 1)].into_iter().collect(), "{v:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A solid whose geometry only the data store keeps (read from a 2013+ file) has nothing to write
|
||||
/// to a DXF of 2010 or earlier, which has no data store: the save leaves it out and says so, and
|
||||
/// the interactive save knows it beforehand; 2013 and later keep it (#2334).
|
||||
#[test]
|
||||
fn saving_data_store_solids_as_dxf_2010_reports_them() {
|
||||
use cadcraft_engine::cmd::file::loss_on_save;
|
||||
use cadcraft_engine::doc::foreign::Foreign;
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec()));
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", "AC1032");
|
||||
let h = d.add(&Space::Model, Common::default(), unknown("3DSOLID")).unwrap();
|
||||
let record = vec![
|
||||
RawTag { code: 0, value: "ACDSRECORD".into() },
|
||||
RawTag { code: 320, value: h.hex() },
|
||||
RawTag { code: 2, value: "ASM_Data".into() },
|
||||
RawTag { code: 310, value: "00".into() },
|
||||
];
|
||||
d.foreign = std::sync::Arc::new(Foreign { data_store: record, ..Foreign::default() });
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "solid.dxf", None);
|
||||
assert!(loss_on_save(&s, "solid.dxf").is_empty(), "2018 keeps it");
|
||||
|
||||
let path = std::env::temp_dir().join(format!("cadcraft-ds-note-{}.dxf", std::process::id()));
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2010 })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "3DSOLID": 1 }));
|
||||
assert!(s.log.iter().any(|l| l.contains("2010 and earlier have no data store") && l.contains("1 3DSOLID")), "{:?}", s.log);
|
||||
assert_eq!(loss_on_save(&s, "solid.dxf"), [("3DSOLID".to_string(), 1)].into_iter().collect(), "now a 2010 drawing");
|
||||
|
||||
let n = s.log.len();
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2018 })).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(r.get("notSaved").is_none() && s.log.len() == n);
|
||||
}
|
||||
|
||||
/// A proxy entity (as a 2010 file has it) whose string stream is `strings` long (group 162).
|
||||
fn proxy_entity(strings: &str) -> EntityKind {
|
||||
let tags = [(8, "0"), (100, "AcDbProxyEntity"), (90, "498"), (91, "500"), (162, strings), (161, "16"), (310, "AABB")];
|
||||
EntityKind::Unknown(Unknown {
|
||||
dxf_type: "ACAD_PROXY_ENTITY".into(),
|
||||
tags: tags.iter().map(|(code, value)| RawTag { code: *code, value: (*value).into() }).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A DXF before 2007 has no form for a proxy's separate string stream: the writer leaves such a
|
||||
/// proxy out, and the save says so instead of dropping it silently (#3229).
|
||||
#[test]
|
||||
fn a_dxf_before_2007_reports_the_proxies_it_leaves_out() {
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
// SAVEAS at a chosen version goes through this hook (each test may run in its own process).
|
||||
set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec()));
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "proxy.dxf", None);
|
||||
let path = std::env::temp_dir().join(format!("cadcraft-proxy-r2000-{}.dxf", std::process::id()));
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2000 })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings");
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2007 })).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(r.get("notSaved").is_none(), "2007 keeps it");
|
||||
}
|
||||
|
||||
/// The interactive QSAVE asks before a pre-2007 DXF replaces a file and leaves such proxies out,
|
||||
/// with the same list (#3229).
|
||||
#[test]
|
||||
fn a_pre_2007_dxf_proxy_loss_is_known_before_saving() {
|
||||
use cadcraft_engine::cmd::file::loss_on_save;
|
||||
let drawing = |acadver: &str| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d
|
||||
};
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015"), "proxy.dxf", None);
|
||||
assert_eq!(loss_on_save(&s, "proxy.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect());
|
||||
s.open_drawing(drawing("AC1021"), "proxy.dxf", None);
|
||||
assert!(loss_on_save(&s, "proxy.dxf").is_empty(), "2007 keeps it");
|
||||
}
|
||||
|
||||
/// EXPORT writes a DXF at the drawing's own version: before 2007 it leaves the same proxies out
|
||||
/// and says so, like a save (#3229).
|
||||
#[test]
|
||||
fn exporting_a_dxf_before_2007_reports_the_proxies_it_leaves_out() {
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
let drawing = |acadver: &str| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap();
|
||||
d
|
||||
};
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015"), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings");
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1021"), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert!(r.get("notSaved").is_none(), "2007 keeps it");
|
||||
}
|
||||
|
||||
@@ -31,7 +31,6 @@ fn folder(tag: &str) -> TempDir {
|
||||
}
|
||||
|
||||
fn save(d: &Drawing, path: &Path) {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
std::fs::write(path, cadcraft_io::write(d, path).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -477,18 +477,6 @@ mod tests {
|
||||
ttf::fallback_for('\u{0E01}').filter(|f| ['\u{0E14}', '\u{0E34}', '\u{0E4C}', '\u{0E33}', '\u{0E10}'].iter().all(|c| f.has_glyph(*c)))
|
||||
}
|
||||
|
||||
/// A Thai face's letters are measured in ems: ก has neither ascender nor descender, ไ rises
|
||||
/// above it, and a space or an unmapped character has no height.
|
||||
#[test]
|
||||
fn thai_glyph_heights_are_measured_in_ems() {
|
||||
let Some(face) = thai_face() else { return };
|
||||
let ko = face.glyph_height('ก').unwrap_or_default();
|
||||
assert!((0.2..1.0).contains(&ko), "ก is {ko} em");
|
||||
assert!(face.glyph_height('ไ').is_some_and(|h| h > ko), "ไ is taller than ก");
|
||||
assert_eq!(face.glyph_height(' '), None);
|
||||
assert_eq!(face.glyph_height('\u{10fffd}'), None);
|
||||
}
|
||||
|
||||
/// Lowest point of the glyph that shows `c`.
|
||||
fn bottom_of(sh: &Shaped, c: char) -> Option<f64> {
|
||||
let t = sh.text.iter().find(|t| t.ch == c)?;
|
||||
|
||||
+22
-42
@@ -649,41 +649,31 @@ fn frame(font: &TextFont, s: &str, p: &TextParams) -> (Vec2, Vec2, f64, Vec2) {
|
||||
(origin, justify_offset(font, &sh, height, p.h, p.v), rot, mirror)
|
||||
}
|
||||
|
||||
/// Resolve Aligned/Fit dimensions with the same shaping direction as [`place`].
|
||||
/// Missing, coincident or nonfinite points leave the parameters unchanged.
|
||||
pub fn fit_params(font: &TextFont, s: &str, p: &TextParams) -> TextParams {
|
||||
let mut fitted = *p;
|
||||
if !matches!(p.h, Align::Aligned | Align::Fit) {
|
||||
return fitted;
|
||||
}
|
||||
let Some(second) = p.align_pt else { return fitted };
|
||||
let distance = p.insert.dist(second);
|
||||
if !distance.is_finite() || distance <= 1e-12 {
|
||||
return fitted;
|
||||
}
|
||||
fitted.rotation = p.insert.angle_to(second);
|
||||
let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
|
||||
let width = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL).width;
|
||||
if width.is_finite() && width > 1e-12 {
|
||||
let scale = distance / width;
|
||||
if p.h == Align::Aligned {
|
||||
fitted.height = height * scale;
|
||||
} else {
|
||||
fitted.width_factor *= scale;
|
||||
}
|
||||
}
|
||||
fitted
|
||||
}
|
||||
|
||||
/// Place a single-line TEXT in world coordinates with any font. Returns the shaped text and its
|
||||
/// bounding box.
|
||||
pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) {
|
||||
let fitted = fit_params(font, s, p);
|
||||
let p = &fitted;
|
||||
let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
|
||||
let rot = if p.rotation.is_finite() { p.rotation } else { 0.0 };
|
||||
let mut height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
|
||||
let mut wf = p.width_factor;
|
||||
let mut rot = if p.rotation.is_finite() { p.rotation } else { 0.0 };
|
||||
let insert = p.insert;
|
||||
let mut sh = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL);
|
||||
if matches!(p.h, Align::Aligned | Align::Fit)
|
||||
&& let Some(p2) = p.align_pt
|
||||
{
|
||||
let len = insert.dist(p2);
|
||||
rot = insert.angle_to(p2);
|
||||
// Measured as it is placed, left to right: the stroke font's trailing gap follows the
|
||||
// glyph that ends the line.
|
||||
let w = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL).width;
|
||||
if w > 1e-12 && len > 1e-12 {
|
||||
let k = len / w;
|
||||
if p.h == Align::Aligned {
|
||||
height *= k;
|
||||
} else {
|
||||
wf *= k;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut sh = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL);
|
||||
let width = sh.width;
|
||||
// Every justification but baseline-left (and aligned/fit, which span both points) is placed by
|
||||
// its alignment point (DXF group 11); the insertion point (group 10) is then a computed point.
|
||||
@@ -750,15 +740,6 @@ mod tests {
|
||||
assert!((text.width - 10.0).abs() < 1e-9, "{}", text.width);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_point_middle_vertical_spans_points() {
|
||||
for h in [Align::Aligned, Align::Fit] {
|
||||
let p = TextParams { h, v: VAlign::Middle, align_pt: Some(Vec2::new(12.0, 5.0)), ..TextParams::new(Vec2::ZERO, 2.0) };
|
||||
let (shaped, _) = place(&TextFont::Stroke, "SYNTHETIC", &p);
|
||||
assert!((shaped.width - p.insert.dist(p.align_pt.unwrap())).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_ascii_printable_has_a_glyph() {
|
||||
for c in ' '..='~' {
|
||||
@@ -858,14 +839,13 @@ mod ttf_tests {
|
||||
#[test]
|
||||
fn fallback_ranking_prefers_wide_coverage_regular_fonts() {
|
||||
let stems: Vec<String> =
|
||||
["zapfino", "dejavusans", "notosanscjk-bold", "notosanscjk-regular", "wqy-zenhei", "notosansarabic-regular", "arial", "unifont"]
|
||||
["zapfino", "dejavusans", "notosanscjk-bold", "notosanscjk-regular", "wqy-zenhei", "notosansarabic-regular", "arial"]
|
||||
.map(String::from)
|
||||
.to_vec();
|
||||
let r = crate::ttf::rank_fallback(&stems);
|
||||
assert_eq!(r.first().map(String::as_str), Some("notosanscjk-regular"));
|
||||
assert_eq!(r.get(1).map(String::as_str), Some("notosanscjk-bold"));
|
||||
assert_eq!(r.get(2).map(String::as_str), Some("wqy-zenhei"));
|
||||
assert_eq!(r.get(r.len().wrapping_sub(2)).map(String::as_str), Some("unifont"), "a last resort, but ahead of unknown fonts");
|
||||
assert_eq!(r.last().map(String::as_str), Some("zapfino"));
|
||||
assert_eq!(r.len(), stems.len());
|
||||
}
|
||||
|
||||
@@ -102,9 +102,6 @@ pub struct MTextLayout {
|
||||
/// Geometry by colour run (strokes plus fillable glyph outlines).
|
||||
pub pieces: Vec<MTextPiece>,
|
||||
pub bounds: Bounds2,
|
||||
/// The box of each column, in the order the text flows through them, measured like `bounds`
|
||||
/// but without the gutters and to each column's own height. One column: `bounds`.
|
||||
pub column_bounds: Vec<Bounds2>,
|
||||
/// Plain text of each laid-out line.
|
||||
pub lines: Vec<String>,
|
||||
/// Whether the geometry stops short: the layout reached its allowance of retained points
|
||||
@@ -734,7 +731,6 @@ pub fn layout_mtext_with(contents: &str, p: &MTextParams) -> MTextLayout {
|
||||
out.bounds = Bounds2::from_points(
|
||||
[Vec2::new(x0, top), Vec2::new(x0 + block_w, top), Vec2::new(x0 + block_w, top - block_h), Vec2::new(x0, top - block_h)].map(xf),
|
||||
);
|
||||
out.column_bounds = vec![out.bounds];
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -700,14 +700,6 @@ pub(super) fn layout(contents: &str, params: &MTextParams, base: &Fmt) -> MTextL
|
||||
[Vec2::new(box_x0, top), Vec2::new(box_x0 + total_w, top), Vec2::new(box_x0 + total_w, top - block_h), Vec2::new(box_x0, top - block_h)]
|
||||
.map(xf),
|
||||
);
|
||||
out.column_bounds = (0..n_cols)
|
||||
.map(|column| {
|
||||
let h = col_bottom.get(column).copied().unwrap_or(0.0).max(col_height(column));
|
||||
let slot = if reversed { n_cols.saturating_sub(1).saturating_sub(column) } else { column };
|
||||
let x0 = box_x0 + slot as f64 * (col_w + gutter);
|
||||
Bounds2::from_points([Vec2::new(x0, top), Vec2::new(x0 + col_w, top), Vec2::new(x0 + col_w, top - h), Vec2::new(x0, top - h)].map(xf))
|
||||
})
|
||||
.collect();
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
+8
-156
@@ -35,9 +35,6 @@ use skrifa::{FontRef, GlyphId, MetadataProvider};
|
||||
|
||||
use crate::{Run, Shaped};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod dirs;
|
||||
|
||||
/// One face of a font file (a TrueType collection holds several).
|
||||
#[derive(Clone)]
|
||||
pub struct Face {
|
||||
@@ -95,17 +92,6 @@ impl Face {
|
||||
Some(s.chars().filter(|c| !c.is_control()).take(80).collect::<String>()).filter(|s| !s.trim().is_empty())
|
||||
})
|
||||
}
|
||||
/// How tall the glyph of `c` is, from its lowest to its highest point, in ems: `None` when the
|
||||
/// face doesn't map `c` or its glyph has no outline (a space, or one too big to keep).
|
||||
pub fn glyph_height(&self, c: char) -> Option<f64> {
|
||||
let g = glyph(self, c);
|
||||
if !g.mapped {
|
||||
return None;
|
||||
}
|
||||
let (low, high) = g.contours.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), p| (low.min(p.y), high.max(p.y)));
|
||||
let height = (high - low) / f64::from(UPEM);
|
||||
(height.is_finite() && height > 0.0).then_some(height)
|
||||
}
|
||||
|
||||
/// The glyph ids the face's character map gives `chars` (`None` for an unmapped one).
|
||||
pub(crate) fn glyph_ids(&self, chars: &[char]) -> Vec<Option<u32>> {
|
||||
@@ -158,11 +144,7 @@ const MAX_CACHED_CHARS: usize = 50_000;
|
||||
pub(crate) const MAX_SHAPED_POINTS: usize = 8_000_000;
|
||||
|
||||
/// Fonts known to cover many scripts (CJK first), tried first for missing glyphs. Matched as
|
||||
/// substrings of the normalised file stem. The last two are the wide nets: GNU FreeSerif (most
|
||||
/// non-CJK scripts, with real OpenType shaping; in the default font set of NixOS and many
|
||||
/// distributions), then Unifont (every BMP character, as bitmap-like outlines; the only
|
||||
/// CJK-capable font of NixOS's default set) for what FreeSerif lacks. Both come before the
|
||||
/// alphabetical rest, which the bounded search never gets through.
|
||||
/// substrings of the normalised file stem.
|
||||
const PREFERRED_FALLBACK: &[&str] = &[
|
||||
"notosanscjk",
|
||||
"sourcehansans",
|
||||
@@ -186,8 +168,6 @@ const PREFERRED_FALLBACK: &[&str] = &[
|
||||
"dejavusans",
|
||||
"segoeui",
|
||||
"arial",
|
||||
"freeserif",
|
||||
"unifont",
|
||||
];
|
||||
/// Fonts known to cover a right-to-left script, tried before the general search for its
|
||||
/// characters (the general search loads a bounded number of files, and wide-coverage CJK fonts
|
||||
@@ -362,11 +342,11 @@ fn system_font_dirs() -> Vec<PathBuf> {
|
||||
dirs.push(PathBuf::from(l).join("Microsoft\\Windows\\Fonts"));
|
||||
}
|
||||
} else {
|
||||
// Where fontconfig looks: NixOS, Guix and Flatpak keep fonts outside /usr/share/fonts
|
||||
// (#674). Later directories take precedence (the stack pops them first), so the
|
||||
// resolver's priority order is reversed; [`scan_dirs`] reads each resolved
|
||||
// directory once and skips missing ones.
|
||||
dirs.extend(dirs::font_dirs(|k| std::env::var_os(k), dirs::read_config).into_iter().rev());
|
||||
dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(Into::into));
|
||||
if let Some(h) = std::env::var_os("HOME") {
|
||||
dirs.push(PathBuf::from(&h).join(".fonts"));
|
||||
dirs.push(PathBuf::from(h).join(".local/share/fonts"));
|
||||
}
|
||||
}
|
||||
dirs
|
||||
}
|
||||
@@ -886,16 +866,6 @@ pub fn find(name: &str) -> Option<Face> {
|
||||
r
|
||||
}
|
||||
|
||||
/// The installed font file with this stem (`DejaVuSans`, `NotoSansCJK-Regular`; case and an
|
||||
/// extension don't matter), wherever the system keeps its fonts. A font compiled in from
|
||||
/// craft-fonts is no file and gives `None`.
|
||||
pub fn installed_font_path(stem: &str) -> Option<PathBuf> {
|
||||
match lock().paths.get(&key(stem))? {
|
||||
Source::File(p) => Some(p.clone()),
|
||||
Source::Static(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
struct Prefs {
|
||||
alt: String,
|
||||
fallback: Vec<String>,
|
||||
@@ -1103,38 +1073,9 @@ pub fn descent_ratio(face: &Face) -> Option<f64> {
|
||||
(r.is_finite() && r > 0.0 && r < 2.0).then_some(r)
|
||||
}
|
||||
|
||||
/// Cap heights the installation pins for metric-compatible substitutes, from `CADCRAFT_CAP_HEIGHT`
|
||||
/// (`LiberationSans=715.8;LiberationSans-Bold=715.8`): a substitute keeps the advance widths of
|
||||
/// the font it stands in for but not its cap height, so scaling by the substitute's own OS/2
|
||||
/// value draws text the size of the substitute, not of the requested font. Each entry names a
|
||||
/// substitute's PostScript name and the cap height to give it, in font units at 1000 per em: the
|
||||
/// cap height of the font it replaces, not its own.
|
||||
fn cap_height_overrides() -> &'static HashMap<String, f64> {
|
||||
static OVERRIDES: OnceLock<HashMap<String, f64>> = OnceLock::new();
|
||||
OVERRIDES.get_or_init(|| parse_cap_height_overrides(&std::env::var("CADCRAFT_CAP_HEIGHT").unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Parse a `Name=height;…` list; entries without a name or with a height below 1 unit or not
|
||||
/// finite are dropped (a font's own cap height is never taken below 1 either: a tiny one would
|
||||
/// scale its glyphs past any drawing's extent). Names are matched normalised, like family names.
|
||||
fn parse_cap_height_overrides(spec: &str) -> HashMap<String, f64> {
|
||||
spec.split(';')
|
||||
.filter_map(|entry| {
|
||||
let (name, height) = entry.split_once('=')?;
|
||||
let height: f64 = height.trim().parse().ok()?;
|
||||
(height.is_finite() && height >= 1.0 && !name.trim().is_empty()).then(|| (norm(name.trim()), height))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Cap height of a font in font units at 1000 units per em: the value `CADCRAFT_CAP_HEIGHT`
|
||||
/// pins for this font's PostScript name, else the OS/2 value, else the height of its "H",
|
||||
/// else an estimate from the ascent.
|
||||
/// Cap height of a font in font units at 1000 units per em: the OS/2 value, else the height
|
||||
/// of its "H", else an estimate from the ascent.
|
||||
fn cap_height(f: &FontRef) -> f64 {
|
||||
let named = f.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).next().map(|s| norm(&s.to_string()));
|
||||
if let Some(height) = named.as_deref().and_then(|n| cap_height_overrides().get(n)) {
|
||||
return *height;
|
||||
}
|
||||
let metrics = f.metrics(Size::new(UPEM), LocationRef::default());
|
||||
let measured = || {
|
||||
let gid = f.charmap().map('H')?;
|
||||
@@ -1467,74 +1408,6 @@ mod family_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cap_height_override_tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[test]
|
||||
fn cap_height_env_parses_name_height_entries() {
|
||||
let m = parse_cap_height_overrides("LiberationSans=715.8;LiberationSans-Bold=715.8");
|
||||
let mut want = HashMap::new();
|
||||
want.insert("liberationsans".to_string(), 715.8);
|
||||
want.insert("liberationsansbold".to_string(), 715.8);
|
||||
assert_eq!(m, want);
|
||||
assert_eq!(
|
||||
parse_cap_height_overrides("LiberationSans = 715.8 ; NotoSansCJK=1466"),
|
||||
parse_cap_height_overrides("LiberationSans=715.8;NotoSansCJK=1466").into_iter().collect::<HashMap<_, _>>(),
|
||||
"spaces around names and heights are tolerated"
|
||||
);
|
||||
assert!(
|
||||
parse_cap_height_overrides("noheight;=5;Arial=0;Arial=-1;Arial=abc").is_empty(),
|
||||
"entries without a name or a positive finite height are dropped"
|
||||
);
|
||||
assert!(parse_cap_height_overrides("").is_empty());
|
||||
assert!(
|
||||
parse_cap_height_overrides("Arial=0.0001;Arial=1e-300").is_empty(),
|
||||
"a height below 1 unit is dropped, as `cap_height` never goes below 1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cap_height_override_applies_only_to_the_named_font() {
|
||||
let m = parse_cap_height_overrides("LiberationSans=715.8");
|
||||
assert_eq!(m.get(&norm("LiberationSans")), Some(&715.8));
|
||||
assert_eq!(m.get(&norm("Liberation Sans")), Some(&715.8), "names match normalised");
|
||||
assert_eq!(m.get(&norm("DejaVuSans")), None);
|
||||
assert_eq!(m.get(&norm("LiberationSans-Bold")), None);
|
||||
}
|
||||
|
||||
/// With no override for the face, `cap_height` walks its chain: the OS/2 value when the face
|
||||
/// has one, else the height of its "H", else an estimate from the ascent. Uses the first of
|
||||
/// these common fonts that is installed (Windows, macOS and Linux each have one); skips
|
||||
/// without any. No override is in play: `CADCRAFT_CAP_HEIGHT` names other faces, and the
|
||||
/// test binary's env is read once — a face this test does not name stays unoverridden.
|
||||
#[test]
|
||||
fn cap_height_without_an_override_follows_the_fallback_chain() {
|
||||
let found = ["Arial", "Helvetica", "DejaVuSans", "Verdana", "LiberationSans-Regular"].into_iter().find_map(find);
|
||||
let Some(face) = found else { return };
|
||||
let f = face.font().expect("the face parses");
|
||||
let named = f.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).next().map(|s| norm(&s.to_string())).unwrap_or_default();
|
||||
let m = f.metrics(Size::new(UPEM), LocationRef::default());
|
||||
let h_height = || {
|
||||
let gid = f.charmap().map('H')?;
|
||||
let b = f.glyph_metrics(Size::new(UPEM), LocationRef::default()).bounds(gid)?;
|
||||
Some(b.y_max).filter(|y| y.is_finite() && *y > 0.0)
|
||||
};
|
||||
let got = cap_height(&f);
|
||||
let want = if cap_height_overrides().contains_key(&named) {
|
||||
return; // this installation pins the face: the override leg is covered by the parser tests
|
||||
} else if let Some(cap) = m.cap_height.filter(|c| c.is_finite() && *c > 0.0) {
|
||||
f64::from(cap)
|
||||
} else if let Some(h) = h_height() {
|
||||
f64::from(h)
|
||||
} else {
|
||||
f64::from(m.ascent) * 0.72
|
||||
};
|
||||
assert!((got - want.max(1.0)).abs() < 1.0, "cap height {got} tracks the chain's value {want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod geometry_budget_tests {
|
||||
use super::*;
|
||||
@@ -1622,25 +1495,4 @@ mod scan_tests {
|
||||
#[cfg(all(unix, not(any(target_os = "macos", target_os = "android", target_env = "ohos"))))]
|
||||
assert!(dirs.iter().any(|d| d == std::path::Path::new("/usr/share/fonts")), "{dirs:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_symlink_back_up_the_tree_does_not_hide_the_other_font_directories() {
|
||||
let root = std::env::temp_dir().join(format!("cadcraft-font-walk-{}", std::process::id()));
|
||||
let (looped, other) = (root.join("looped"), root.join("other"));
|
||||
std::fs::create_dir_all(&looped).unwrap();
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
std::fs::write(looped.join("a.ttf"), b"").unwrap();
|
||||
// The kernel gives up on a symlink chain after about 40 hops; with this many entries,
|
||||
// reading the directory at every hop would still run past the 20 000 entry budget.
|
||||
for i in 0..600 {
|
||||
std::fs::write(looped.join(format!("readme{i}.txt")), b"").unwrap();
|
||||
}
|
||||
std::fs::write(other.join("b.ttf"), b"").unwrap();
|
||||
std::os::unix::fs::symlink(&looped, looped.join("again")).unwrap();
|
||||
// The looped directory is walked first.
|
||||
let found = scan_dirs(&[other.clone(), looped.clone()], false);
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
assert!(found.contains_key("a") && found.contains_key("b"), "{found:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,502 +0,0 @@
|
||||
//! Where installed fonts live on Linux and the BSDs, the way fontconfig finds them: the XDG base
|
||||
//! directories, the `<dir>` entries of fontconfig's configuration (NixOS and Guix keep each font
|
||||
//! package in its own store path, nowhere near `/usr/share/fonts`) and the host fonts a Flatpak
|
||||
//! sandbox mounts. Directories only: fontconfig's aliases and matching rules are not read.
|
||||
//!
|
||||
//! The resolver is a pure function of the environment and a configuration reader, so its tests
|
||||
//! run the same on every machine.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Bounds on a configuration a package or a user may have made hostile: files read, `<include>`
|
||||
/// nesting, bytes per file, elements per file, entries per path list, directories returned.
|
||||
const MAX_CONFIG_FILES: usize = 256;
|
||||
const MAX_INCLUDE_DEPTH: usize = 4;
|
||||
const MAX_CONFIG_BYTES: u64 = 1 << 20;
|
||||
const MAX_ELEMENTS: usize = 4096;
|
||||
const MAX_PATH_LIST: usize = 64;
|
||||
const MAX_DIRS: usize = 1024;
|
||||
|
||||
/// Where Flatpak mounts the host's system, local and user font directories in a sandbox (it also
|
||||
/// lists them in `/run/host/font-dirs.xml`, which the runtime's `fonts.conf` includes).
|
||||
const FLATPAK_FONT_DIRS: &[&str] = &["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"];
|
||||
|
||||
/// What an `<include>` names: a configuration file's text, or the `[0-9]*.conf` files of a
|
||||
/// directory, sorted, as fontconfig reads them.
|
||||
pub(super) enum Include {
|
||||
File(String),
|
||||
Dir(Vec<PathBuf>),
|
||||
}
|
||||
|
||||
/// Font directories in priority order, without duplicates: the user's XDG font directories,
|
||||
/// `$XDG_DATA_DIRS/fonts` (`/usr/local/share/fonts` and `/usr/share/fonts` whether listed or
|
||||
/// not), Flatpak's host font mounts, then the `<dir>` entries of fontconfig's configuration
|
||||
/// (`$FONTCONFIG_FILE`, else `fonts.conf` in the configuration path, following its `<include>`s;
|
||||
/// as in fontconfig, the path is `$FONTCONFIG_PATH`'s directories then `/etc/fonts`). `env` reads an
|
||||
/// environment variable, `read` a configuration file or directory (`None` when missing).
|
||||
pub(super) fn font_dirs(env: impl Fn(&str) -> Option<OsString>, read: impl Fn(&Path) -> Option<Include>) -> Vec<PathBuf> {
|
||||
let var = |k: &str| env(k).filter(|v| !v.is_empty());
|
||||
let home = var("HOME").map(PathBuf::from);
|
||||
let data_home = var("XDG_DATA_HOME").map(PathBuf::from).or_else(|| home.as_ref().map(|h| h.join(".local/share")));
|
||||
let config_home = var("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| home.as_ref().map(|h| h.join(".config")));
|
||||
let list = |k: &str, default: &str| -> Vec<PathBuf> {
|
||||
std::env::split_paths(&var(k).unwrap_or_else(|| default.into())).filter(|p| p.is_absolute()).take(MAX_PATH_LIST).collect()
|
||||
};
|
||||
let mut user: Vec<PathBuf> = data_home.iter().map(|d| d.join("fonts")).chain(home.iter().map(|h| h.join(".fonts"))).collect();
|
||||
user.extend(list("XDG_DATA_DIRS", "/usr/local/share:/usr/share").into_iter().map(|d| d.join("fonts")));
|
||||
user.extend(["/usr/local/share/fonts", "/usr/share/fonts"].iter().chain(FLATPAK_FONT_DIRS).map(PathBuf::from));
|
||||
let mut config_path = list("FONTCONFIG_PATH", "/etc/fonts");
|
||||
if !config_path.iter().any(|p| p == Path::new("/etc/fonts")) {
|
||||
config_path.push(PathBuf::from("/etc/fonts"));
|
||||
}
|
||||
let mut r = Resolver { home, data_home, config_home, config_path, read: &read, out: Vec::new(), visited: HashSet::new() };
|
||||
for d in user {
|
||||
r.add(d);
|
||||
}
|
||||
r.include(&var("FONTCONFIG_FILE").map(|f| f.to_string_lossy().into_owned()).unwrap_or_else(|| "fonts.conf".into()), None, 0);
|
||||
r.out
|
||||
}
|
||||
|
||||
struct Resolver<'a> {
|
||||
home: Option<PathBuf>,
|
||||
data_home: Option<PathBuf>,
|
||||
config_home: Option<PathBuf>,
|
||||
/// Where a relative top-level name is looked up: `$FONTCONFIG_PATH`'s directories, then
|
||||
/// `/etc/fonts`.
|
||||
config_path: Vec<PathBuf>,
|
||||
read: &'a dyn Fn(&Path) -> Option<Include>,
|
||||
out: Vec<PathBuf>,
|
||||
/// Configuration files and directories read: cycles and the file bound.
|
||||
visited: HashSet<PathBuf>,
|
||||
}
|
||||
|
||||
impl Resolver<'_> {
|
||||
fn add(&mut self, p: PathBuf) {
|
||||
if p.is_absolute() && self.out.len() < MAX_DIRS && !self.out.contains(&p) {
|
||||
self.out.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
/// A path with a leading `~` meaning `$HOME`.
|
||||
fn expand_home(&self, s: &str) -> Option<PathBuf> {
|
||||
match s.strip_prefix('~') {
|
||||
Some(rest) => self.home.as_ref().map(|h| h.join(rest.trim_start_matches('/'))),
|
||||
None => Some(PathBuf::from(s)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Follow an `<include>` (or the top-level file): an absolute name, or a relative one looked
|
||||
/// up in the configuration path. `here` is the including file's directory.
|
||||
fn include(&mut self, name: &str, here: Option<&Path>, depth: usize) {
|
||||
match self.expand_home(name) {
|
||||
Some(p) if p.is_absolute() => {
|
||||
self.config(&p, depth);
|
||||
}
|
||||
Some(p) => {
|
||||
let bases: Vec<PathBuf> = if here.is_some() { here.map(Path::to_path_buf).into_iter().collect() } else { self.config_path.clone() };
|
||||
for base in bases {
|
||||
if self.config(&base.join(&p), depth) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a configuration file (or every file of a directory) and its includes, nested at most
|
||||
/// `MAX_INCLUDE_DEPTH` deep. True when something was read.
|
||||
fn config(&mut self, file: &Path, depth: usize) -> bool {
|
||||
if depth > MAX_INCLUDE_DEPTH || self.visited.len() >= MAX_CONFIG_FILES || !self.visited.insert(file.to_path_buf()) {
|
||||
return false;
|
||||
}
|
||||
let xml = match (self.read)(file) {
|
||||
Some(Include::File(xml)) => xml,
|
||||
Some(Include::Dir(files)) => {
|
||||
for f in files.iter().take(MAX_CONFIG_FILES) {
|
||||
self.config(f, depth);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
None => return false,
|
||||
};
|
||||
let here = file.parent().map(Path::to_path_buf);
|
||||
for e in elements(&xml) {
|
||||
match (e.name, e.prefix) {
|
||||
("dir", Some("xdg")) => {
|
||||
if let Some(d) = self.data_home.as_ref().map(|d| d.join(&e.text)) {
|
||||
self.add(d);
|
||||
}
|
||||
}
|
||||
("dir", Some("relative")) => {
|
||||
if let Some(d) = here.as_ref().map(|h| h.join(&e.text)) {
|
||||
self.add(d);
|
||||
}
|
||||
}
|
||||
// "default", "cwd" or none: as written; a relative directory is skipped.
|
||||
("dir", _) => {
|
||||
if let Some(d) = self.expand_home(&e.text) {
|
||||
self.add(d);
|
||||
}
|
||||
}
|
||||
("include", Some("xdg")) => {
|
||||
if let Some(f) = self.config_home.as_ref().map(|c| c.join(&e.text)) {
|
||||
self.config(&f, depth + 1);
|
||||
}
|
||||
}
|
||||
("include", Some("relative")) => self.include(&e.text, here.as_deref(), depth + 1),
|
||||
("include", _) => self.include(&e.text, None, depth + 1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
struct Element<'a> {
|
||||
name: &'a str,
|
||||
prefix: Option<&'a str>,
|
||||
text: String,
|
||||
}
|
||||
|
||||
/// The `<dir>` and `<include>` elements of a configuration file with text, in order, with their
|
||||
/// `prefix` attribute; comments are skipped. A bounded scan over the text: fontconfig files are
|
||||
/// small and regular.
|
||||
fn elements(xml: &str) -> Vec<Element<'_>> {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = xml;
|
||||
while let Some(i) = rest.find('<') {
|
||||
let Some(tag) = rest.get(i + 1..) else { break };
|
||||
if let Some(c) = tag.strip_prefix("!--") {
|
||||
rest = c.find("-->").and_then(|j| c.get(j + 3..)).unwrap_or("");
|
||||
continue;
|
||||
}
|
||||
let Some(end) = tag.find('>') else { break };
|
||||
let (head, after) = (tag.get(..end).unwrap_or(""), tag.get(end + 1..).unwrap_or(""));
|
||||
rest = after;
|
||||
let (name, attrs) = head.split_once(char::is_whitespace).unwrap_or((head, ""));
|
||||
if !matches!(name, "dir" | "include") {
|
||||
continue;
|
||||
}
|
||||
let prefix = attribute(attrs, "prefix");
|
||||
let text = unescape(after.split('<').next().unwrap_or("").trim());
|
||||
if !text.is_empty() {
|
||||
out.push(Element { name, prefix, text });
|
||||
}
|
||||
if out.len() >= MAX_ELEMENTS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The value of the attribute `name` in a start tag's attribute list: name, optional whitespace,
|
||||
/// `=`, optional whitespace, a single- or double-quoted value, in any order. `None` when absent
|
||||
/// or not well-formed up to it.
|
||||
fn attribute<'a>(attrs: &'a str, name: &str) -> Option<&'a str> {
|
||||
let mut rest = attrs;
|
||||
loop {
|
||||
rest = rest.trim_start();
|
||||
let key_end = rest.find(|c: char| c == '=' || c.is_whitespace())?;
|
||||
let key = rest.get(..key_end)?;
|
||||
rest = rest.get(key_end..)?.trim_start().strip_prefix('=')?.trim_start();
|
||||
let quote = rest.chars().next().filter(|c| matches!(c, '"' | '\''))?;
|
||||
rest = rest.get(1..)?;
|
||||
let value_end = rest.find(quote)?;
|
||||
let value = rest.get(..value_end)?;
|
||||
if key == name {
|
||||
return Some(value);
|
||||
}
|
||||
rest = rest.get(value_end + 1..)?;
|
||||
}
|
||||
}
|
||||
|
||||
fn unescape(s: &str) -> String {
|
||||
if !s.contains('&') {
|
||||
return s.to_string();
|
||||
}
|
||||
s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&")
|
||||
}
|
||||
|
||||
/// Read a configuration file (skipped beyond `MAX_CONFIG_BYTES`) or list a directory's
|
||||
/// `[0-9]*.conf` files, sorted.
|
||||
pub(super) fn read_config(path: &Path) -> Option<Include> {
|
||||
use std::io::Read as _;
|
||||
if path.is_dir() {
|
||||
let conf =
|
||||
|p: &Path| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.ends_with(".conf"));
|
||||
let mut files: Vec<PathBuf> = std::fs::read_dir(path).ok()?.flatten().map(|e| e.path()).filter(|p| conf(p)).take(MAX_CONFIG_FILES).collect();
|
||||
files.sort();
|
||||
return Some(Include::Dir(files));
|
||||
}
|
||||
let mut xml = String::new();
|
||||
std::fs::File::open(path).ok()?.take(MAX_CONFIG_BYTES.saturating_add(1)).read_to_string(&mut xml).ok()?;
|
||||
(xml.len() as u64 <= MAX_CONFIG_BYTES).then_some(Include::File(xml))
|
||||
}
|
||||
|
||||
/// The tests build configurations from POSIX paths such as `/usr/share/fonts`, which only a Unix
|
||||
/// `Path` takes as absolute, so they run on Unix only; the resolver itself builds everywhere.
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn env_of<'a>(vars: &'a [(&str, &str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
|
||||
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
|
||||
}
|
||||
|
||||
fn reader<'a>(files: &'a [(&str, &str)], dirs: &'a [(&str, &[&str])]) -> impl Fn(&Path) -> Option<Include> + 'a {
|
||||
move |p| {
|
||||
if let Some((_, xml)) = files.iter().find(|(n, _)| Path::new(n) == p) {
|
||||
return Some(Include::File((*xml).to_string()));
|
||||
}
|
||||
dirs.iter().find(|(n, _)| Path::new(n) == p).map(|(_, fs)| Include::Dir(fs.iter().map(PathBuf::from).collect()))
|
||||
}
|
||||
}
|
||||
|
||||
fn paths(v: &[&str]) -> Vec<PathBuf> {
|
||||
v.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
const XDG: &[&str] = &["/usr/local/share/fonts", "/usr/share/fonts", "/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"];
|
||||
|
||||
#[test]
|
||||
fn xdg_defaults_without_variables() {
|
||||
let d = font_dirs(env_of(&[("HOME", "/home/u")]), |_| None);
|
||||
assert_eq!(d, paths(&[&["/home/u/.local/share/fonts", "/home/u/.fonts"], XDG].concat()));
|
||||
assert_eq!(font_dirs(|_| None, |_| None), paths(XDG), "no HOME: system directories only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xdg_variables_name_the_font_dirs() {
|
||||
let env = env_of(&[
|
||||
("HOME", "/home/u"),
|
||||
("XDG_DATA_HOME", "/data"),
|
||||
("XDG_DATA_DIRS", "/nix/profile/share:/run/current-system/sw/share:relative:/usr/share/:"),
|
||||
]);
|
||||
let d = font_dirs(env, |_| None);
|
||||
assert_eq!(
|
||||
d.get(..6),
|
||||
Some(
|
||||
paths(&[
|
||||
"/data/fonts",
|
||||
"/home/u/.fonts",
|
||||
"/nix/profile/share/fonts",
|
||||
"/run/current-system/sw/share/fonts",
|
||||
"/usr/share/fonts",
|
||||
"/usr/local/share/fonts"
|
||||
])
|
||||
.as_slice()
|
||||
)
|
||||
);
|
||||
assert_eq!(d.len(), 9, "{d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fontconfig_dirs_nixos_style() {
|
||||
let files = [
|
||||
(
|
||||
"/etc/fonts/fonts.conf",
|
||||
"<?xml version=\"1.0\"?>\n<!DOCTYPE fontconfig SYSTEM \"urn:fontconfig:fonts.dtd\">\n<fontconfig>\n\
|
||||
<!-- Font directory list -->\n<cachedir prefix=\"xdg\">fontconfig</cachedir>\n\
|
||||
<include ignore_missing=\"yes\">/etc/fonts/conf.d</include>\n<dir prefix=\"xdg\">fonts</dir>\n\
|
||||
<dir>/nix/store/aaa-dejavu-fonts-minimal-2.37</dir>\n</fontconfig>\n",
|
||||
),
|
||||
(
|
||||
"/etc/fonts/conf.d/00-nixos-cache.conf",
|
||||
"<fontconfig>\n <!-- Font directories -->\n <dir>/nix/store/bbb-dejavu-fonts-2.37</dir>\n<dir salt=\"x\">/nix/store/ccc-unifont-16.0.03</dir>\n\
|
||||
<!-- <dir>/commented/out</dir> -->\n <cachedir>/nix/store/ddd-fc-cache</cachedir>\n</fontconfig>\n",
|
||||
),
|
||||
(
|
||||
"/etc/fonts/conf.d/50-user.conf",
|
||||
"<fontconfig>\n<include ignore_missing=\"yes\" prefix=\"xdg\">fontconfig/conf.d</include>\n</fontconfig>\n",
|
||||
),
|
||||
(
|
||||
"/home/u/.config/fontconfig/conf.d/10-hm-fonts.conf",
|
||||
"<fontconfig>\n<include ignore_missing=\"yes\">/nix/store/eee-home-manager-path/etc/fonts/conf.d</include>\n\
|
||||
<dir>/nix/store/eee-home-manager-path/share/fonts</dir>\n<dir>/etc/profiles/per-user/u/share/fonts</dir>\n</fontconfig>\n",
|
||||
),
|
||||
];
|
||||
let dirs: [(&str, &[&str]); 2] = [
|
||||
("/etc/fonts/conf.d", &["/etc/fonts/conf.d/00-nixos-cache.conf", "/etc/fonts/conf.d/50-user.conf"]),
|
||||
("/home/u/.config/fontconfig/conf.d", &["/home/u/.config/fontconfig/conf.d/10-hm-fonts.conf"]),
|
||||
];
|
||||
let d = font_dirs(env_of(&[("HOME", "/home/u"), ("XDG_DATA_DIRS", "/etc/profiles/per-user/u/share")]), reader(&files, &dirs));
|
||||
let expect = [
|
||||
"/home/u/.local/share/fonts",
|
||||
"/home/u/.fonts",
|
||||
"/etc/profiles/per-user/u/share/fonts",
|
||||
"/usr/local/share/fonts",
|
||||
"/usr/share/fonts",
|
||||
"/run/host/fonts",
|
||||
"/run/host/local-fonts",
|
||||
"/run/host/user-fonts",
|
||||
"/nix/store/bbb-dejavu-fonts-2.37",
|
||||
"/nix/store/ccc-unifont-16.0.03",
|
||||
"/nix/store/eee-home-manager-path/share/fonts",
|
||||
"/nix/store/aaa-dejavu-fonts-minimal-2.37",
|
||||
];
|
||||
assert_eq!(d, paths(&expect));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fontconfig_dirs_debian_style() {
|
||||
let files = [
|
||||
(
|
||||
"/etc/fonts/fonts.conf",
|
||||
"<fontconfig>\n<dir>/usr/share/fonts</dir>\n<dir>/usr/local/share/fonts</dir>\n<dir prefix=\"xdg\">fonts</dir>\n\
|
||||
<dir>~/.fonts</dir>\n<dir>/opt/fonts & more</dir>\n<dir>relative/skipped</dir>\n<dir prefix=\"cwd\">also/skipped</dir>\n\
|
||||
<include ignore_missing=\"yes\">conf.d</include>\n</fontconfig>\n",
|
||||
),
|
||||
("/etc/fonts/conf.d/51-local.conf", "<fontconfig><include ignore_missing=\"yes\">local.conf</include></fontconfig>"),
|
||||
("/etc/fonts/conf.d/52-site.conf", "<fontconfig><include prefix=\"relative\">../site/fonts.conf</include></fontconfig>"),
|
||||
("/etc/fonts/local.conf", "<fontconfig><dir>/srv/fonts</dir><dir prefix=\"relative\">more</dir></fontconfig>"),
|
||||
("/etc/fonts/conf.d/../site/fonts.conf", "<fontconfig><dir>/site/fonts</dir></fontconfig>"),
|
||||
];
|
||||
let dirs: [(&str, &[&str]); 1] = [("/etc/fonts/conf.d", &["/etc/fonts/conf.d/51-local.conf", "/etc/fonts/conf.d/52-site.conf"])];
|
||||
let d = font_dirs(env_of(&[("HOME", "/home/u")]), reader(&files, &dirs));
|
||||
let tail: Vec<PathBuf> = d.iter().skip(7).cloned().collect();
|
||||
assert_eq!(tail, paths(&["/opt/fonts & more", "/srv/fonts", "/etc/fonts/more", "/site/fonts"]));
|
||||
assert_eq!(d.len(), 11, "the directories already listed are not repeated: {d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fontconfig_file_and_path_variables() {
|
||||
let files = [("/cfg/custom.conf", "<fontconfig><dir>/custom/fonts</dir></fontconfig>")];
|
||||
let env = env_of(&[("FONTCONFIG_FILE", "custom.conf"), ("FONTCONFIG_PATH", "/nowhere:/cfg")]);
|
||||
let d = font_dirs(env, reader(&files, &[]));
|
||||
assert_eq!(d.last(), Some(&PathBuf::from("/custom/fonts")));
|
||||
let d = font_dirs(env_of(&[("FONTCONFIG_FILE", "/cfg/custom.conf")]), reader(&files, &[]));
|
||||
assert_eq!(d.last(), Some(&PathBuf::from("/custom/fonts")));
|
||||
assert_eq!(font_dirs(env_of(&[("FONTCONFIG_FILE", "/cfg/missing.conf")]), reader(&files, &[])), paths(XDG));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fontconfig_path_names_the_default_configuration() {
|
||||
// FONTCONFIG_PATH alone: its fonts.conf is the configuration, and /etc/fonts still
|
||||
// follows it in the path, as in fontconfig.
|
||||
let files = [
|
||||
("/cfg/fonts.conf", "<fontconfig><dir>/cfg/fonts</dir></fontconfig>"),
|
||||
("/etc/fonts/fonts.conf", "<fontconfig><dir>/etc/listed</dir></fontconfig>"),
|
||||
];
|
||||
let d = font_dirs(env_of(&[("FONTCONFIG_PATH", "/nowhere:/cfg")]), reader(&files, &[]));
|
||||
assert_eq!(d.last(), Some(&PathBuf::from("/cfg/fonts")), "{d:?}");
|
||||
let d = font_dirs(env_of(&[("FONTCONFIG_PATH", "/nowhere")]), reader(&files, &[]));
|
||||
assert_eq!(d.last(), Some(&PathBuf::from("/etc/listed")), "{d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefix_attributes_with_whitespace_around_equals() {
|
||||
// Legal XML: whitespace, newlines included, on either side of '=', attributes in any
|
||||
// order. /cfg is not on the configuration path, so a relative include or directory is
|
||||
// found only through its prefix.
|
||||
let files = [
|
||||
(
|
||||
"/cfg/fonts.conf",
|
||||
"<fontconfig>\n<dir prefix = \"relative\">extra-fonts</dir>\n<dir\n prefix\n =\n 'xdg'\n>more-fonts</dir>\n\
|
||||
<include ignore_missing = \"yes\" prefix = \"xdg\">fontconfig/fonts.conf</include>\n\
|
||||
<include\n\tignore_missing=\"yes\"\n\tprefix\n\t=\n\t\"relative\"\n>site.conf</include>\n</fontconfig>\n",
|
||||
),
|
||||
("/home/u/.config/fontconfig/fonts.conf", "<fontconfig><dir>/xdg-included</dir></fontconfig>"),
|
||||
("/cfg/site.conf", "<fontconfig><dir>/site-included</dir></fontconfig>"),
|
||||
];
|
||||
let env = env_of(&[("HOME", "/home/u"), ("XDG_DATA_HOME", "/data"), ("FONTCONFIG_FILE", "/cfg/fonts.conf")]);
|
||||
let d = font_dirs(env, reader(&files, &[]));
|
||||
let tail: Vec<PathBuf> = d.iter().skip(XDG.len() + 2).cloned().collect();
|
||||
assert_eq!(tail, paths(&["/cfg/extra-fonts", "/data/more-fonts", "/xdg-included", "/site-included"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn include_cycles_and_depth_are_bounded() {
|
||||
let files = [
|
||||
("/etc/fonts/fonts.conf", "<fontconfig><dir>/d0</dir><include>/etc/fonts/b.conf</include></fontconfig>"),
|
||||
(
|
||||
"/etc/fonts/b.conf",
|
||||
"<fontconfig><dir>/d1</dir><include>/etc/fonts/fonts.conf</include><include>/etc/fonts/b.conf</include></fontconfig>",
|
||||
),
|
||||
];
|
||||
let d = font_dirs(|_| None, reader(&files, &[]));
|
||||
assert_eq!(d.iter().skip(XDG.len()).cloned().collect::<Vec<_>>(), paths(&["/d0", "/d1"]));
|
||||
|
||||
let chain: Vec<(String, String)> = (0..10)
|
||||
.map(|i| {
|
||||
(format!("/etc/fonts/{i}.conf"), format!("<fontconfig><dir>/depth{i}</dir><include>/etc/fonts/{}.conf</include></fontconfig>", i + 1))
|
||||
})
|
||||
.collect();
|
||||
let read = |p: &Path| chain.iter().find(|(n, _)| Path::new(n) == p).map(|(_, xml)| Include::File(xml.clone()));
|
||||
let d = font_dirs(env_of(&[("FONTCONFIG_FILE", "/etc/fonts/0.conf")]), read);
|
||||
let depths: Vec<&PathBuf> = d.iter().skip(XDG.len()).collect();
|
||||
assert_eq!(depths.len(), MAX_INCLUDE_DEPTH + 1, "{depths:?}");
|
||||
assert_eq!(depths.last().map(|p| p.as_path()), Some(Path::new("/depth4")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_files_are_bounded() {
|
||||
let names: Vec<String> = (0..1000).map(|i| format!("/etc/fonts/conf.d/{i:04}.conf")).collect();
|
||||
let read = |p: &Path| {
|
||||
if p == Path::new("/etc/fonts/fonts.conf") {
|
||||
return Some(Include::File("<fontconfig><include>/etc/fonts/conf.d</include></fontconfig>".into()));
|
||||
}
|
||||
if p == Path::new("/etc/fonts/conf.d") {
|
||||
return Some(Include::Dir(names.iter().map(PathBuf::from).collect()));
|
||||
}
|
||||
p.starts_with("/etc/fonts/conf.d").then(|| Include::File(format!("<fontconfig><dir>{}</dir></fontconfig>", p.display())))
|
||||
};
|
||||
let d = font_dirs(|_| None, read);
|
||||
assert!(d.len() <= XDG.len() + MAX_CONFIG_FILES, "{}", d.len());
|
||||
assert!(d.len() > XDG.len() + 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elements_survive_odd_markup() {
|
||||
let xml = "<dir><dir>/unterminated<include>/x</include><dir prefix='relative'>r</dir><dir></dir><!-- never closed <dir>/no</dir>";
|
||||
let e = elements(xml);
|
||||
let got: Vec<(&str, Option<&str>, &str)> = e.iter().map(|e| (e.name, e.prefix, e.text.as_str())).collect();
|
||||
assert_eq!(got, [("dir", None, "/unterminated"), ("include", None, "/x"), ("dir", Some("relative"), "r")]);
|
||||
assert!(elements("").is_empty());
|
||||
assert!(elements("<").is_empty());
|
||||
assert!(elements("<dir").is_empty());
|
||||
let huge: String = "<dir>/a</dir>".repeat(MAX_ELEMENTS * 2);
|
||||
assert_eq!(elements(&huge).len(), MAX_ELEMENTS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_in_any_order_and_spacing() {
|
||||
let prefix = |xml: &str| elements(xml).first().and_then(|e| e.prefix).map(str::to_string);
|
||||
assert_eq!(prefix("<dir salt=\"x\" prefix='xdg'>f</dir>"), Some("xdg".into()));
|
||||
assert_eq!(prefix("<dir prefix=\"relative\" salt=\"x\">f</dir>"), Some("relative".into()));
|
||||
assert_eq!(prefix("<dir salt = 'prefix=\"xdg\"' prefix = \"cwd\">f</dir>"), Some("cwd".into()), "a value is not an attribute");
|
||||
assert_eq!(prefix("<include\nignore_missing = \"yes\"\nprefix\n=\n\"xdg\"\n>f</include>"), Some("xdg".into()));
|
||||
assert_eq!(prefix("<dir prefix=xdg>f</dir>"), None, "an unquoted value is not well-formed");
|
||||
assert_eq!(prefix("<dir prefix>f</dir>"), None);
|
||||
assert_eq!(prefix("<dir prefix=\"unterminated>f</dir>"), None);
|
||||
assert_eq!(prefix("<dir salt=\"x\">f</dir>"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_config_skips_oversize_files_and_lists_conf_files() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"cadcraft-fontdirs-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::UNIX_EPOCH.elapsed().map(|d| d.as_nanos()).unwrap_or(0)
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("10-small.conf"), "<fontconfig><dir>/small</dir></fontconfig>").unwrap();
|
||||
std::fs::write(dir.join("05-first.conf"), "<fontconfig/>").unwrap();
|
||||
std::fs::write(dir.join("README"), "not a config").unwrap();
|
||||
std::fs::write(dir.join("local.conf"), "<fontconfig/>").unwrap();
|
||||
std::fs::write(dir.join("99-big.conf"), vec![b' '; (MAX_CONFIG_BYTES + 1) as usize]).unwrap();
|
||||
match read_config(&dir) {
|
||||
Some(Include::Dir(files)) => assert_eq!(files, [dir.join("05-first.conf"), dir.join("10-small.conf"), dir.join("99-big.conf")]),
|
||||
_ => panic!("a directory lists its [0-9]*.conf files"),
|
||||
}
|
||||
assert!(matches!(read_config(&dir.join("10-small.conf")), Some(Include::File(x)) if x.contains("/small")));
|
||||
assert!(read_config(&dir.join("99-big.conf")).is_none(), "oversize file skipped");
|
||||
assert!(read_config(&dir.join("missing.conf")).is_none());
|
||||
let small = dir.join("10-small.conf").to_string_lossy().into_owned();
|
||||
let d = font_dirs(env_of(&[("FONTCONFIG_FILE", &small)]), read_config);
|
||||
assert_eq!(d.last(), Some(&PathBuf::from("/small")));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -109,66 +109,6 @@ fn reversed_columns_run_right_to_left() {
|
||||
assert!(first > 0 && second > 0 && min_x(&l) >= 0.0);
|
||||
}
|
||||
|
||||
/// The geometry points inside `b`.
|
||||
fn points_in(l: &MTextLayout, b: &cadcraft_geom::Bounds2) -> usize {
|
||||
l.strokes.iter().flatten().filter(|p| b.contains(**p)).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_column_has_its_own_box_without_the_gutter() {
|
||||
let two = lay(&"word ".repeat(12), 10.0, Some(MTextColumnSpec { count: 2, gutter: 2.0, height: 6.0, ..Default::default() }));
|
||||
let [a, b] = two.column_bounds.as_slice() else { panic!("{:?}", two.column_bounds) };
|
||||
assert!(two.bounds.contains_box(a) && two.bounds.contains_box(b));
|
||||
assert!(a.max.x < b.min.x, "the gutter lies between the columns: {a:?} {b:?}");
|
||||
assert!(a.width() + b.width() < two.bounds.width());
|
||||
let total = two.strokes.iter().map(Vec::len).sum::<usize>();
|
||||
assert!(points_in(&two, a) > 0 && points_in(&two, b) > 0);
|
||||
assert_eq!(points_in(&two, a) + points_in(&two, b), total, "every point is in its column's box");
|
||||
|
||||
// Three static columns, the text filling two and a half: the half-full column keeps the
|
||||
// column height; text past the last column lengthens only that one.
|
||||
let spec = MTextColumnSpec { count: 3, gutter: 2.0, height: 6.0, ..Default::default() };
|
||||
let three = lay(&"word ".repeat(20), 10.0, Some(spec.clone()));
|
||||
assert_eq!(three.column_bounds.len(), 3);
|
||||
assert!(three.column_bounds.windows(2).all(|w| w[0].max.x < w[1].min.x && (w[0].height() - w[1].height()).abs() < 1e-9));
|
||||
let over = lay(&"word ".repeat(40), 10.0, Some(spec));
|
||||
let [first, .., last] = over.column_bounds.as_slice() else { panic!("{:?}", over.column_bounds) };
|
||||
assert!(last.height() > first.height() && (last.height() - over.bounds.height()).abs() < 1e-9);
|
||||
|
||||
// Manual heights: each column as tall as its own height.
|
||||
let manual = lay("one\\Ntwo", 5.0, Some(MTextColumnSpec { dynamic: true, heights: vec![3.0, 5.0], ..Default::default() }));
|
||||
let [a, b] = manual.column_bounds.as_slice() else { panic!("{:?}", manual.column_bounds) };
|
||||
assert!(a.height() < b.height());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_column_keeps_its_place() {
|
||||
let l = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 3, gutter: 1.0, height: 4.0, ..Default::default() }));
|
||||
let [a, b, c] = l.column_bounds.as_slice() else { panic!("{:?}", l.column_bounds) };
|
||||
assert!(a.max.x < b.min.x && b.max.x < c.min.x);
|
||||
assert!(points_in(&l, a) > 0 && points_in(&l, b) > 0 && points_in(&l, c) == 0);
|
||||
assert!((c.max.x - l.bounds.max.x).abs() < 1e-9 && (c.height() - a.height()).abs() < 1e-9);
|
||||
// Reversed: the column the text starts in is the rightmost.
|
||||
let r = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 2, height: 1.0, reversed: true, ..Default::default() }));
|
||||
let [a, b] = r.column_bounds.as_slice() else { panic!("{:?}", r.column_bounds) };
|
||||
assert!(a.min.x > b.max.x - 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_column_is_the_whole_box() {
|
||||
let rotated = |p: MTextParams| MTextParams { rotation: 0.4, attach: 5, insert: Vec2::new(3.0, -2.0), ..p };
|
||||
for (s, width, columns) in [
|
||||
("plain text that wraps a few times", 6.0, None),
|
||||
("\\pxl1;paragraph text that wraps\\Pagain", 6.0, None),
|
||||
("no width\\Pat all", 0.0, None),
|
||||
(&*"word ".repeat(30), 10.0, Some(MTextColumnSpec { count: 1, gutter: 5.0, height: 3.0, ..Default::default() })),
|
||||
("one\\Ptwo", 10.0, Some(MTextColumnSpec { dynamic: true, gutter: 5.0, height: 30.0, ..Default::default() })),
|
||||
] {
|
||||
let l = layout_mtext_with(s, &rotated(MTextParams { width, columns, ..MTextParams::new(Vec2::ZERO, 1.0) }));
|
||||
assert_eq!(l.column_bounds, vec![l.bounds], "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_paragraph_codes_do_not_panic() {
|
||||
let huge_tabs = format!("\\pt{};a\tb", (0..100_000).map(|i| i.to_string()).collect::<Vec<_>>().join(","));
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
//! A synthetic TrueType (sfnt) font file, built in code for tests that need a real font without a
|
||||
//! font file in the repository or one installed on the machine: `head`, `hhea`, `maxp`, `hmtx`,
|
||||
//! `glyf`, `loca`, a format-4 `cmap` and `OS/2`, laid out in a sorted table directory.
|
||||
//!
|
||||
//! Test-only, and shared: `crates/render/src/tests.rs` (the level-of-detail fixture) and
|
||||
//! `crates/io/tests/pdf_text.rs` (the PDF writer's embedding fixtures) build their fonts with it,
|
||||
//! each including this file with `#[path]`, so neither needs a published API, a dependency or a
|
||||
//! copy of the other's tables. `crates/fonts` is the layer that reads those tables
|
||||
//! (`crates/fonts/src/ttf.rs`), which is why the skeleton lives beside its tests; the glyph shapes,
|
||||
//! the character map ranges and the metrics a font records stay at the caller that needs them.
|
||||
|
||||
fn be16(v: &mut Vec<u8>, x: u16) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
|
||||
fn be32(v: &mut Vec<u8>, x: u32) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
|
||||
/// A simple glyph, with the point and contour counts `maxp` records for the font.
|
||||
pub struct Glyph {
|
||||
bytes: Vec<u8>,
|
||||
points: usize,
|
||||
contours: usize,
|
||||
}
|
||||
|
||||
/// `.notdef`: no contours, no bytes.
|
||||
pub fn notdef() -> Glyph {
|
||||
Glyph { bytes: Vec::new(), points: 0, contours: 0 }
|
||||
}
|
||||
|
||||
/// One simple glyph: closed contours of on-curve points, with the box the file records for it.
|
||||
pub fn glyph(contours: &[Vec<(i16, i16)>]) -> Glyph {
|
||||
let points: Vec<(i16, i16)> = contours.iter().flatten().copied().collect();
|
||||
let mut g = Vec::new();
|
||||
be16(&mut g, contours.len() as u16);
|
||||
let box_ = points.iter().fold((i16::MAX, i16::MAX, i16::MIN, i16::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));
|
||||
for v in [box_.0, box_.1, box_.2, box_.3] {
|
||||
be16(&mut g, v as u16);
|
||||
}
|
||||
let mut end = 0u16;
|
||||
for c in contours {
|
||||
end = end.saturating_add(c.len() as u16);
|
||||
be16(&mut g, end.saturating_sub(1));
|
||||
}
|
||||
be16(&mut g, 0);
|
||||
g.extend(std::iter::repeat_n(1u8, points.len()));
|
||||
let (mut px, mut py) = (0i16, 0i16);
|
||||
for (x, _) in &points {
|
||||
be16(&mut g, x.wrapping_sub(px) as u16);
|
||||
px = *x;
|
||||
}
|
||||
for (_, y) in &points {
|
||||
be16(&mut g, y.wrapping_sub(py) as u16);
|
||||
py = *y;
|
||||
}
|
||||
while g.len() % 4 != 0 {
|
||||
g.push(0);
|
||||
}
|
||||
Glyph { bytes: g, points: points.len(), contours: contours.len() }
|
||||
}
|
||||
|
||||
/// What the callers differ in; every other table field is the same in each font this builds.
|
||||
pub struct Sfnt<'a> {
|
||||
/// `glyf` entries, `.notdef` first.
|
||||
pub glyphs: &'a [Glyph],
|
||||
/// `cmap` format-4 segments: first character code, last character code, and glyph id minus
|
||||
/// code. The `0xFFFF` segment that ends the map is added here.
|
||||
pub cmap: &'a [(u16, u16, i16)],
|
||||
/// The advance width every glyph shares, in em units.
|
||||
pub advance: u16,
|
||||
/// The left side bearing every glyph shares.
|
||||
pub lsb: i16,
|
||||
/// `hmtx` entries written. Fewer than the glyphs `hhea` declares is a deliberately short
|
||||
/// table: that font is malformed on purpose, and a reader must cope with it, not repair it.
|
||||
pub metrics: usize,
|
||||
/// `OS/2` `fsType`: the embedding permissions, `0` for any use.
|
||||
pub fs_type: u16,
|
||||
/// `head`'s ink box: xMin, yMin, xMax, yMax.
|
||||
pub ink_box: [i16; 4],
|
||||
}
|
||||
|
||||
/// Em units per em: with a 700-unit cap height, one em is 1000 units, so a text height of one unit
|
||||
/// is a cap height of one unit.
|
||||
const UNITS_PER_EM: u16 = 1000;
|
||||
|
||||
/// The font file `f` describes, as a TrueType file.
|
||||
pub fn bytes(f: &Sfnt<'_>) -> Vec<u8> {
|
||||
let mut glyf = Vec::new();
|
||||
let mut loca = Vec::new();
|
||||
for g in f.glyphs {
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
glyf.extend_from_slice(&g.bytes);
|
||||
}
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
let mut head = Vec::new();
|
||||
be32(&mut head, 0x0001_0000); // version
|
||||
be32(&mut head, 0x0001_0000); // fontRevision
|
||||
be32(&mut head, 0); // checkSumAdjustment
|
||||
be32(&mut head, 0x5F0F_3CF5); // magic
|
||||
be16(&mut head, 0); // flags
|
||||
be16(&mut head, UNITS_PER_EM);
|
||||
head.extend_from_slice(&[0; 16]); // created, modified
|
||||
for v in f.ink_box {
|
||||
be16(&mut head, v as u16);
|
||||
}
|
||||
// macStyle, lowestRecPPEM, fontDirectionHint, indexToLocFormat 1 = long offsets (`loca` holds
|
||||
// `u32`), glyphDataFormat.
|
||||
for v in [0u16, 8, 2, 1, 0] {
|
||||
be16(&mut head, v);
|
||||
}
|
||||
let mut hhea = Vec::new();
|
||||
be32(&mut hhea, 0x0001_0000);
|
||||
// ascender, descender, lineGap, advanceWidthMax, minLeftSideBearing, minRightSideBearing,
|
||||
// xMaxExtent, caretSlopeRise, caretSlopeRun, caretOffset, four reserved, metricDataFormat.
|
||||
for v in [800i16, -200, 0, f.advance as i16, 0, 0, f.advance as i16, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut hhea, v as u16);
|
||||
}
|
||||
be16(&mut hhea, f.glyphs.len() as u16); // numberOfHMetrics
|
||||
let max_points = f.glyphs.iter().map(|g| g.points).max().unwrap_or(0);
|
||||
let max_contours = f.glyphs.iter().map(|g| g.contours).max().unwrap_or(0);
|
||||
let mut maxp = Vec::new();
|
||||
be32(&mut maxp, 0x0001_0000);
|
||||
// numGlyphs, maxPoints, maxContours, maxCompositePoints, maxCompositeContours, maxZones, and
|
||||
// the composite and instruction maxima after them.
|
||||
for v in [f.glyphs.len() as u16, max_points as u16, max_contours as u16, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut maxp, v);
|
||||
}
|
||||
let mut hmtx = Vec::new();
|
||||
for _ in 0..f.metrics {
|
||||
be16(&mut hmtx, f.advance);
|
||||
be16(&mut hmtx, f.lsb as u16);
|
||||
}
|
||||
// cmap: version 0 with one encoding record (Windows, Unicode BMP), a format-4 subtable over
|
||||
// the caller's segments and the `0xFFFF` one that ends it.
|
||||
let segs: Vec<(u16, u16, i16)> = f.cmap.iter().copied().chain([(0xFFFF, 0xFFFF, 1)]).collect();
|
||||
let seg_count = segs.len() as u32;
|
||||
let seg_selector = seg_count.ilog2();
|
||||
let seg_search_range = 2 * (1 << seg_selector);
|
||||
let mut sub = Vec::new();
|
||||
be16(&mut sub, 4); // format
|
||||
be16(&mut sub, (16 + segs.len() * 8) as u16); // length
|
||||
be16(&mut sub, 0); // language
|
||||
be16(&mut sub, (segs.len() * 2) as u16); // segCountX2
|
||||
for v in [seg_search_range as u16, seg_selector as u16, (2 * seg_count - seg_search_range) as u16] {
|
||||
be16(&mut sub, v);
|
||||
}
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.1);
|
||||
}
|
||||
be16(&mut sub, 0); // reservedPad
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.0);
|
||||
}
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.2 as u16);
|
||||
}
|
||||
for _ in &segs {
|
||||
be16(&mut sub, 0); // idRangeOffset
|
||||
}
|
||||
let mut cmap = Vec::new();
|
||||
for v in [0u16, 1, 3, 1] {
|
||||
be16(&mut cmap, v);
|
||||
}
|
||||
be32(&mut cmap, 12); // the subtable, straight after the records
|
||||
cmap.extend_from_slice(&sub);
|
||||
let mut os2 = vec![0u8; 78];
|
||||
os2[8..10].copy_from_slice(&f.fs_type.to_be_bytes());
|
||||
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
|
||||
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
|
||||
tables.sort_by_key(|t| *t.0);
|
||||
let mut out = Vec::new();
|
||||
be32(&mut out, 0x0001_0000); // sfnt version 1.0
|
||||
let num_tables = tables.len() as u32;
|
||||
let table_selector = num_tables.ilog2();
|
||||
let dir_search_range = 16 * (1 << table_selector);
|
||||
// numTables, searchRange, entrySelector, rangeShift: 16-byte records, largest power of two first.
|
||||
for v in [num_tables as u16, dir_search_range as u16, table_selector as u16, (16 * num_tables - dir_search_range) as u16] {
|
||||
be16(&mut out, v);
|
||||
}
|
||||
let mut off = 12 + 16 * tables.len();
|
||||
for (t, d) in &tables {
|
||||
out.extend_from_slice(*t);
|
||||
be32(&mut out, 0); // checkSum: the readers here do not verify it
|
||||
be32(&mut out, off as u32);
|
||||
be32(&mut out, d.len() as u32);
|
||||
off += d.len().div_ceil(4) * 4;
|
||||
}
|
||||
for (_, d) in &tables {
|
||||
out.extend_from_slice(d);
|
||||
while out.len() % 4 != 0 {
|
||||
out.push(0);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
//! The angles of a hatch's elliptic boundary edges in the DXF a DWG is read through.
|
||||
//!
|
||||
//! A DWG holds an elliptic edge's start and end angles in radians, and so does the DXF the DWG
|
||||
//! decoder writes (groups 50 and 51 of an edge of type 3). DXF itself keeps them in degrees, which
|
||||
//! is how [`crate::dxf_read`] reads them: a circle stored as an elliptic edge with the end angle
|
||||
//! 6.2832 became an arc of 6.28 degrees, and the hatch covered the hole it should have left open.
|
||||
//! Only the DWG path needs this; a DXF file is read as written.
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
/// `dxf` with the start and end angles (groups 50 and 51) of every elliptic hatch edge (edge type
|
||||
/// 3, group 72) turned from radians to degrees. The text is handled as bytes: a drawing from
|
||||
/// before 2007 is written in its code page, which is not UTF-8, and every other byte is kept as it
|
||||
/// was. Binary DXF, and text with no such edge, come back as they were.
|
||||
pub(crate) fn elliptic_edge_degrees(dxf: Vec<u8>) -> Vec<u8> {
|
||||
if dxf.starts_with(b"AutoCAD Binary DXF") || !dxf.windows(5).any(|w| w == b"HATCH") {
|
||||
return dxf;
|
||||
}
|
||||
let mut out = Vec::with_capacity(dxf.len());
|
||||
let mut lines = dxf.split_inclusive(|b| *b == b'\n');
|
||||
let mut in_hatch = false;
|
||||
// After an elliptic edge's type, until the next edge or loop: the angles still to convert.
|
||||
let mut ellipse = false;
|
||||
let mut changed = false;
|
||||
while let Some(code_line) = lines.next() {
|
||||
let Some(value_line) = lines.next() else {
|
||||
out.extend_from_slice(code_line);
|
||||
break;
|
||||
};
|
||||
let code = code_line.trim_ascii();
|
||||
let value = value_line.trim_ascii();
|
||||
match code {
|
||||
b"0" => {
|
||||
in_hatch = value == b"HATCH";
|
||||
ellipse = false;
|
||||
}
|
||||
b"72" if in_hatch => ellipse = value == b"3",
|
||||
b"92" | b"97" if in_hatch => ellipse = false,
|
||||
b"50" | b"51" if in_hatch && ellipse => {
|
||||
if let Some(radians) = std::str::from_utf8(value).ok().and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) {
|
||||
let ending = &value_line[value_line.trim_ascii_end().len()..];
|
||||
out.extend_from_slice(code_line);
|
||||
out.extend_from_slice(format!("{}", radians * 180.0 / PI).as_bytes());
|
||||
out.extend_from_slice(ending);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out.extend_from_slice(code_line);
|
||||
out.extend_from_slice(value_line);
|
||||
}
|
||||
if changed { out } else { dxf }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pairs(text: &str) -> Vec<(String, String)> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
|
||||
}
|
||||
|
||||
const HATCH: &str = "0\r\nHATCH\r\n91\r\n1\r\n92\r\n1\r\n93\r\n2\r\n72\r\n3\r\n10\r\n5.0\r\n20\r\n6.0\r\n11\r\n-55.5\r\n21\r\n0.0\r\n40\r\n1.0\r\n50\r\n0.0\r\n51\r\n6.283185307179586\r\n73\r\n1\r\n72\r\n1\r\n10\r\n1.0\r\n20\r\n2.0\r\n11\r\n3.0\r\n21\r\n4.0\r\n50\r\n7.0\r\n0\r\nLINE\r\n50\r\n9.0\r\n";
|
||||
|
||||
#[test]
|
||||
fn an_elliptic_edge_gets_its_angles_in_degrees_and_nothing_else_changes() {
|
||||
let out = String::from_utf8(elliptic_edge_degrees(HATCH.as_bytes().to_vec())).unwrap();
|
||||
let p = pairs(&out.replace("\r\n", "\n"));
|
||||
let value = |code: &str, n: usize| p.iter().filter(|(c, _)| c == code).nth(n).map(|(_, v)| v.parse::<f64>().unwrap());
|
||||
assert!((value("51", 0).unwrap() - 360.0).abs() < 1e-9);
|
||||
assert_eq!(value("50", 0), Some(0.0));
|
||||
// A line edge's 50 and another entity's are left alone, as is the line ending.
|
||||
assert_eq!(value("50", 1), Some(7.0));
|
||||
assert_eq!(value("50", 2), Some(9.0));
|
||||
assert!(out.contains("\r\n") && !out.replace("\r\n", "").contains('\r'));
|
||||
}
|
||||
|
||||
/// A drawing from before 2007 is written in its code page: an accented letter is one byte that
|
||||
/// is not valid UTF-8, and it must not stop the angles being converted or change.
|
||||
#[test]
|
||||
fn a_code_page_drawing_still_has_its_angles_converted() {
|
||||
let mut dxf = b"0\r\nTEXT\r\n1\r\ncaf".to_vec();
|
||||
dxf.push(0xE9);
|
||||
dxf.extend_from_slice(b"\r\n");
|
||||
dxf.extend_from_slice(HATCH.as_bytes());
|
||||
let out = elliptic_edge_degrees(dxf.clone());
|
||||
assert!(std::str::from_utf8(&dxf).is_err(), "the input is not UTF-8");
|
||||
assert!(out.windows(4).any(|w| w == b"caf\xE9"), "the accented byte is kept");
|
||||
let text: String = out.iter().map(|b| char::from(*b)).collect();
|
||||
assert!(text.contains("51\r\n360"), "the end angle is 360 degrees: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_without_a_hatch_ellipse_comes_back_untouched() {
|
||||
let dxf = b"0\nLINE\n50\n1.5\n".to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(dxf.clone()), dxf);
|
||||
let binary = b"AutoCAD Binary DXF\r\n\x1a\x00HATCH".to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(binary.clone()), binary);
|
||||
// A hatch with no elliptic edge is left as it is.
|
||||
let plain = "0\nHATCH\n72\n1\n50\n2.0\n".as_bytes().to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(plain.clone()), plain);
|
||||
}
|
||||
}
|
||||
@@ -79,12 +79,24 @@ fn has_images(store: &EntityStore) -> bool {
|
||||
}
|
||||
|
||||
/// Fill in each image's definition (path, name, pixel size) from the IMAGEDEF it points to.
|
||||
/// `refs`: each IMAGE entity's handle in the drawing → its IMAGEDEF handle (upper case), noted
|
||||
/// as the entity was read, so an image whose repeated handle was reassigned keeps its own.
|
||||
pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing, refs: &HashMap<Handle, String>) {
|
||||
pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
if !has_images(&d.model) && !d.layouts.iter().any(|l| has_images(&l.entities)) && !d.blocks.values().any(|b| has_images(&b.entities)) {
|
||||
return;
|
||||
}
|
||||
// IMAGE handle → IMAGEDEF handle.
|
||||
let mut refs: HashMap<Handle, String> = HashMap::new();
|
||||
for s in secs.iter().filter(|s| s.name == "ENTITIES" || s.name == "BLOCKS") {
|
||||
each_record(s.tags, |kind, tags| {
|
||||
if kind != "IMAGE" {
|
||||
return;
|
||||
}
|
||||
let h = tags.iter().find(|t| t.code == 5).and_then(|t| Handle::parse_hex(&t.str()));
|
||||
let def = tags.iter().find(|t| t.code == 340).map(|t| key(&t.str()));
|
||||
if let (Some(h), Some(def)) = (h, def) {
|
||||
refs.insert(h, def);
|
||||
}
|
||||
});
|
||||
}
|
||||
// IMAGEDEF objects, and the names dictionaries give them.
|
||||
let mut defs: HashMap<String, Def> = HashMap::new();
|
||||
let mut names: HashMap<String, String> = HashMap::new();
|
||||
|
||||
+13
-179
@@ -16,9 +16,9 @@ use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
|
||||
use craft_dxf::{SectionRef, Tag, Version};
|
||||
use craft_dxf::{SectionRef, Tag};
|
||||
|
||||
/// Named object dictionary entries CADCraft writes itself from its model (plus every key that
|
||||
/// starts with `CADCRAFT`): they are read into the model, not kept raw. A change that starts
|
||||
@@ -457,10 +457,6 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
if !f.is_empty() {
|
||||
f.version = file_version(secs);
|
||||
}
|
||||
// Added after the version: registered applications alone are no kept objects whose groups
|
||||
// the DWG writer must read as the file's version, and nearly every file has some (ACAD).
|
||||
let appids = tables.iter().filter(|(k, _, _)| k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string());
|
||||
f.appids = appids.take(MAX_OBJECTS).collect();
|
||||
// The file's handles of the objects CADCraft writes itself (AutoLISP's `handent`).
|
||||
f.handles = ids.iter().filter(|(h, _)| !ents.contains_key(*h)).filter_map(|(h, k)| Some((handle(h)?, k.clone()))).take(MAX_OBJECTS).collect();
|
||||
if !f.is_empty() || !f.handles.is_empty() {
|
||||
@@ -690,102 +686,6 @@ pub(crate) fn data_store(tags: &mut Vec<Tag>, d: &Drawing, modern: bool) {
|
||||
tags.splice(at..at, out);
|
||||
}
|
||||
|
||||
/// Most constraint nodes, and connections per node, looked at in one constraint group.
|
||||
const MAX_CONSTRAINT_NODES: usize = 100_000;
|
||||
|
||||
/// Put the status of every node of the kept 2D constraint groups (`ACDBASSOC2DCONSTRAINTGROUP`)
|
||||
/// where a reader of the version the text is read as expects it: AutoCAD 2013 and later
|
||||
/// (`modern`) write it after the node's connections, earlier versions right after its id. The
|
||||
/// groups are kept as read, so a 2013+ drawing written in an older version's form had them in the
|
||||
/// wrong order, and its reader took every node's status from somewhere else: AutoCAD refused the
|
||||
/// DWG the bridge made from it ("Error Decrypting Data"). A group whose nodes can't all be found
|
||||
/// is left as it is.
|
||||
pub(crate) fn constraint_node_order(tags: &mut [Tag], modern: bool) {
|
||||
let mut i = 0;
|
||||
while i < tags.len() {
|
||||
let end = tags.iter().skip(i + 1).position(|t| t.code == 0).map_or(tags.len(), |k| i + 1 + k);
|
||||
if tags.get(i).is_some_and(|t| t.code == 0 && t.str().trim().eq_ignore_ascii_case("ACDBASSOC2DCONSTRAINTGROUP"))
|
||||
&& let Some(rec) = tags.get_mut(i + 1..end)
|
||||
{
|
||||
constraint_group_order(rec, modern);
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
}
|
||||
|
||||
/// [`constraint_node_order`] for one group's groups after its type.
|
||||
fn constraint_group_order(rec: &mut [Tag], modern: bool) {
|
||||
let Some(start) = rec.iter().position(|t| t.code == 100 && t.str().trim().eq_ignore_ascii_case("AcDbAssoc2dConstraintGroup")) else {
|
||||
return;
|
||||
};
|
||||
let end = rec.iter().skip(start + 1).position(|t| t.code == 100 || t.code >= 1000).map_or(rec.len(), |k| start + 1 + k);
|
||||
let Some(sec) = rec.get_mut(start + 1..end) else { return };
|
||||
let Some(nodes) = constraint_nodes(sec) else { return };
|
||||
for (at, len, old) in nodes {
|
||||
// Old order: id, status, count, connections; modern: id, count, connections, status.
|
||||
if let Some(head) = sec.get_mut(at + 1..at + len) {
|
||||
match (old, modern) {
|
||||
(true, true) => head.rotate_left(1),
|
||||
(false, false) => head.rotate_right(1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where each non-root node of a constraint group section starts: (index of its id, length of its
|
||||
/// id, status and connections, whether its status comes right after the id). `None` unless every
|
||||
/// node the group lists is found.
|
||||
fn constraint_nodes(sec: &[Tag]) -> Option<Vec<(usize, usize, bool)>> {
|
||||
let int = |p: usize, code: i32| sec.get(p).filter(|t| t.code == code).and_then(|t| t.str().trim().parse::<i64>().ok());
|
||||
let count = |p: usize| int(p, 90).and_then(|n| usize::try_from(n).ok()).filter(|n| *n <= MAX_CONSTRAINT_NODES);
|
||||
// Version, flag and work plane, then the dependency and the actions.
|
||||
let mut p = sec.iter().position(|t| t.code == 360)? + 1;
|
||||
p += count(p)? + 1;
|
||||
// The next node id, then the root node: id, connections, status (290).
|
||||
int(p, 90)?;
|
||||
int(p + 1, 90)?;
|
||||
p += count(p + 2)? + 3;
|
||||
int(p, 290)?;
|
||||
p += 1;
|
||||
// The registry: class name and id of each node.
|
||||
let n = count(p)?;
|
||||
p += 1;
|
||||
let mut ids = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
sec.get(p).filter(|t| t.code == 1)?;
|
||||
ids.push(int(p + 1, 90)?);
|
||||
p += 2;
|
||||
}
|
||||
let known: HashSet<i64> = ids.iter().copied().collect();
|
||||
// Groups looked at while searching for headers, capped so a hostile group can't take long.
|
||||
let budget = std::cell::Cell::new(MAX_CONSTRAINT_NODES.saturating_mul(100));
|
||||
// A node header at `q`: its length and whether it is in the old order. Connections are ids of
|
||||
// nodes (or of the root, 0), which keeps a node's data from passing for the next header.
|
||||
let header = |q: usize, id: i64| -> Option<(usize, bool)> {
|
||||
int(q, 90).filter(|v| *v == id)?;
|
||||
let old = sec.get(q + 1)?.code == 70;
|
||||
let c = q + 1 + usize::from(old);
|
||||
let n = count(c).filter(|n| *n <= known.len())?;
|
||||
budget.set(budget.get().checked_sub(n + 1)?);
|
||||
for k in 0..n {
|
||||
int(c + 1 + k, 90).filter(|v| *v == 0 || known.contains(v))?;
|
||||
}
|
||||
if !old {
|
||||
int(c + 1 + n, 70)?;
|
||||
}
|
||||
Some((n + 3, old))
|
||||
};
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
let at = (p..sec.len()).find(|q| header(*q, id).is_some())?;
|
||||
let (len, old) = header(at, id)?;
|
||||
out.push((at, len, old));
|
||||
p = at + len;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Drop a dictionary's modelled entries (key and handle) from its groups.
|
||||
fn strip_entries(tags: &mut Vec<RawTag>) {
|
||||
let mut out = Vec::with_capacity(tags.len());
|
||||
@@ -1041,61 +941,13 @@ fn unknown_handles(d: &Drawing) -> HashSet<String> {
|
||||
all_entities(d).filter(|e| matches!(e.kind, EntityKind::Unknown(_))).map(|e| e.handle.hex()).collect()
|
||||
}
|
||||
|
||||
/// Render settings (`RENDERSETTINGS`, `MENTALRAYRENDERSETTINGS`, `RAPIDRTRENDERSETTINGS`) store
|
||||
/// their `AcDbRenderSettings` class version (the first group 90 after that marker) in the form of
|
||||
/// the file's version: a 2013+ file stores it one higher, and a 2013 file stores a rapid RT one
|
||||
/// one lower, as acadrust reads and writes them (`write_render_settings_dxf` in acadrust 0.6.6's
|
||||
/// `io/dxf/writer/section_writer.rs`, and its DWG class-object reader and writer; the test
|
||||
/// `render_settings_class_version_matches_what_acadrust_writes` fails if the two drift apart). A
|
||||
/// kept object carries the form of the file it was read from ([`Foreign::version`], not the
|
||||
/// drawing's `$ACADVER`, which SAVEAS changes); written into a file read as another version, it
|
||||
/// takes that version's form. The DWG bridge's R2000 text is read as the version the kept objects
|
||||
/// came from (craft-dwg's `encode_kept_noted`), so there they stay as read (#907, #2471).
|
||||
///
|
||||
/// Only that first group 90 is converted, on purpose: the group 90 that starts a kind's own
|
||||
/// subclass (`AcDbMentalRayRenderSettings`, `AcDbRapidRTRenderSettings`) is that kind's version,
|
||||
/// stored the same in every file version, and is left as read.
|
||||
pub(crate) fn render_settings_versions(tags: &mut [Tag], source: Option<Version>, declared: Version) {
|
||||
let Some(source) = source.filter(|s| *s != declared) else { return };
|
||||
let shift = |rapid: bool, v: Version| if rapid { -i64::from(v == Version::R2013) } else { i64::from(v >= Version::R2013) };
|
||||
let (mut kind, mut in_base) = (String::new(), false);
|
||||
for t in tags.iter_mut() {
|
||||
match t.code {
|
||||
0 => {
|
||||
kind = up(&t.str());
|
||||
in_base = false;
|
||||
}
|
||||
100 if matches!(kind.as_str(), "RENDERSETTINGS" | "MENTALRAYRENDERSETTINGS" | "RAPIDRTRENDERSETTINGS") => {
|
||||
in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings");
|
||||
}
|
||||
90 if in_base => {
|
||||
let rapid = kind == "RAPIDRTRENDERSETTINGS";
|
||||
let logical = t.i64().saturating_sub(shift(rapid, source));
|
||||
*t = Tag::i(90, logical.saturating_add(shift(rapid, declared)));
|
||||
in_base = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the drawing's foreign data back into a written file's tags (see the module comment).
|
||||
/// `strings`: whether the file has a form for a proxy's separate string stream (a DXF of 2007 or
|
||||
/// later, or the DWG bridge); without one such a proxy is left out (#3229). Returns the foreign
|
||||
/// objects written, by their handles in the drawing (the file gives them new ones).
|
||||
pub(crate) fn finish(
|
||||
tags: &mut Vec<Tag>,
|
||||
d: &Drawing,
|
||||
reactors: &HashMap<Handle, Vec<String>>,
|
||||
modern: bool,
|
||||
target_modern: bool,
|
||||
strings: bool,
|
||||
) -> HashSet<Handle> {
|
||||
pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle, Vec<String>>, modern: bool) {
|
||||
let f = d.foreign.as_ref();
|
||||
let unknown = unknown_handles(d);
|
||||
let xd: XdataOf = all_entities(d).filter(|e| !e.common.xdata.is_empty()).map(|e| (e.handle, e.common.xdata.as_slice())).collect();
|
||||
if f.is_empty() && unknown.is_empty() && xd.is_empty() {
|
||||
return HashSet::new();
|
||||
return;
|
||||
}
|
||||
let recs = written_records(tags);
|
||||
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
|
||||
@@ -1118,21 +970,14 @@ pub(crate) fn finish(
|
||||
numbers.entry(n).or_insert(500_i64.saturating_add(i64::try_from(i).unwrap_or(i64::MAX)));
|
||||
}
|
||||
let renumber = |old| proxy_class_number(f, &numbers, old);
|
||||
// A proxy is dropped when its class isn't written, or when its strings have no place here.
|
||||
let no_room = |t: &[(i32, &str)]| !strings && proxy_has_string_stream(t.iter().copied());
|
||||
// Entities of types CADCraft doesn't model, placed among the written ones.
|
||||
let mut planned = plan_unknown(d, &recs, tags, &roles, modern, target_modern);
|
||||
let mut planned = plan_unknown(d, &recs, tags, &roles, modern);
|
||||
for list in planned.values_mut() {
|
||||
list.retain_mut(|(_, t)| {
|
||||
if !t.first().is_some_and(|z| is_proxy(&z.str())) {
|
||||
return true;
|
||||
}
|
||||
let groups: Vec<(i32, String)> = t.iter().map(|x| (x.code, x.str())).collect();
|
||||
let groups: Vec<(i32, &str)> = groups.iter().map(|(c, v)| (*c, v.as_str())).collect();
|
||||
if no_room(&groups) {
|
||||
return false;
|
||||
}
|
||||
let Some(n) = renumber(class_number(groups.iter().copied())) else { return false };
|
||||
let Some(n) = renumber(class_number(t.iter().map(|x| (x.code, x.str())))) else { return false };
|
||||
set_class_number(t, n);
|
||||
true
|
||||
});
|
||||
@@ -1170,11 +1015,8 @@ pub(crate) fn finish(
|
||||
// Keep established live paths available to descendants during this pass as well.
|
||||
let mut alive_memo: HashMap<String, bool> = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect();
|
||||
let kept = |h: &str| kept.get(h) == Some(&true);
|
||||
let dropped = |o: &ForeignObject| {
|
||||
let groups: Vec<(i32, &str)> = o.tags.iter().map(|r| (r.code, r.value.as_str())).collect();
|
||||
no_room(&groups) || renumber(class_number(groups.iter().copied())).is_none()
|
||||
};
|
||||
for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && dropped(o)) {
|
||||
for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none())
|
||||
{
|
||||
alive_memo.insert(o.handle.hex(), false);
|
||||
}
|
||||
for o in &f.objects {
|
||||
@@ -1271,7 +1113,7 @@ pub(crate) fn finish(
|
||||
join_entries(&map, b, kept, &mut out);
|
||||
}
|
||||
}
|
||||
add_appids(&mut out, &f.appids);
|
||||
add_appids(&mut out);
|
||||
let top = max_handle(&out).saturating_add(1);
|
||||
if let Some(t) = seed_index(&out).and_then(|i| out.get_mut(i))
|
||||
&& Handle::parse_hex(&t.str()).is_none_or(|h| h.0 < top)
|
||||
@@ -1279,7 +1121,6 @@ pub(crate) fn finish(
|
||||
*t = Tag::s(5, format!("{top:X}"));
|
||||
}
|
||||
*tags = out;
|
||||
map.alive.keys().filter_map(|h| handle(h)).collect()
|
||||
}
|
||||
|
||||
/// Kept extension dictionaries of written records: those that go on a record without its own,
|
||||
@@ -1361,7 +1202,6 @@ fn plan_unknown(
|
||||
tags: &[Tag],
|
||||
roles: &HashMap<ForeignKey, String>,
|
||||
modern: bool,
|
||||
target_modern: bool,
|
||||
) -> HashMap<usize, Vec<(String, Vec<Tag>)>> {
|
||||
let stored = d.foreign.data_store_entities();
|
||||
let mut out: HashMap<usize, Vec<(String, Vec<Tag>)>> = HashMap::new();
|
||||
@@ -1401,9 +1241,7 @@ fn plan_unknown(
|
||||
for e in store.iter() {
|
||||
match &e.kind {
|
||||
EntityKind::Unknown(u) => {
|
||||
if (modern && cadcraft_doc::foreign::sat_text_acis(u, e.handle, &stored))
|
||||
|| (!target_modern && cadcraft_doc::foreign::acis_left_out(u, e.handle, &stored, false))
|
||||
{
|
||||
if modern && cadcraft_doc::foreign::sat_text_acis(u, e.handle, &stored) {
|
||||
continue;
|
||||
}
|
||||
let t = unknown_entity(u, e, &owner, paper);
|
||||
@@ -1597,13 +1435,9 @@ fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>)
|
||||
}
|
||||
}
|
||||
|
||||
/// APPID records for every application with xdata in the file and every one the file read had
|
||||
/// (`kept`), added to the APPID table.
|
||||
fn add_appids(out: &mut Vec<Tag>, kept: &[String]) {
|
||||
let mut used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
|
||||
for name in kept.iter().filter(|n| !n.is_empty()) {
|
||||
used.entry(up(name)).or_insert_with(|| name.clone());
|
||||
}
|
||||
/// APPID records for every application with xdata in the file, added to the APPID table.
|
||||
fn add_appids(out: &mut Vec<Tag>) {
|
||||
let used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
|
||||
let recs = written_records(out);
|
||||
let Some(table) = recs.iter().position(|r| {
|
||||
r.sec == "TABLES" && r.kind == "TABLE" && val(out.get(r.start + 1..r.end).unwrap_or(&[]), 2).is_some_and(|n| up(&n) == "APPID")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! DXF → Drawing.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use cadcraft_color::{Color, Rgb};
|
||||
use cadcraft_doc::{
|
||||
@@ -24,8 +24,8 @@ mod tables;
|
||||
mod text;
|
||||
|
||||
use document::{
|
||||
HandlePolicy, apply_sortents, count_skipped, dropped_paper_views, outside_sections, parse_entities, place_blocks, place_entities, read_blocks,
|
||||
read_objects, setup_layouts,
|
||||
apply_sortents, count_skipped, dropped_paper_views, outside_sections, parse_entities, place_blocks, place_entities, read_blocks, read_objects,
|
||||
setup_layouts,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use entities::acad_table;
|
||||
@@ -71,8 +71,6 @@ struct Rx {
|
||||
block: Option<String>,
|
||||
/// The points HATCH boundary curves may still be sampled into.
|
||||
curves: hatch::CurvePoints,
|
||||
/// IMAGE entity handle, as read (a repeated one reassigned) → its IMAGEDEF handle (upper case).
|
||||
image_defs: HashMap<Handle, String>,
|
||||
}
|
||||
|
||||
/// Read a DXF file into a drawing.
|
||||
@@ -104,18 +102,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
||||
let mut blocks: Vec<BlockDef> = Vec::new();
|
||||
let mut layout_objs: Vec<LayoutDef> = Vec::new();
|
||||
let mut entities = Vec::new();
|
||||
// One set for every list: a generated handle must be unique across blocks and ENTITIES
|
||||
// (a *MODEL_SPACE block and an ENTITIES record both land in the model space).
|
||||
let mut seen_handles = HashSet::new();
|
||||
// Model/paper-space handles retain priority if an in-memory drawing or damaged DXF also
|
||||
// assigns one to a block entity. This preserves top-level references while letting block
|
||||
// handles be repaired before their deferred fixups are recorded.
|
||||
let reserved_entity_handles: HashSet<Handle> = secs
|
||||
.iter()
|
||||
.filter(|s| s.name == "ENTITIES")
|
||||
.flat_map(|s| record_slices(s.tags))
|
||||
.filter_map(|(_, tags)| common::T(tags).s(5).and_then(|h| Handle::parse_hex(&h)))
|
||||
.collect();
|
||||
let mut objs = Objects::default();
|
||||
// Every handle another program's file already uses is taken before anything gets a new one:
|
||||
// its $HANDSEED can be lower than its handles, and entities made while reading (the faces of
|
||||
@@ -159,20 +145,11 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
||||
match s.name {
|
||||
"HEADER" => header(s.tags, &mut d),
|
||||
"TABLES" => tables(s.tags, &mut d, &mut rx),
|
||||
"BLOCKS" => {
|
||||
blocks.extend(read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped, &mut seen_handles, &reserved_entity_handles))
|
||||
}
|
||||
"BLOCKS" => blocks.extend(read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped)),
|
||||
// A damaged file may split its entities over several ENTITIES sections (#865).
|
||||
"ENTITIES" => {
|
||||
let mut n = 0;
|
||||
entities.extend(parse_entities(
|
||||
&record_slices(s.tags),
|
||||
&mut d,
|
||||
&mut rx,
|
||||
&mut n,
|
||||
&mut table_cells_left,
|
||||
&mut HandlePolicy { seen: &mut seen_handles, reserved: &reserved_entity_handles, source_wins: true },
|
||||
));
|
||||
entities.extend(parse_entities(&record_slices(s.tags), &mut d, &mut rx, &mut n, &mut table_cells_left));
|
||||
count_skipped(&mut skipped, "ENTITIES", n);
|
||||
}
|
||||
"OBJECTS" => read_objects(s.tags, &mut objs, &mut layout_objs),
|
||||
@@ -188,7 +165,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
||||
number_unknown_viewport_ids(&mut d, &dropped_paper_views(&rx, &paper_block_for, &first_layout));
|
||||
apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout);
|
||||
objs.apply(&mut d, &rx);
|
||||
crate::dxf_image::resolve(&secs, &mut d, &rx.image_defs);
|
||||
crate::dxf_image::resolve(&secs, &mut d);
|
||||
crate::dxf_mline::resolve(&secs, &mut d);
|
||||
// Keep handles unique against the header's seed.
|
||||
let seed = d.header.str("HANDSEED", "");
|
||||
@@ -212,7 +189,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
||||
// Every record is placed now, and an object holding a reserved handle keeps it from new
|
||||
// objects by itself. Kept, the set would be copied with every undo step of the drawing.
|
||||
d.reserved_handles.clear();
|
||||
remember_text_fits(&mut d);
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
@@ -245,23 +221,6 @@ fn number_unknown_viewport_ids(d: &mut Drawing, sheet_dropped: &std::collections
|
||||
}
|
||||
}
|
||||
|
||||
/// Capture after all tables and entity fixups, including files whose tables follow entities.
|
||||
fn remember_text_fits(d: &mut Drawing) {
|
||||
let mut fits = std::collections::BTreeMap::new();
|
||||
for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())) {
|
||||
let texts: Vec<&Text> = match &e.kind {
|
||||
EntityKind::Text(t) => vec![t],
|
||||
EntityKind::AttDef(a) => vec![&a.text],
|
||||
EntityKind::Insert(i) => i.attribs.iter().map(|a| &a.text).collect(),
|
||||
_ => continue,
|
||||
};
|
||||
if texts.iter().any(|t| matches!(t.halign, HAlign::Aligned | HAlign::Fit)) {
|
||||
fits.insert(e.handle, texts.into_iter().map(|t| (t.clone(), d.text_style(&t.style).cloned().unwrap_or_default())).collect());
|
||||
}
|
||||
}
|
||||
std::sync::Arc::make_mut(&mut d.foreign).text_fits = fits;
|
||||
}
|
||||
|
||||
/// An entity from the groups of a DXF record of type `kind` (without its `0` group), as the
|
||||
/// reader makes it, with plain strings as [`crate::entity_groups`] gives them (not the file's
|
||||
/// `^ ` escapes). AutoLISP's `entmake` and `entmod` are built on it.
|
||||
|
||||
@@ -1,57 +1,14 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::common::T;
|
||||
use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity};
|
||||
use super::objects::{MAX_OBJECTS, Objects, page_setup};
|
||||
use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, Vec2, record_slices};
|
||||
|
||||
/// Allocate an entity handle that is unique within the DXF, including against handles assigned
|
||||
/// to earlier malformed or generated entities.
|
||||
fn fresh_entity_handle(d: &mut Drawing, seen: &mut HashSet<Handle>, reserved: &HashSet<Handle>) -> Handle {
|
||||
// The seed saturates at `u64::MAX`: once a file uses that handle, `new_handle` keeps
|
||||
// returning it and a plain retry loop would never terminate. Stop as soon as it stops
|
||||
// advancing.
|
||||
let mut previous = None;
|
||||
loop {
|
||||
let h = d.new_handle();
|
||||
if !reserved.contains(&h) && seen.insert(h) {
|
||||
return h;
|
||||
}
|
||||
if previous == Some(h) {
|
||||
break;
|
||||
}
|
||||
previous = Some(h);
|
||||
}
|
||||
// Every value the seed can still reach is taken, so scan from the bottom: the occupied set
|
||||
// is finite, which guarantees a free handle within its size plus one candidates.
|
||||
let limit = seen.len().saturating_add(reserved.len()).saturating_add(1);
|
||||
let mut candidate = 1u64;
|
||||
for _ in 0..limit {
|
||||
let h = Handle(candidate);
|
||||
if !reserved.contains(&h) && seen.insert(h) {
|
||||
return h;
|
||||
}
|
||||
candidate = candidate.saturating_add(1);
|
||||
}
|
||||
// Unreachable in practice (pigeonhole over the finite occupied set); never lose the entity.
|
||||
d.new_handle()
|
||||
}
|
||||
|
||||
/// How an ENTITIES list assigns handles: the handles already seen anywhere in the file, the
|
||||
/// ones the block records reserved, and whether a record's own handle beats the reservation.
|
||||
pub(super) struct HandlePolicy<'a> {
|
||||
pub seen: &'a mut HashSet<Handle>,
|
||||
pub reserved: &'a HashSet<Handle>,
|
||||
pub source_wins: bool,
|
||||
}
|
||||
|
||||
pub(super) fn parse_entities(
|
||||
recs: &[(String, &[Tag])],
|
||||
d: &mut Drawing,
|
||||
rx: &mut Rx,
|
||||
skipped: &mut usize,
|
||||
table_cells_left: &mut usize,
|
||||
hp: &mut HandlePolicy<'_>,
|
||||
) -> Vec<(Option<String>, bool, Entity)> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
@@ -101,18 +58,13 @@ pub(super) fn parse_entities(
|
||||
// A file's handles keep their identity, however high they are (#913, #939).
|
||||
Some(h) => {
|
||||
d.bump_handseed(h);
|
||||
// A file's own handle wins when it is the first copy on a source list that
|
||||
// keeps them (ENTITIES); block copies yield to the reserved top-level ones.
|
||||
let kept = if hp.source_wins { hp.seen.insert(h) } else { !hp.reserved.contains(&h) && hp.seen.insert(h) };
|
||||
if kept { h } else { fresh_entity_handle(d, hp.seen, hp.reserved) }
|
||||
h
|
||||
}
|
||||
None => fresh_entity_handle(d, hp.seen, hp.reserved),
|
||||
None => d.new_handle(),
|
||||
};
|
||||
entity_extras(kind, tags, h, &mut k, rx);
|
||||
let more: Vec<_> = extra
|
||||
.into_iter()
|
||||
.map(|f| (owner.clone(), paper, Entity { handle: fresh_entity_handle(d, hp.seen, hp.reserved), common: c.clone(), kind: f }))
|
||||
.collect();
|
||||
let more: Vec<_> =
|
||||
extra.into_iter().map(|f| (owner.clone(), paper, Entity { handle: d.new_handle(), common: c.clone(), kind: f })).collect();
|
||||
out.push((owner, paper, Entity { handle: h, common: c, kind: k }));
|
||||
out.extend(more);
|
||||
} else if kind == "HATCH" {
|
||||
@@ -121,6 +73,14 @@ pub(super) fn parse_entities(
|
||||
*skipped = skipped.saturating_add(1);
|
||||
}
|
||||
}
|
||||
// Assign fresh handles to duplicates (hostile files).
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for (_, _, e) in &mut out {
|
||||
if !seen.insert(e.handle) {
|
||||
e.handle = d.new_handle();
|
||||
seen.insert(e.handle);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -131,8 +91,6 @@ pub(super) fn read_blocks(
|
||||
rx: &mut Rx,
|
||||
table_cells_left: &mut usize,
|
||||
skipped: &mut std::collections::BTreeMap<String, usize>,
|
||||
seen_handles: &mut HashSet<Handle>,
|
||||
reserved_handles: &HashSet<Handle>,
|
||||
) -> Vec<BlockDef> {
|
||||
let recs = record_slices(tags);
|
||||
for (k, tg) in &recs {
|
||||
@@ -158,14 +116,7 @@ pub(super) fn read_blocks(
|
||||
}
|
||||
let body = recs.get(i + 1..j).unwrap_or(&[]);
|
||||
rx.block = Some(name.to_ascii_uppercase());
|
||||
let ents = parse_entities(
|
||||
body,
|
||||
d,
|
||||
rx,
|
||||
&mut n,
|
||||
table_cells_left,
|
||||
&mut HandlePolicy { seen: seen_handles, reserved: reserved_handles, source_wins: false },
|
||||
);
|
||||
let ents = parse_entities(body, d, rx, &mut n, table_cells_left);
|
||||
rx.block = None;
|
||||
blocks.push((name, base, description, ents, xref));
|
||||
i = j + 1;
|
||||
|
||||
@@ -88,7 +88,6 @@ fn lwpolyline(tags: &[Tag], c: &mut Common, t: &T) -> Option<EntityKind> {
|
||||
// In a tilted plane: drawn as seen from above, at the vertices' mean height, its
|
||||
// vertices now plan coordinates.
|
||||
(verts, elevation) = plan_of_tilted(c.extrusion, elevation, &verts, flags & 1 != 0);
|
||||
thickness_along_z(c);
|
||||
c.extrusion = Vec3::Z;
|
||||
} else if c.extrusion.z < 0.0 {
|
||||
for v in &mut verts {
|
||||
@@ -516,13 +515,6 @@ pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityK
|
||||
rx.table_style_fix.push((h, t.s(342).map(|sh| sh.trim().to_ascii_uppercase()).unwrap_or_default()));
|
||||
}
|
||||
}
|
||||
// Keyed by the handle the entity was given, so an IMAGE whose repeated handle was
|
||||
// reassigned still finds its own IMAGEDEF.
|
||||
("IMAGE", EntityKind::Image(_)) => {
|
||||
if let Some(def) = tags.iter().find(|t| t.code == 340) {
|
||||
rx.image_defs.insert(h, def.str().trim().to_ascii_uppercase());
|
||||
}
|
||||
}
|
||||
("INSERT", EntityKind::Insert(ins)) => {
|
||||
rx.inserted.insert(ins.block.to_ascii_uppercase());
|
||||
}
|
||||
@@ -578,7 +570,7 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut c = common(t);
|
||||
let c = common(t);
|
||||
let mut extra: Vec<EntityKind> = Vec::new();
|
||||
let k = if flags & 64 != 0 {
|
||||
// Face records that name a missing vertex (or fewer than three) are dropped: they draw
|
||||
@@ -600,26 +592,13 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
|
||||
} else if flags & 8 != 0 {
|
||||
EntityKind::Polyline3d(Polyline3d { points: pts.iter().map(|p| p.0).collect(), closed: flags & 1 != 0 })
|
||||
} else {
|
||||
// A 2D polyline's vertices are in its OCS, at the elevation of the POLYLINE's own point:
|
||||
// in a tilted plane drawn as seen from above like LWPOLYLINE, else mirrored like it.
|
||||
let closed = flags & 1 != 0;
|
||||
let mut vertices: Vec<PolyVertex> = pts.iter().map(|p| PolyVertex { p: p.0.xy(), bulge: p.1, start_width: p.2, end_width: p.3 }).collect();
|
||||
let mut elevation = t.p(10).z;
|
||||
if tilted(c.extrusion, run_points(&vertices, elevation, closed)) {
|
||||
(vertices, elevation) = plan_of_tilted(c.extrusion, elevation, &vertices, closed);
|
||||
thickness_along_z(&mut c);
|
||||
c.extrusion = Vec3::Z;
|
||||
} else if c.extrusion.z < 0.0 {
|
||||
for v in &mut vertices {
|
||||
v.p.x = -v.p.x;
|
||||
v.bulge = -v.bulge;
|
||||
}
|
||||
}
|
||||
// A 2D polyline's vertices are in its OCS: mirrored like LWPOLYLINE.
|
||||
let m = if c.extrusion.z < 0.0 { -1.0 } else { 1.0 };
|
||||
EntityKind::LwPolyline(LwPolyline {
|
||||
vertices,
|
||||
closed,
|
||||
vertices: pts.iter().map(|p| PolyVertex { p: Vec2::new(m * p.0.x, p.0.y), bulge: m * p.1, start_width: p.2, end_width: p.3 }).collect(),
|
||||
closed: flags & 1 != 0,
|
||||
const_width: t.fd(40, 0.0).min(t.fd(41, 0.0)).max(0.0),
|
||||
elevation,
|
||||
elevation: t.p(10).z,
|
||||
plinegen: flags & 128 != 0,
|
||||
})
|
||||
};
|
||||
@@ -728,11 +707,3 @@ fn helix(tags: &[Tag]) -> Helix {
|
||||
}
|
||||
.sanitized()
|
||||
}
|
||||
|
||||
/// A polyline drawn as seen from above gets the normal +Z: its thickness keeps the side of Z it
|
||||
/// extruded toward, which the normal it is losing said.
|
||||
fn thickness_along_z(c: &mut Common) {
|
||||
if c.extrusion.z < 0.0 {
|
||||
c.thickness = -c.thickness;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ pub(super) fn hatch(tags: &[Tag], t: &T, curves: &mut CurvePoints) -> Option<Ent
|
||||
verts.pop();
|
||||
}
|
||||
let sources = boundary_sources(tags, &mut i);
|
||||
loops.push(HatchLoop { vertices: verts, outer, boundary_flags: Some(flags), sources });
|
||||
loops.push(HatchLoop { vertices: verts, outer, sources });
|
||||
}
|
||||
curves.left = curves.left.saturating_sub(start_left.saturating_sub(budget.left));
|
||||
if budget.cut {
|
||||
|
||||
@@ -421,8 +421,6 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
|
||||
// Plot layout flags: 2 display plot styles, 4 centred, 16 standard scale (75 = 0: scaled
|
||||
// to fit), 128 lineweights.
|
||||
if let Some(flags) = t.i(70) {
|
||||
// Kept to be written back (a 16-bit group: only those bits).
|
||||
p.file_plot_flags = Some(flags & 0xFFFF);
|
||||
p.show_plot_styles = flags & 2 != 0;
|
||||
p.center = flags & 4 != 0;
|
||||
p.lineweights = flags & 128 != 0;
|
||||
@@ -434,13 +432,6 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
|
||||
if let Some(s) = pos(ratio).or_else(|| pos(t.f(147))) {
|
||||
p.scale = s;
|
||||
}
|
||||
// A standard scale (flag 16, group 75 above 0: 0 is scaled to fit, the DXF Reference lists
|
||||
// 1 to 32), kept with the scale it stands for so a save can tell it was not changed.
|
||||
if t.i(70).is_some_and(|f| f & 16 != 0)
|
||||
&& let Some(code) = t.i(75).filter(|c| (1..=32).contains(c))
|
||||
{
|
||||
p.file_standard_scale = Some((code, p.scale));
|
||||
}
|
||||
p.plot_area = match t.i(74) {
|
||||
Some(0) => "display",
|
||||
Some(1) => "extents",
|
||||
|
||||
@@ -70,8 +70,7 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option<EntityKind>
|
||||
let list = xdata_list(x, "REGION");
|
||||
let fin = |v: &PolyVertex| v.p.is_finite() && v.bulge.is_finite();
|
||||
let first_outer = list.iter().find(|t| t.code == 1070).is_none_or(|t| t.i64() != 0);
|
||||
let mut loops =
|
||||
vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, boundary_flags: None, sources: Vec::new() }];
|
||||
let mut loops = vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, sources: Vec::new() }];
|
||||
let mut total = 0usize;
|
||||
let mut cur: Option<HatchLoop> = None;
|
||||
let mut expect_flag = false;
|
||||
@@ -82,7 +81,7 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option<EntityKind>
|
||||
if loops.len() >= MAX_REGION_LOOPS {
|
||||
break;
|
||||
}
|
||||
cur = Some(HatchLoop { vertices: Vec::new(), outer: false, boundary_flags: None, sources: Vec::new() });
|
||||
cur = Some(HatchLoop { vertices: Vec::new(), outer: false, sources: Vec::new() });
|
||||
expect_flag = true;
|
||||
}
|
||||
1070 if expect_flag => {
|
||||
|
||||
@@ -24,8 +24,6 @@ mod entity;
|
||||
mod header;
|
||||
mod layout;
|
||||
mod objects;
|
||||
mod proxy;
|
||||
pub use proxy::proxies_lost;
|
||||
mod sections;
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -151,70 +149,15 @@ pub fn write(d: &Drawing) -> String {
|
||||
|
||||
/// The drawing's DXF tags, declaring `version` in `$ACADVER`.
|
||||
pub fn tags(d: &Drawing, version: Version) -> Vec<Tag> {
|
||||
tags_kept(d, version).0
|
||||
}
|
||||
|
||||
/// [`tags`], with the foreign objects the file keeps, by their handles in the drawing.
|
||||
fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::HashSet<cadcraft_doc::Handle>) {
|
||||
let (mut tags, kept) = sections::tags_kept_for(d, version, version, version < Version::R2004, false);
|
||||
// Kept proxies in this version's layout (#3229). Not for the DWG bridge, whose writer reads
|
||||
// them in the layout of the DWG they came from.
|
||||
proxy::proxy_layout(&mut tags, version);
|
||||
(tags, kept)
|
||||
tags_for(d, version, version, version < Version::R2004)
|
||||
}
|
||||
|
||||
/// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG
|
||||
/// version's (MULTILEADER from 2007).
|
||||
pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> (String, craft_dwg::Unwritten) {
|
||||
let (mut tags, kept) = sections::tags_kept_for(d, Version::R2000, dwg, false, true);
|
||||
let mut unwritten = craft_dwg::Unwritten::new();
|
||||
if dwg == Version::R2007 {
|
||||
let omitted = legacy_visualstyles_kept(d, &kept);
|
||||
if omitted != 0 {
|
||||
let mut source = d.clone();
|
||||
std::sync::Arc::make_mut(&mut source.foreign).objects.retain(|object| !legacy_visual_style(object));
|
||||
tags = tags_for(&source, Version::R2000, dwg, false);
|
||||
unwritten.insert("VISUALSTYLE".into(), omitted);
|
||||
}
|
||||
}
|
||||
pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> String {
|
||||
let mut tags = tags_for(d, Version::R2000, dwg, false);
|
||||
bridge_markers(&mut tags);
|
||||
(craft_dxf::write_ascii(&tags), unwritten)
|
||||
}
|
||||
|
||||
/// Version-specific DWG compatibility omissions, counted from the actual saved view.
|
||||
/// Hosts use this before saving and when reporting saves through their byte-only I/O hooks.
|
||||
pub fn dwg_compat_lost(d: &Drawing, version: Version) -> craft_dwg::Unwritten {
|
||||
let mut lost = craft_dwg::Unwritten::new();
|
||||
if version == Version::R2007 && d.foreign.objects.iter().any(legacy_visual_style) {
|
||||
let (_, kept) = sections::tags_kept_for(d, Version::R2000, version, false, true);
|
||||
let omitted = legacy_visualstyles_kept(d, &kept);
|
||||
if omitted != 0 {
|
||||
lost.insert("VISUALSTYLE".into(), omitted);
|
||||
}
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
fn legacy_visualstyles_kept(d: &Drawing, kept: &HashSet<cadcraft_doc::Handle>) -> usize {
|
||||
d.foreign.objects.iter().filter(|object| kept.contains(&object.handle) && legacy_visual_style(object)).count()
|
||||
}
|
||||
|
||||
/// The fixed-property VISUALSTYLE layout in the 2007/2010 DXF Reference has no 176/177
|
||||
/// property pairs. The bridge cannot faithfully save this layout as a 2007 DWG.
|
||||
fn legacy_visual_style(object: &cadcraft_doc::foreign::ForeignObject) -> bool {
|
||||
if !object.kind.trim().eq_ignore_ascii_case("VISUALSTYLE") {
|
||||
return false;
|
||||
}
|
||||
let mut properties = object.tags.iter().skip_while(|tag| tag.code != 100 || tag.value.trim() != "AcDbVisualStyle");
|
||||
properties.next();
|
||||
let mut fixed = false;
|
||||
for tag in properties.take_while(|tag| tag.code != 100 && tag.code < 1000) {
|
||||
if matches!(tag.code, 176 | 177) {
|
||||
return false;
|
||||
}
|
||||
fixed |= matches!(tag.code, 40 | 71);
|
||||
}
|
||||
fixed
|
||||
craft_dxf::write_ascii(&tags)
|
||||
}
|
||||
|
||||
/// Proxy type names and lookup-parameter subclass names must match the bridge reader's spelling.
|
||||
|
||||
@@ -2,15 +2,13 @@ use super::{
|
||||
Block, Color, Common, Dimension, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext,
|
||||
};
|
||||
|
||||
/// What happens to the dimension blocks read from a file (#495): a dimension that still names
|
||||
/// its block is written with that block, under its name, and `*D` blocks nothing else
|
||||
/// references are not written again. The block a dimension names may have any name: other
|
||||
/// programs don't always use `*D` (#3299).
|
||||
/// What happens to the anonymous `*D` blocks read from a file (#495): a dimension that still
|
||||
/// names its block regenerates its geometry under that name, keeping the block's entity
|
||||
/// handles, and `*D` blocks nothing else references are not written again.
|
||||
pub(super) struct DimBlockPlan {
|
||||
/// Dimension (model or paper space) → the read block whose name and handles it reuses.
|
||||
pub(super) reuse: HashMap<Handle, std::sync::Arc<Block>>,
|
||||
/// Upper-case names of blocks not written as ordinary blocks: `*D` blocks and the blocks
|
||||
/// dimensions name, when nothing else uses them.
|
||||
/// Upper-case names of `*D` blocks not written as ordinary blocks.
|
||||
pub(super) skip: std::collections::HashSet<String>,
|
||||
}
|
||||
|
||||
@@ -18,12 +16,6 @@ fn is_dim_block(name: &str) -> bool {
|
||||
name.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("*D"))
|
||||
}
|
||||
|
||||
/// The read block, not named `*D`, that a dimension block definition named `name` is written
|
||||
/// from (#3299): its record and block properties are written as read.
|
||||
pub(super) fn kept_named_dim_block<'a>(d: &'a Drawing, name: &str) -> Option<&'a Block> {
|
||||
d.block(name).filter(|_| !is_dim_block(name)).map(|b| b.as_ref())
|
||||
}
|
||||
|
||||
pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan {
|
||||
let spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect();
|
||||
// Block names other objects use: inserts and multileader contents anywhere, and dimensions
|
||||
@@ -43,19 +35,12 @@ pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan {
|
||||
for e in d.blocks.values().flat_map(|b| b.entities.iter()) {
|
||||
note(e, true, &mut used);
|
||||
}
|
||||
// Blocks the dimensions of model and paper space still name, whatever their names.
|
||||
let named: std::collections::HashSet<String> = spaces
|
||||
.iter()
|
||||
.flat_map(|s| s.iter())
|
||||
.filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { dm.block.as_ref().map(|n| n.to_ascii_uppercase()) } else { None })
|
||||
.collect();
|
||||
let skip =
|
||||
d.blocks.keys().map(|n| n.to_ascii_uppercase()).filter(|n| is_dim_block(n) || named.contains(n)).filter(|n| !used.contains(n)).collect();
|
||||
let skip = d.blocks.keys().filter(|n| is_dim_block(n)).map(|n| n.to_ascii_uppercase()).filter(|n| !used.contains(n)).collect();
|
||||
let mut plan = DimBlockPlan { reuse: HashMap::new(), skip };
|
||||
let mut claimed = std::collections::HashSet::new();
|
||||
for e in spaces.iter().flat_map(|s| s.iter()) {
|
||||
let EntityKind::Dimension(dm) = &e.kind else { continue };
|
||||
let Some(b) = dm.block.as_deref().and_then(|n| d.block(n)) else { continue };
|
||||
let Some(b) = dm.block.as_deref().filter(|n| is_dim_block(n)).and_then(|n| d.block(n)) else { continue };
|
||||
let key = b.name.to_ascii_uppercase();
|
||||
if plan.skip.contains(&key) && claimed.insert(key) {
|
||||
plan.reuse.insert(e.handle, b.clone());
|
||||
|
||||
@@ -254,69 +254,8 @@ fn computed_text_insert(d: &Drawing, t: &Text) -> Vec3 {
|
||||
if q.is_finite() { Vec3::new(q.x, q.y, t.insert.z) } else { t.insert }
|
||||
}
|
||||
|
||||
fn relative_match(a: f64, b: f64) -> bool {
|
||||
a.is_finite() && b.is_finite() && (a - b).abs() <= 1e-9 * a.abs().max(b.abs())
|
||||
}
|
||||
|
||||
// A fitted dimension depends on the point distance, independently of position and direction.
|
||||
fn imported_fit_scale(original: &Text, current: &Text) -> Option<f64> {
|
||||
let (Some(first), Some(second)) = (original.align_pt, current.align_pt) else {
|
||||
return None;
|
||||
};
|
||||
let before = original.insert.xy().dist(first.xy());
|
||||
let after = current.insert.xy().dist(second.xy());
|
||||
if !before.is_finite() || !after.is_finite() || before <= 0.0 || after <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
if relative_match(before, after) {
|
||||
return Some(1.0);
|
||||
}
|
||||
let scale = after / before;
|
||||
(scale.is_finite() && scale > 0.0).then_some(scale)
|
||||
}
|
||||
|
||||
/// `attdef_prompt` is `Some` for an ATTDEF (its prompt, which may be empty) and `None` for an ATTRIB.
|
||||
pub(super) fn text_tags(
|
||||
w: &mut W,
|
||||
d: &Drawing,
|
||||
t: &Text,
|
||||
attrib: Option<(&Attrib, Version)>,
|
||||
attdef_prompt: Option<&str>,
|
||||
source: (cadcraft_doc::Handle, usize),
|
||||
) {
|
||||
let fitted;
|
||||
let t = if matches!(t.halign, HAlign::Aligned | HAlign::Fit) {
|
||||
let mut resolved = t.clone();
|
||||
// Imported dimensions use the originating font's measurements. A substituted font
|
||||
// must not replace them while the fitting inputs still match the read-time snapshot.
|
||||
if let Some((original, style)) = d.foreign.text_fits.get(&source.0).and_then(|texts| texts.get(source.1))
|
||||
&& original.value == t.value
|
||||
&& let Some(scale) = imported_fit_scale(original, t)
|
||||
&& original.style == t.style
|
||||
&& *style == d.text_style(&t.style).cloned().unwrap_or_default()
|
||||
&& original.halign == t.halign
|
||||
&& original.valign == t.valign
|
||||
&& original.oblique == t.oblique
|
||||
&& original.width_factor == t.width_factor
|
||||
&& (t.halign != HAlign::Fit || relative_match(t.height, original.height * scale))
|
||||
{
|
||||
if t.halign == HAlign::Aligned && !t.value.is_empty() {
|
||||
resolved.height = original.height * scale;
|
||||
}
|
||||
if let Some(second) = t.align_pt {
|
||||
let distance = t.insert.xy().dist(second.xy());
|
||||
if distance.is_finite() && distance > 1e-12 {
|
||||
resolved.rotation = t.insert.xy().angle_to(second.xy());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
resolved = cadcraft_render::fitted_text_entity(d, t, &t.value);
|
||||
}
|
||||
fitted = resolved;
|
||||
&fitted
|
||||
} else {
|
||||
t
|
||||
};
|
||||
pub(super) fn text_tags(w: &mut W, d: &Drawing, t: &Text, attrib: Option<(&Attrib, Version)>, attdef_prompt: Option<&str>) {
|
||||
let attdef = attdef_prompt.is_some();
|
||||
// An attribute definition with no default value is drawn as its tag, whatever its prompt: the
|
||||
// baseline start AutoCAD stored is judged against the tag's width too. A stored point that is
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user