mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-23 14:25:22 -06:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6cc7e0c881 | ||
|
|
f7f409b2b0 | ||
|
|
16929ef8ef | ||
|
|
a8c50b0924 | ||
|
|
bebbdca51a | ||
|
|
90d0942548 | ||
|
|
186e465487 | ||
|
|
c79fdde52d | ||
|
|
d4fd0dd7a2 | ||
|
|
a70b9b02e4 | ||
|
|
b206eab39b | ||
|
|
8d3236c5a3 | ||
|
|
f4d4a6e4e1 | ||
|
|
80e9a97164 | ||
|
|
b39170aded | ||
|
|
318d8d9de1 | ||
|
|
4076a71dee | ||
|
|
e5a7d38a67 | ||
|
|
46053d43c1 | ||
|
|
6aa64fb5ae | ||
|
|
543285778b | ||
|
|
fed8b0f4e4 | ||
|
|
dab89a38ed | ||
|
|
3ee12a8c62 | ||
|
|
5869cf91f9 | ||
|
|
8e2aa822f7 | ||
|
|
a34cf69439 | ||
|
|
6ec0f2400a | ||
|
|
18effe68b4 | ||
|
|
b325046f76 | ||
|
|
48bcb817ed | ||
|
|
275f989aa5 | ||
|
|
ad6d3d12ca | ||
|
|
6412e9c99a | ||
|
|
f7c4c148a3 | ||
|
|
0bd4d54f4a | ||
|
|
11ee9f1f64 | ||
|
|
e928316c4d | ||
|
|
1a3d2f6015 | ||
|
|
41f9e394b9 | ||
|
|
2bd916661d | ||
|
|
b3a1e1af40 |
@@ -38,7 +38,7 @@ jobs:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
|
||||
with:
|
||||
dry-run: ${{ github.event_name == 'schedule' }}
|
||||
nightly: ${{ github.event_name == 'schedule' }}
|
||||
app-name: cadcraft
|
||||
app-title: CADCraft
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
@@ -60,3 +60,4 @@ 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 }}
|
||||
|
||||
@@ -81,3 +81,38 @@ Generated-in-code assets are original and have no file to list:
|
||||
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
|
||||
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending |
|
||||
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
|
||||
|
||||
|
||||
## PDF import
|
||||
|
||||
The CAD mapping and initial synthetic PDF tests are adapted from CADCraft contributor
|
||||
@DuukDuul's [PR #2787](https://github.com/storytold/cadcraft/pull/2787), commit
|
||||
`ec17f63f189d1dccf91357701f9bba243ca88dd5`, under MIT OR Apache-2.0. The mapping has
|
||||
been changed for the current shared reader, bounded import, fill rules and diagnostics.
|
||||
PDF test inputs in `crates/io/tests/it/pdf_import.rs`, `crates/io/src/pdf_read.rs`, and
|
||||
`apps/cadcraft-cli/tests/it/pdf_import.rs` are generated from literal content streams or
|
||||
CadCraft's own plotter. No customer documents are included.
|
||||
|
||||
Enabling `craft-pdf` interpretation uses the following unchanged dependency assets from
|
||||
`craft-libs` revision `453b0da782ccef39be9a6dac8d27c80b553ef1cc`. Fonts remain in the
|
||||
shared dependency. Their source and hashes are retained below; notices are in `NOTICE`.
|
||||
|
||||
| Asset | Author | Source | Licence | SHA-256 | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
|
||||
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/pdfcraft/blob/a2ec27b4775f53c40cad3456936d9406611e3a8d/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
|
||||
|
||||
Generated
+123
-6
@@ -156,19 +156,34 @@ dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib 2.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-no-stdlib 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -592,14 +607,35 @@ dependencies = [
|
||||
"piper",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli"
|
||||
version = "8.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib 2.0.4",
|
||||
"alloc-stdlib 0.2.4",
|
||||
"brotli-decompressor 5.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "5.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib 2.0.4",
|
||||
"alloc-stdlib 0.2.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "6.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
"alloc-no-stdlib 3.0.0",
|
||||
"alloc-stdlib 0.3.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -784,6 +820,8 @@ dependencies = [
|
||||
"craft-pdf",
|
||||
"craft-svg",
|
||||
"image",
|
||||
"kurbo",
|
||||
"lyon_tessellation",
|
||||
"miniz_oxide 0.9.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1320,7 +1358,7 @@ name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
"craft-tiff",
|
||||
"quick-xml 0.41.0",
|
||||
@@ -1342,6 +1380,7 @@ name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
"krilla",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2474,11 +2513,39 @@ version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
"hayro-syntax",
|
||||
"kurbo",
|
||||
"moxcms",
|
||||
"phf 0.13.1",
|
||||
"rustc-hash 2.1.3",
|
||||
"siphasher",
|
||||
"skrifa 0.47.0",
|
||||
"smallvec",
|
||||
"yoke",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
]
|
||||
|
||||
@@ -2491,13 +2558,21 @@ dependencies = [
|
||||
"fearless_simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
"hayro-jbig2",
|
||||
"hayro-jpeg2000",
|
||||
"memchr",
|
||||
"rustc-hash 2.1.3",
|
||||
"smallvec",
|
||||
"stringprep",
|
||||
@@ -3897,17 +3972,37 @@ dependencies = [
|
||||
"phf_shared 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
|
||||
dependencies = [
|
||||
"phf_macros 0.13.1",
|
||||
"phf_shared 0.13.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"
|
||||
dependencies = [
|
||||
"phf_macros",
|
||||
"phf_macros 0.14.0",
|
||||
"phf_shared 0.14.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_generator"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"phf_shared 0.13.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_generator"
|
||||
version = "0.14.0"
|
||||
@@ -3918,13 +4013,26 @@ dependencies = [
|
||||
"phf_shared 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_macros"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
|
||||
dependencies = [
|
||||
"phf_generator 0.13.1",
|
||||
"phf_shared 0.13.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_macros"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085"
|
||||
dependencies = [
|
||||
"phf_generator",
|
||||
"phf_generator 0.14.0",
|
||||
"phf_shared 0.14.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -3940,6 +4048,15 @@ dependencies = [
|
||||
"siphasher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_shared"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
|
||||
dependencies = [
|
||||
"siphasher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_shared"
|
||||
version = "0.14.0"
|
||||
|
||||
@@ -48,6 +48,8 @@ thiserror = "2"
|
||||
same-file = "1"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip", "raw_value"] }
|
||||
# Geometry types shared with the PDF interpreter.
|
||||
kurbo = "0.13"
|
||||
log = "0.4"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
@@ -116,6 +118,9 @@ debug = 0
|
||||
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" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -172,3 +172,192 @@ Original src/avx2/fdct.rs opening notice
|
||||
* Based on the x86 SIMD extension for IJG JPEG library
|
||||
* Copyright (C) 1999-2006, MIYASAKA Masaru.
|
||||
*/
|
||||
|
||||
|
||||
PDF import dependency notices
|
||||
=============================
|
||||
|
||||
The PDF import mapping and synthetic tests derive from CADCraft PR #2787,
|
||||
commit ec17f63f189d1dccf91357701f9bba243ca88dd5 (MIT OR Apache-2.0).
|
||||
Local adaptations retain the project licences.
|
||||
|
||||
Standard PDF font programs (PDFium, BSD-3-Clause)
|
||||
|
||||
// Copyright 2014 PDFium Authors. All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
CMYK profile (CC0-1.0)
|
||||
|
||||
CC0 1.0 Universal
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator and
|
||||
subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for the
|
||||
purpose of contributing to a commons of creative, cultural and scientific
|
||||
works ("Commons") that the public can reliably and without fear of later
|
||||
claims of infringement build upon, modify, incorporate in other works, reuse
|
||||
and redistribute as freely as possible in any form whatsoever and for any
|
||||
purposes, including without limitation commercial purposes. These owners may
|
||||
contribute to the Commons to promote the ideal of a free culture and the
|
||||
further production of creative, cultural and scientific works, or to gain
|
||||
reputation or greater distribution for their Work in part through the use and
|
||||
efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any expectation
|
||||
of additional consideration or compensation, the person associating CC0 with a
|
||||
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
|
||||
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
|
||||
and publicly distribute the Work under its terms, with knowledge of his or her
|
||||
Copyright and Related Rights in the Work and the meaning and intended legal
|
||||
effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not limited
|
||||
to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display, communicate,
|
||||
and translate a Work;
|
||||
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
|
||||
iii. publicity and privacy rights pertaining to a person's image or likeness
|
||||
depicted in a Work;
|
||||
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data in
|
||||
a Work;
|
||||
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation thereof,
|
||||
including any amended or successor version of such directive); and
|
||||
|
||||
vii. other similar, equivalent or corresponding rights throughout the world
|
||||
based on applicable law or treaty, and any national implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention of,
|
||||
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
|
||||
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
|
||||
and Related Rights and associated claims and causes of action, whether now
|
||||
known or unknown (including existing as well as future claims and causes of
|
||||
action), in the Work (i) in all territories worldwide, (ii) for the maximum
|
||||
duration provided by applicable law or treaty (including future time
|
||||
extensions), (iii) in any current or future medium and for any number of
|
||||
copies, and (iv) for any purpose whatsoever, including without limitation
|
||||
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
|
||||
the Waiver for the benefit of each member of the public at large and to the
|
||||
detriment of Affirmer's heirs and successors, fully intending that such Waiver
|
||||
shall not be subject to revocation, rescission, cancellation, termination, or
|
||||
any other legal or equitable action to disrupt the quiet enjoyment of the Work
|
||||
by the public as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason be
|
||||
judged legally invalid or ineffective under applicable law, then the Waiver
|
||||
shall be preserved to the maximum extent permitted taking into account
|
||||
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
|
||||
is so judged Affirmer hereby grants to each affected person a royalty-free,
|
||||
non transferable, non sublicensable, non exclusive, irrevocable and
|
||||
unconditional license to exercise Affirmer's Copyright and Related Rights in
|
||||
the Work (i) in all territories worldwide, (ii) for the maximum duration
|
||||
provided by applicable law or treaty (including future time extensions), (iii)
|
||||
in any current or future medium and for any number of copies, and (iv) for any
|
||||
purpose whatsoever, including without limitation commercial, advertising or
|
||||
promotional purposes (the "License"). The License shall be deemed effective as
|
||||
of the date CC0 was applied by Affirmer to the Work. Should any part of the
|
||||
License for any reason be judged legally invalid or ineffective under
|
||||
applicable law, such partial invalidity or ineffectiveness shall not
|
||||
invalidate the remainder of the License, and in such case Affirmer hereby
|
||||
affirms that he or she will not (i) exercise any of his or her remaining
|
||||
Copyright and Related Rights in the Work or (ii) assert any associated claims
|
||||
and causes of action with respect to the Work, in either case contrary to
|
||||
Affirmer's express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
|
||||
b. Affirmer offers the Work as-is and makes no representations or warranties
|
||||
of any kind concerning the Work, express, implied, statutory or otherwise,
|
||||
including without limitation warranties of title, merchantability, fitness
|
||||
for a particular purpose, non infringement, or the absence of latent or
|
||||
other defects, accuracy, or the present or absence of errors, whether or not
|
||||
discoverable, all to the greatest extent permissible under applicable law.
|
||||
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without limitation
|
||||
any person's Copyright and Related Rights in the Work. Further, Affirmer
|
||||
disclaims responsibility for obtaining any necessary consents, permissions
|
||||
or other rights required for any use of the Work.
|
||||
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to this
|
||||
CC0 or use of the Work.
|
||||
|
||||
For more information, please see
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
|
||||
PDF character maps: LICENSE.txt
|
||||
|
||||
Copyright 1990-2023 Adobe. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
Neither the name of Adobe nor the names of its contributors may be
|
||||
used to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
@@ -26,12 +26,12 @@ fn with_formats(cell: &'static std::sync::OnceLock<String>, before: &str, list:
|
||||
/// The drawing an input argument names.
|
||||
fn read_help() -> &'static str {
|
||||
static C: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
with_formats(&C, "The drawing to read ", Format::READ, "")
|
||||
with_formats(&C, "The drawing to read ", Format::READ, ", or a PDF whose first page opens as editable vector content")
|
||||
}
|
||||
|
||||
fn open_help() -> &'static str {
|
||||
static C: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
with_formats(&C, "Drawings to open ", Format::READ, "")
|
||||
with_formats(&C, "Drawings to open ", Format::READ, ", or PDFs (their first page)")
|
||||
}
|
||||
|
||||
fn write_help() -> &'static str {
|
||||
|
||||
@@ -49,6 +49,7 @@ fn install_io() {
|
||||
cadcraft_engine::cmd::file::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())
|
||||
});
|
||||
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
|
||||
@@ -2,6 +2,7 @@ mod cli;
|
||||
mod drafting_spacing;
|
||||
mod help;
|
||||
mod mcp_connect;
|
||||
mod pdf_import;
|
||||
mod skipped_records;
|
||||
mod undrawn_entities;
|
||||
mod usage;
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! A PDF page converted on the command line keeps its geometry and its fill rules through a DXF
|
||||
//! or DWG save and reopen.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
const MM_PER_PT: f64 = 25.4 / 72.0;
|
||||
|
||||
/// A line, a nonzero fill of two nested squares wound the same way (all of it filled), an
|
||||
/// even-odd fill of the same squares (the inner one a hole) and a nonzero fill of two
|
||||
/// overlapping squares (split into triangles).
|
||||
const CONTENT: &str = "1 0 0 RG 2 w 10 10 m 100 10 l S\n\
|
||||
0 0 1 rg 200 200 m 300 200 l 300 300 l 200 300 l h 220 220 m 280 220 l 280 280 l 220 280 l h f\n\
|
||||
0 1 0 rg 400 400 m 500 400 l 500 500 l 400 500 l h 420 420 m 480 420 l 480 480 l 420 480 l h f*\n\
|
||||
1 0 1 rg 50 600 m 150 600 l 150 700 l 50 700 l h 100 650 m 200 650 l 200 750 l 100 750 l h f\n";
|
||||
|
||||
fn page(content: &str) -> Vec<u8> {
|
||||
format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R >> endobj\n\
|
||||
4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF\n",
|
||||
content.len()
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
/// A fresh scratch directory that is removed on drop, also when an assertion fails.
|
||||
struct Scratch(std::path::PathBuf);
|
||||
|
||||
impl Scratch {
|
||||
fn new(tag: &str) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir(&dir).expect("create scratch dir");
|
||||
Scratch(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The model space of `file` with each object's geometry.
|
||||
fn inspect(file: &str) -> Value {
|
||||
let out = cli(&["run", file, "--cmd", r#"drawing.inspect {"entities":true}"#]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(out.status.success(), "{file}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
serde_json::from_str(stdout.lines().last().unwrap_or_default()).unwrap_or_else(|e| panic!("{file}: {e}: {stdout}"))
|
||||
}
|
||||
|
||||
fn inside(ring: &[(f64, f64)], (x, y): (f64, f64)) -> bool {
|
||||
let mut odd = false;
|
||||
for (i, &(ax, ay)) in ring.iter().enumerate() {
|
||||
let (bx, by) = ring[(i + 1) % ring.len()];
|
||||
if (ay > y) != (by > y) && x < (bx - ax) * (y - ay) / (by - ay) + ax {
|
||||
odd = !odd;
|
||||
}
|
||||
}
|
||||
odd
|
||||
}
|
||||
|
||||
/// Whether a hatch covers the page point `at` (in PDF points), by odd parity as hatches are drawn.
|
||||
fn filled(drawing: &Value, at: (f64, f64)) -> bool {
|
||||
let at = (at.0 * MM_PER_PT, at.1 * MM_PER_PT);
|
||||
let entities = drawing["entities"].as_array().cloned().unwrap_or_default();
|
||||
entities.iter().filter(|e| e["type"] == "Hatch").any(|hatch| {
|
||||
let loops = hatch["geometry"]["loops"].as_array().cloned().unwrap_or_default();
|
||||
let rings = loops.iter().map(|l| {
|
||||
l["vertices"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|v| (v["p"]["x"].as_f64().unwrap_or(0.0), v["p"]["y"].as_f64().unwrap_or(0.0)))
|
||||
.collect()
|
||||
});
|
||||
rings.filter(|ring: &Vec<(f64, f64)>| inside(ring, at)).count() % 2 == 1
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pdf_page_keeps_its_fills_through_dxf_and_dwg() {
|
||||
let scratch = Scratch::new("pdf-import");
|
||||
let pdf = scratch.0.join("plan.pdf");
|
||||
std::fs::write(&pdf, page(CONTENT)).unwrap();
|
||||
let pdf = pdf.to_str().unwrap().to_string();
|
||||
let mut files = vec![pdf.clone()];
|
||||
for ext in ["dxf", "dwg"] {
|
||||
let out = scratch.0.join(format!("plan.{ext}"));
|
||||
let out = out.to_str().unwrap().to_string();
|
||||
let run = cli(&["convert", &pdf, &out]);
|
||||
assert!(run.status.success(), "convert to {ext}: {}", String::from_utf8_lossy(&run.stderr));
|
||||
files.push(out);
|
||||
}
|
||||
for file in &files {
|
||||
let d = inspect(file);
|
||||
assert_eq!(d["counts"]["Line"], 1, "{file}: {}", d["counts"]);
|
||||
assert_eq!(d["counts"]["Hatch"], 3, "{file}: {}", d["counts"]);
|
||||
assert!(filled(&d, (251.3, 247.7)), "{file}: the nonzero fill keeps its centre");
|
||||
assert!(filled(&d, (210.2, 205.9)), "{file}: the nonzero fill keeps its rim");
|
||||
assert!(!filled(&d, (451.3, 447.7)), "{file}: the even-odd fill keeps its hole");
|
||||
assert!(filled(&d, (410.2, 405.9)), "{file}: the even-odd fill keeps its rim");
|
||||
assert!(!filled(&d, (350.4, 351.7)), "{file}: nothing is filled between the shapes");
|
||||
assert!(filled(&d, (125.3, 675.2)), "{file}: the overlap of the crossing squares stays filled");
|
||||
assert!(filled(&d, (60.4, 610.3)) && filled(&d, (190.2, 740.1)), "{file}: both crossing squares stay filled");
|
||||
assert!(!filled(&d, (60.4, 740.1)), "{file}: the corner beside the crossing squares stays empty");
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,7 @@ mod web {
|
||||
cadcraft_engine::cmd::file::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())
|
||||
});
|
||||
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
|
||||
@@ -18,7 +18,7 @@ use web_sys::js_sys;
|
||||
/// The hidden file input (one at a time; a cancelled pick leaves it until the next one).
|
||||
const INPUT_ID: &str = "cadcraft_open_input";
|
||||
/// What the picker offers: the formats OPEN reads, and the SHX fonts drawings name.
|
||||
const ACCEPT: &str = ".dxf,.dwg,.shx";
|
||||
const ACCEPT: &str = ".dxf,.dwg,.pdf,.shx";
|
||||
|
||||
/// Most files taken from one pick.
|
||||
const MAX_PICKED: u32 = 64;
|
||||
|
||||
@@ -167,6 +167,7 @@ pub fn install_io() {
|
||||
cadcraft_engine::cmd::file::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())
|
||||
});
|
||||
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
@@ -200,6 +201,7 @@ fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> {
|
||||
Pick::Open => vec![
|
||||
(i18n::t("Drawings (DWG, DXF)"), vec!["dwg", "dxf", "dwt"]),
|
||||
(i18n::t("SVG drawings (SVG, SVGZ)"), vec!["svg", "svgz"]),
|
||||
(i18n::t("PDF files (PDF)"), vec!["pdf"]),
|
||||
(i18n::t("All files"), vec!["*"]),
|
||||
],
|
||||
Pick::Save(name) => filters_for_save(name).iter().map(|(label, ext)| (i18n::t(label), vec![*ext])).collect(),
|
||||
|
||||
@@ -85,6 +85,9 @@ 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 {
|
||||
@@ -103,6 +106,7 @@ 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
|
||||
|
||||
@@ -821,6 +821,18 @@ 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 {
|
||||
@@ -844,6 +856,8 @@ impl Default for PageSetup {
|
||||
paper_mm: None,
|
||||
file_paper: None,
|
||||
image_origin: None,
|
||||
file_plot_flags: None,
|
||||
file_standard_scale: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ mod draw;
|
||||
mod draw2;
|
||||
mod draworder;
|
||||
mod edit;
|
||||
mod exchange;
|
||||
pub mod exchange;
|
||||
pub mod file;
|
||||
mod gripcmds;
|
||||
mod griphot;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Moving drawings in and out: EXPORT (DXF, DWG, SVG, PNG or PDF), IMPORT (the objects of another
|
||||
//! DXF/DWG file), PREVIEW (a picture of the plot) and PUBLISH (plot several sheets at once).
|
||||
//! DXF/DWG file or a PDF page), PREVIEW (a picture of the plot) and PUBLISH (plot several sheets at once).
|
||||
//! ATTACH, SHARE and 3DORBIT are registered so the tool bar and command line say they are not
|
||||
//! available yet.
|
||||
//!
|
||||
@@ -35,7 +35,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec::new("import", "Import...", run_import)
|
||||
.menu(&["File", "Import..."])
|
||||
.alias(&["imp"])
|
||||
.params("{path | data: base64, name?: \"x.dwg\"} (DXF or DWG), at?: [x,y] (default 0,0), scale?: (default 1) → {imported, handles, layers, styles, blocks}"),
|
||||
.params("{path | data: base64, name?: \"x.dwg\"} (DXF or DWG; PDF pages can be imported too), at?: [x,y] (default 0,0), scale?: (default 1) → {imported, handles, layers, styles, blocks}"),
|
||||
CommandSpec::new("pdfimport", "Import PDF...", run_pdfimport)
|
||||
.menu(&["File", "Import PDF..."])
|
||||
.alias(&["pdfi"])
|
||||
.params("{path | data: base64, name?: \"x.pdf\", page?: 1.. (default 1), password?, at?: [x,y] (default 0,0), scale?: (default 1), text?: true, fills?: true, lineweights?: true} → {imported, handles, layers, pages, page, warnings?}: vector paths, fills and supported text become editable objects; raster images and other unsupported content are reported. A scanned PDF has no editable vector content"),
|
||||
CommandSpec::new("export", "Export...", run_export)
|
||||
.menu(&["File", "Export..."])
|
||||
.alias(&["exp"])
|
||||
@@ -135,28 +139,153 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ---------- IMPORT ----------
|
||||
|
||||
fn run_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hooks = io().ok_or_else(|| bad("import", "file formats are not available in this build"))?;
|
||||
/// A PDF page reader installed by the app that links the PDF library.
|
||||
pub type PdfImportHook = fn(&[u8], &Value) -> std::result::Result<(Drawing, usize), String>;
|
||||
|
||||
static PDF_IMPORT: std::sync::OnceLock<PdfImportHook> = std::sync::OnceLock::new();
|
||||
|
||||
/// Install the PDF page reader used by OPEN, IMPORT and PDFIMPORT.
|
||||
pub fn set_pdf_import(hook: PdfImportHook) {
|
||||
let _ = PDF_IMPORT.set(hook);
|
||||
}
|
||||
|
||||
fn is_pdf(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(b"%PDF-")
|
||||
}
|
||||
|
||||
/// Read a PDF's first page as a metric drawing when this host has installed a PDF reader.
|
||||
pub(super) fn open_pdf(bytes: &[u8]) -> Option<std::result::Result<Drawing, String>> {
|
||||
if !is_pdf(bytes) {
|
||||
return None;
|
||||
}
|
||||
let read = PDF_IMPORT.get()?;
|
||||
Some(read(bytes, &json!({ "unit": 25.4 / 72.0 })).and_then(|(drawing, _)| {
|
||||
if drawing.model.is_empty() {
|
||||
let notes = drawing.read_notes.join("; ");
|
||||
let message = if notes.is_empty() {
|
||||
"PDF page 1 has no editable vector content; scanned drawings need manual tracing".to_string()
|
||||
} else {
|
||||
format!("PDF page 1 has no editable vector content; scanned drawings need manual tracing. {notes}")
|
||||
};
|
||||
Err(message)
|
||||
} else {
|
||||
Ok(drawing)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
/// Read an import source from a path or base64 data.
|
||||
fn source_file(cmd: &str, p: &Value, default_name: &str) -> Result<(Vec<u8>, String)> {
|
||||
if let Some(path) = str_param(p, "path") {
|
||||
return Ok((read_file(path)?, path.to_string()));
|
||||
}
|
||||
let data = str_param(p, "data").ok_or_else(|| bad(cmd, "`path` or `data` (base64) is required"))?;
|
||||
Ok((base64_decode(data).ok_or_else(|| bad(cmd, "invalid base64"))?, str_param(p, "name").unwrap_or(default_name).to_string()))
|
||||
}
|
||||
|
||||
/// Parse the optional insertion point and scale shared by import commands.
|
||||
fn placement(cmd: &str, p: &Value) -> Result<(Vec2, f64)> {
|
||||
let at = match p.get("at") {
|
||||
Some(v) => point_value(v).ok_or_else(|| bad("import", "`at` must be a point [x, y]"))?,
|
||||
Some(v) => point_value(v).ok_or_else(|| bad(cmd, "`at` must be a point [x, y]"))?,
|
||||
None => Vec2::ZERO,
|
||||
};
|
||||
let scale = match p.get("scale") {
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|k| k.is_finite() && (1e-9..=1e9).contains(&k.abs()))
|
||||
.ok_or_else(|| bad("import", "`scale` must be a non-zero number"))?,
|
||||
Some(v) => {
|
||||
v.as_f64().filter(|k| k.is_finite() && (1e-9..=1e9).contains(&k.abs())).ok_or_else(|| bad(cmd, "`scale` must be a non-zero number"))?
|
||||
}
|
||||
None => 1.0,
|
||||
};
|
||||
let (bytes, name) = if let Some(path) = str_param(p, "path") {
|
||||
(read_file(path)?, path.to_string())
|
||||
} else {
|
||||
let data = str_param(p, "data").ok_or_else(|| bad("import", "`path` or `data` (base64) is required"))?;
|
||||
(base64_decode(data).ok_or_else(|| bad("import", "invalid base64"))?, str_param(p, "name").unwrap_or("import.dxf").to_string())
|
||||
};
|
||||
Ok((at, scale))
|
||||
}
|
||||
|
||||
fn source_name(name: &str) -> String {
|
||||
std::path::Path::new(name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn run_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (at, scale) = placement("import", p)?;
|
||||
let (bytes, name) = source_file("import", p, "import.dxf")?;
|
||||
if is_pdf(&bytes) {
|
||||
return import_pdf(s, "import", p, &bytes, &name, at, scale);
|
||||
}
|
||||
let hooks = io().ok_or_else(|| bad("import", "file formats are not available in this build"))?;
|
||||
let src = (hooks.read)(&bytes, &name).map_err(|e| bad("import", e))?;
|
||||
let file = std::path::Path::new(&name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
import_drawing(s, &src, at, scale, &file)
|
||||
import_drawing(s, &src, at, scale, &source_name(&name))
|
||||
}
|
||||
|
||||
/// Convert millimetres to the current drawing's `$INSUNITS`.
|
||||
fn units_per_mm(d: &Drawing) -> f64 {
|
||||
match d.header.i64("INSUNITS", 4) {
|
||||
1 => 1.0 / 25.4,
|
||||
2 => 1.0 / 304.8,
|
||||
3 => 1.0 / 1_609_344.0,
|
||||
5 => 0.1,
|
||||
6 => 0.001,
|
||||
7 => 1e-6,
|
||||
8 => 39_370.078_74,
|
||||
9 => 39.370_078_74,
|
||||
10 => 1.0 / 914.4,
|
||||
11 => 1e7,
|
||||
12 => 1e6,
|
||||
13 => 1e3,
|
||||
14 => 0.01,
|
||||
15 => 1e-4,
|
||||
16 => 1e-5,
|
||||
17 => 1e-12,
|
||||
18 => 1.0 / 1.495_978_707e14,
|
||||
19 => 1.0 / 9.460_730_472_580_8e18,
|
||||
20 => std::f64::consts::PI / (648_000.0 * 1.495_978_707e14),
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn run_pdfimport(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (at, scale) = placement("pdfimport", p)?;
|
||||
let (bytes, name) = source_file("pdfimport", p, "import.pdf")?;
|
||||
if !is_pdf(&bytes) {
|
||||
return Err(bad("pdfimport", format!("{} is not a PDF file", source_name(&name))));
|
||||
}
|
||||
import_pdf(s, "pdfimport", p, &bytes, &name, at, scale)
|
||||
}
|
||||
|
||||
fn import_pdf(s: &mut Session, cmd: &str, p: &Value, bytes: &[u8], name: &str, at: Vec2, scale: f64) -> Result<Value> {
|
||||
let read = PDF_IMPORT.get().ok_or_else(|| bad(cmd, "PDF import is not available in this build"))?;
|
||||
let unit = 25.4 / 72.0 * units_per_mm(s.doc()?);
|
||||
let mut options = serde_json::Map::new();
|
||||
options.insert("unit".into(), json!(unit));
|
||||
for key in ["page", "password", "text", "fills", "lineweights"] {
|
||||
if let Some(value) = p.get(key) {
|
||||
options.insert(key.into(), value.clone());
|
||||
}
|
||||
}
|
||||
let (source, pages) = read(bytes, &Value::Object(options)).map_err(|e| bad(cmd, e))?;
|
||||
let page = p.get("page").and_then(Value::as_u64).unwrap_or(1);
|
||||
if source.model.is_empty() {
|
||||
let detail = source.read_notes.join("; ");
|
||||
let message = if detail.is_empty() {
|
||||
"the selected PDF page has no editable vector content; scanned drawings need manual tracing".to_string()
|
||||
} else {
|
||||
format!("the selected PDF page has no editable vector content; scanned drawings need manual tracing. {detail}")
|
||||
};
|
||||
return Err(bad(cmd, message));
|
||||
}
|
||||
let warnings = source.read_notes.clone();
|
||||
let mut result = import_drawing(s, &source, at, scale, &source_name(name))?;
|
||||
if let Some(object) = result.as_object_mut() {
|
||||
object.insert("pages".into(), json!(pages));
|
||||
object.insert("page".into(), json!(page));
|
||||
object.insert("warnings".into(), json!(warnings));
|
||||
let imported = object.get("imported").and_then(Value::as_u64).unwrap_or(0);
|
||||
let mut message = format!("{imported} objects imported from page {page} of {pages} of {}", source_name(name));
|
||||
if !source.read_notes.is_empty() {
|
||||
message.push_str(". Some PDF content was omitted or approximated. See the command history for details.");
|
||||
for note in &source.read_notes {
|
||||
s.echo(note.clone());
|
||||
}
|
||||
}
|
||||
object.insert("message".into(), json!(message));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Copy `src`'s model space into the current space (scaled about the origin, then moved to
|
||||
@@ -592,6 +721,25 @@ mod tests {
|
||||
s
|
||||
}
|
||||
|
||||
fn scanned_pdf(_: &[u8], _: &Value) -> std::result::Result<(Drawing, usize), String> {
|
||||
let mut drawing = Drawing::new_metric();
|
||||
drawing.read_notes.push("PDF: 1 raster image was not imported".into());
|
||||
Ok((drawing, 1))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanned_pdf_does_not_open_or_import_as_an_empty_drawing() {
|
||||
set_pdf_import(scanned_pdf);
|
||||
let data = base64_encode(b"%PDF-1.7 synthetic scan");
|
||||
let mut s = Session::new();
|
||||
let before = s.doc().unwrap().model.len();
|
||||
let open = s.execute("open", &json!({ "data": data, "name": "scan.pdf" })).unwrap_err().to_string();
|
||||
assert!(open.contains("no editable vector content") && open.contains("raster image"), "{open}");
|
||||
let import = s.execute("pdfimport", &json!({ "data": data, "name": "scan.pdf" })).unwrap_err().to_string();
|
||||
assert!(import.contains("manual tracing") && import.contains("raster image"), "{import}");
|
||||
assert_eq!(s.doc().unwrap().model.len(), before, "no empty drawing was opened or imported");
|
||||
}
|
||||
|
||||
fn temp(name: &str) -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!("cadcraft-exchange-{}-{name}", std::process::id()))
|
||||
}
|
||||
|
||||
@@ -373,11 +373,16 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result<Value> {
|
||||
|
||||
/// Parse a drawing's bytes, and search its folder for fonts where the automation roots allow.
|
||||
fn read_bytes(bytes: &[u8], name: &str, path: Option<String>) -> Result<ReadFile> {
|
||||
let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?;
|
||||
let drawing = (hooks.read)(bytes, name).map_err(|e| bad("open", e))?;
|
||||
let drawing = match super::exchange::open_pdf(bytes) {
|
||||
Some(result) => result.map_err(|e| bad("open", e))?,
|
||||
None => {
|
||||
let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?;
|
||||
(hooks.read)(bytes, name).map_err(|e| bad("open", e))?
|
||||
}
|
||||
};
|
||||
// A file that isn't a drawing (an imported SVG) gives the drawing no file name: QSAVE then
|
||||
// asks where to save instead of exporting over the original.
|
||||
let path = path.filter(|p| is_drawing_file(p));
|
||||
let path = path.filter(|p| is_drawing_file(p) && !bytes.starts_with(b"%PDF-"));
|
||||
// The SHX fonts its text styles name are looked for beside the drawing too.
|
||||
if let Some(dir) = path.as_deref().and_then(|p| std::path::Path::new(p).parent()) {
|
||||
// A bare file name is in the current folder.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! 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};
|
||||
@@ -36,6 +37,9 @@ 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)
|
||||
|
||||
@@ -29,6 +29,59 @@ 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)
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ pub const FILES: &[&str] = &[
|
||||
"options",
|
||||
"pagesetup",
|
||||
"pdfbook",
|
||||
"pdfimport",
|
||||
"plot",
|
||||
"plotstyle",
|
||||
"plottermanager",
|
||||
@@ -235,6 +236,7 @@ pub const NO_FILES: &[&str] = &[
|
||||
"boundary",
|
||||
"region",
|
||||
"hatchedit",
|
||||
"hatchgenerateboundary",
|
||||
"hatchpick",
|
||||
"overkill",
|
||||
"block",
|
||||
|
||||
@@ -126,23 +126,14 @@ 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: the snap [`crate::snap::osnap`] picks
|
||||
/// first, then the closest snap of each other mode in `osmode`, nearest first, without repeats.
|
||||
/// 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.
|
||||
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();
|
||||
}
|
||||
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
|
||||
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
|
||||
}
|
||||
|
||||
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
|
||||
|
||||
+143
-59
@@ -72,6 +72,33 @@ 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.
|
||||
@@ -211,6 +238,14 @@ 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,
|
||||
@@ -237,19 +272,39 @@ 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 (None, None);
|
||||
return (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 (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 views = viewport::near(d, space, cursor, aperture);
|
||||
if views.is_empty() {
|
||||
return (best, near_prims);
|
||||
return (all, 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;
|
||||
@@ -257,7 +312,7 @@ pub(crate) fn osnap_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 hit = osnap_in(
|
||||
let hits = osnap_in(
|
||||
d,
|
||||
&model,
|
||||
&model_ix,
|
||||
@@ -268,15 +323,36 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
deferred,
|
||||
&view.viewport.frozen_layers,
|
||||
Some(view.model_clip),
|
||||
)
|
||||
.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))
|
||||
);
|
||||
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))
|
||||
{
|
||||
best = Some(hit);
|
||||
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, near_prims)
|
||||
out
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -291,10 +367,11 @@ fn osnap_in(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit)
|
||||
) -> Vec<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 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,
|
||||
@@ -307,7 +384,7 @@ fn osnap_in_with_prims(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<(Option<SnapHit>, Vec<Prim>)> {
|
||||
) -> Option<(Vec<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
|
||||
@@ -345,8 +422,8 @@ fn osnap_in_with_prims(
|
||||
}
|
||||
}
|
||||
}
|
||||
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hit, near_prims))
|
||||
let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hits, near_prims))
|
||||
}
|
||||
|
||||
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
|
||||
@@ -458,7 +535,8 @@ fn gather_in(
|
||||
Some((cands, near_prims))
|
||||
}
|
||||
|
||||
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps.
|
||||
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
|
||||
/// snaps, the deferred snaps and Nearest.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish(
|
||||
mut cands: Vec<(u32, Vec2)>,
|
||||
@@ -469,7 +547,7 @@ fn finish(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<SnapHit> {
|
||||
) -> Vec<SnapHit> {
|
||||
// Perpendicular / tangent from the base point.
|
||||
if let Some(bp) = base {
|
||||
for p in near_prims {
|
||||
@@ -507,20 +585,10 @@ fn finish(
|
||||
}
|
||||
}
|
||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||
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);
|
||||
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));
|
||||
}
|
||||
if osmode & mode::NEA != 0 {
|
||||
// The closest point of all nearby objects, whatever their drawing order.
|
||||
@@ -540,12 +608,13 @@ fn finish(
|
||||
}
|
||||
}
|
||||
if let Some((_, p)) = nb {
|
||||
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
|
||||
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
|
||||
}
|
||||
}
|
||||
None
|
||||
ranked(hits, cursor, aperture)
|
||||
}
|
||||
|
||||
/// 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 }
|
||||
}
|
||||
@@ -848,9 +917,11 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
/// 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();
|
||||
for p in prims {
|
||||
let curve = match p {
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||
@@ -859,32 +930,28 @@ fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip:
|
||||
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
|
||||
_ => continue,
|
||||
};
|
||||
let (m, name, at) = match curve {
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
|
||||
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
|
||||
// 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);
|
||||
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
|
||||
if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) }
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let dd = at.dist(cursor);
|
||||
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
|
||||
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) }));
|
||||
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 }) });
|
||||
}
|
||||
}
|
||||
best.map(|(_, h)| h)
|
||||
hits
|
||||
}
|
||||
|
||||
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
|
||||
@@ -1121,6 +1188,23 @@ 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();
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
//! 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,6 +68,7 @@ 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;
|
||||
|
||||
@@ -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};
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -278,6 +278,46 @@ 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,7 +1,9 @@
|
||||
//! 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.
|
||||
@@ -62,6 +64,27 @@ 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();
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
//! 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,6 +1,6 @@
|
||||
[package]
|
||||
name = "cadcraft-io"
|
||||
description = "CADCraft file formats: DXF read/write mapping, SVG, PNG and PDF export"
|
||||
description = "CADCraft file formats: DXF/DWG, SVG and PDF import, SVG/PNG/PDF export"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -21,7 +21,9 @@ cadcraft-fonts = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
craft-pdf = { workspace = true, features = ["write"] }
|
||||
craft-pdf = { workspace = true, features = ["write", "interpret"] }
|
||||
kurbo = { workspace = true }
|
||||
lyon_tessellation = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
miniz_oxide = "0.9"
|
||||
|
||||
@@ -457,6 +457,10 @@ 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() {
|
||||
@@ -1267,7 +1271,7 @@ pub(crate) fn finish(
|
||||
join_entries(&map, b, kept, &mut out);
|
||||
}
|
||||
}
|
||||
add_appids(&mut out);
|
||||
add_appids(&mut out, &f.appids);
|
||||
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)
|
||||
@@ -1593,9 +1597,13 @@ fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
/// 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());
|
||||
}
|
||||
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")
|
||||
|
||||
@@ -88,6 +88,7 @@ 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 {
|
||||
@@ -577,7 +578,7 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
|
||||
break;
|
||||
}
|
||||
}
|
||||
let c = common(t);
|
||||
let mut 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
|
||||
@@ -599,13 +600,26 @@ 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: mirrored like LWPOLYLINE.
|
||||
let m = if c.extrusion.z < 0.0 { -1.0 } else { 1.0 };
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
EntityKind::LwPolyline(LwPolyline {
|
||||
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,
|
||||
vertices,
|
||||
closed,
|
||||
const_width: t.fd(40, 0.0).min(t.fd(41, 0.0)).max(0.0),
|
||||
elevation: t.p(10).z,
|
||||
elevation,
|
||||
plinegen: flags & 128 != 0,
|
||||
})
|
||||
};
|
||||
@@ -714,3 +728,11 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,6 +421,8 @@ 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;
|
||||
@@ -432,6 +434,13 @@ 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",
|
||||
|
||||
@@ -108,7 +108,10 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
EntityKind::Line(l) => {
|
||||
w.s(0, "LINE");
|
||||
common(w, e, owner, paper, "AcDbLine");
|
||||
thickness(w, e);
|
||||
// Along the normal written with it (210 below), as read.
|
||||
if e.common.thickness != 0.0 {
|
||||
w.f(39, e.common.thickness);
|
||||
}
|
||||
w.p(10, l.a);
|
||||
w.p(11, l.b);
|
||||
extrusion(w, e);
|
||||
@@ -156,8 +159,13 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
if p.const_width > 0.0 {
|
||||
w.f(43, p.const_width);
|
||||
}
|
||||
if p.elevation != 0.0 {
|
||||
w.f(38, p.elevation);
|
||||
// The elevation runs along the polyline's normal, which isn't written: one facing down
|
||||
// Z is at the elevation's negative. That is exact for a normal of 0,0,-1 only; a tilted
|
||||
// one pointing partly down is flipped the same way (the reader brings tilted polylines
|
||||
// into plan with normal Z, so only other sources make one).
|
||||
let elevation = if e.common.extrusion.z < 0.0 { -p.elevation } else { p.elevation };
|
||||
if elevation != 0.0 {
|
||||
w.f(38, elevation);
|
||||
}
|
||||
thickness(w, e);
|
||||
for v in &p.vertices {
|
||||
@@ -609,7 +617,10 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
|
||||
if let EntityKind::Hatch(h) = &e.kind {
|
||||
w.s(0, "HATCH");
|
||||
common(w, e, owner, paper, "AcDbHatch");
|
||||
w.p(10, Vec3::new(0.0, 0.0, h.elevation));
|
||||
// Its elevation runs along its normal, written as Z: one facing down is at the negative.
|
||||
// Exact for a normal of 0,0,-1; the reader brings a tilted hatch into plan with normal Z.
|
||||
let elevation = if e.common.extrusion.z < 0.0 { -h.elevation } else { h.elevation };
|
||||
w.p(10, Vec3::new(0.0, 0.0, elevation));
|
||||
w.p(210, Vec3::Z);
|
||||
w.s(2, &h.pattern);
|
||||
w.i(70, i64::from(h.solid));
|
||||
@@ -829,10 +840,14 @@ fn gradient(w: &mut W, g: &Gradient) {
|
||||
w.s(1000, g.color2.name());
|
||||
}
|
||||
|
||||
/// Group 39 (thickness) of the entities whose DXF Reference record has one; only when set.
|
||||
/// Group 39 (thickness) of the entities whose DXF Reference record has one; only when set. They
|
||||
/// are written with no normal, so they extrude along Z: one whose normal points down Z extrudes
|
||||
/// the other way, and its thickness changes sign. That is exact for a normal of 0,0,-1; a tilted
|
||||
/// one pointing partly down only gets the closer of the two directions.
|
||||
fn thickness(w: &mut W, e: &Entity) {
|
||||
if e.common.thickness != 0.0 {
|
||||
w.f(39, e.common.thickness);
|
||||
let t = if e.common.extrusion.z < 0.0 { -e.common.thickness } else { e.common.thickness };
|
||||
if t != 0.0 {
|
||||
w.f(39, t);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -413,6 +413,23 @@ struct LayoutWriteData<'a> {
|
||||
limits: Option<(Vec2, Vec2)>,
|
||||
}
|
||||
|
||||
/// The plot layout flags (AcDbPlotSettings group 70) for `page`. The bits CADCraft models come
|
||||
/// from the page: 2 display plot styles, 4 centred, 128 lineweights, and 16 standard scale where
|
||||
/// the scale decides it (scaled to fit: set; a custom scale: clear). The rest are kept as the file
|
||||
/// had them (#3227); a page CADCraft made gets 512 (plot paper space last) and 32 (plot with plot
|
||||
/// styles), and 16 when its scale is standard.
|
||||
fn plot_layout_flags(page: &PageSetup, standard: bool) -> i64 {
|
||||
const MODELED: i64 = 2 | 4 | 128;
|
||||
const STANDARD_SCALE: i64 = 16;
|
||||
let kept = match page.file_plot_flags {
|
||||
Some(f) if page.scale_to_fit => (f & !MODELED) | STANDARD_SCALE,
|
||||
Some(f) if !standard => f & !MODELED & !STANDARD_SCALE,
|
||||
Some(f) => f & !MODELED,
|
||||
None => 512 | 32 | if standard { STANDARD_SCALE } else { 0 },
|
||||
};
|
||||
kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 }
|
||||
}
|
||||
|
||||
fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<'_>) {
|
||||
let d = context.drawing;
|
||||
let layout_dict = context.dictionary;
|
||||
@@ -426,13 +443,10 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
|
||||
// Plot scale: a standard scale when fitting or 1:1, otherwise custom (142 paper units
|
||||
// per 143 drawing units).
|
||||
let scale = if page.scale.is_finite() && page.scale > 0.0 { page.scale } else { 1.0 };
|
||||
let standard = page.scale_to_fit || scale == 1.0;
|
||||
let plot_flags = 512
|
||||
| 32
|
||||
| if standard { 16 } else { 0 }
|
||||
| if page.lineweights { 128 } else { 0 }
|
||||
| if page.center { 4 } else { 0 }
|
||||
| if page.show_plot_styles { 2 } else { 0 };
|
||||
// The file's standard scale (such as 1:50) while the scale is still the one read with it.
|
||||
let file_standard = page.file_standard_scale.filter(|&(_, s)| !page.scale_to_fit && s == scale).map(|(code, _)| code);
|
||||
let standard = page.scale_to_fit || scale == 1.0 || file_standard.is_some();
|
||||
let plot_flags = plot_layout_flags(page, standard);
|
||||
let plot_type = match page.plot_area.as_str() {
|
||||
"display" => 0,
|
||||
"extents" => 1,
|
||||
@@ -474,7 +488,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
|
||||
w.i(73, rotation);
|
||||
w.i(74, plot_type);
|
||||
w.s(7, &page.plot_style_table);
|
||||
w.i(75, if page.scale_to_fit { 0 } else { 16 });
|
||||
w.i(75, if page.scale_to_fit { 0 } else { file_standard.unwrap_or(16) });
|
||||
w.f(147, scale);
|
||||
// The paper image origin the file had (#2109), else 0,0.
|
||||
let origin = page.image_origin.filter(|o| o.is_finite()).unwrap_or(Vec2::ZERO);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! CADCraft file formats: DXF/DWG read, SVG and SVGZ import, SVG/PNG/PDF export (plotting).
|
||||
//! CADCraft file formats: DXF/DWG read, SVG/SVGZ import, PDF page conversion and SVG/PNG/PDF plotting.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
@@ -18,6 +18,7 @@ mod dxf_table;
|
||||
mod dxf_write;
|
||||
mod dxf_xref;
|
||||
pub mod pdf;
|
||||
pub mod pdf_read;
|
||||
pub mod plotter;
|
||||
/// Raster image files (PNG, JPEG, BMP, TIFF) decoded to pixels.
|
||||
pub mod raster;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,569 @@
|
||||
//! Preserve the PDF fill rule when PDF paths become CAD hatch boundaries.
|
||||
//!
|
||||
//! Hatch rendering uses even-odd parity. A nonzero PDF fill whose contours neither cross nor touch
|
||||
//! keeps the contours where the winding number changes between zero and non-zero, so its loops
|
||||
//! and bulge arcs survive import. Crossing contours are resolved into disjoint triangles by
|
||||
//! Lyon's tessellator.
|
||||
|
||||
use cadcraft_doc::HatchLoop;
|
||||
use cadcraft_geom::{PolyVertex, Vec2};
|
||||
use craft_pdf::interpret::FillRule;
|
||||
use lyon_tessellation::geometry_builder::{FillGeometryBuilder, GeometryBuilder, GeometryBuilderError};
|
||||
use lyon_tessellation::math::point;
|
||||
use lyon_tessellation::path::Path;
|
||||
use lyon_tessellation::{FillOptions, FillTessellator, FillVertex, VertexId};
|
||||
|
||||
/// Work charged to input sampling and containment checks.
|
||||
const MAX_WORK: usize = 20_000_000;
|
||||
/// Bounding-box tests between contours before a fill is refused.
|
||||
const MAX_BOX_CHECKS: usize = 50_000_000;
|
||||
/// Edge pairs compared when looking for crossings; past this a nonzero fill is tessellated.
|
||||
const MAX_EDGE_PAIRS: usize = 20_000_000;
|
||||
/// Sampled points above which a nonzero fill is tessellated without looking for crossings.
|
||||
const MAX_TOPOLOGY_POINTS: usize = 1_000_000;
|
||||
/// Lyon uses `f32`; work in a local frame and refuse a fill wider than this many tolerances.
|
||||
const MAX_SPAN_OVER_TOLERANCE: f64 = 5.0e7;
|
||||
/// Most points one bulge arc is sampled into.
|
||||
const MAX_ARC_STEPS: usize = 10_000;
|
||||
|
||||
/// Convert PDF boundaries to hatch boundaries that keep the PDF's fill rule.
|
||||
///
|
||||
/// `max_vertices` covers sampled input points and output triangle vertices. `tolerance` is how far,
|
||||
/// in drawing units, a sampled arc may leave the real one. Even-odd loops and nonzero loops that
|
||||
/// don't cross retain their original curves. Crossing nonzero contours are tessellated into
|
||||
/// disjoint triangles, each represented by one hatch loop.
|
||||
pub(super) fn normalize(mut loops: Vec<HatchLoop>, rule: FillRule, max_vertices: usize, tolerance: f64) -> Result<Vec<HatchLoop>, &'static str> {
|
||||
if loops.is_empty() {
|
||||
return Ok(loops);
|
||||
}
|
||||
if !tolerance.is_finite() || tolerance <= 0.0 {
|
||||
return Err("PDF fill tolerance is not usable");
|
||||
}
|
||||
let mut work = 0usize;
|
||||
let mut sampled = 0usize;
|
||||
let mut polygons = Vec::new();
|
||||
for loop_ in &loops {
|
||||
let polygon = flatten_loop(loop_, tolerance, &mut work, max_vertices.saturating_sub(sampled))?;
|
||||
sampled = sampled.checked_add(polygon.len()).ok_or("PDF fill exceeds vertex limit")?;
|
||||
polygons.push(polygon);
|
||||
}
|
||||
|
||||
match rule {
|
||||
FillRule::EvenOdd => {
|
||||
let probes: Vec<Vec2> = polygons.iter().map(|p| interior_probe(p)).collect();
|
||||
let mut depth = vec![0usize; loops.len()];
|
||||
containment(&polygons, &probes, &mut work, |i, _| depth[i] += 1)?;
|
||||
for (loop_, depth) in loops.iter_mut().zip(depth) {
|
||||
loop_.outer = depth.is_multiple_of(2);
|
||||
}
|
||||
Ok(loops)
|
||||
}
|
||||
FillRule::NonZero if sampled > MAX_TOPOLOGY_POINTS || edges_meet(&polygons).unwrap_or(true) => {
|
||||
tessellate_nonzero(&polygons, sampled, max_vertices, tolerance)
|
||||
}
|
||||
FillRule::NonZero => {
|
||||
let sign: Vec<i64> = polygons
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let area = signed_area(p);
|
||||
if p.len() < 3 || area == 0.0 { 0 } else { area.signum() as i64 }
|
||||
})
|
||||
.collect();
|
||||
// No two contours meet, so a contour lies inside another exactly when a point of its
|
||||
// own boundary does.
|
||||
let probes: Vec<Vec2> = polygons.iter().map(|p| longest_edge(p).map_or(Vec2::ZERO, |(a, b)| (a + b) * 0.5)).collect();
|
||||
// The winding number just inside each contour.
|
||||
let mut winding = sign.clone();
|
||||
containment(&polygons, &probes, &mut work, |i, j| winding[i] += sign[j])?;
|
||||
// A contour bounds the fill where the winding number changes between zero and non-zero.
|
||||
let keep: Vec<bool> = winding.iter().zip(&sign).map(|(&w, &s)| s != 0 && (w != 0) != (w - s != 0)).collect();
|
||||
let mut depth = vec![0usize; loops.len()];
|
||||
containment(&polygons, &probes, &mut work, |i, j| {
|
||||
if keep[i] && keep[j] {
|
||||
depth[i] += 1;
|
||||
}
|
||||
})?;
|
||||
Ok(loops
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| keep[*i])
|
||||
.map(|(i, mut loop_)| {
|
||||
loop_.outer = depth[i].is_multiple_of(2);
|
||||
loop_
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn flatten_loop(loop_: &HatchLoop, tolerance: f64, work: &mut usize, max_vertices: usize) -> Result<Vec<Vec2>, &'static str> {
|
||||
let n = loop_.vertices.len();
|
||||
// Two vertices enclose an area only through an arc.
|
||||
if n < 2 || (n == 2 && loop_.vertices.iter().all(|v| v.bulge.abs() < 1e-12)) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut points = Vec::new();
|
||||
for i in 0..n {
|
||||
let vertex = loop_.vertices[i];
|
||||
if !vertex.p.is_finite() || !vertex.bulge.is_finite() {
|
||||
return Err("PDF fill contains invalid coordinates");
|
||||
}
|
||||
push_bounded(&mut points, vertex.p, max_vertices)?;
|
||||
let next = loop_.vertices[(i + 1) % n].p;
|
||||
if vertex.bulge.abs() < 1e-12 || vertex.p == next {
|
||||
continue;
|
||||
}
|
||||
// A polyline bulge is tan(sweep/4). Sampling is used only for containment and lyon's
|
||||
// topology. Even-odd output keeps the original circular arc vertices.
|
||||
let dx = next.x - vertex.p.x;
|
||||
let dy = next.y - vertex.p.y;
|
||||
let bulge = vertex.bulge;
|
||||
let center = Vec2::new(
|
||||
(vertex.p.x + next.x) * 0.5 - dy * (1.0 - bulge * bulge) / (4.0 * bulge),
|
||||
(vertex.p.y + next.y) * 0.5 + dx * (1.0 - bulge * bulge) / (4.0 * bulge),
|
||||
);
|
||||
let start = (vertex.p.y - center.y).atan2(vertex.p.x - center.x);
|
||||
let sweep = 4.0 * bulge.atan();
|
||||
let radius = vertex.p.dist(center);
|
||||
if !radius.is_finite() {
|
||||
return Err("PDF fill contains invalid coordinates");
|
||||
}
|
||||
let max_angle = if radius <= tolerance { std::f64::consts::TAU } else { 2.0 * (1.0 - tolerance / radius).clamp(-1.0, 1.0).acos() };
|
||||
let steps = (sweep.abs() / max_angle.max(1e-12)).ceil().max(1.0) as usize;
|
||||
if steps > MAX_ARC_STEPS {
|
||||
return Err("PDF fill arc exceeds sampling limit");
|
||||
}
|
||||
for step in 1..steps {
|
||||
let angle = start + sweep * step as f64 / steps as f64;
|
||||
let point = Vec2::new(center.x + radius * angle.cos(), center.y + radius * angle.sin());
|
||||
if !point.is_finite() {
|
||||
return Err("PDF fill contains invalid coordinates");
|
||||
}
|
||||
push_bounded(&mut points, point, max_vertices)?;
|
||||
}
|
||||
}
|
||||
*work = work.checked_add(points.len()).ok_or("PDF fill exceeds work limit")?;
|
||||
if *work > MAX_WORK {
|
||||
return Err("PDF fill exceeds work limit");
|
||||
}
|
||||
Ok(points)
|
||||
}
|
||||
|
||||
fn push_bounded(points: &mut Vec<Vec2>, point: Vec2, max_vertices: usize) -> Result<(), &'static str> {
|
||||
if points.len() >= max_vertices {
|
||||
return Err("PDF fill exceeds vertex limit");
|
||||
}
|
||||
points.push(point);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Call `found(i, j)` for each contour `j` that contains `probes[i]`, the point standing for contour `i`.
|
||||
fn containment(polygons: &[Vec<Vec2>], probes: &[Vec2], work: &mut usize, mut found: impl FnMut(usize, usize)) -> Result<(), &'static str> {
|
||||
let boxes: Vec<(Vec2, Vec2)> = polygons.iter().map(|p| bounds(p)).collect();
|
||||
let mut checks = 0usize;
|
||||
for (i, polygon) in polygons.iter().enumerate() {
|
||||
if polygon.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let probe = probes[i];
|
||||
for (j, other) in polygons.iter().enumerate() {
|
||||
if i == j || other.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
checks += 1;
|
||||
if checks > MAX_BOX_CHECKS {
|
||||
return Err("PDF fill exceeds work limit");
|
||||
}
|
||||
let (lo, hi) = boxes[j];
|
||||
if probe.x < lo.x || probe.x > hi.x || probe.y < lo.y || probe.y > hi.y {
|
||||
continue;
|
||||
}
|
||||
*work = work.checked_add(other.len()).ok_or("PDF fill exceeds work limit")?;
|
||||
if *work > MAX_WORK {
|
||||
return Err("PDF fill exceeds work limit");
|
||||
}
|
||||
if contains(other, probe) {
|
||||
found(i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn bounds(points: &[Vec2]) -> (Vec2, Vec2) {
|
||||
let first = points.first().copied().unwrap_or(Vec2::ZERO);
|
||||
points.iter().fold((first, first), |(lo, hi), p| (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))))
|
||||
}
|
||||
|
||||
/// Whether two contours cross or touch, or one crosses, touches or folds back on itself. `None`
|
||||
/// when the search would compare more than [`MAX_EDGE_PAIRS`] edge pairs.
|
||||
fn edges_meet(polygons: &[Vec<Vec2>]) -> Option<bool> {
|
||||
let rings: Vec<Vec<Vec2>> = polygons
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let mut ring: Vec<Vec2> = Vec::with_capacity(p.len());
|
||||
for &q in p {
|
||||
if ring.last() != Some(&q) {
|
||||
ring.push(q);
|
||||
}
|
||||
}
|
||||
while ring.len() > 1 && ring.first() == ring.last() {
|
||||
ring.pop();
|
||||
}
|
||||
ring
|
||||
})
|
||||
.collect();
|
||||
let edge = |r: usize, k: usize| (rings[r][k], rings[r][(k + 1) % rings[r].len()]);
|
||||
// Each edge by its smallest x, so only edges whose x ranges overlap are compared.
|
||||
let mut edges: Vec<(f64, usize, usize)> = Vec::new();
|
||||
for (r, ring) in rings.iter().enumerate() {
|
||||
if ring.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
for k in 0..ring.len() {
|
||||
let (a, b) = edge(r, k);
|
||||
edges.push((a.x.min(b.x), r, k));
|
||||
}
|
||||
}
|
||||
edges.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut pairs = 0usize;
|
||||
for (n, &(_, r, k)) in edges.iter().enumerate() {
|
||||
let (a, b) = edge(r, k);
|
||||
let right = a.x.max(b.x);
|
||||
for &(left, s, m) in &edges[n + 1..] {
|
||||
if left > right {
|
||||
break;
|
||||
}
|
||||
pairs += 1;
|
||||
if pairs > MAX_EDGE_PAIRS {
|
||||
return None;
|
||||
}
|
||||
let (c, d) = edge(s, m);
|
||||
if a.y.max(b.y) < c.y.min(d.y) || c.y.max(d.y) < a.y.min(b.y) {
|
||||
continue;
|
||||
}
|
||||
if r == s {
|
||||
let len = rings[r].len();
|
||||
// Neighbouring edges share a vertex; they only meet elsewhere by folding back.
|
||||
if (k + 1) % len == m {
|
||||
if folds_back(a, b, d) {
|
||||
return Some(true);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (m + 1) % len == k {
|
||||
if folds_back(c, d, b) {
|
||||
return Some(true);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if segments_meet(a, b, c, d) {
|
||||
return Some(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(false)
|
||||
}
|
||||
|
||||
/// Whether the path a to b to c turns straight back over itself at b.
|
||||
fn folds_back(a: Vec2, b: Vec2, c: Vec2) -> bool {
|
||||
(b - a).cross(c - b) == 0.0 && (b.x - a.x) * (c.x - b.x) + (b.y - a.y) * (c.y - b.y) < 0.0
|
||||
}
|
||||
|
||||
/// Whether the closed segments a to b and c to d share a point.
|
||||
fn segments_meet(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> bool {
|
||||
let side = |p: Vec2, q: Vec2, r: Vec2| (q - p).cross(r - p);
|
||||
let within = |p: Vec2, q: Vec2, r: Vec2| r.x >= p.x.min(q.x) && r.x <= p.x.max(q.x) && r.y >= p.y.min(q.y) && r.y <= p.y.max(q.y);
|
||||
let (d1, d2, d3, d4) = (side(c, d, a), side(c, d, b), side(a, b, c), side(a, b, d));
|
||||
if ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0)) && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0)) {
|
||||
return true;
|
||||
}
|
||||
(d1 == 0.0 && within(c, d, a)) || (d2 == 0.0 && within(c, d, b)) || (d3 == 0.0 && within(a, b, c)) || (d4 == 0.0 && within(a, b, d))
|
||||
}
|
||||
|
||||
/// Find a point slightly inside the longest edge. The scan across edges handles concave loops
|
||||
/// without relying on their vertex average being inside.
|
||||
fn interior_probe(polygon: &[Vec2]) -> Vec2 {
|
||||
let area = signed_area(polygon);
|
||||
let sign = if area >= 0.0 { 1.0 } else { -1.0 };
|
||||
let Some((a, b)) = longest_edge(polygon) else { return Vec2::ZERO };
|
||||
let edge = b - a;
|
||||
let len = edge.len().max(1e-30);
|
||||
let mut epsilon = (len * 1e-6).max(1e-12);
|
||||
for _ in 0..32 {
|
||||
let probe = Vec2::new((a.x + b.x) * 0.5 - sign * edge.y / len * epsilon, (a.y + b.y) * 0.5 + sign * edge.x / len * epsilon);
|
||||
if contains(polygon, probe) {
|
||||
return probe;
|
||||
}
|
||||
epsilon *= 0.5;
|
||||
}
|
||||
Vec2::new((a.x + b.x) * 0.5, (a.y + b.y) * 0.5)
|
||||
}
|
||||
|
||||
fn longest_edge(polygon: &[Vec2]) -> Option<(Vec2, Vec2)> {
|
||||
polygon
|
||||
.iter()
|
||||
.copied()
|
||||
.zip(polygon.iter().copied().cycle().skip(1))
|
||||
.take(polygon.len())
|
||||
.max_by(|(a, b), (c, d)| a.dist(*b).total_cmp(&c.dist(*d)))
|
||||
}
|
||||
|
||||
fn signed_area(polygon: &[Vec2]) -> f64 {
|
||||
polygon.iter().zip(polygon.iter().cycle().skip(1)).take(polygon.len()).map(|(a, b)| a.x * b.y - b.x * a.y).sum::<f64>() * 0.5
|
||||
}
|
||||
|
||||
fn contains(polygon: &[Vec2], point: Vec2) -> bool {
|
||||
let mut inside = false;
|
||||
for (a, b) in polygon.iter().zip(polygon.iter().cycle().skip(1)).take(polygon.len()) {
|
||||
if (a.y > point.y) != (b.y > point.y) && point.x < (b.x - a.x) * (point.y - a.y) / (b.y - a.y) + a.x {
|
||||
inside = !inside;
|
||||
}
|
||||
}
|
||||
inside
|
||||
}
|
||||
|
||||
fn tessellate_nonzero(polygons: &[Vec<Vec2>], sampled_vertices: usize, max_vertices: usize, tolerance: f64) -> Result<Vec<HatchLoop>, &'static str> {
|
||||
let Some(origin) = polygons.iter().flatten().next().copied() else { return Ok(Vec::new()) };
|
||||
let (min, max) = polygons
|
||||
.iter()
|
||||
.flatten()
|
||||
.fold((origin, origin), |(lo, hi), p| (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))));
|
||||
let span = tolerance * MAX_SPAN_OVER_TOLERANCE;
|
||||
if max.x - min.x > span || max.y - min.y > span {
|
||||
return Err("PDF fill is too large for stable vector conversion");
|
||||
}
|
||||
let mut path = Path::builder();
|
||||
for polygon in polygons {
|
||||
let Some(first) = polygon.first() else { continue };
|
||||
path.begin(point((first.x - origin.x) as f32, (first.y - origin.y) as f32));
|
||||
for p in polygon.iter().skip(1) {
|
||||
path.line_to(point((p.x - origin.x) as f32, (p.y - origin.y) as f32));
|
||||
}
|
||||
path.end(true);
|
||||
}
|
||||
let mut output = CappedGeometry::new(max_vertices.saturating_sub(sampled_vertices));
|
||||
FillTessellator::new().tessellate_path(&path.build(), &FillOptions::non_zero(), &mut output).map_err(|_| "PDF fill tessellation failed")?;
|
||||
if output.exceeded || output.indices.len().checked_add(sampled_vertices).is_none_or(|n| n > max_vertices) {
|
||||
return Err("PDF fill exceeds vertex limit");
|
||||
}
|
||||
if !output.indices.len().is_multiple_of(3) {
|
||||
return Err("PDF fill tessellation returned invalid triangles");
|
||||
}
|
||||
output
|
||||
.indices
|
||||
.as_chunks::<3>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|triangle| {
|
||||
let vertices = triangle
|
||||
.iter()
|
||||
.map(|&index| {
|
||||
output
|
||||
.vertices
|
||||
.get(index as usize)
|
||||
.copied()
|
||||
.map(|p| PolyVertex::new(Vec2::new(p.x + origin.x, p.y + origin.y)))
|
||||
.ok_or("PDF fill tessellation returned an invalid index")
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(HatchLoop { vertices, outer: true, sources: Vec::new() })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lyon's triangle callback cannot report a capacity error. This builder caps both buffers and
|
||||
/// records rejected triangles so extraction remains bounded even for pathological intersections.
|
||||
struct CappedGeometry {
|
||||
vertices: Vec<Vec2>,
|
||||
indices: Vec<u32>,
|
||||
limit: usize,
|
||||
exceeded: bool,
|
||||
}
|
||||
|
||||
impl CappedGeometry {
|
||||
fn new(limit: usize) -> Self {
|
||||
Self { vertices: Vec::new(), indices: Vec::new(), limit, exceeded: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl GeometryBuilder for CappedGeometry {
|
||||
fn add_triangle(&mut self, a: VertexId, b: VertexId, c: VertexId) {
|
||||
if self.indices.len().saturating_add(3) > self.limit {
|
||||
self.exceeded = true;
|
||||
return;
|
||||
}
|
||||
self.indices.extend([a.0, b.0, c.0]);
|
||||
}
|
||||
}
|
||||
|
||||
impl FillGeometryBuilder for CappedGeometry {
|
||||
fn add_fill_vertex(&mut self, vertex: FillVertex<'_>) -> Result<VertexId, GeometryBuilderError> {
|
||||
if self.vertices.len() >= self.limit {
|
||||
self.exceeded = true;
|
||||
return Err(GeometryBuilderError::TooManyVertices);
|
||||
}
|
||||
let id = u32::try_from(self.vertices.len()).map_err(|_| GeometryBuilderError::TooManyVertices)?;
|
||||
let p = vertex.position();
|
||||
self.vertices.push(Vec2::new(f64::from(p.x), f64::from(p.y)));
|
||||
Ok(VertexId(id))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn polygon(points: &[(f64, f64)]) -> HatchLoop {
|
||||
HatchLoop { vertices: points.iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(), outer: false, sources: Vec::new() }
|
||||
}
|
||||
|
||||
fn square(x0: f64, y0: f64, x1: f64, y1: f64, clockwise: bool) -> HatchLoop {
|
||||
let points = if clockwise { vec![(x0, y0), (x0, y1), (x1, y1), (x1, y0)] } else { vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1)] };
|
||||
polygon(&points)
|
||||
}
|
||||
|
||||
/// The arc tolerance of a drawing in millimetres.
|
||||
const TOL: f64 = 0.02;
|
||||
|
||||
fn filled(loops: &[HatchLoop], point: Vec2) -> bool {
|
||||
loops.iter().filter(|l| contains(&l.vertices.iter().map(|v| v.p).collect::<Vec<_>>(), point)).count() % 2 == 1
|
||||
}
|
||||
|
||||
/// A circle about the origin as four quarter arcs.
|
||||
fn circle(r: f64, clockwise: bool) -> HatchLoop {
|
||||
let quarter = (std::f64::consts::PI / 8.0).tan();
|
||||
let turn = if clockwise { -1.0 } else { 1.0 };
|
||||
HatchLoop {
|
||||
vertices: [(r, 0.0), (0.0, r * turn), (-r, 0.0), (0.0, -r * turn)]
|
||||
.iter()
|
||||
.map(|&(x, y)| PolyVertex { bulge: quarter * turn, ..PolyVertex::new(Vec2::new(x, y)) })
|
||||
.collect(),
|
||||
outer: false,
|
||||
sources: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_circle_keeps_its_curve_when_tessellated_in_a_large_unit() {
|
||||
// A circle of radius 5 mm in a drawing in metres, crossed by a bar so the fill is
|
||||
// tessellated. Its arcs are sampled to the given tolerance, not cut to their four vertices.
|
||||
let r = 0.005;
|
||||
let metres = 0.02 * 25.4 / 72.0 / 1000.0;
|
||||
let bar = square(0.5 * r, -0.2 * r, 2.0 * r, 0.2 * r, false);
|
||||
let result = normalize(vec![circle(r, false), bar], FillRule::NonZero, 100_000, metres).expect("valid contours");
|
||||
assert!(result.len() > 3, "tessellated into triangles");
|
||||
assert!(filled(&result, Vec2::new(0.65 * r, 0.65 * r)), "the arc between two vertices stays filled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disc_of_two_half_circles_is_kept() {
|
||||
let half = |x: f64| PolyVertex { bulge: 1.0, ..PolyVertex::new(Vec2::new(x, 0.0)) };
|
||||
let disc = HatchLoop { vertices: vec![half(-1.0), half(1.0)], outer: false, sources: Vec::new() };
|
||||
for rule in [FillRule::EvenOdd, FillRule::NonZero] {
|
||||
let result = normalize(vec![disc.clone()], rule, 10_000, TOL).expect("valid contour");
|
||||
assert_eq!(result.len(), 1);
|
||||
assert!(result[0].outer);
|
||||
assert_eq!(result[0].vertices, disc.vertices, "the arcs are kept");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonzero_contour_hugging_its_parents_edge_keeps_the_fill() {
|
||||
// The inner square runs 1e-7 from the outer one's left edge, closer than a point nudged
|
||||
// inside that edge: each contour is placed by a point of its own boundary.
|
||||
let input = vec![square(0.0, 0.0, 10.0, 10.0, false), square(1e-7, 4.0, 1.0, 6.0, false)];
|
||||
let result = normalize(input, FillRule::NonZero, 1000, TOL).expect("valid contours");
|
||||
assert!(filled(&result, Vec2::new(5.0, 5.0)) && filled(&result, Vec2::new(0.5, 5.0)), "{result:?}");
|
||||
assert!(result.iter().all(|l| l.vertices.len() == 4), "kept as drawn, not split into triangles");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_disconnected_contours_are_both_outer() {
|
||||
let input = vec![square(0.0, 0.0, 2.0, 2.0, false), square(4.0, 0.0, 6.0, 2.0, false)];
|
||||
let result = normalize(input, FillRule::EvenOdd, 100, TOL).expect("valid contours");
|
||||
assert!(result.iter().all(|loop_| loop_.outer));
|
||||
assert!(filled(&result, Vec2::new(1.0, 1.0)));
|
||||
assert!(filled(&result, Vec2::new(5.0, 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonzero_nested_same_direction_contours_keep_the_center_filled() {
|
||||
let result = normalize(vec![square(0.0, 0.0, 10.0, 10.0, false), square(2.0, 2.0, 8.0, 8.0, false)], FillRule::NonZero, 1000, TOL)
|
||||
.expect("valid contours");
|
||||
assert!(filled(&result, Vec2::new(5.0, 5.0)));
|
||||
assert!(filled(&result, Vec2::new(1.0, 1.0)));
|
||||
assert!(result.iter().all(|l| l.vertices.len() == 4), "the outer square is kept, not split into triangles");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonzero_nested_opposite_direction_contours_leave_a_hole() {
|
||||
let result = normalize(vec![square(0.0, 0.0, 10.0, 10.0, false), square(2.0, 2.0, 8.0, 8.0, true)], FillRule::NonZero, 1000, TOL)
|
||||
.expect("valid contours");
|
||||
assert!(!filled(&result, Vec2::new(5.0, 5.0)));
|
||||
assert!(filled(&result, Vec2::new(1.0, 1.0)));
|
||||
assert!(result.iter().all(|l| l.vertices.len() == 4), "both squares are kept as drawn");
|
||||
assert!(result.iter().any(|l| l.outer) && result.iter().any(|l| !l.outer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonzero_concave_contour_stays_one_loop() {
|
||||
let points = [(0.0, 0.0), (10.0, 0.0), (10.0, 3.0), (3.0, 3.0), (3.0, 10.0), (0.0, 10.0)];
|
||||
let result = normalize(vec![polygon(&points)], FillRule::NonZero, 1000, TOL).expect("valid contour");
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(result[0].vertices, polygon(&points).vertices);
|
||||
assert!(result[0].outer);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonzero_curved_nested_contours_keep_their_arcs() {
|
||||
// Circles of radius 10 and 5, wound opposite ways.
|
||||
let result = normalize(vec![circle(10.0, false), circle(5.0, true)], FillRule::NonZero, 10_000, TOL).expect("valid contours");
|
||||
assert_eq!(result.len(), 2);
|
||||
assert!(result.iter().all(|l| l.vertices.iter().all(|v| v.bulge != 0.0)), "the arcs are kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonzero_overlapping_contours_keep_the_overlap_filled() {
|
||||
let result = normalize(vec![square(0.0, 0.0, 6.0, 6.0, false), square(3.0, 0.0, 9.0, 6.0, false)], FillRule::NonZero, 1000, TOL)
|
||||
.expect("valid contours");
|
||||
assert!(filled(&result, Vec2::new(4.0, 3.0)));
|
||||
assert!(filled(&result, Vec2::new(1.0, 3.0)));
|
||||
assert!(filled(&result, Vec2::new(8.0, 3.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonzero_self_crossing_contour_is_split_into_triangles() {
|
||||
let points = [(0.0, 0.0), (10.0, 10.0), (0.0, 10.0), (6.0, 0.0), (3.0, 8.0)];
|
||||
let result = normalize(vec![polygon(&points)], FillRule::NonZero, 1000, TOL).expect("valid contour");
|
||||
assert!(result.len() > 1);
|
||||
assert!(filled(&result, Vec2::new(4.0, 5.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonzero_tessellation_keeps_coordinates_away_from_the_local_origin() {
|
||||
let shift = 50_000.0;
|
||||
// The third square crosses the first, so the fill is tessellated.
|
||||
let input = vec![
|
||||
square(shift, shift, shift + 10.0, shift + 10.0, false),
|
||||
square(shift + 2.0, shift + 2.0, shift + 8.0, shift + 8.0, true),
|
||||
square(shift + 9.0, shift + 4.0, shift + 12.0, shift + 6.0, false),
|
||||
];
|
||||
let result = normalize(input, FillRule::NonZero, 1000, TOL).expect("valid translated contours");
|
||||
assert!(result.len() > 3, "tessellated into triangles");
|
||||
assert!(!filled(&result, Vec2::new(shift + 5.0, shift + 5.0)));
|
||||
assert!(filled(&result, Vec2::new(shift + 1.0, shift + 1.0)));
|
||||
assert!(filled(&result, Vec2::new(shift + 11.0, shift + 5.1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_odd_nested_contours_are_classified_by_depth() {
|
||||
let result = normalize(vec![square(0.0, 0.0, 10.0, 10.0, false), square(2.0, 2.0, 8.0, 8.0, false)], FillRule::EvenOdd, 1000, TOL)
|
||||
.expect("valid contours");
|
||||
assert!(result[0].outer);
|
||||
assert!(!result[1].outer);
|
||||
assert!(!filled(&result, Vec2::new(5.0, 5.0)));
|
||||
assert!(filled(&result, Vec2::new(1.0, 1.0)));
|
||||
}
|
||||
}
|
||||
@@ -422,6 +422,30 @@ fn hostile_dxf_does_not_panic() {
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for #1336: the LAYER table of a DXF had no record cap, so a hostile file could
|
||||
// grow the layer list without bound (its VIEW/UCS/VPORT peers stop at one million records).
|
||||
#[test]
|
||||
fn dxf_layer_table_stops_at_the_record_cap() {
|
||||
use std::fmt::Write as _;
|
||||
let records = 1_000_100;
|
||||
let mut text = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n");
|
||||
for i in 0..records {
|
||||
let _ = write!(text, "0\nLAYER\n2\nL{i}\n");
|
||||
}
|
||||
text.push_str("0\nENDTAB\n0\nENDSEC\n0\nEOF\n");
|
||||
let d = read(text.as_bytes(), "layers.dxf").unwrap();
|
||||
// The exact total, not a range: the layer list stops at 1,000,000 layers, the drawing's own
|
||||
// default layers counted among them, so a cap that truncates early or late fails as loudly as
|
||||
// none at all. The count is a literal on purpose -- if the constant changes, this test must fail
|
||||
// rather than follow it.
|
||||
assert_eq!(
|
||||
d.layers.len(),
|
||||
1_000_000,
|
||||
"the LAYER table must stop at exactly 1,000,000 layers in total, defaults included, reading {records} records, but kept {}",
|
||||
d.layers.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_and_png_export() {
|
||||
let d = sample();
|
||||
@@ -2683,6 +2707,84 @@ fn mirrored_2d_polyline_extrusion_flips_x_and_bulge() {
|
||||
assert_eq!(got, vec![(-1.0, 0.0, -1.0), (-3.0, 0.0, 0.0)]);
|
||||
}
|
||||
|
||||
/// Objects whose normal is 0,0,-1, at OCS height 5 and most of them 2 thick, keep their world height
|
||||
/// and the side they extrude to through a save. They are written with no normal (along Z), so an
|
||||
/// elevation or a thickness written as read put a polyline or a hatch at Z +5 instead of -5, and
|
||||
/// extruded a circle, point, solid or text up instead of down (AutoCAD 2024 opening the saved file,
|
||||
/// measured). A line writes its normal, and keeps its thickness as read. The same objects facing up
|
||||
/// (no normal, and 0,0,1) keep +5 and +2: only a normal pointing down Z changes the sign.
|
||||
#[test]
|
||||
fn mirrored_objects_keep_their_world_height_and_thickness_side() {
|
||||
let records = |normal: &str| {
|
||||
format!(
|
||||
"0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n38\n5\n39\n2\n{normal}10\n0\n20\n0\n42\n0.5\n10\n-10\n20\n0\n\
|
||||
0\nPOLYLINE\n8\n0\n66\n1\n70\n0\n10\n0\n20\n0\n30\n5\n{normal}0\nVERTEX\n8\n0\n10\n0\n20\n10\n0\nVERTEX\n8\n0\n10\n-10\n20\n10\n0\nSEQEND\n\
|
||||
0\nCIRCLE\n8\n0\n10\n-10\n20\n5\n30\n5\n40\n5\n39\n2\n{normal}\
|
||||
0\nARC\n8\n0\n10\n-30\n20\n5\n30\n5\n40\n5\n50\n180\n51\n270\n{normal}\
|
||||
0\nPOINT\n8\n0\n10\n-40\n20\n0\n30\n5\n39\n2\n{normal}\
|
||||
0\nSOLID\n8\n0\n10\n50\n20\n0\n30\n5\n11\n60\n21\n0\n31\n5\n12\n50\n22\n5\n32\n5\n13\n60\n23\n5\n33\n5\n39\n2\n{normal}\
|
||||
0\nHATCH\n8\n0\n10\n0\n20\n0\n30\n5\n{normal}2\nSOLID\n70\n1\n71\n0\n91\n1\n92\n2\n72\n0\n73\n1\n93\n4\n\
|
||||
10\n70\n20\n0\n10\n80\n20\n0\n10\n80\n20\n5\n10\n70\n20\n5\n97\n0\n75\n0\n76\n1\n98\n0\n\
|
||||
0\nTEXT\n8\n0\n10\n-90\n20\n0\n30\n5\n40\n2\n1\nA\n39\n2\n{normal}\
|
||||
0\nLINE\n8\n0\n39\n2\n10\n0\n20\n20\n30\n3\n11\n10\n21\n20\n31\n3\n{normal}"
|
||||
)
|
||||
};
|
||||
let (down, up) = ("210\n0\n220\n0\n230\n-1\n", "210\n0\n220\n0\n230\n1\n");
|
||||
let text = format!("0\nSECTION\n2\nENTITIES\n{}{}{}0\nENDSEC\n0\nEOF\n", records(down), records(""), records(up));
|
||||
// Each object's kind, world height and thickness along world Z.
|
||||
let place = |d: &Drawing| -> Vec<(&'static str, f64, f64)> {
|
||||
d.model
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let n = e.common.extrusion.z.signum();
|
||||
let (kind, z) = match &e.kind {
|
||||
EntityKind::LwPolyline(p) => ("polyline", n * p.elevation),
|
||||
EntityKind::Circle(c) => ("circle", c.center.z),
|
||||
EntityKind::Arc(a) => ("arc", a.center.z),
|
||||
EntityKind::Point(p) => ("point", p.p.z),
|
||||
EntityKind::Solid(s) => ("solid", s.corners[0].z),
|
||||
EntityKind::Hatch(h) => ("hatch", n * h.elevation),
|
||||
EntityKind::Text(t) => ("text", t.insert.z),
|
||||
EntityKind::Line(l) => ("line", l.a.z),
|
||||
_ => ("other", f64::NAN),
|
||||
};
|
||||
(kind, z, n * e.common.thickness)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let d = read(text.as_bytes(), "m.dxf").unwrap();
|
||||
let mut want = vec![
|
||||
("polyline", -5.0, -2.0),
|
||||
("polyline", -5.0, 0.0),
|
||||
("circle", -5.0, -2.0),
|
||||
("arc", -5.0, 0.0),
|
||||
("point", 5.0, -2.0),
|
||||
("solid", -5.0, -2.0),
|
||||
("hatch", -5.0, 0.0),
|
||||
("text", -5.0, -2.0),
|
||||
("line", 3.0, -2.0),
|
||||
];
|
||||
let facing_up = [
|
||||
("polyline", 5.0, 2.0),
|
||||
("polyline", 5.0, 0.0),
|
||||
("circle", 5.0, 2.0),
|
||||
("arc", 5.0, 0.0),
|
||||
("point", 5.0, 2.0),
|
||||
("solid", 5.0, 2.0),
|
||||
("hatch", 5.0, 0.0),
|
||||
("text", 5.0, 2.0),
|
||||
("line", 3.0, 2.0),
|
||||
];
|
||||
want.extend(facing_up);
|
||||
want.extend(facing_up);
|
||||
assert_eq!(place(&d), want, "as read");
|
||||
let out = write(&d, "m.dxf").unwrap();
|
||||
assert_eq!(place(&read(&out, "m.dxf").unwrap()), want, "after a save");
|
||||
let pairs = dxf_pairs(std::str::from_utf8(&out).unwrap());
|
||||
let lines: Vec<_> = dxf_records(&pairs, "LINE").into_iter().map(|l| (group(l, "39"), group(l, "230"))).collect();
|
||||
assert_eq!(lines, [(Some("2.0"), Some("-1.0")), (Some("2.0"), None), (Some("2.0"), None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirrored_hatch_extrusion_flips_boundary() {
|
||||
// HATCH boundaries are OCS: the square (1,0)..(3,2) under extrusion (0,0,-1) lies at (-3,0)..(-1,2).
|
||||
@@ -2727,6 +2829,20 @@ fn tilted_hatch_turns_its_gradient() {
|
||||
assert!((g.angle - std::f64::consts::PI).abs() < 1e-9, "gradient angle {}", g.angle);
|
||||
}
|
||||
|
||||
/// A tilted polyline with a thickness, its normal pointing partly down Z, still extrudes toward -Z
|
||||
/// once it is drawn as seen from above and saved with no normal.
|
||||
#[test]
|
||||
fn tilted_thick_polyline_keeps_its_extrusion_side() {
|
||||
let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n39\n5\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\
|
||||
10\n1\n20\n0\n10\n3\n20\n2\n0\nENDSEC\n0\nEOF\n";
|
||||
let d = read(text.as_bytes(), "p.dxf").unwrap();
|
||||
let e = d.model.iter().next().unwrap();
|
||||
assert_eq!((e.common.thickness, e.common.extrusion), (-5.0, Vec3::Z));
|
||||
let back = roundtrip(&d);
|
||||
let e = back.model.iter().next().unwrap();
|
||||
assert_eq!((e.common.thickness, e.common.extrusion), (-5.0, Vec3::Z), "saved with no normal, it still extrudes toward -Z");
|
||||
}
|
||||
|
||||
/// A straight tilted LWPOLYLINE keeps its vertex widths (groups 40/41) on the projected vertices.
|
||||
#[test]
|
||||
fn tilted_straight_lwpolyline_keeps_its_widths() {
|
||||
@@ -2841,6 +2957,57 @@ fn tilted_lwpolyline_is_drawn_as_seen_from_above() {
|
||||
assert_eq!(p.vertices.iter().map(|v| v.bulge).collect::<Vec<_>>(), vec![1.0, 1.0]);
|
||||
}
|
||||
|
||||
/// A 2D POLYLINE (heavy polyline) in a tilted plane is drawn as seen from above, like a
|
||||
/// LWPOLYLINE: before, its OCS points were taken for world coordinates. With extrusion
|
||||
/// (0, 0.5, -√3/2) the OCS axes are x = (-1,0,0) and y = (0, √3/2, 1/2), and the elevation of 2
|
||||
/// moves the plane by twice the normal, (0, 1, -√3): the square (1,0)..(3,2) lies over
|
||||
/// (-3,1)..(-1,1+√3), its corners at a mean height of 1/2 - √3.
|
||||
#[test]
|
||||
fn tilted_2d_polyline_is_drawn_as_seen_from_above() {
|
||||
let square = |n: &str| {
|
||||
format!(
|
||||
"0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n2\n70\n1\n{n}\
|
||||
0\nVERTEX\n8\n0\n10\n1\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n2\n\
|
||||
0\nVERTEX\n8\n0\n10\n1\n20\n2\n0\nSEQEND\n0\nENDSEC\n0\nEOF\n"
|
||||
)
|
||||
};
|
||||
let d = read(square("210\n0\n220\n0.5\n230\n-0.8660254037844386\n").as_bytes(), "p.dxf").unwrap();
|
||||
let b = d.extents(&Space::Model);
|
||||
let r3 = 3f64.sqrt();
|
||||
for (got, want) in [(b.min.x, -3.0), (b.min.y, 1.0), (b.max.x, -1.0), (b.max.y, 1.0 + r3)] {
|
||||
assert!((got - want).abs() < 1e-9, "extents {b:?}");
|
||||
}
|
||||
let e = d.model.iter().next().unwrap();
|
||||
assert_eq!(e.common.extrusion, Vec3::Z, "its points are plan coordinates now");
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
|
||||
assert!((p.elevation - (0.5 - r3)).abs() < 1e-9, "the mean height of its corners: {}", p.elevation);
|
||||
// In plan and in the mirrored plane the polyline stays as it was: mirrored only in x.
|
||||
let plain = read(square("").as_bytes(), "p.dxf").unwrap();
|
||||
let b = plain.extents(&Space::Model);
|
||||
assert!((b.min.x - 1.0).abs() < 1e-9 && (b.max.y - 2.0).abs() < 1e-9, "extents {b:?}");
|
||||
let mirrored = read(square("210\n0\n220\n0\n230\n-1\n").as_bytes(), "p.dxf").unwrap();
|
||||
let b = mirrored.extents(&Space::Model);
|
||||
assert!((b.min.x + 3.0).abs() < 1e-9 && (b.max.x + 1.0).abs() < 1e-9, "extents {b:?}");
|
||||
assert_eq!(mirrored.model.iter().next().unwrap().common.extrusion, Vec3::new(0.0, 0.0, -1.0));
|
||||
}
|
||||
|
||||
/// A tilted 2D POLYLINE with an arc keeps its shape as seen from above: the half circle from
|
||||
/// (0,0) to (2,0) is flattened into its half ellipse, in plan x from -2 to 0 and reaching √3/2.
|
||||
#[test]
|
||||
fn tilted_2d_polyline_arc_is_flattened() {
|
||||
let text = "0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n0\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\
|
||||
0\nVERTEX\n8\n0\n10\n0\n20\n0\n42\n1\n0\nVERTEX\n8\n0\n10\n2\n20\n0\n0\nSEQEND\n0\nENDSEC\n0\nEOF\n";
|
||||
let d = read(text.as_bytes(), "p.dxf").unwrap();
|
||||
let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None });
|
||||
assert!(p.vertices.len() > 8 && p.vertices.iter().all(|v| v.bulge == 0.0), "{} vertices", p.vertices.len());
|
||||
let b = d.extents(&Space::Model);
|
||||
// Bulge 1 turns counter-clockwise from (0,0) to (2,0), so the arc runs below its chord, down
|
||||
// to OCS y -1: plan y -√3/2.
|
||||
for (got, want) in [(b.min.x, -2.0), (b.max.x, 0.0), (b.min.y, -(3f64.sqrt()) / 2.0), (b.max.y, 0.0)] {
|
||||
assert!((got - want).abs() < 5e-3, "extents {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The model extents of a one-loop solid HATCH whose edge boundary is `edges` (group 72 onwards).
|
||||
fn hatch_edge_extents(edges: &str) -> Bounds2 {
|
||||
let n = edges.matches("72\n").count();
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! #3227: saving kept the layout's plot flags only for the bits CADCraft models and forced 512
|
||||
//! (plot paper space last), 32 (plot with plot styles) and 16 (standard scale) on, so a layout
|
||||
//! with flags 0 came back as 560, in DXF and in DWG.
|
||||
|
||||
use cadcraft_doc::{Drawing, Layout, PageSetup};
|
||||
use cadcraft_io::{read, write};
|
||||
|
||||
/// A drawing with layout SHEET read with plot layout `flags` (lineweights, centring and display
|
||||
/// plot styles follow them, as the reader sets them).
|
||||
fn drawing(flags: i64) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
let mut l = Layout::new("SHEET", 1);
|
||||
l.page = PageSetup {
|
||||
lineweights: flags & 128 != 0,
|
||||
center: flags & 4 != 0,
|
||||
show_plot_styles: flags & 2 != 0,
|
||||
file_plot_flags: Some(flags),
|
||||
..PageSetup::default()
|
||||
};
|
||||
d.layouts.push(l);
|
||||
d
|
||||
}
|
||||
|
||||
/// The plot layout flags of SHEET after saving `d` as `name` and reading it back.
|
||||
fn flags_after_save(d: &Drawing, name: &str) -> Option<i64> {
|
||||
let bytes = write(d, name).unwrap();
|
||||
let back = read(&bytes, name).unwrap();
|
||||
back.layouts.iter().find(|l| l.name == "SHEET")?.page.file_plot_flags
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plot_layout_flags_are_saved_as_read() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
for name in ["sheet.dxf", "sheet.dwg"] {
|
||||
for flags in [0, 176, 560, 688] {
|
||||
assert_eq!(flags_after_save(&drawing(flags), name), Some(flags), "{name}: flags {flags}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_standard_scale_keeps_its_flag_and_choice() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
// Flags 176 with standard scale 25 (1:50): the scale is 0.02, not 1:1, and still standard.
|
||||
let mut d = drawing(176);
|
||||
let page = &mut d.layouts.last_mut().unwrap().page;
|
||||
page.scale = 0.02;
|
||||
page.file_standard_scale = Some((25, 0.02));
|
||||
for name in ["sheet.dxf", "sheet.dwg"] {
|
||||
let back = read(&write(&d, name).unwrap(), name).unwrap();
|
||||
let page = &back.layouts.iter().find(|l| l.name == "SHEET").unwrap().page;
|
||||
assert_eq!(page.file_plot_flags, Some(176), "{name}");
|
||||
assert_eq!(page.file_standard_scale, Some((25, 0.02)), "{name}");
|
||||
}
|
||||
// A scale changed after reading is a custom one: 16 is cleared and the choice dropped.
|
||||
d.layouts.last_mut().unwrap().page.scale = 0.05;
|
||||
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(160));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_still_decides_the_bits_cadcraft_models() {
|
||||
// Lineweights turned on and a custom scale chosen after reading flags 16: 128 is set and the
|
||||
// standard scale bit cleared, the rest kept.
|
||||
let mut d = drawing(16 | 512);
|
||||
let page = &mut d.layouts.last_mut().unwrap().page;
|
||||
page.lineweights = true;
|
||||
page.scale = 0.02;
|
||||
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128));
|
||||
// A page made in CADCraft keeps the defaults (plot paper space last, plot with plot styles,
|
||||
// standard scale, lineweights).
|
||||
let mut d = drawing(0);
|
||||
d.layouts.last_mut().unwrap().page = PageSetup::default();
|
||||
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128 | 32 | 16));
|
||||
}
|
||||
@@ -36,6 +36,7 @@ mod helix_roundtrip;
|
||||
mod layer_states_acad;
|
||||
mod layout_limits_roundtrip;
|
||||
mod layout_paper_units;
|
||||
mod layout_plot_flags;
|
||||
mod layout_plot_window;
|
||||
mod leader_vertex_elevation;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -58,6 +59,7 @@ mod ole_frame;
|
||||
mod paperview_marker;
|
||||
mod passthrough_image_roundtrip;
|
||||
mod pdf_followups;
|
||||
mod pdf_import;
|
||||
mod pdf_layers;
|
||||
#[path = "../support/pdf_read.rs"]
|
||||
mod pdf_read;
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
//! PDFIMPORT: the vector content of a PDF page as editable objects. The PDFs are written here by
|
||||
//! hand (a content stream and the standard Helvetica) or by CADCraft's own plotter.
|
||||
|
||||
use cadcraft_color::{Color, Rgb};
|
||||
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, HAlign, Line, Lineweight, Space, Text};
|
||||
use cadcraft_geom::Vec3;
|
||||
use cadcraft_io::pdf_read::{MM_PER_PT, PdfImportOptions, read};
|
||||
use serde_json::json;
|
||||
|
||||
/// A one-page PDF, 600 × 800 points, drawing `content` with Helvetica as `/F1`.
|
||||
fn page(content: &str) -> Vec<u8> {
|
||||
pages(&[content])
|
||||
}
|
||||
|
||||
fn pages(contents: &[&str]) -> Vec<u8> {
|
||||
pages_by(contents, Some("(Autodesk AutoCAD 2024 DWG To PDF)"))
|
||||
}
|
||||
|
||||
/// Like [`pages`], with the `/Producer` value (a PDF string) the file's information names, or none.
|
||||
fn pages_by(contents: &[&str], producer: Option<&str>) -> Vec<u8> {
|
||||
let n = contents.len();
|
||||
let kids: String = (0..n).map(|i| format!("{} 0 R ", 10 + 2 * i)).collect();
|
||||
let mut pdf = format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [{kids}] /Count {n} >> endobj\n\
|
||||
3 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\n"
|
||||
);
|
||||
for (i, c) in contents.iter().enumerate() {
|
||||
pdf.push_str(&format!(
|
||||
"{} 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents {} 0 R /Resources << /Font << /F1 3 0 R >> >> >> endobj\n\
|
||||
{} 0 obj << /Length {} >> stream\n{c}\nendstream endobj\n",
|
||||
10 + 2 * i,
|
||||
11 + 2 * i,
|
||||
11 + 2 * i,
|
||||
c.len()
|
||||
));
|
||||
}
|
||||
match producer {
|
||||
Some(p) => pdf.push_str(&format!("4 0 obj << /Producer {p} >> endobj\ntrailer << /Root 1 0 R /Info 4 0 R >>\n%%EOF\n")),
|
||||
None => pdf.push_str("trailer << /Root 1 0 R >>\n%%EOF\n"),
|
||||
}
|
||||
pdf.into_bytes()
|
||||
}
|
||||
|
||||
fn import(content: &str) -> Drawing {
|
||||
read(&page(content), &PdfImportOptions::default()).unwrap().0
|
||||
}
|
||||
|
||||
fn kinds(d: &Drawing) -> Vec<&Entity> {
|
||||
d.model.iter().map(|e| &**e).collect()
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-6
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroked_line_is_a_line_with_its_colour_weight_and_layer() {
|
||||
let d = import("1 0 0 RG 2 w 10 20 m 110 20 l S");
|
||||
let all = kinds(&d);
|
||||
assert_eq!(all.len(), 1);
|
||||
let e = all[0];
|
||||
let EntityKind::Line(l) = &e.kind else { panic!("{:?}", e.kind) };
|
||||
assert!(near(l.a.x, 10.0 * MM_PER_PT) && near(l.a.y, 20.0 * MM_PER_PT), "{l:?}");
|
||||
assert!(near(l.b.x, 110.0 * MM_PER_PT) && near(l.b.y, 20.0 * MM_PER_PT), "{l:?}");
|
||||
assert_eq!(e.common.color, Color::True(Rgb(255, 0, 0)));
|
||||
assert_eq!(e.common.layer, "PDF_Geometry");
|
||||
// 2 pt = 0.7 mm.
|
||||
assert_eq!(e.common.lineweight, Lineweight::Mm100(70));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_is_the_automatic_colour() {
|
||||
let d = import("0 G 0 0 m 10 10 l S");
|
||||
assert_eq!(kinds(&d)[0].common.color, Color::Index(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rectangle_is_a_closed_polyline() {
|
||||
let d = import("10 10 50 30 re S");
|
||||
let EntityKind::LwPolyline(p) = &kinds(&d)[0].kind else { panic!() };
|
||||
assert!(p.closed);
|
||||
assert_eq!(p.vertices.len(), 4);
|
||||
assert!(p.vertices.iter().all(|v| v.bulge == 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_drawn_as_beziers_keeps_its_arcs() {
|
||||
let k = 0.552_284_75 * 50.0;
|
||||
let c = format!(
|
||||
"100 100 m 100 {a} {b} 150 150 150 c {c} 150 200 {a} 200 100 c 200 {d} {c} 50 150 50 c {b} 50 100 {d} 100 100 c h S",
|
||||
a = 100.0 + k,
|
||||
b = 150.0 - k,
|
||||
c = 150.0 + k,
|
||||
d = 100.0 - k + 0.0
|
||||
);
|
||||
// Four quarter arcs: out of the first point, counter-clockwise.
|
||||
let content = format!(
|
||||
"150 100 m 150 {k1} {k2} 150 100 150 c {k3} 150 50 {k1} 50 100 c 50 {k4} {k3} 50 100 50 c {k2} 50 150 {k4} 150 100 c h S",
|
||||
k1 = 100.0 + k,
|
||||
k2 = 100.0 + k,
|
||||
k3 = 100.0 - k,
|
||||
k4 = 100.0 - k
|
||||
);
|
||||
let _ = c;
|
||||
let d = import(&content);
|
||||
let all = kinds(&d);
|
||||
assert_eq!(all.len(), 1);
|
||||
let EntityKind::LwPolyline(p) = &all[0].kind else { panic!("{:?}", all[0].kind) };
|
||||
assert!(p.closed);
|
||||
assert_eq!(p.vertices.len(), 4, "{:?}", p.vertices);
|
||||
for v in &p.vertices {
|
||||
assert!((v.bulge - (std::f64::consts::PI / 8.0).tan()).abs() < 1e-3, "counter-clockwise quarter arcs: {v:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filled_shape_is_a_solid_hatch_and_a_white_one_is_left_out() {
|
||||
let d = import("0 0 1 rg 0 0 100 50 re f 1 1 1 rg 200 200 40 40 re f");
|
||||
let all = kinds(&d);
|
||||
assert_eq!(all.len(), 1);
|
||||
let EntityKind::Hatch(h) = &all[0].kind else { panic!("{:?}", all[0].kind) };
|
||||
assert!(h.solid && h.loops.len() == 1 && h.loops[0].vertices.len() == 4);
|
||||
assert_eq!(all[0].common.color, Color::True(Rgb(0, 0, 255)));
|
||||
assert_eq!(all[0].common.layer, "PDF_Solid Fills");
|
||||
assert!(d.read_notes.iter().any(|n| n.contains("1 white or near-white fill")), "{:?}", d.read_notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_near_white_fill_is_left_out_like_a_white_one() {
|
||||
// 245, 245, 245 table shading is left out; a light grey (230) is a fill.
|
||||
let d = import("0.96 0.96 0.96 rg 0 0 50 50 re f 0.9 0.9 0.9 rg 100 100 50 50 re f");
|
||||
let all = kinds(&d);
|
||||
assert_eq!(all.len(), 1, "{all:?}");
|
||||
assert_eq!(all[0].common.color, Color::True(Rgb(230, 230, 230)));
|
||||
assert!(d.read_notes.iter().any(|n| n.contains("1 white or near-white fill")), "{:?}", d.read_notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hole_stays_a_second_loop() {
|
||||
let d = import("0 0 1 rg 0 0 100 100 re 25 25 50 50 re f*");
|
||||
let EntityKind::Hatch(h) = &kinds(&d)[0].kind else { panic!() };
|
||||
assert_eq!(h.loops.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_is_one_text_object_per_baseline() {
|
||||
let d = import("BT /F1 12 Tf 100 200 Td (Hello World) Tj ET");
|
||||
let all = kinds(&d);
|
||||
assert_eq!(all.len(), 1, "{all:?}");
|
||||
let EntityKind::Text(t) = &all[0].kind else { panic!("{:?}", all[0].kind) };
|
||||
assert_eq!(t.value, "Hello World");
|
||||
assert!(near(t.insert.x, 100.0 * MM_PER_PT) && near(t.insert.y, 200.0 * MM_PER_PT), "{t:?}");
|
||||
assert!(near(t.height, 12.0 * MM_PER_PT * 0.72), "{t:?}");
|
||||
assert!(t.rotation.abs() < 1e-9);
|
||||
assert_eq!(t.halign, HAlign::Fit);
|
||||
let end = t.align_pt.unwrap();
|
||||
assert!(end.x > t.insert.x + 10.0 * MM_PER_PT && near(end.y, t.insert.y), "{t:?}");
|
||||
assert_eq!(all[0].common.layer, "PDF_Text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_text_keeps_its_angle() {
|
||||
// A 90 degree text matrix.
|
||||
let d = import("BT /F1 10 Tf 0 1 -1 0 300 300 Tm (Up) Tj ET");
|
||||
let EntityKind::Text(t) = &kinds(&d)[0].kind else { panic!() };
|
||||
assert_eq!(t.value, "Up");
|
||||
assert!((t.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{t:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_far_apart_on_a_line_are_separate_texts() {
|
||||
let d = import("BT /F1 10 Tf 50 100 Td (Left) Tj 400 0 Td (Right) Tj ET");
|
||||
let texts: Vec<_> = kinds(&d).into_iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.value.clone()) } else { None }).collect();
|
||||
assert_eq!(texts, ["Left", "Right"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_leave_out_text_fills_and_weights() {
|
||||
let bytes = page("BT /F1 12 Tf 10 10 Td (Hi) Tj ET 0 0 1 rg 0 0 5 5 re f 2 w 0 0 m 9 9 l S");
|
||||
let (d, pages) = read(&bytes, &PdfImportOptions { text: false, fills: false, lineweights: false, ..Default::default() }).unwrap();
|
||||
assert_eq!(pages, 1);
|
||||
let all = kinds(&d);
|
||||
assert_eq!(all.len(), 1);
|
||||
assert_eq!(all[0].common.lineweight, Lineweight::ByLayer);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rectangular_clip_cuts_a_line_and_drops_what_lies_outside() {
|
||||
let d = import("q 100 100 100 100 re W n 0 150 m 300 150 l S 0 0 m 10 10 l S Q");
|
||||
let all = kinds(&d);
|
||||
assert_eq!(all.len(), 1, "{all:?}");
|
||||
let EntityKind::Line(l) = &all[0].kind else { panic!("{:?}", all[0].kind) };
|
||||
assert!(near(l.a.x, 100.0 * MM_PER_PT) && near(l.b.x, 200.0 * MM_PER_PT), "{l:?}");
|
||||
assert!(near(l.a.y, 150.0 * MM_PER_PT) && near(l.b.y, 150.0 * MM_PER_PT), "{l:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rectangular_clip_cuts_a_fill_to_its_corners() {
|
||||
let d = import("q 100 100 100 100 re W n 0 0 1 rg 50 50 200 200 re f Q 0 1 0 rg 0 0 10 10 re f");
|
||||
let hatches: Vec<_> = kinds(&d).into_iter().filter_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h) } else { None }).collect();
|
||||
assert_eq!(hatches.len(), 2);
|
||||
let xs: Vec<f64> = hatches[0].loops[0].vertices.iter().map(|v| v.p.x).collect();
|
||||
let ys: Vec<f64> = hatches[0].loops[0].vertices.iter().map(|v| v.p.y).collect();
|
||||
assert!(xs.iter().all(|x| *x >= 100.0 * MM_PER_PT - 1e-6 && *x <= 200.0 * MM_PER_PT + 1e-6), "{xs:?}");
|
||||
assert!(ys.iter().all(|y| *y >= 100.0 * MM_PER_PT - 1e-6 && *y <= 200.0 * MM_PER_PT + 1e-6), "{ys:?}");
|
||||
// After the clip is restored, the next fill is whole again.
|
||||
assert_eq!(hatches[1].loops[0].vertices.len(), 4);
|
||||
}
|
||||
|
||||
fn texts(d: &Drawing) -> Vec<String> {
|
||||
kinds(d).into_iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.value.clone()) } else { None }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_starting_on_a_clip_edge_is_kept() {
|
||||
// A cell clipped to a box whose left side runs a hair right of the text's start, as a plotter
|
||||
// draws it: a viewer shows the whole word.
|
||||
let d = import("q 100.001 200 200 14 re W n BT /F1 10 Tf 100 202 Td (MATERIAL) Tj ET Q");
|
||||
assert_eq!(texts(&d), ["MATERIAL"]);
|
||||
// A label turned to read downwards with its start just off a page clip.
|
||||
let d = import("q 0.12 0.12 599 799 re W n BT /F1 10 Tf 0 -1 1 0 -0.5 300 Tm (B) Tj ET Q");
|
||||
assert_eq!(texts(&d), ["B"]);
|
||||
// Text wholly outside the clip is still left out, and a glyph is cut at the clip.
|
||||
let d = import("q 100 200 200 14 re W n BT /F1 10 Tf 400 202 Td (Gone) Tj ET BT /F1 10 Tf 88 202 Td (XYZ) Tj ET Q");
|
||||
assert_eq!(texts(&d), ["Z"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_outside_its_clip_is_left_out() {
|
||||
let d = import("q 100 100 50 50 re W n 0 0 m 10 10 l S Q");
|
||||
assert_eq!(kinds(&d).len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_clip_shape_is_not_applied_and_the_read_note_says_so() {
|
||||
let d = import("q 100 100 m 200 100 l 150 200 l h W n 0 0 m 300 300 l S Q");
|
||||
assert_eq!(kinds(&d).len(), 1);
|
||||
assert!(d.read_notes.iter().any(|n| n.contains("clips by a shape other than a rectangle")), "{:?}", d.read_notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unit_sets_the_scale() {
|
||||
let (d, _) = read(&page("0 0 m 72 0 l S"), &PdfImportOptions { unit: 1.0 / 72.0, ..Default::default() }).unwrap();
|
||||
let EntityKind::Line(l) = &kinds(&d)[0].kind else { panic!() };
|
||||
assert!(near(l.b.x, 1.0), "{l:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_is_chosen_by_number() {
|
||||
let bytes = pages(&["0 0 m 10 0 l S", "0 0 m 20 0 l S", "0 0 m 30 0 l S"]);
|
||||
let (d, n) = read(&bytes, &PdfImportOptions { page: 2, ..Default::default() }).unwrap();
|
||||
assert_eq!(n, 3);
|
||||
let EntityKind::Line(l) = &kinds(&d)[0].kind else { panic!() };
|
||||
assert!(near(l.b.x, 20.0 * MM_PER_PT));
|
||||
let e = read(&bytes, &PdfImportOptions { page: 4, ..Default::default() }).unwrap_err().to_string();
|
||||
assert!(e.contains("page 4") && e.contains("3 pages"), "{e}");
|
||||
assert!(read(&bytes, &PdfImportOptions { page: 0, ..Default::default() }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_is_not_a_pdf_is_an_error_not_a_panic() {
|
||||
assert!(read(b"%PDF-1.7 garbage", &PdfImportOptions::default()).is_err());
|
||||
assert!(read(b"", &PdfImportOptions::default()).is_err());
|
||||
assert!(read(&page("0 0 m 1 1 l S"), &PdfImportOptions { unit: 0.0, ..Default::default() }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_pdf_is_imported_whatever_made_it() {
|
||||
// A plot that another program merged or printed again no longer names the CAD program.
|
||||
let content = ["0 0 m 10 10 l S"];
|
||||
for producer in [Some("(Skia/PDF m120)"), Some("(Example PDF Tool)"), Some("<FEFF004400570047>"), None] {
|
||||
let (d, _) = read(&pages_by(&content, producer), &PdfImportOptions::default()).unwrap();
|
||||
assert_eq!(kinds(&d).len(), 1, "{producer:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonsense_content_does_not_panic() {
|
||||
for c in ["q q q", "1 2 3 re re re f", "BT (x) Tj ET", "0 0 m 1e300 1e300 l 1e300 -1e300 l S", "Q Q Q h h S"] {
|
||||
let _ = read(&page(c), &PdfImportOptions::default());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_or_damaged_file_is_never_a_panic() {
|
||||
let whole = page("1 0 0 RG 2 w 10 20 m 110 20 l S 0 0 1 rg 0 0 50 50 re f BT /F1 12 Tf 100 200 Td (Hello) Tj ET");
|
||||
for len in (0..whole.len()).step_by(3) {
|
||||
let _ = read(&whole[..len], &PdfImportOptions::default());
|
||||
}
|
||||
for at in (0..whole.len()).step_by(2) {
|
||||
for byte in [0x00, 0xFF, b'<', b'0'] {
|
||||
let mut damaged = whole.clone();
|
||||
damaged[at] = byte;
|
||||
let _ = read(&damaged, &PdfImportOptions::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_with_a_great_many_objects_is_read_or_refused_not_hung() {
|
||||
let content = "0 0 m 1 1 l S ".repeat(60_000);
|
||||
let (d, _) = read(&page(&content), &PdfImportOptions::default()).unwrap();
|
||||
assert_eq!(d.model.iter().count(), 60_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_general_reader_does_not_take_a_pdf() {
|
||||
// INSERT, XREF, COMPARE, RECOVER and templates read drawings through `read`; a PDF is taken
|
||||
// only by the engine's OPEN, IMPORT and PDFIMPORT, through `pdf_read`.
|
||||
let e = cadcraft_io::read(&page("0 0 m 10 10 l S"), "plan.pdf").unwrap_err().to_string();
|
||||
assert!(e.contains("unsupported file type"), "{e}");
|
||||
}
|
||||
|
||||
/// A one-page PDF whose page draws the form `/X` once; the form's content is `form`, and it may
|
||||
/// draw `/X` itself.
|
||||
fn form_page(form: &str) -> String {
|
||||
format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [10 0 R] /Count 1 >> endobj\n\
|
||||
10 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 11 0 R /Resources << /XObject << /X 5 0 R >> >> >> endobj\n\
|
||||
11 0 obj << /Length 5 >> stream\n/X Do\nendstream endobj\n\
|
||||
5 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 600 800] /Resources << /XObject << /X 5 0 R >> >> /Length {} >> stream\n{form}\nendstream endobj\n\
|
||||
4 0 obj << /Producer (AutoCAD) >> endobj\n\
|
||||
trailer << /Root 1 0 R /Info 4 0 R >>\n%%EOF\n",
|
||||
form.len()
|
||||
)
|
||||
}
|
||||
|
||||
fn lines_of(d: &Drawing) -> usize {
|
||||
kinds(d).iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count()
|
||||
}
|
||||
|
||||
/// A form that draws itself twice asks for about 2^50 nested interpretations unless the interpreter
|
||||
/// limits how often forms nest (craft-libs' patched hayro-interpret does).
|
||||
#[test]
|
||||
fn a_form_that_draws_itself_twice_is_stopped() {
|
||||
// The same page with a form that doesn't call itself draws its line once.
|
||||
let (d, _) = read(form_page("0 0 m 1 1 l S").as_bytes(), &PdfImportOptions::default()).unwrap();
|
||||
assert_eq!(lines_of(&d), 1);
|
||||
let pdf = form_page("/X Do /X Do 0 0 m 1 1 l S");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(read(pdf.as_bytes(), &PdfImportOptions::default()).map(|(d, _)| lines_of(&d)));
|
||||
});
|
||||
let result = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("the self-calling form was not stopped");
|
||||
// The page still reads, with the form's own line drawn and the nesting cut off.
|
||||
let lines = result.unwrap_or_else(|e| panic!("{e}"));
|
||||
// The top-level form plus 50_000 nested paints (`MAX_NESTED_PAINTS` in craft-libs' hayro-interpret).
|
||||
assert!((1..=50_001).contains(&lines), "{lines} lines");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_curve_is_bounded_and_an_out_of_range_one_is_left_out() {
|
||||
// A million points across: its flattening is capped, not millions of segments.
|
||||
let d = import("1000000 0 0 1000000 0 0 cm 0 0 m 0 1 1 1 1 0 c S");
|
||||
let verts: usize = kinds(&d).iter().map(|e| if let EntityKind::LwPolyline(p) = &e.kind { p.vertices.len() } else { 2 }).sum();
|
||||
assert!(verts < 5_000, "{verts} vertices");
|
||||
// 1e20 points across: out of any drawing's range, named in a read note, and nothing runs away.
|
||||
let d = import("100000000000000000000 0 0 100000000000000000000 0 0 cm 0 0 m 0 1 1 1 1 0 c S");
|
||||
assert_eq!(kinds(&d).len(), 0);
|
||||
assert!(d.read_notes.iter().any(|n| n.contains("out-of-range")), "{:?}", d.read_notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_drawn_as_fill_and_stroke_is_one_text() {
|
||||
// Render mode 2 draws each glyph twice at one origin: fill, then stroke.
|
||||
let d = import("BT /F1 12 Tf 100 200 Td 2 Tr (Hello) Tj ET");
|
||||
let texts: Vec<String> =
|
||||
kinds(&d).into_iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.value.clone()) } else { None }).collect();
|
||||
assert_eq!(texts, ["Hello"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plot_of_a_drawing_imports_back_as_its_geometry() {
|
||||
let mut d = Drawing::new_metric();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(100.0, 0.0, 0.0) })).unwrap();
|
||||
d.add(
|
||||
&Space::Model,
|
||||
Common::default(),
|
||||
EntityKind::Text(Text {
|
||||
insert: Vec3::new(10.0, 20.0, 0.0),
|
||||
align_pt: None,
|
||||
height: 5.0,
|
||||
value: "Plan".into(),
|
||||
rotation: 0.0,
|
||||
width_factor: 1.0,
|
||||
oblique: 0.0,
|
||||
style: "Standard".into(),
|
||||
halign: HAlign::Left,
|
||||
valign: Default::default(),
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
let pdf = cadcraft_io::plot(&d, &Space::Model, &json!({ "compress": false, "paper": "A4", "fit": true })).unwrap();
|
||||
let (back, _) = read(&pdf, &PdfImportOptions::default()).unwrap();
|
||||
let lines = back.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_) | EntityKind::LwPolyline(_))).count();
|
||||
assert!(lines >= 1, "{:?}", back.model.iter().map(|e| &e.kind).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// A one-page PDF drawing `content` with Helvetica as `/F1`, whose ToUnicode CMap maps the code
|
||||
/// `<41>` to `to` (a hex string of UTF-16 code units).
|
||||
fn page_with_to_unicode(content: &str, to: &str) -> Vec<u8> {
|
||||
let cmap = format!(
|
||||
"/CIDInit /ProcSet findresource begin 12 dict begin begincmap\n\
|
||||
/CMapName /Test def /CMapType 2 def\n\
|
||||
1 begincodespacerange <00> <FF> endcodespacerange\n\
|
||||
1 beginbfchar <41> <{to}> endbfchar\n\
|
||||
endcmap CMapName currentdict /CMap defineresource pop end end"
|
||||
);
|
||||
format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [10 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding /ToUnicode 5 0 R >> endobj\n\
|
||||
5 0 obj << /Length {} >> stream\n{cmap}\nendstream endobj\n\
|
||||
10 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 11 0 R /Resources << /Font << /F1 3 0 R >> >> >> endobj\n\
|
||||
11 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF\n",
|
||||
cmap.len(),
|
||||
content.len()
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_glyph_gives_at_most_32_characters_and_a_page_a_bounded_text() {
|
||||
// `<41>` (an A) stands for 16 000 Bs.
|
||||
let long = "0042".repeat(16_000);
|
||||
let d = read(&page_with_to_unicode("BT /F1 12 Tf 100 200 Td (A) Tj ET", &long), &PdfImportOptions::default()).unwrap().0;
|
||||
assert_eq!(texts(&d), ["B".repeat(32)]);
|
||||
// 125 000 of them, each kerned back onto the one before: more text than a page may hold, so
|
||||
// the import stops with a reason instead of growing the text.
|
||||
let content = format!("BT /F1 12 Tf 100 200 Td [{}] TJ ET", "(A) 667 ".repeat(125_000));
|
||||
let e = read(&page_with_to_unicode(&content, &long), &PdfImportOptions::default()).unwrap_err().to_string();
|
||||
assert!(e.contains("characters of text on the page"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_with_a_scale_too_large_for_numbers_is_skipped_not_added() {
|
||||
// Ten times 1e30 makes 1e300; a larger font size pushes the em square past what a number holds,
|
||||
// and a horizontal scaling of 1000 % its width alone (the baseline's direction).
|
||||
let big = "1000000000000000000000000000000 0 0 1000000000000000000000000000000 0 0 cm ".repeat(10);
|
||||
for (size, scaling) in [1, 100, 10_000, 1_000_000, 100_000_000].into_iter().flat_map(|s| [(s, 100), (s, 1000)]) {
|
||||
let r = read(&page(&format!("{big} BT /F1 {size} Tf {scaling} Tz (AB) Tj ET")), &PdfImportOptions::default());
|
||||
let (d, _) = r.unwrap_or_else(|e| panic!("size {size}, scaling {scaling}: {e}"));
|
||||
for e in kinds(&d) {
|
||||
if let EntityKind::Text(t) = &e.kind {
|
||||
let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite();
|
||||
assert!(finite(t.insert) && t.align_pt.is_none_or(finite) && t.rotation.is_finite() && t.height.is_finite(), "{t:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_after_a_close_starts_where_the_subpath_did() {
|
||||
let d = import("0 0 m 100 0 l 100 100 l h 0 50 50 100 100 100 c S");
|
||||
let all = kinds(&d);
|
||||
assert_eq!(all.len(), 2, "{all:?}");
|
||||
let EntityKind::LwPolyline(p) = &all[1].kind else { panic!("{:?}", all[1].kind) };
|
||||
let (first, last) = (p.vertices.first().unwrap().p, p.vertices.last().unwrap().p);
|
||||
assert!(near(first.x, 0.0) && near(first.y, 0.0), "{first:?}");
|
||||
assert!(near(last.x, 100.0 * MM_PER_PT) && near(last.y, 100.0 * MM_PER_PT), "{last:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_origin_user_units_and_page_rotation_are_applied() {
|
||||
let pdf = String::from_utf8(page("100 200 m 150 200 l S")).unwrap();
|
||||
let pdf = pdf.replace("/MediaBox [0 0 600 800]", "/MediaBox [0 0 600 800] /CropBox [100 200 300 400] /UserUnit 2 /Rotate 90");
|
||||
let (d, _) = read(pdf.as_bytes(), &PdfImportOptions::default()).unwrap();
|
||||
let all = kinds(&d);
|
||||
assert_eq!(all.len(), 1);
|
||||
let EntityKind::Line(line) = &all[0].kind else { panic!("expected a line") };
|
||||
assert!(near(line.a.x, line.b.x), "rotation makes the line vertical: {line:?}");
|
||||
assert!(near((line.b.y - line.a.y).abs(), 100.0 * MM_PER_PT), "UserUnit doubles the length: {line:?}");
|
||||
assert!(line.a.x >= 0.0 && line.a.y >= 0.0 && line.b.x >= 0.0 && line.b.y >= 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_boundary_and_nested_clips_both_limit_the_import() {
|
||||
let d = import("q -100 -100 800 1000 re W n q 10 10 40 40 re W n -50 30 m 100 30 l S Q -100 60 m 700 60 l S Q");
|
||||
let all = kinds(&d);
|
||||
assert_eq!(all.len(), 2);
|
||||
let lines: Vec<_> = all.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l) } else { None }).collect();
|
||||
assert!(lines[0].a.x > lines[1].a.x && lines[0].b.x < lines[1].b.x, "inner clip narrows the first line");
|
||||
assert!(near(lines[1].a.x, 0.0) && near(lines[1].b.x, 600.0 * MM_PER_PT), "page clips the restored outer line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_and_shapes_keep_their_paint_order() {
|
||||
let d = import("BT /F1 12 Tf 20 20 Td (Below) Tj ET 1 0 0 rg 10 10 100 40 re f BT /F1 12 Tf 20 80 Td (Above) Tj ET");
|
||||
let all = kinds(&d);
|
||||
assert!(matches!(all[0].kind, EntityKind::Text(_)));
|
||||
assert!(matches!(all[1].kind, EntityKind::Hatch(_)));
|
||||
assert!(matches!(all[2].kind, EntityKind::Text(_)));
|
||||
assert!(d.read_notes.iter().any(|n| n.contains("Standard font")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_text_drawn_again_over_a_shape_is_kept() {
|
||||
// A label, a fill over it, then the label again on top: the second one is what shows.
|
||||
let d = import("BT /F1 12 Tf 20 20 Td (Label) Tj ET 1 0 0 rg 10 10 100 40 re f BT /F1 12 Tf 20 20 Td (Label) Tj ET");
|
||||
assert_eq!(texts(&d), ["Label", "Label"]);
|
||||
assert!(matches!(kinds(&d).last().map(|e| &e.kind), Some(EntityKind::Text(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagonal_edges_are_not_mistaken_for_a_rectangular_clip() {
|
||||
let d = import("q 0 0 m 100 100 l 100 0 l 0 100 l h W n 0 50 m 150 50 l S Q");
|
||||
assert!(d.read_notes.iter().any(|n| n.contains("clips by a shape other than a rectangle")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_that_doubles_back_along_an_edge_is_not_a_rectangular_clip() {
|
||||
// Every point lies on the box's edges, but the corner at (0, 100) is never reached.
|
||||
let d = import("q 0 0 m 100 0 l 100 100 l 100 0 l h W n 0 50 m 150 50 l S Q");
|
||||
assert!(d.read_notes.iter().any(|n| n.contains("clips by a shape other than a rectangle")), "{:?}", d.read_notes);
|
||||
let EntityKind::Line(line) = &kinds(&d)[0].kind else { panic!("expected a line") };
|
||||
assert!(line.b.x > 100.0 * MM_PER_PT, "the line was cut at the box: {line:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_only_pages_are_identified_without_fabricated_geometry() {
|
||||
let d = import("q 100 0 0 100 0 0 cm BI /W 1 /H 1 /CS /RGB /BPC 8 /F /AHx ID FF0000> EI Q");
|
||||
assert!(d.model.is_empty());
|
||||
assert!(d.read_notes.iter().any(|n| n.contains("raster image")), "{:?}", d.read_notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn form_transforms_and_bounding_boxes_are_respected() {
|
||||
let form = "0 0 m 100 0 l S";
|
||||
let mut pdf = String::from_utf8(page("/Fm Do"))
|
||||
.unwrap()
|
||||
.replace("/Resources << /Font << /F1 3 0 R >> >>", "/Resources << /Font << /F1 3 0 R >> /XObject << /Fm 6 0 R >> >>");
|
||||
let object = format!(
|
||||
"6 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Matrix [2 0 0 2 10 30] /Length {} >> stream\n{form}\nendstream endobj\n",
|
||||
form.len()
|
||||
);
|
||||
pdf = pdf.replace("trailer <<", &format!("{object}trailer <<"));
|
||||
let (d, _) = read(pdf.as_bytes(), &PdfImportOptions::default()).unwrap();
|
||||
let all = kinds(&d);
|
||||
assert_eq!(all.len(), 1);
|
||||
let EntityKind::Line(line) = &all[0].kind else { panic!("expected a line") };
|
||||
assert!(near(line.a.x, 10.0 * MM_PER_PT) && near(line.b.x, 50.0 * MM_PER_PT), "{line:?}");
|
||||
assert!(near(line.a.y, 30.0 * MM_PER_PT) && near(line.b.y, line.a.y), "{line:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_dash_appearance_is_reported() {
|
||||
let d = import("[5 3] 0 d 10 10 m 100 10 l S");
|
||||
assert!(!d.model.is_empty());
|
||||
assert!(d.read_notes.iter().any(|n| n.contains("dashed paths")), "{:?}", d.read_notes);
|
||||
}
|
||||
@@ -257,7 +257,8 @@ pub(super) fn assert_layouts(a: &Drawing, b: &Drawing, context: &str) {
|
||||
let back = b.layouts.iter().find(|l| l.name == layout.name).expect("layout must survive");
|
||||
assert_eq!(back.tab_order, layout.tab_order, "{context}.{}.tab_order", layout.name);
|
||||
// The groups 44, 45 and 73 the file stored are provenance, not a setting.
|
||||
let setting = |p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, ..p.clone() };
|
||||
let setting =
|
||||
|p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..p.clone() };
|
||||
assert_eq!(setting(&back.page), setting(&layout.page), "{context}.{}.page", layout.name);
|
||||
assert_eq!(back.view, layout.view, "{context}.{}.view", layout.name);
|
||||
compare::entities(a, b, &layout.entities, &back.entities, &format!("{context}.layout[{}]", layout.name));
|
||||
|
||||
@@ -112,7 +112,7 @@ fn layout_page_setup_and_paper_view_round_trip() {
|
||||
for (a, b) in d.layouts.iter().zip(&r.layouts) {
|
||||
assert_eq!(a.name, b.name);
|
||||
// The groups 44, 45 and 73 the file stored are provenance, not a setting.
|
||||
let read = cadcraft_doc::PageSetup { file_paper: None, ..b.page.clone() };
|
||||
let read = cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..b.page.clone() };
|
||||
assert_eq!(a.page, read, "{}", a.name);
|
||||
assert_eq!(a.view, b.view, "{}", a.name);
|
||||
}
|
||||
|
||||
+22
-128
@@ -3,7 +3,8 @@
|
||||
//! rotation, width factor and obliquing; fonts whose licence bits forbid embedding, the stroke
|
||||
//! font and the `text: "geometry"` option keep filled outlines.
|
||||
//!
|
||||
//! The fonts are tiny synthetic TrueType files built here (no font files in the repository).
|
||||
//! The fonts are tiny synthetic TrueType files built by the shared test helper in
|
||||
//! `crates/fonts/tests/support/sfnt.rs` (no font files in the repository).
|
||||
|
||||
use cadcraft_doc::{Common, Drawing, EntityKind, Space, Text, TextStyle, Viewport};
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
@@ -15,137 +16,30 @@ mod pdf_read;
|
||||
|
||||
use pdf_read::Doc;
|
||||
|
||||
// The synthetic TrueType file: the fonts layer's test-only helper, inlined rather than published
|
||||
// or depended on.
|
||||
#[path = "../../fonts/tests/support/sfnt.rs"]
|
||||
mod sfnt;
|
||||
|
||||
// ---------- a minimal TrueType font: .notdef, "A" (triangle), "B" (square) ----------
|
||||
|
||||
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: one closed contour of on-curve points.
|
||||
fn simple_glyph(pts: &[(i16, i16)]) -> Vec<u8> {
|
||||
let mut g = Vec::new();
|
||||
let xs: Vec<i16> = pts.iter().map(|p| p.0).collect();
|
||||
let ys: Vec<i16> = pts.iter().map(|p| p.1).collect();
|
||||
be16(&mut g, 1);
|
||||
for v in [*xs.iter().min().unwrap(), *ys.iter().min().unwrap(), *xs.iter().max().unwrap(), *ys.iter().max().unwrap()] {
|
||||
be16(&mut g, v as u16);
|
||||
}
|
||||
be16(&mut g, pts.len() as u16 - 1);
|
||||
be16(&mut g, 0);
|
||||
g.extend(std::iter::repeat_n(1u8, pts.len()));
|
||||
let (mut px, mut py) = (0i16, 0i16);
|
||||
for (x, _) in pts {
|
||||
be16(&mut g, (x - px) as u16);
|
||||
px = *x;
|
||||
}
|
||||
for (_, y) in pts {
|
||||
be16(&mut g, (y - py) as u16);
|
||||
py = *y;
|
||||
}
|
||||
while g.len() % 4 != 0 {
|
||||
g.push(0);
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
/// A TrueType font with glyphs .notdef (empty), A and B, and OS/2 `fsType`. `hmtx` holds
|
||||
/// `metrics` of the three metrics `hhea` declares.
|
||||
/// `metrics` of the three metrics `hhea` declares: fewer is a font the writer cannot subset.
|
||||
fn test_font(fs_type: u16, metrics: usize) -> Vec<u8> {
|
||||
let glyphs = [Vec::new(), simple_glyph(&[(50, 0), (550, 0), (300, 700)]), simple_glyph(&[(50, 0), (550, 0), (550, 700), (50, 700)])];
|
||||
let mut glyf = Vec::new();
|
||||
let mut loca = Vec::new();
|
||||
for g in &glyphs {
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
glyf.extend_from_slice(g);
|
||||
}
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
let mut head = Vec::new();
|
||||
be32(&mut head, 0x0001_0000);
|
||||
be32(&mut head, 0x0001_0000);
|
||||
be32(&mut head, 0);
|
||||
be32(&mut head, 0x5F0F_3CF5);
|
||||
be16(&mut head, 0);
|
||||
be16(&mut head, 1000);
|
||||
head.extend_from_slice(&[0; 16]);
|
||||
for v in [0i16, 0, 600, 700] {
|
||||
be16(&mut head, v as u16);
|
||||
}
|
||||
for v in [0u16, 8, 2, 1, 0] {
|
||||
be16(&mut head, v);
|
||||
}
|
||||
let mut hhea = Vec::new();
|
||||
be32(&mut hhea, 0x0001_0000);
|
||||
for v in [800i16, -200, 0, 600, 0, 0, 600, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut hhea, v as u16);
|
||||
}
|
||||
be16(&mut hhea, 3);
|
||||
let mut maxp = Vec::new();
|
||||
be32(&mut maxp, 0x0001_0000);
|
||||
for v in [3u16, 4, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut maxp, v);
|
||||
}
|
||||
let mut hmtx = Vec::new();
|
||||
for _ in 0..metrics {
|
||||
be16(&mut hmtx, 600);
|
||||
be16(&mut hmtx, 50);
|
||||
}
|
||||
// cmap: format 4, 'A'..'B' → 1..2.
|
||||
let mut sub = Vec::new();
|
||||
let segs: [(u16, u16, u16); 2] = [(0x41, 0x42, 1u16.wrapping_sub(0x41)), (0xFFFF, 0xFFFF, 1)];
|
||||
be16(&mut sub, 4);
|
||||
be16(&mut sub, (16 + segs.len() * 8) as u16);
|
||||
be16(&mut sub, 0);
|
||||
be16(&mut sub, (segs.len() * 2) as u16);
|
||||
for v in [4u16, 1, 0] {
|
||||
be16(&mut sub, v);
|
||||
}
|
||||
for s in segs {
|
||||
be16(&mut sub, s.1);
|
||||
}
|
||||
be16(&mut sub, 0);
|
||||
for s in segs {
|
||||
be16(&mut sub, s.0);
|
||||
}
|
||||
for s in segs {
|
||||
be16(&mut sub, s.2);
|
||||
}
|
||||
for _ in segs {
|
||||
be16(&mut sub, 0);
|
||||
}
|
||||
let mut cmap = Vec::new();
|
||||
for v in [0u16, 1, 3, 1] {
|
||||
be16(&mut cmap, v);
|
||||
}
|
||||
be32(&mut cmap, 12);
|
||||
cmap.extend_from_slice(&sub);
|
||||
let mut os2 = vec![0u8; 78];
|
||||
os2[8..10].copy_from_slice(&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);
|
||||
for v in [tables.len() as u16, 128, 3, tables.len() as u16 * 16 - 128] {
|
||||
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);
|
||||
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
|
||||
sfnt::bytes(&sfnt::Sfnt {
|
||||
// "A" is a triangle and "B" a square: one contour each.
|
||||
glyphs: &[
|
||||
sfnt::notdef(),
|
||||
sfnt::glyph(&[vec![(50, 0), (550, 0), (300, 700)]]),
|
||||
sfnt::glyph(&[vec![(50, 0), (550, 0), (550, 700), (50, 700)]]),
|
||||
],
|
||||
cmap: &[(0x41, 0x42, 1 - 0x41)], // "A".."B" → glyphs 1..2
|
||||
advance: 600,
|
||||
lsb: 50,
|
||||
metrics,
|
||||
fs_type,
|
||||
ink_box: [0, 0, 600, 700],
|
||||
})
|
||||
}
|
||||
|
||||
/// Register the test fonts once: an embeddable one, one with a restricted licence, and one
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! The registered applications (APPID) of a file are saved back, in DXF and in DWG, save after
|
||||
//! save, also those no xdata names.
|
||||
|
||||
use cadcraft_doc::Drawing;
|
||||
use cadcraft_io::{read, read_dxf, write, write_dxf};
|
||||
|
||||
/// The records of a DXF: each `(code, value)` from its `0` group on.
|
||||
fn records(text: &str) -> Vec<Vec<(i32, String)>> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let mut out: Vec<Vec<(i32, String)>> = Vec::new();
|
||||
for chunk in lines.chunks(2) {
|
||||
let [code, value] = chunk else { break };
|
||||
let Ok(c) = code.trim().parse::<i32>() else { continue };
|
||||
let pair = (c, value.trim().to_string());
|
||||
if c == 0 {
|
||||
out.push(vec![pair]);
|
||||
} else if let Some(r) = out.last_mut() {
|
||||
r.push(pair);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The value of the record's first group `code`.
|
||||
fn value(r: &[(i32, String)], code: i32) -> Option<&str> {
|
||||
r.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// A file whose APPID table has `Other_App` (handle 7A00), which no xdata names; with `xdata`,
|
||||
/// a line's xdata names it as `OTHER_APP`.
|
||||
fn source(xdata: bool) -> String {
|
||||
let mut out = String::new();
|
||||
let mut put = |c: i32, v: &str| out.push_str(&format!("{c:>3}\n{v}\n"));
|
||||
for r in records(&write_dxf(&Drawing::new_metric())) {
|
||||
for (c, v) in &r {
|
||||
put(*c, v);
|
||||
}
|
||||
if xdata && r[0].1 == "SECTION" && value(&r, 2) == Some("ENTITIES") {
|
||||
for (c, v) in [
|
||||
(0, "LINE"),
|
||||
(5, "7A01"),
|
||||
(100, "AcDbEntity"),
|
||||
(8, "0"),
|
||||
(100, "AcDbLine"),
|
||||
(10, "0"),
|
||||
(20, "0"),
|
||||
(30, "0"),
|
||||
(11, "10"),
|
||||
(21, "0"),
|
||||
(31, "0"),
|
||||
(1001, "OTHER_APP"),
|
||||
(1000, "x"),
|
||||
] {
|
||||
put(c, v);
|
||||
}
|
||||
}
|
||||
if r[0].1 == "TABLE" && value(&r, 2) == Some("APPID") {
|
||||
let table = value(&r, 5).unwrap_or("0").to_string();
|
||||
for (c, v) in [
|
||||
(0, "APPID"),
|
||||
(5, "7A00"),
|
||||
(330, table.as_str()),
|
||||
(100, "AcDbSymbolTableRecord"),
|
||||
(100, "AcDbRegAppTableRecord"),
|
||||
(2, "Other_App"),
|
||||
(70, "0"),
|
||||
] {
|
||||
put(c, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How many APPID records of the DXF are named `Other_App`, in any case.
|
||||
fn appids(text: &str) -> usize {
|
||||
records(text).into_iter().filter(|r| r[0].1 == "APPID" && value(r, 2).is_some_and(|n| n.eq_ignore_ascii_case("Other_App"))).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_applications_no_xdata_names_are_kept() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read_dxf(source(false).as_bytes()).expect("read");
|
||||
for generation in 1..=2 {
|
||||
let text = write_dxf(&d);
|
||||
assert_eq!(appids(&text), 1, "DXF {generation}");
|
||||
d = read_dxf(text.as_bytes()).expect("reread");
|
||||
}
|
||||
for generation in 1..=2 {
|
||||
let dwg = write(&d, "kept.dwg").expect("DWG");
|
||||
d = read(&dwg, "kept.dwg").expect("DWG read");
|
||||
assert_eq!(appids(&write_dxf(&d)), 1, "DWG {generation}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An application both registered and named by xdata, in another case, gets one record.
|
||||
#[test]
|
||||
fn a_registered_application_xdata_names_gets_one_record() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut d = read_dxf(source(true).as_bytes()).expect("read");
|
||||
for generation in 1..=2 {
|
||||
let text = write_dxf(&d);
|
||||
assert!(text.contains("OTHER_APP"), "DXF {generation}: the line's xdata is kept");
|
||||
assert_eq!(appids(&text), 1, "DXF {generation}");
|
||||
d = read_dxf(text.as_bytes()).expect("reread");
|
||||
}
|
||||
for generation in 1..=2 {
|
||||
let dwg = write(&d, "kept.dwg").expect("DWG");
|
||||
d = read(&dwg, "kept.dwg").expect("DWG read");
|
||||
assert_eq!(appids(&write_dxf(&d)), 1, "DWG {generation}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Registered applications alone are not kept objects: a file with nothing else to keep notes no
|
||||
/// version, so the DWG writer reads its R2000 text as before rather than as the file's version.
|
||||
#[test]
|
||||
fn registered_applications_alone_note_no_version() {
|
||||
let d = read_dxf(source(false).as_bytes()).expect("read");
|
||||
assert!(d.foreign.appids.iter().any(|n| n == "Other_App"), "{:?}", d.foreign.appids);
|
||||
assert_eq!(d.foreign.version, None);
|
||||
}
|
||||
@@ -3,6 +3,11 @@ use crate::*;
|
||||
use cadcraft_doc::{Common, Drawing, EntityKind, Hatch, HatchLoop, Space};
|
||||
use cadcraft_geom::{PolyVertex, Vec3};
|
||||
|
||||
// The synthetic TrueType file both this suite and the PDF writer's build: the fonts layer's
|
||||
// test-only helper, inlined rather than published or depended on.
|
||||
#[path = "../../fonts/tests/support/sfnt.rs"]
|
||||
mod sfnt;
|
||||
|
||||
fn sample() -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) }))
|
||||
@@ -277,6 +282,44 @@ fn system_font() -> Option<&'static str> {
|
||||
["Arial", "Helvetica", "DejaVuSans", "Verdana", "LiberationSans-Regular"].into_iter().find(|n| cadcraft_fonts::ttf::find(n).is_some())
|
||||
}
|
||||
|
||||
// ---------- a fixture TrueType font: no font file, no installed font ----------
|
||||
|
||||
/// A closed ellipse round (500, 350), wound by `clockwise`: one contour of a glyph outline.
|
||||
fn ring(rx: f64, ry: f64, points: usize, clockwise: bool) -> Vec<(i16, i16)> {
|
||||
let dir = if clockwise { -1.0 } else { 1.0 };
|
||||
(0..points)
|
||||
.map(|i| {
|
||||
(
|
||||
(500.0 + rx * (dir * std::f64::consts::TAU * i as f64 / points as f64).cos()) as i16,
|
||||
(350.0 + ry * (dir * std::f64::consts::TAU * i as f64 / points as f64).sin()) as i16,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A TrueType font whose only glyph, "O", is a 128-point ring: the flattened outline a real font's
|
||||
/// curve gives, at the same scale, with plenty of detail to simplify. It is built in code so the
|
||||
/// level-of-detail test needs no installed font and no font file in the repository (#651).
|
||||
fn fixture_font() -> &'static str {
|
||||
const NAME: &str = "cadcraft-render-lod.ttf";
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| cadcraft_fonts::ttf::register(NAME, fixture_font_bytes()));
|
||||
NAME
|
||||
}
|
||||
|
||||
fn fixture_font_bytes() -> Vec<u8> {
|
||||
sfnt::bytes(&sfnt::Sfnt {
|
||||
// Glyph 1 is "O": a 128-point ring, its counter a second, oppositely wound contour.
|
||||
glyphs: &[sfnt::notdef(), sfnt::glyph(&[ring(500.0, 350.0, 128, false), ring(250.0, 150.0, 128, true)])],
|
||||
cmap: &[(0x4F, 0x4F, 1 - 0x4F)], // "O" → glyph 1
|
||||
advance: 1000, // one em wide
|
||||
lsb: 0,
|
||||
metrics: 2, // hmtx matches the two metrics hhea declares
|
||||
fs_type: 0, // any use
|
||||
ink_box: [0, 0, 1000, 700], // the ring's box; the 700-unit cap height is the unit scale
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truetype_text_is_filled_or_outlined() {
|
||||
let Some(font) = system_font() else { return };
|
||||
@@ -298,6 +341,31 @@ fn truetype_text_is_filled_or_outlined() {
|
||||
assert!(l.prims.len() >= 3, "O has two contours, H one");
|
||||
}
|
||||
|
||||
// Regression test for #651: filled TrueType text was triangulated at full outline detail at every
|
||||
// zoom, so a page of small text on screen produced millions of triangles and froze the canvas.
|
||||
#[test]
|
||||
fn small_filled_text_on_screen_is_simplified_but_plots_keep_full_detail() {
|
||||
let d = text_doc(fixture_font(), "OOOO");
|
||||
let tris = |l: &DisplayList| l.prims.iter().filter(|p| p.kind == Kind::Tris).map(|p| l.points(p).len() / 3).sum::<usize>();
|
||||
let plot = build_plot(&d, &Space::Model, &Options::default());
|
||||
let full = tris(&plot);
|
||||
assert!(full > 100, "a plot keeps every point of the 128-point rings: {full} triangles");
|
||||
// One pixel is a tenth of the cap height: the rings are simplified to a few points, the shapes
|
||||
// stay.
|
||||
let reduced = build(&d, &Space::Model, &screen(0.1, None));
|
||||
assert!(tris(&reduced) < full / 2, "{} triangles at 10 px per cap height, {full} in a plot", tris(&reduced));
|
||||
assert!(tris(&reduced) > 0 && reduced.bounds.width() > plot.bounds.width() * 0.9, "{:?} vs {:?}", reduced.bounds, plot.bounds);
|
||||
// An em under two pixels is drawn as the ink's box: two triangles a glyph, same extent.
|
||||
let tiny = build(&d, &Space::Model, &screen(2.0, None));
|
||||
assert_eq!(tris(&tiny), 2 * 4, "one box per glyph");
|
||||
assert!(
|
||||
tiny.bounds.width() > plot.bounds.width() * 0.9 && tiny.bounds.height() > plot.bounds.height() * 0.9,
|
||||
"{:?} vs {:?}",
|
||||
tiny.bounds,
|
||||
plot.bounds
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_font_falls_back_to_stroke() {
|
||||
let d = text_doc("NoSuchFontAnywhere.ttf", "OH");
|
||||
|
||||
@@ -256,6 +256,34 @@ mod tests {
|
||||
assert!(tris.iter().all(|p| (5.0e5..=5.0e5 + 2.0).contains(&p.x) && (-3.0e5..=-3.0e5 + 2.0).contains(&p.y)));
|
||||
}
|
||||
|
||||
// Regression test for #651: the level of detail followed the pixel size, so a page of small
|
||||
// filled text on screen kept a few points a glyph while a plot kept all of them.
|
||||
#[test]
|
||||
fn a_small_on_screen_pixel_simplifies_glyphs_and_a_plot_does_not() {
|
||||
// Text of height 1 has a 700-unit cap height: one font unit is 1/700 of a drawing unit.
|
||||
let xf = Mat3 { a: 1.0 / 700.0, b: 0.0, c: 0.0, d: 1.0 / 700.0, e: 0.0, f: 0.0 };
|
||||
assert!(matches!(detail(xf, 0.0), Detail::Full), "a plot keeps every point");
|
||||
assert!(matches!(detail(xf, 2.0), Detail::Box), "an em under two pixels is the ink's box");
|
||||
assert!(matches!(detail(xf, 0.1), Detail::Reduced(band) if band >= 2), "10 px per cap height simplifies");
|
||||
assert!(matches!(detail(xf, f64::NAN), Detail::Full), "a pixel size that is not a size keeps full detail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_coarse_band_drops_the_points_of_a_flattened_curve() {
|
||||
// A ring of 64 points, the outline a flattened curve gives.
|
||||
let ring: Vec<Vec2> = (0..64u32)
|
||||
.map(|i| {
|
||||
let t = std::f64::consts::TAU * f64::from(i) / 64.0;
|
||||
Vec2::new(500.0 * t.cos(), 350.0 * t.sin())
|
||||
})
|
||||
.collect();
|
||||
let coarse = simplify(&ring, 8.0);
|
||||
assert!(coarse.len() < ring.len() / 2, "{} of {} points kept at 8 font units", coarse.len(), ring.len());
|
||||
assert!(coarse.len() >= 4, "a ring never collapses to a line: {}", coarse.len());
|
||||
let fine = simplify(&ring, 0.01);
|
||||
assert!(fine.len() >= ring.len(), "a fine band keeps every point: {} of {}", fine.len(), ring.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_placed_outline_never_panics() {
|
||||
assert!(triangulate_placed(&[]).is_empty());
|
||||
|
||||
@@ -133,8 +133,8 @@ pub fn entries(app: &CadApp) -> Vec<Vec<Entry>> {
|
||||
}
|
||||
|
||||
/// The edit commands of the selected objects' type (when they are all of one type), with their
|
||||
/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit,
|
||||
/// Polyline Edit, Spline Edit…
|
||||
/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit
|
||||
/// and Generate Boundary for hatches, Polyline Edit, Spline Edit…
|
||||
fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> {
|
||||
let Ok(d) = app.session.doc() else { return Vec::new() };
|
||||
let sel = app.session.selection();
|
||||
@@ -153,7 +153,7 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> {
|
||||
}
|
||||
v
|
||||
}
|
||||
EntityKind::Hatch(_) => vec![("hatchedit", None)],
|
||||
EntityKind::Hatch(_) => vec![("hatchedit", None), ("hatchgenerateboundary", None)],
|
||||
EntityKind::LwPolyline(_) | EntityKind::Polyline3d(_) => vec![("pedit", Some("Polyline Edit"))],
|
||||
EntityKind::Spline(_) => vec![("splinedit", Some("Spline Edit"))],
|
||||
EntityKind::Dimension(_) => vec![("dimtedit", None)],
|
||||
|
||||
@@ -28,6 +28,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) {
|
||||
crate::keys::DIALOG => crate::keys::dialog(app, ctx, &mut open),
|
||||
"about" => about(ctx, &mut open),
|
||||
"preview" => crate::exchange::dialog(app, ctx, &mut open),
|
||||
"pdfimport" => crate::exchange::pdf_dialog(app, ctx, &mut open),
|
||||
"commands" => commands(app, ctx, &mut open),
|
||||
"bedit" => crate::bedit::dialog(app, ctx, &mut open),
|
||||
"authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open),
|
||||
|
||||
@@ -26,6 +26,28 @@ pub fn route(app: &mut CadApp, id: &str) -> Result<Value, String> {
|
||||
"import" | "imp" => app
|
||||
.pick_then(Pick::Open, |app, path| app.run("import", json!({ "path": path })))
|
||||
.unwrap_or_else(|| no_picker(app, "IMPORT", r#"import {"path": "parts.dxf"}"#)),
|
||||
"pdfimport" | "pdfi" => app
|
||||
.pick_then(Pick::Open, |app, path| {
|
||||
let doc = app.session.state().ok().map(|s| s.uid);
|
||||
PDF_PENDING.with(|pending| {
|
||||
*pending.borrow_mut() = Some(PdfImport {
|
||||
doc,
|
||||
path,
|
||||
page: 1,
|
||||
scale: 1.0,
|
||||
at: [0.0, 0.0],
|
||||
password: String::new(),
|
||||
text: true,
|
||||
fills: true,
|
||||
lineweights: true,
|
||||
focus_page: true,
|
||||
error: None,
|
||||
});
|
||||
});
|
||||
app.ui.dialog = Some("pdfimport".into());
|
||||
Ok(Value::Null)
|
||||
})
|
||||
.unwrap_or_else(|| no_picker(app, "PDFIMPORT", r#"pdfimport {"path": "plan.pdf", "page": 1}"#)),
|
||||
"publish" => app
|
||||
.pick_then(Pick::Save(format!("{stem}.pdf")), |app, path| app.run("publish", json!({ "path": path })))
|
||||
.unwrap_or_else(|| no_picker(app, "PUBLISH", "publish {}")),
|
||||
@@ -35,6 +57,102 @@ pub fn route(app: &mut CadApp, id: &str) -> Result<Value, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A chosen PDF and the editable content requested from its page.
|
||||
struct PdfImport {
|
||||
/// The drawing the window was opened for; the page goes there even if another is shown now.
|
||||
doc: Option<u64>,
|
||||
path: String,
|
||||
page: u32,
|
||||
scale: f64,
|
||||
at: [f64; 2],
|
||||
password: String,
|
||||
text: bool,
|
||||
fills: bool,
|
||||
lineweights: bool,
|
||||
focus_page: bool,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static PDF_PENDING: std::cell::RefCell<Option<PdfImport>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Show page and content options before adding the selected PDF page to the drawing.
|
||||
pub fn pdf_dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
|
||||
let Some(mut state) = PDF_PENDING.with(|pending| pending.borrow_mut().take()) else {
|
||||
*open = false;
|
||||
return;
|
||||
};
|
||||
let name = std::path::Path::new(&state.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
let (mut import, mut cancel) = (false, false);
|
||||
egui::Window::new(crate::tl!("Import PDF")).id(egui::Id::unique("cc_pdf_import")).open(open).collapsible(false).resizable(false).show(
|
||||
ctx,
|
||||
|ui| {
|
||||
ui.label(&name);
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(crate::tl!("Page number"));
|
||||
let page = ui.add(egui::DragValue::new(&mut state.page).range(1..=100_000)).labelled_by(label.id);
|
||||
if state.focus_page {
|
||||
page.request_focus();
|
||||
state.focus_page = false;
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(crate::tl!("Scale factor"));
|
||||
ui.add(egui::DragValue::new(&mut state.scale).speed(0.1).range(1e-9..=1e9).clamp_existing_to_range(false)).labelled_by(label.id);
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(crate::tl!("Insertion X"));
|
||||
ui.add(egui::DragValue::new(&mut state.at[0]).speed(1.0).range(-1e9..=1e9).clamp_existing_to_range(false)).labelled_by(label.id);
|
||||
let label = ui.label(crate::tl!("Insertion Y"));
|
||||
ui.add(egui::DragValue::new(&mut state.at[1]).speed(1.0).range(-1e9..=1e9).clamp_existing_to_range(false)).labelled_by(label.id);
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(crate::tl!("Password"));
|
||||
ui.add(egui::TextEdit::singleline(&mut state.password).password(true)).labelled_by(label.id);
|
||||
});
|
||||
ui.checkbox(&mut state.text, crate::tl!("Import text as TEXT"));
|
||||
ui.checkbox(&mut state.fills, crate::tl!("Import filled shapes as solid hatches"));
|
||||
ui.checkbox(&mut state.lineweights, crate::tl!("Use the PDF's line widths"));
|
||||
if let Some(error) = &state.error {
|
||||
let t = crate::theme::Tokens::get();
|
||||
let shown = ui.label(egui::RichText::new(crate::tf!("Import failed: {error}", error = error)).color(t.warn));
|
||||
// Focus stays on the Import button, so the failure is announced.
|
||||
ui.ctx().accesskit_node_builder(shown.id, |node| node.set_live(egui::accesskit::Live::Assertive));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
import = ui.button(crate::tl!("Import Page")).clicked();
|
||||
cancel = ui.button(crate::tl!("Cancel")).clicked();
|
||||
});
|
||||
},
|
||||
);
|
||||
if ctx.input(|input| input.key_pressed(egui::Key::Escape)) {
|
||||
cancel = true;
|
||||
}
|
||||
if import {
|
||||
let mut params = json!({ "path": state.path, "page": state.page, "scale": state.scale, "at": state.at, "text": state.text, "fills": state.fills, "lineweights": state.lineweights });
|
||||
if !state.password.is_empty() {
|
||||
params["password"] = json!(state.password);
|
||||
}
|
||||
let index = state.doc.and_then(|uid| app.session.docs.iter().position(|d| d.uid == uid));
|
||||
let result = match index {
|
||||
None => Err(crate::tl!("The drawing this window was opened for is closed; nothing was imported.").to_string()),
|
||||
Some(i) if i != app.session.active => app.run("document.switch", json!({ "index": i })).and_then(|_| app.run("pdfimport", params)),
|
||||
Some(_) => app.run("pdfimport", params),
|
||||
};
|
||||
match result {
|
||||
Ok(_) => *open = false,
|
||||
Err(error) => state.error = Some(error),
|
||||
}
|
||||
}
|
||||
if cancel {
|
||||
*open = false;
|
||||
}
|
||||
if *open {
|
||||
PDF_PENDING.with(|pending| *pending.borrow_mut() = Some(state));
|
||||
}
|
||||
}
|
||||
|
||||
fn no_picker(app: &mut CadApp, name: &str, example: &str) -> Result<Value, String> {
|
||||
let msg = format!("{name}: there is no file dialog here; run it with parameters, e.g. {example}");
|
||||
app.session.echo(msg.clone());
|
||||
|
||||
@@ -374,6 +374,7 @@
|
||||
From Desde
|
||||
From Template... Desde plantilla...
|
||||
General General
|
||||
Generate Boundary Generar contorno
|
||||
Geometric Center Centro geométrico
|
||||
Geometric Constraint Restricción geométrica
|
||||
Geometric Constraints Restricciones geométricas
|
||||
|
||||
|
@@ -296,6 +296,7 @@
|
||||
Freeze/Thaw in the current viewport 在当前视口中冻结/解冻
|
||||
From 自
|
||||
General 常规
|
||||
Generate Boundary 生成边界
|
||||
Geometric Center 几何中心
|
||||
Geometric Constraint 几何约束
|
||||
Geometric Constraints 几何约束
|
||||
@@ -1033,6 +1034,7 @@
|
||||
Not a number or distance: {text} 不是数字或距离:{text}
|
||||
Plotter Manager... 绘图仪管理器...
|
||||
Import... 导入...
|
||||
Import PDF... 导入 PDF...
|
||||
Export... 导出...
|
||||
Batch Publish... 批量发布...
|
||||
New from Template... 根据样板新建...
|
||||
|
||||
|
@@ -489,7 +489,9 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Re
|
||||
app.ui.start_tab = false;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"export" | "exp" | "import" | "imp" | "publish" | "preview" | "pre" if params.is_null() && app.session.state().is_ok() => {
|
||||
"export" | "exp" | "import" | "imp" | "pdfimport" | "pdfi" | "publish" | "preview" | "pre"
|
||||
if params.is_null() && app.session.state().is_ok() =>
|
||||
{
|
||||
return Some(crate::exchange::route(app, id));
|
||||
}
|
||||
"ui.hidepalettes" => {
|
||||
|
||||
@@ -27,10 +27,12 @@ mod mtext_double_click;
|
||||
mod named_viewports_dialog;
|
||||
mod native_menu_text_keys;
|
||||
mod native_windows;
|
||||
mod offset_clicks;
|
||||
mod options_dialog;
|
||||
mod options_right_click;
|
||||
mod page_setup_paper_units;
|
||||
mod parameters_rename;
|
||||
mod pdf_import_dialog;
|
||||
mod pickdrag;
|
||||
mod press_first_clicks;
|
||||
mod properties_described;
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! OFFSET on the canvas: the distance can be clicked, and picking the source is not moved by the
|
||||
//! grid snap (#618).
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
|
||||
fn harness() -> Harness<'static, CadApp> {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec2::new(0.0, 2.0).to3(0.0), b: Vec2::new(10.0, 2.0).to3(0.0) })).unwrap();
|
||||
let mut session = Session::empty();
|
||||
session.open_drawing(d, "Offset clicks", None);
|
||||
session.execute("view.set", &json!({"center":[5,5],"height":20})).unwrap();
|
||||
session.settings.osmode = 0;
|
||||
session.settings.snapmode = true;
|
||||
session.execute("setvar", &json!({"name":"SNAPUNIT","value":[5,5]})).unwrap();
|
||||
session.settings.orthomode = false;
|
||||
let mut app = CadApp::new(session, Services::default());
|
||||
app.canvas.zoom_pending = false;
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, CadApp>, world: Vec2) {
|
||||
let pos: Pos2 = h.state().canvas.xf.unwrap().to_screen(world);
|
||||
h.event(Event::PointerMoved(pos));
|
||||
h.run_steps(2);
|
||||
for pressed in [true, false] {
|
||||
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for #618: OFFSET's distance could not be clicked, and with grid snap on a click
|
||||
// meant to pick the source object was moved to the nearest grid point, missing the object.
|
||||
#[test]
|
||||
fn offset_takes_a_clicked_distance_and_picks_its_source_under_grid_snap() {
|
||||
let mut h = harness();
|
||||
h.state_mut().start("offset");
|
||||
h.run_steps(2);
|
||||
// Two clicks, snapped to the grid points (5, 5) and (10, 5): a distance of 5.
|
||||
click(&mut h, Vec2::new(5.1, 4.9));
|
||||
assert!(h.state().session.prompt_text().contains("second point"), "{}", h.state().session.prompt_text());
|
||||
click(&mut h, Vec2::new(9.9, 5.1));
|
||||
assert_eq!(h.state().session.doc().unwrap().header.f64("OFFSETDIST", -1.0), 5.0);
|
||||
assert!(h.state().session.prompt_text().contains("Select object"), "{}", h.state().session.prompt_text());
|
||||
// The source line is at y = 2, two units from the grid point (5, 0) the click would snap to.
|
||||
click(&mut h, Vec2::new(7.0, 2.04));
|
||||
let prompt = h.state().session.prompt_text();
|
||||
assert!(prompt.contains("side to offset"), "the line was not picked: {prompt}");
|
||||
// A side click above the line (snapped to (5, 5)) makes the copy 5 units up, at y = 7.
|
||||
click(&mut h, Vec2::new(7.0, 7.0));
|
||||
let lines: Vec<(f64, f64)> = h
|
||||
.state()
|
||||
.session
|
||||
.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::Line(line) => Some((line.a.y, line.b.y)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(lines.len(), 2, "OFFSET added no line: {lines:?}");
|
||||
assert!(lines.iter().any(|&(a, b)| (a - 7.0).abs() < 1e-9 && (b - 7.0).abs() < 1e-9), "no copy at y = 7: {lines:?}");
|
||||
// OFFSET asks for the next object; Enter ends it.
|
||||
assert!(h.state().session.prompt_text().contains("Select object to offset"), "{}", h.state().session.prompt_text());
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.prompt_text(), "Command:", "Enter ends OFFSET");
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//! PDF import exposes named placement controls and gives the page field initial keyboard focus.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::exchange::set_pdf_import;
|
||||
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
|
||||
use cadcraft_engine::geom::Vec3;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use egui::accesskit::{Action, ActionData, ActionRequest, Live, Role};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
static NEXT_FILE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
fn read_pdf(_: &[u8], options: &serde_json::Value) -> Result<(Drawing, usize), String> {
|
||||
if options["page"].as_u64() != Some(2) {
|
||||
return Err("expected page 2".into());
|
||||
}
|
||||
let mut drawing = Drawing::new_metric();
|
||||
drawing
|
||||
.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) }))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok((drawing, 4))
|
||||
}
|
||||
|
||||
fn harness(path: String) -> Harness<'static, CadApp> {
|
||||
let services = Services { pick_open: Some(Box::new(move || Some(path.clone()))), ..Services::default() };
|
||||
let mut app = CadApp::new(Session::new(), services);
|
||||
app.start("pdfimport");
|
||||
Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(&ui.ctx().clone());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
)
|
||||
}
|
||||
|
||||
fn set_number(h: &mut Harness<'_, CadApp>, name: &str, value: f64) {
|
||||
let (target_node, target_tree) = h.get_by_role_and_label(Role::SpinButton, name).accesskit_node().locate();
|
||||
h.event(egui::Event::AccessKitActionRequest(ActionRequest {
|
||||
action: Action::SetValue,
|
||||
target_node,
|
||||
target_tree,
|
||||
data: Some(ActionData::NumericValue(value)),
|
||||
}));
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn pdf_path() -> (std::path::PathBuf, String) {
|
||||
let name = format!("cadcraft-import-{}-{}.pdf", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed));
|
||||
let path = std::env::temp_dir().join(name);
|
||||
std::fs::write(&path, b"%PDF-1.7\nsynthetic\n").unwrap();
|
||||
(path.clone(), path.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_focus_placement_acceptance_and_escape_cancellation_work() {
|
||||
set_pdf_import(read_pdf);
|
||||
let (path, name) = pdf_path();
|
||||
let mut h = harness(name.clone());
|
||||
h.run_steps(3);
|
||||
assert!(h.get_by_role_and_label(Role::SpinButton, "Page number").is_focused());
|
||||
for label in ["Page number", "Scale factor", "Insertion X", "Insertion Y"] {
|
||||
h.get_by_role_and_label(Role::SpinButton, label);
|
||||
}
|
||||
h.get_by_role_and_label(Role::PasswordInput, "Password");
|
||||
for label in ["Import text as TEXT", "Import filled shapes as solid hatches", "Use the PDF's line widths"] {
|
||||
h.get_by_role_and_label(Role::CheckBox, label);
|
||||
}
|
||||
h.get_by_role_and_label(Role::Button, "Import Page");
|
||||
h.get_by_role_and_label(Role::Button, "Cancel");
|
||||
|
||||
// The reader refuses page 1: the window stays open and announces the failure.
|
||||
h.get_by_role_and_label(Role::Button, "Import Page").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().ui.dialog.is_some(), "a failed import keeps the options window open");
|
||||
assert_eq!(h.get_by_label_contains("Import failed").accesskit_node().live(), Live::Assertive);
|
||||
|
||||
set_number(&mut h, "Page number", 2.0);
|
||||
set_number(&mut h, "Scale factor", 2.0);
|
||||
set_number(&mut h, "Insertion X", 10.0);
|
||||
set_number(&mut h, "Insertion Y", 20.0);
|
||||
h.get_by_role_and_label(Role::Button, "Import Page").click();
|
||||
h.run_steps(3);
|
||||
let drawing = h.state().session.doc().unwrap();
|
||||
let Some(entity) = drawing.model.iter().next() else { panic!("the page was imported") };
|
||||
let EntityKind::Line(line) = &entity.kind else { panic!("the line remains editable geometry") };
|
||||
assert_eq!(line.a, Vec3::new(10.0, 20.0, 0.0));
|
||||
assert_eq!(line.b, Vec3::new(30.0, 20.0, 0.0));
|
||||
assert!(h.state().ui.dialog.is_none(), "successful import closes the options window");
|
||||
|
||||
let mut cancelled = harness(name);
|
||||
cancelled.run_steps(3);
|
||||
cancelled.key_press(egui::Key::Escape);
|
||||
cancelled.run_steps(3);
|
||||
assert!(cancelled.state().ui.dialog.is_none(), "Escape closes the PDF options window");
|
||||
assert!(cancelled.state().session.doc().unwrap().model.is_empty(), "cancelling leaves the drawing unchanged");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_goes_to_the_drawing_the_window_was_opened_for() {
|
||||
set_pdf_import(read_pdf);
|
||||
let (path, name) = pdf_path();
|
||||
let mut h = harness(name);
|
||||
h.run_steps(3);
|
||||
// Another drawing is made active while the window is still open.
|
||||
h.state_mut().run("new", serde_json::json!({ "template": "." })).unwrap();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.active, 1);
|
||||
set_number(&mut h, "Page number", 2.0);
|
||||
h.get_by_role_and_label(Role::Button, "Import Page").click();
|
||||
h.run_steps(3);
|
||||
let docs = &h.state().session.docs;
|
||||
assert!(!docs[0].doc.model.is_empty(), "the page went into the drawing that asked for it");
|
||||
assert!(docs[1].doc.model.is_empty(), "the drawing shown meanwhile is unchanged");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
# Import a PDF as editable CAD geometry
|
||||
|
||||
Choose **File > Import PDF...**, select the PDF, then choose a page and import options.
|
||||
The selected page becomes editable objects in the current drawing. Use **File > Save As...**
|
||||
to save the result as DXF or DWG. The source PDF is not changed.
|
||||
|
||||
The command is `PDFIMPORT` (alias `PDFI`). It is also available to the CLI and automation:
|
||||
|
||||
```text
|
||||
pdfimport {"path":"plan.pdf","page":2,"scale":50}
|
||||
```
|
||||
|
||||
Page numbers start at 1. The scale multiplies the printed page size. For a drawing printed
|
||||
at 1:50, use 50 to restore model size, then check a known dimension. The import converts
|
||||
PDF points to the current drawing's units. A page containing viewports at different scales
|
||||
needs separate calibration for each viewport. An `at` point sets the insertion offset.
|
||||
|
||||
Automation can pass base64 `data` with `name: "plan.pdf"` instead of a file path. The JSON
|
||||
options include `page`, `password`, `at`, `scale`, `text`, `fills`, and `lineweights`.
|
||||
File access still follows the CLI/MCP automation roots.
|
||||
|
||||
To convert the first page into a new drawing from a terminal:
|
||||
|
||||
```sh
|
||||
cadcraft-cli convert plan.pdf plan.dxf
|
||||
cadcraft-cli convert plan.pdf plan.dwg
|
||||
```
|
||||
|
||||
For another page, create a drawing, run `pdfimport` with its page number, then export it.
|
||||
The same reader handles PDFs opened as new drawings. Save the drawing under a DXF or DWG
|
||||
name to keep the editable objects.
|
||||
|
||||
## What is converted
|
||||
|
||||
- Stroked paths become lines and polylines. Recognized circular curves retain arc segments;
|
||||
other curves become short line segments.
|
||||
- Solid fills become hatches. PDF fill rules determine holes and overlapping contours.
|
||||
A nonzero-rule fill whose contours overlap or nest in the same direction is split into
|
||||
triangles so the filled area matches the PDF. That hatch has one boundary loop per
|
||||
triangle and its curved edges become short straight segments.
|
||||
- Recoverable text becomes editable text with the drawing's Standard text style. Its font
|
||||
appearance can differ from the PDF. Text already converted to outlines remains geometry.
|
||||
- Colours and lineweights are mapped to CAD properties. Objects are grouped into
|
||||
`PDF_Geometry`, `PDF_Solid Fills`, and `PDF_Text`, rather than original CAD layers.
|
||||
- Page rotation, crop origin and PDF user units are applied. Rectangular clipping is applied.
|
||||
|
||||
The import reports omissions and approximations in its result and command history.
|
||||
Scanned images are not traced and OCR is not provided. Raster images, unsupported fonts,
|
||||
gradient and pattern paints, and white background fills can be omitted. Nonrectangular
|
||||
clips, transparency, blend modes, dash patterns and some curves crossing clips can differ
|
||||
from the PDF. Check the imported drawing against the source before using its dimensions.
|
||||
|
||||
A PDF is a plotted page. It does not normally contain the original blocks, constraints,
|
||||
associative dimensions, unprinted entities or 3D model. Those cannot be restored by import.
|
||||
|
||||
## Implementation and provenance
|
||||
|
||||
The application maps the shared `craft-pdf` interpreter output into `cadcraft-doc` entities.
|
||||
The engine command is independent of the GUI and imports a page as one undoable action.
|
||||
Input bytes, pages, entities, vertices and text are bounded. A truncated interpreter result
|
||||
fails the import rather than claiming a complete conversion.
|
||||
|
||||
This adapts the existing CADCraft work in [PR #2787](https://github.com/storytold/cadcraft/pull/2787),
|
||||
commit `ec17f63f189d1dccf91357701f9bba243ca88dd5`. Attribution and dependency asset notices
|
||||
are recorded in `ATTRIBUTION.md` and `NOTICE`.
|
||||
Reference in New Issue
Block a user