diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index cabf50d94..cf177e6bd 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -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 | diff --git a/Cargo.lock b/Cargo.lock index 799501df0..5ec7f622f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index b330e260a..dc061e78a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/NOTICE b/NOTICE index f3ecf5fc1..b920e5e3e 100644 --- a/NOTICE +++ b/NOTICE @@ -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. diff --git a/ROADMAP.md b/ROADMAP.md index e30b0d73f..7ee8ccb61 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -187,3 +187,7 @@ REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the D ## Shared UI workspace integration Tool Sets, Layers and Properties use shared docking with persisted layouts, keyboard focus and compact toolbar overflow. No milestone percentage change. + +## PDF vector import + +PDFIMPORT and File > Import PDF... convert a selected PDF page into editable geometry, fills and text. The CLI converts PDF pages to DXF/DWG. Import reports skipped or approximated content; PDF underlays and scanned-page tracing remain unavailable. See [the import guide](docs/pdf-import.md). diff --git a/apps/cadcraft-cli/src/args.rs b/apps/cadcraft-cli/src/args.rs index c8daf8d14..5b5b9ef0e 100644 --- a/apps/cadcraft-cli/src/args.rs +++ b/apps/cadcraft-cli/src/args.rs @@ -26,12 +26,12 @@ fn with_formats(cell: &'static std::sync::OnceLock, before: &str, list: /// The drawing an input argument names. fn read_help() -> &'static str { static C: std::sync::OnceLock = 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 = 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 { diff --git a/apps/cadcraft-cli/src/lib.rs b/apps/cadcraft-cli/src/lib.rs index dde0be127..f7182330a 100644 --- a/apps/cadcraft-cli/src/lib.rs +++ b/apps/cadcraft-cli/src/lib.rs @@ -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, diff --git a/apps/cadcraft-cli/tests/it/main.rs b/apps/cadcraft-cli/tests/it/main.rs index adb3f3749..6c282f006 100644 --- a/apps/cadcraft-cli/tests/it/main.rs +++ b/apps/cadcraft-cli/tests/it/main.rs @@ -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; diff --git a/apps/cadcraft-cli/tests/it/pdf_import.rs b/apps/cadcraft-cli/tests/it/pdf_import.rs new file mode 100644 index 000000000..33aeb1cbd --- /dev/null +++ b/apps/cadcraft-cli/tests/it/pdf_import.rs @@ -0,0 +1,111 @@ +//! 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 { + 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"); + } +} diff --git a/apps/cadcraft-web/src/main.rs b/apps/cadcraft-web/src/main.rs index 7a6a372f1..1e5594c73 100644 --- a/apps/cadcraft-web/src/main.rs +++ b/apps/cadcraft-web/src/main.rs @@ -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, diff --git a/apps/cadcraft-web/src/upload.rs b/apps/cadcraft-web/src/upload.rs index 333c4906b..a2f4f3b6a 100644 --- a/apps/cadcraft-web/src/upload.rs +++ b/apps/cadcraft-web/src/upload.rs @@ -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; diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 442523ad3..2206161ed 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -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(), diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 6600b418a..e3107bd62 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -14,7 +14,7 @@ mod draw; mod draw2; mod draworder; mod edit; -mod exchange; +pub mod exchange; pub mod file; mod gripcmds; mod griphot; diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index 53adfbd5a..dd8512386 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -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::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 { // ---------- IMPORT ---------- -fn run_import(s: &mut Session, p: &Value) -> Result { - 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 = 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> { + 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, 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 { + 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 { + 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 { + 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())) } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 47acb3a08..25914fd4d 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -373,11 +373,16 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result { /// 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) -> Result { - 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. diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index 7b26f14f8..acbe0f36f 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -41,6 +41,7 @@ pub const FILES: &[&str] = &[ "options", "pagesetup", "pdfbook", + "pdfimport", "plot", "plotstyle", "plottermanager", diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 593f5e0cf..a7d47e208 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -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" diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 4f698d662..4dba955e4 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -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; diff --git a/crates/io/src/pdf_read.rs b/crates/io/src/pdf_read.rs new file mode 100644 index 000000000..b6f5e685a --- /dev/null +++ b/crates/io/src/pdf_read.rs @@ -0,0 +1,1004 @@ +//! PDF → Drawing (PDFIMPORT): the vector content of one page as editable objects. +//! +//! Stroked paths become `LINE`s and `LWPOLYLINE`s (a curve that is a circular arc becomes a bulge +//! vertex, any other curve is flattened into short segments), filled paths become solid `HATCH`es +//! and text becomes `TEXT`: the glyphs of one baseline are joined into a single string and fitted +//! to the width the PDF gave them. Each kind goes to its own layer (`PDF_Geometry`, +//! `PDF_Solid Fills`, `PDF_Text`) with the colour and line width the PDF used, in millimetres with +//! the page's lower-left corner at the origin. +//! +//! Any PDF is read; a drawing plotted from a CAD program imports best, since that is what the +//! mapping above is made for. +//! +//! Not imported (each is named in a read note, so it is never left out silently): raster images, +//! Type 3 glyphs and glyphs without a Unicode value, gradient and pattern fills, and white or +//! near-white fills (they only hide what lies under them on paper). A rectangular clip (the usual +//! page, viewport and frame clip) cuts the lines and filled shapes it crosses and drops what lies +//! outside it, and text whose glyphs' middles lie outside it; other clip shapes, transparency and +//! dash patterns are not applied, and a read note says how often. +//! +//! Adapted from CADCraft PR #2787, commit ec17f63f189d1dccf91357701f9bba243ca88dd5 +//! (MIT OR Apache-2.0). PDF interpretation stays in craft-pdf; this module maps it to CAD entities. + +use std::collections::BTreeMap; +use std::sync::{ + Arc, + atomic::{AtomicU8, Ordering}, +}; + +use cadcraft_color::{Color, Rgb}; +use cadcraft_doc::{Common, Drawing, EntityKind, HAlign, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Space, Text}; +use cadcraft_geom::{PolyVertex, Polyline, Vec2, Vec3}; +use craft_pdf::interpret::hayro_cmap::BfString; +use craft_pdf::interpret::{ + BlendMode, ClipPath, Context, Device, FillRule, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, InterpreterWarning, Paint, + PathDrawMode, RectExt, SoftMask, TransformExt, font::Glyph, +}; +use kurbo::{Affine, BezPath, PathEl, Point, Rect}; + +use crate::{IoError, Result}; + +mod fill; + +/// Objects one import creates. +const MAX_ENTITIES: usize = 1_000_000; +/// Vertices kept across the whole import, so a page of curves cannot grow without bound. +const MAX_TOTAL_VERTS: usize = 8_000_000; +/// Vertices in one polyline. +const MAX_POLY_VERTS: usize = 100_001; +/// Glyphs read from one page. +const MAX_GLYPHS: usize = 2_000_000; +/// Characters one glyph may stand for (a ToUnicode entry may map a code to a string of any length). +const MAX_GLYPH_CHARS: usize = 32; +/// Characters of text read from one page. +const MAX_TEXT_CHARS: usize = 4_000_000; +/// A page is refused when its sides, in points, are not between these. +const MAX_PAGE_PT: f64 = 200_000.0; +/// Bound the input before the parser copies it and the page tree before interpretation. +const MAX_INPUT_BYTES: usize = 64 << 20; +const MAX_PAGES: usize = 1000; +/// Millimetres in a PDF point (1/72 inch). +pub const MM_PER_PT: f64 = 25.4 / 72.0; +/// How far a flattened curve may leave the real one, in points. +const FLATTEN_TOL_PT: f64 = 0.02; +/// Cap height of a typical text face, as a fraction of its em square. +const CAP_HEIGHT: f64 = 0.72; +/// A path with a point further than this from the origin, in drawing units, is left out: no real +/// page reaches it, and the numbers past it overflow into infinity. +const MAX_COORD: f64 = 1.0e9; +/// A curve is flattened to no finer than its size over this, so one huge curve cannot grow into +/// millions of segments (about 500 at most). +const CURVE_RESOLUTION: f64 = 250_000.0; + +const LAYER_GEOMETRY: &str = "PDF_Geometry"; +const LAYER_FILLS: &str = "PDF_Solid Fills"; +const LAYER_TEXT: &str = "PDF_Text"; + +/// What PDFIMPORT reads and how it places it. +#[derive(Clone, Debug)] +pub struct PdfImportOptions { + /// The page to import, counted from 1. + pub page: usize, + /// The password of an encrypted file. + pub password: Option, + /// Drawing units per PDF point (millimetres by default). + pub unit: f64, + /// Import text as `TEXT` (else it is left out). + pub text: bool, + /// Import filled shapes as solid hatches. + pub fills: bool, + /// Give strokes the line width the PDF drew them with. + pub lineweights: bool, +} + +impl Default for PdfImportOptions { + fn default() -> Self { + PdfImportOptions { page: 1, password: None, unit: MM_PER_PT, text: true, fills: true, lineweights: true } + } +} + +/// Read one page of a PDF. Returns the drawing and the number of pages in the file. +pub fn read(bytes: &[u8], o: &PdfImportOptions) -> Result<(Drawing, usize)> { + read_within(bytes, o, MAX_TOTAL_VERTS) +} + +/// [`read`] with the page's vertex budget given (the tests use a small one). +fn read_within(bytes: &[u8], o: &PdfImportOptions, verts: usize) -> Result<(Drawing, usize)> { + if !o.unit.is_finite() || o.unit <= 0.0 { + return Err(IoError::Format("PDF: the unit must be a positive number".into())); + } + let options = craft_pdf::OpenOptions { max_input_bytes: MAX_INPUT_BYTES, ..Default::default() }; + let pdf = craft_pdf::open_slice_with_options(bytes, o.password.as_deref(), &options).map_err(|e| IoError::Format(format!("PDF: {e}")))?; + let pages = pdf.pages(); + let count = pages.len(); + if count > MAX_PAGES { + return Err(IoError::Format(format!("PDF: more than {MAX_PAGES} pages"))); + } + let page = o.page.checked_sub(1).and_then(|i| pages.get(i)).ok_or_else(|| { + IoError::Format(format!("PDF: page {} doesn't exist; the file has {count} page{}", o.page, if count == 1 { "" } else { "s" })) + })?; + let (w, h) = page.render_dimensions(); + let (w, h) = (f64::from(w), f64::from(h)); + if !(w.is_finite() && h.is_finite() && (1.0..=MAX_PAGE_PT).contains(&w) && (1.0..=MAX_PAGE_PT).contains(&h)) { + return Err(IoError::Format(format!("PDF: page size {w} × {h} points is not usable"))); + } + let cache = InterpreterCache::new(); + let warnings = Arc::new(AtomicU8::new(0)); + let sink = warnings.clone(); + let settings = InterpreterSettings { + warning_sink: Arc::new(move |warning| { + let flag = match warning { + InterpreterWarning::UnsupportedFont => 1, + InterpreterWarning::ImageDecodeFailure => 2, + InterpreterWarning::ContentTruncated => 4, + }; + sink.fetch_or(flag, Ordering::Relaxed); + }), + ..Default::default() + }; + let mut context = Context::new(page.initial_transform(false).to_kurbo(), page.intersected_crop_box().to_kurbo(), &cache, page.xref(), settings); + let mut dev = Collector::new(o); + // The page boundary clips content even if its stream has no explicit clipping operator. + dev.clips.push(Some(Rect::new(0.0, 0.0, w, h))); + dev.verts_left = verts; + craft_pdf::interpret_page(page, &mut context, &mut dev).map_err(|e| IoError::Format(format!("PDF: {e}")))?; + dev.flush_text(); + if let Some(e) = dev.failure.take() { + return Err(IoError::Format(e)); + } + let warnings = warnings.load(Ordering::Relaxed); + if warnings & 4 != 0 { + return Err(IoError::Format("PDF: page content exceeds the interpreter limits; import cancelled".into())); + } + if warnings & 1 != 0 { + dev.left_out(LeftOut::UnsupportedFont); + } + if warnings & 2 != 0 { + dev.left_out(LeftOut::Image); + } + if dev.glyphs > 0 { + dev.approximated("text runs using the drawing's Standard font"); + } + let notes = dev.note(); + dev.drawing.read_notes.extend(notes); + Ok((dev.drawing, count)) +} + +/// [`read`] with options as JSON, the form the engine's PDFIMPORT passes: +/// `{page?, password?, unit?, text?, fills?, lineweights?}`. A value of the wrong type is an error. +pub fn read_json(bytes: &[u8], opts: &serde_json::Value) -> Result<(Drawing, usize)> { + let mut o = PdfImportOptions::default(); + let bad = |key: &str, want: &str| IoError::Format(format!("PDF: `{key}` must be {want}")); + if let Some(v) = opts.get("page") { + o.page = v.as_u64().and_then(|n| usize::try_from(n).ok()).filter(|n| *n >= 1).ok_or_else(|| bad("page", "a page number from 1"))?; + } + if let Some(v) = opts.get("password") { + o.password = Some(v.as_str().ok_or_else(|| bad("password", "text"))?.to_string()); + } + if let Some(v) = opts.get("unit") { + o.unit = v.as_f64().filter(|u| u.is_finite() && *u > 0.0).ok_or_else(|| bad("unit", "a positive number"))?; + } + for (key, slot) in [("text", &mut o.text), ("fills", &mut o.fills), ("lineweights", &mut o.lineweights)] { + if let Some(v) = opts.get(key) { + *slot = v.as_bool().ok_or_else(|| bad(key, "true or false"))?; + } + } + read(bytes, &o) +} + +/// Drawn content that isn't imported, named in the drawing's read note. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum LeftOut { + Image, + Type3, + NoUnicode, + UnsupportedFont, + PatternFill, + WhiteFill, + OutOfRange, +} + +impl LeftOut { + fn describe(self, n: usize) -> String { + let (one, many) = match self { + Self::Image => ("raster image", "raster images"), + Self::Type3 => ("Type 3 glyph", "Type 3 glyphs"), + Self::NoUnicode => ("glyph without a Unicode value", "glyphs without a Unicode value"), + Self::UnsupportedFont => ("unsupported font", "unsupported fonts"), + Self::PatternFill => ("gradient or pattern fill", "gradient or pattern fills"), + Self::WhiteFill => ("white or near-white fill", "white or near-white fills"), + Self::OutOfRange => ("path with out-of-range coordinates", "paths with out-of-range coordinates"), + }; + format!("{n} {}", if n == 1 { one } else { many }) + } +} + +/// The glyphs of one baseline gathered so far. +struct Run { + start: Vec2, + /// Unit vector along the baseline. + dir: Vec2, + em: f64, + color: Color, + text: String, + glyphs: usize, + /// Where the last glyph's advance ends, when the font said. + end: Option, + last: Vec2, +} + +struct Collector { + drawing: Drawing, + opts: PdfImportOptions, + entities: usize, + verts_left: usize, + glyphs: usize, + /// Characters of text the page may still add. + text_left: usize, + run: Option, + /// The text last added: where it starts, its string and its size, so the same text drawn again + /// at the same place (a fill and then its stroke, render mode 2) is not added twice. + last_text: Option<(Vec2, String, f64)>, + left_out: BTreeMap, + failure: Option, + /// The clips in force, outermost first: a rectangle in page points, or `None` for another shape. + clips: Vec>, + /// What was drawn only approximately, by description. + approx: BTreeMap<&'static str, usize>, +} + +fn v3(p: Vec2) -> Vec3 { + Vec3::new(p.x, p.y, 0.0) +} + +fn pt(p: Point) -> Vec2 { + Vec2::new(p.x, p.y) +} + +/// A PDF colour as a drawing colour; black and white (which a sheet of paper and a drawing screen +/// swap) become the automatic colour 7. +fn color_of(paint: &Paint<'_>) -> Option { + let Paint::Color(c) = paint else { return None }; + let [r, g, b, a] = c.to_rgba().to_rgba8(); + if a == 0 { + return None; + } + Some(match (r, g, b) { + (0, 0, 0) | (255, 255, 255) => Color::Index(7), + _ => Color::True(Rgb(r, g, b)), + }) +} + +/// A fill this light (each of red, green and blue at least this, out of 255) counts as white: table +/// shading such as 245, 245, 245 is barely visible on paper, but as a solid hatch on a dark screen +/// it hides the text drawn over it (which turns white there). +const NEAR_WHITE: u8 = 240; + +fn is_white(paint: &Paint<'_>) -> bool { + matches!(paint, Paint::Color(c) if { let [r, g, b, a] = c.to_rgba().to_rgba8(); a > 0 && r.min(g).min(b) >= NEAR_WHITE }) +} + +/// The nearest standard lineweight to a width in millimetres. +fn lineweight(mm: f64) -> Lineweight { + let hundredths = (mm * 100.0).clamp(0.0, 211.0); + let nearest = + Lineweight::STANDARD.iter().copied().min_by(|a, b| (f64::from(*a) - hundredths).abs().total_cmp(&(f64::from(*b) - hundredths).abs())); + Lineweight::Mm100(nearest.unwrap_or(0)) +} + +impl Collector { + fn new(o: &PdfImportOptions) -> Self { + Collector { + drawing: Drawing::new_metric(), + opts: o.clone(), + entities: 0, + verts_left: MAX_TOTAL_VERTS, + glyphs: 0, + text_left: MAX_TEXT_CHARS, + run: None, + last_text: None, + left_out: BTreeMap::new(), + failure: None, + clips: Vec::new(), + approx: BTreeMap::new(), + } + } + + fn approximated(&mut self, what: &'static str) { + *self.approx.entry(what).or_default() += 1; + } + + /// The intersection of the rectangular clips in force, as corners in drawing units. + fn clip(&self) -> Option<(Vec2, Vec2)> { + let r = self.clips.iter().flatten().copied().reduce(|a, b| a.intersect(b))?; + let u = self.opts.unit; + Some((Vec2::new(r.x0 * u, r.y0 * u), Vec2::new(r.x1 * u, r.y1 * u))) + } + + fn add_poly(&mut self, verts: Vec, closed: bool, color: Color, weight: Lineweight) { + let n = verts.len(); + let straight = verts.iter().all(|v| v.bulge == 0.0); + let kind = if n == 2 && !closed && straight { + EntityKind::Line(Line { a: v3(verts[0].p), b: v3(verts[1].p) }) + } else { + EntityKind::LwPolyline(LwPolyline { vertices: verts, closed, const_width: 0.0, elevation: 0.0, plinegen: false }) + }; + self.add(LAYER_GEOMETRY, color, weight, kind, n); + } + + fn left_out(&mut self, kind: LeftOut) { + *self.left_out.entry(kind).or_default() += 1; + } + + fn note(&self) -> Vec { + let mut notes = Vec::new(); + if !self.left_out.is_empty() { + let list: Vec = self.left_out.iter().map(|(k, n)| k.describe(*n)).collect(); + notes.push(format!("PDF: CADCraft doesn't import these, so they were left out: {}", list.join(", "))); + } + if !self.approx.is_empty() { + let list: Vec = self.approx.iter().map(|(what, n)| format!("{n} {what}")).collect(); + notes.push(format!("PDF: drawn only approximately: {}", list.join(", "))); + } + notes + } + + fn fail(&mut self, why: &str) { + self.failure.get_or_insert_with(|| format!("PDF: {why}")); + } + + fn add(&mut self, layer: &str, color: Color, lineweight: Lineweight, kind: EntityKind, verts: usize) { + if self.failure.is_some() { + return; + } + self.entities += 1; + if self.entities > MAX_ENTITIES { + return self.fail(&format!("more than {MAX_ENTITIES} objects on the page")); + } + let Some(left) = self.verts_left.checked_sub(verts) else { return self.fail("too much geometry on the page") }; + self.verts_left = left; + let common = Common { layer: layer.into(), color, lineweight, ..Common::default() }; + if self.drawing.add(&Space::Model, common, kind).is_err() { + self.fail("the drawing refused an object"); + } + } + + /// The path's subpaths in drawing units: vertices (curves flattened or kept as bulges) and + /// whether each is closed. + fn subpaths(&mut self, path: &BezPath, to_page: Affine) -> Vec<(Vec, bool)> { + let m = Affine::scale(self.opts.unit) * to_page; + if !path_in_range(path, m) { + self.left_out(LeftOut::OutOfRange); + return Vec::new(); + } + let tol = FLATTEN_TOL_PT * self.opts.unit; + let mut out: Vec<(Vec, bool)> = Vec::new(); + let mut cur: Vec = Vec::new(); + let mut start = Vec2::ZERO; + // The vertices in `out` so far: with those in `cur` they are held against what is left of + // the page's budget here, before the objects are added, so that one path of many curves + // can't build more than the page may hold. + let mut kept = 0usize; + let finish = |cur: &mut Vec, closed: bool, out: &mut Vec<(Vec, bool)>, kept: &mut usize| { + let mut v = std::mem::take(cur); + if closed && v.len() > 1 && v.first().zip(v.last()).is_some_and(|(a, b)| (a.p - b.p).len() < 1e-9) { + v.pop(); + } + if v.len() >= 2 { + *kept = kept.saturating_add(v.len()); + out.push((v, closed)); + } + }; + for el in path.elements() { + if cur.len() > MAX_POLY_VERTS { + self.fail("one path has too many vertices"); + return Vec::new(); + } + if kept.saturating_add(cur.len()) > self.verts_left { + self.fail("too much geometry on the page"); + return Vec::new(); + } + match *el { + PathEl::MoveTo(p) => { + finish(&mut cur, false, &mut out, &mut kept); + start = pt(m * p); + cur.push(PolyVertex::new(start)); + } + PathEl::LineTo(p) => { + // After a close the current point is where the subpath started. + if cur.is_empty() { + cur.push(PolyVertex::new(start)); + } + cur.push(PolyVertex::new(pt(m * p))); + } + PathEl::QuadTo(c, p) => { + if cur.is_empty() { + cur.push(PolyVertex::new(start)); + } + let p0 = cur.last().map_or(start, |v| v.p); + let q = pt(m * c); + let p3 = pt(m * p); + let c1 = p0 + (q - p0) * (2.0 / 3.0); + let c2 = p3 + (q - p3) * (2.0 / 3.0); + curve(&mut cur, [p0, c1, c2, p3], tol); + } + PathEl::CurveTo(a, b, p) => { + if cur.is_empty() { + cur.push(PolyVertex::new(start)); + } + let p0 = cur.last().map_or(start, |v| v.p); + curve(&mut cur, [p0, pt(m * a), pt(m * b), pt(m * p)], tol); + } + PathEl::ClosePath => { + finish(&mut cur, true, &mut out, &mut kept); + // A path may go on from the point it closed to. + } + } + } + if cur.len() > MAX_POLY_VERTS { + self.fail("one path has too many vertices"); + return Vec::new(); + } + if kept.saturating_add(cur.len()) > self.verts_left { + self.fail("too much geometry on the page"); + return Vec::new(); + } + finish(&mut cur, false, &mut out, &mut kept); + out + } + + fn stroke(&mut self, path: &BezPath, to_page: Affine, paint: &Paint<'_>, width: f32) { + let Some(color) = color_of(paint) else { return }; + let det = to_page.determinant().abs().sqrt(); + let mm = f64::from(width) * det * MM_PER_PT; + let weight = if self.opts.lineweights { lineweight(mm) } else { Lineweight::ByLayer }; + if translucent(paint) { + self.approximated("translucent objects drawn opaque"); + } + let clip = self.clip(); + for (verts, closed) in self.subpaths(path, to_page) { + let Some((lo, hi)) = clip else { + self.add_poly(verts, closed, color, weight); + continue; + }; + match relation(&verts, closed, lo, hi) { + Relation::Inside => self.add_poly(verts, closed, color, weight), + Relation::Outside => {} + Relation::Crossing if verts.iter().all(|v| v.bulge == 0.0) => { + for run in clipped_runs(&verts, closed, lo, hi) { + self.add_poly(run, false, color, weight); + } + } + Relation::Crossing => { + self.approximated("curved lines crossing a clip kept whole"); + self.add_poly(verts, closed, color, weight); + } + } + } + } + + fn fill(&mut self, path: &BezPath, to_page: Affine, paint: &Paint<'_>, rule: &FillRule) { + if !self.opts.fills { + return; + } + if is_white(paint) { + return self.left_out(LeftOut::WhiteFill); + } + let Some(color) = color_of(paint) else { + if matches!(paint, Paint::Pattern(_)) { + self.left_out(LeftOut::PatternFill); + } + return; + }; + if translucent(paint) { + self.approximated("translucent objects drawn opaque"); + } + let clip = self.clip(); + let mut kept_whole = false; + let loops: Vec = self + .subpaths(path, to_page) + .into_iter() + .filter(|(v, _)| v.len() >= 3) + .filter_map(|(v, closed)| { + let Some((lo, hi)) = clip else { return Some((v, closed)) }; + match relation(&v, closed, lo, hi) { + Relation::Inside => Some((v, closed)), + Relation::Outside => None, + Relation::Crossing if v.iter().all(|p| p.bulge == 0.0) => { + let cut = clip_polygon(v.iter().map(|p| p.p).collect(), lo, hi); + (cut.len() >= 3).then(|| (cut.into_iter().map(PolyVertex::new).collect(), closed)) + } + Relation::Crossing => { + kept_whole = true; + Some((v, closed)) + } + } + }) + .enumerate() + .map(|(i, (vertices, _))| HatchLoop { vertices, outer: i == 0, sources: Vec::new() }) + .collect(); + if kept_whole { + self.approximated("curved filled shapes crossing a clip kept whole"); + } + if loops.is_empty() { + return; + } + let curved = loops.iter().any(|l| l.vertices.iter().any(|v| v.bulge != 0.0)); + let loops = match fill::normalize(loops, *rule, self.verts_left) { + Ok(loops) => loops, + Err(reason) => return self.fail(reason), + }; + if loops.is_empty() { + return; + } + if curved && loops.iter().all(|l| l.vertices.iter().all(|v| v.bulge == 0.0)) { + self.approximated("curved fill boundaries sampled for winding-rule conversion"); + } + let verts = loops.iter().map(|l| l.vertices.len()).sum(); + let hatch = Hatch { + pattern: "SOLID".into(), + solid: true, + loops, + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + }; + self.add(LAYER_FILLS, color, Lineweight::ByLayer, EntityKind::Hatch(hatch), verts); + } + + fn glyph_text(&mut self, glyph: &Glyph<'_>, to_page: Affine, glyph_to_text: Affine, paint: &Paint<'_>) { + if !self.opts.text || self.failure.is_some() { + return; + } + self.glyphs += 1; + if self.glyphs > MAX_GLYPHS { + return self.fail(&format!("more than {MAX_GLYPHS} glyphs on the page")); + } + let Glyph::Outline(g) = glyph else { return self.left_out(LeftOut::Type3) }; + let Some(color) = color_of(paint) else { return }; + let ch = match g.as_unicode() { + Some(BfString::Char(c)) => c.to_string(), + Some(BfString::String(s)) => s, + None => return self.left_out(LeftOut::NoUnicode), + }; + // A ToUnicode entry may map one code to a string of any length: one glyph gives at most + // MAX_GLYPH_CHARS characters. + if ch.chars().take(MAX_GLYPH_CHARS + 1).count() > MAX_GLYPH_CHARS { + self.approximated("glyph text mappings shortened to 32 characters"); + } + let ch: String = ch.chars().filter(|c| !c.is_control() && *c != '\u{FFFD}').take(MAX_GLYPH_CHARS).collect(); + if ch.is_empty() { + return; + } + // The outline's 1000-unit em square on the page, in drawing units. + let m = Affine::scale(self.opts.unit) * to_page * glyph_to_text; + let origin = pt(m * Point::ZERO); + let ex = pt(m * Point::new(1000.0, 0.0)) - origin; + let ey = pt(m * Point::new(0.0, 1000.0)) - origin; + let (lx, em) = (ex.len(), ey.len()); + if !(origin.x.is_finite() && origin.y.is_finite() && lx > 0.0 && lx.is_finite() && em > 0.0 && em.is_finite()) { + return; + } + let dir = ex * (1.0 / lx); + if !(dir.x.is_finite() && dir.y.is_finite()) { + return; + } + let end = g.advance_width().map(|w| pt(m * Point::new(f64::from(w), 0.0))).filter(|e| e.x.is_finite() && e.y.is_finite()); + // A glyph is kept when its middle (half its advance along, half the cap height up) lies in + // the clip. Its origin is no test: a plotter often clips each text to a box drawn through + // that origin (or ends the page clip there), and rounding then puts it a hair outside. + let half = end.map_or(dir * (0.25 * em), |e| (e - origin) * 0.5); + let middle = origin + half + ey * (0.5 * CAP_HEIGHT); + if let Some((lo, hi)) = self.clip() + && !((lo.x..=hi.x).contains(&middle.x) && (lo.y..=hi.y).contains(&middle.y)) + { + return; + } + // The characters this glyph adds, and a space before them, against the page's text budget. + let Some(left) = self.text_left.checked_sub(ch.chars().count().saturating_add(1)) else { + return self.fail(&format!("more than {MAX_TEXT_CHARS} characters of text on the page")); + }; + self.text_left = left; + + if let Some(run) = &mut self.run { + // A fill and its stroke (render mode 2) arrive as two calls for one glyph at one origin; + // this is tested first, since the gap measured from where the glyph ended is negative. + if run.color == color && (origin - run.last).len() <= 1e-9 * em.max(1.0) && run.text.ends_with(&ch) { + return; + } + let rel = origin - run.last; + let along = rel.x * run.dir.x + rel.y * run.dir.y; + let across = (rel.x * run.dir.y - rel.y * run.dir.x).abs(); + let same = run.color == color && (run.em - em).abs() <= 0.02 * em && run.dir.x * dir.x + run.dir.y * dir.y > 0.9999 && across <= 0.1 * em; + // Where the previous glyph ended, else the previous origin plus an average glyph. + let gap = match run.end { + Some(e) => { + let d = origin - e; + d.x * run.dir.x + d.y * run.dir.y + } + None => along - 0.5 * em, + }; + if same && (-0.3 * em..=1.5 * em).contains(&gap) { + if gap > 0.15 * em && !run.text.ends_with(' ') && !ch.starts_with(' ') { + run.text.push(' '); + } + // A fill and its stroke arrive as two calls for one glyph. + if !(along.abs() < 1e-9 * em.max(1.0) && run.text.ends_with(&ch)) { + run.text.push_str(&ch); + run.glyphs += 1; + } + run.last = origin; + run.end = end; + return; + } + } + self.flush_text(); + self.run = Some(Run { start: origin, dir, em, color, text: ch, glyphs: 1, end, last: origin }); + } + + fn flush_text(&mut self) { + let Some(run) = self.run.take() else { return }; + let value = run.text.trim_end().to_string(); + if value.trim().is_empty() { + return; + } + if let Some((at, text, em)) = &self.last_text + && *text == value + && (*at - run.start).len() <= 1e-9 * run.em.max(1.0) + && (*em - run.em).abs() <= 1e-9 * run.em.max(1.0) + { + return; + } + self.last_text = Some((run.start, value.clone(), run.em)); + let fit_end = run.end.filter(|e| run.glyphs >= 2 && (*e - run.start).len() > 1e-9); + let text = Text { + insert: v3(run.start), + align_pt: fit_end.map(v3), + height: run.em * CAP_HEIGHT, + value, + rotation: run.dir.y.atan2(run.dir.x), + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: if fit_end.is_some() { HAlign::Fit } else { HAlign::Left }, + valign: Default::default(), + }; + self.add(LAYER_TEXT, run.color, Lineweight::ByLayer, EntityKind::Text(text), 1); + } +} + +/// Whether every point of the path, taken to drawing units by `m`, is finite and within +/// [`MAX_COORD`]. +fn path_in_range(path: &BezPath, m: Affine) -> bool { + let ok = |p: Point| { + let q = m * p; + q.x.is_finite() && q.y.is_finite() && q.x.abs() <= MAX_COORD && q.y.abs() <= MAX_COORD + }; + path.elements().iter().all(|el| match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => ok(p), + PathEl::QuadTo(a, b) => ok(a) && ok(b), + PathEl::CurveTo(a, b, c) => ok(a) && ok(b) && ok(c), + PathEl::ClosePath => true, + }) +} + +/// Whether the paint is a colour that lets what is under it show through. +fn translucent(paint: &Paint<'_>) -> bool { + matches!(paint, Paint::Color(c) if { let [_, _, _, a] = c.to_rgba().to_rgba8(); a > 0 && a < 255 }) +} + +/// The rectangle a clip path is, when it is an axis-aligned one (four or five straight points). +fn rect_of(path: &BezPath) -> Option { + let mut pts: Vec = Vec::new(); + for el in path.elements() { + match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => pts.push(p), + PathEl::ClosePath => {} + _ => return None, + } + } + if !(4..=5).contains(&pts.len()) { + return None; + } + if pts.len() == 5 { + if pts.first() != pts.last() { + return None; + } + pts.pop(); + } + // Four corners connected diagonally can form a bow tie, not a rectangular clip. + if !(0..4).all(|i| { + let (a, b) = (pts[i], pts[(i + 1) % 4]); + a != b && ((a.x - b.x).abs() < 1e-6 || (a.y - b.y).abs() < 1e-6) + }) { + return None; + } + let (x0, x1) = pts.iter().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.x), b.max(p.x))); + let (y0, y1) = pts.iter().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.y), b.max(p.y))); + let on = |v: f64, a: f64, b: f64| (v - a).abs() < 1e-6 || (v - b).abs() < 1e-6; + (pts.iter().all(|p| on(p.x, x0, x1) && on(p.y, y0, y1)) && x0.is_finite() && y0.is_finite()).then(|| Rect::new(x0, y0, x1, y1)) +} + +/// How a shape lies against a clip rectangle. +enum Relation { + Inside, + Outside, + Crossing, +} + +fn relation(verts: &[PolyVertex], closed: bool, lo: Vec2, hi: Vec2) -> Relation { + const EPS: f64 = 1e-9; + if lo.x >= hi.x || lo.y >= hi.y { + return Relation::Outside; + } + let (mut min, mut max) = (Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)); + for v in verts { + min = Vec2::new(min.x.min(v.p.x), min.y.min(v.p.y)); + max = Vec2::new(max.x.max(v.p.x), max.y.max(v.p.y)); + } + // A bulged edge can enter a clip even when both endpoints are outside it. + if verts.iter().any(|v| v.bulge != 0.0) { + let bounds = Polyline { vertices: verts.to_vec(), closed }.bounds(); + min = bounds.min; + max = bounds.max; + } + if min.x >= lo.x - EPS && min.y >= lo.y - EPS && max.x <= hi.x + EPS && max.y <= hi.y + EPS { + Relation::Inside + } else if max.x < lo.x || min.x > hi.x || max.y < lo.y || min.y > hi.y { + Relation::Outside + } else { + Relation::Crossing + } +} + +/// The part of the segment a to b inside the rectangle (Liang-Barsky). +fn clip_segment(a: Vec2, b: Vec2, lo: Vec2, hi: Vec2) -> Option<(Vec2, Vec2)> { + let d = b - a; + let (mut t0, mut t1) = (0.0_f64, 1.0_f64); + for (p, q) in [(-d.x, a.x - lo.x), (d.x, hi.x - a.x), (-d.y, a.y - lo.y), (d.y, hi.y - a.y)] { + if p == 0.0 { + if q < 0.0 { + return None; + } + } else { + let r = q / p; + if p < 0.0 { + if r > t1 { + return None; + } + t0 = t0.max(r); + } else { + if r < t0 { + return None; + } + t1 = t1.min(r); + } + } + } + Some((a + d * t0, a + d * t1)) +} + +/// The pieces of a straight-sided polyline inside the rectangle, each an open run of vertices. +fn clipped_runs(verts: &[PolyVertex], closed: bool, lo: Vec2, hi: Vec2) -> Vec> { + fn flush(cur: &mut Vec, runs: &mut Vec>) { + let run = std::mem::take(cur); + if run.windows(2).any(|w| (w[0].p - w[1].p).len() > 1e-9) { + runs.push(run); + } + } + let n = verts.len(); + let segments = if closed { n } else { n.saturating_sub(1) }; + let (mut runs, mut cur) = (Vec::new(), Vec::new()); + for i in 0..segments { + match clip_segment(verts[i].p, verts[(i + 1) % n].p, lo, hi) { + None => flush(&mut cur, &mut runs), + Some((p, q)) => { + if cur.last().is_none_or(|l: &PolyVertex| (l.p - p).len() > 1e-9) { + flush(&mut cur, &mut runs); + cur.push(PolyVertex::new(p)); + } + cur.push(PolyVertex::new(q)); + } + } + } + flush(&mut cur, &mut runs); + runs +} + +/// A polygon cut to the rectangle (Sutherland-Hodgman). +fn clip_polygon(mut poly: Vec, lo: Vec2, hi: Vec2) -> Vec { + // Each edge: the axis (0 = x, 1 = y), its value and whether the kept side is the greater one. + for (axis, value, keep_greater) in [(0, lo.x, true), (0, hi.x, false), (1, lo.y, true), (1, hi.y, false)] { + let get = |v: Vec2| if axis == 0 { v.x } else { v.y }; + let inside = |v: Vec2| if keep_greater { get(v) >= value } else { get(v) <= value }; + let mut out = Vec::with_capacity(poly.len() + 4); + for i in 0..poly.len() { + let (a, b) = (poly[i], poly[(i + 1) % poly.len()]); + if inside(a) { + out.push(a); + } + if inside(a) != inside(b) { + out.push(a + (b - a) * ((value - get(a)) / (get(b) - get(a)))); + } + } + poly = out; + if poly.is_empty() { + break; + } + } + poly +} + +/// Append a cubic from the last vertex of `cur`: a circular arc becomes a bulge on that vertex, +/// any other curve is flattened to `tol`. +fn curve(cur: &mut Vec, c: [Vec2; 4], tol: f64) { + if let Some(bulge) = arc_bulge(c, tol) { + if let Some(last) = cur.last_mut() { + last.bulge = bulge; + } + cur.push(PolyVertex::new(c[3])); + return; + } + let path = [ + PathEl::MoveTo(Point::new(c[0].x, c[0].y)), + PathEl::CurveTo(Point::new(c[1].x, c[1].y), Point::new(c[2].x, c[2].y), Point::new(c[3].x, c[3].y)), + ]; + // The segment count grows with the curve's size over the tolerance: keep the tolerance from + // falling below a fixed fraction of the size. + let (lo, hi) = c.iter().fold((Vec2::new(f64::MAX, f64::MAX), Vec2::new(f64::MIN, f64::MIN)), |(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 size = (hi.x - lo.x).max(hi.y - lo.y); + kurbo::flatten(path, tol.max(size / CURVE_RESOLUTION).max(1e-9), |el| { + // Past the cap the rest is dropped; the caller's next check refuses the path. + if let PathEl::LineTo(p) = el + && cur.len() <= MAX_POLY_VERTS + { + cur.push(PolyVertex::new(pt(p))); + } + }); +} + +fn cubic_at(c: &[Vec2; 4], t: f64) -> Vec2 { + let u = 1.0 - t; + c[0] * (u * u * u) + c[1] * (3.0 * u * u * t) + c[2] * (3.0 * u * t * t) + c[3] * (t * t * t) +} + +/// The bulge of the circular arc a cubic stays within `tol` of, if it is one (and under a full turn). +fn arc_bulge(c: [Vec2; 4], tol: f64) -> Option { + let (a, m, b) = (c[0], cubic_at(&c, 0.5), c[3]); + let chord = b - a; + let len = chord.len(); + if !(len.is_finite() && len > 100.0 * tol) { + return None; + } + // The circle through the ends and the middle. + let d = 2.0 * (a.x * (m.y - b.y) + m.x * (b.y - a.y) + b.x * (a.y - m.y)); + if d.abs() < 1e-12 * len * len { + return None; + } + let (a2, m2, b2) = (a.x * a.x + a.y * a.y, m.x * m.x + m.y * m.y, b.x * b.x + b.y * b.y); + let center = + Vec2::new((a2 * (m.y - b.y) + m2 * (b.y - a.y) + b2 * (a.y - m.y)) / d, (a2 * (b.x - m.x) + m2 * (a.x - b.x) + b2 * (m.x - a.x)) / d); + let r = (a - center).len(); + if !r.is_finite() || r < len * 0.5 * (1.0 - 1e-9) { + return None; + } + // Every sample must lie on it. + for t in [0.125, 0.25, 0.375, 0.625, 0.75, 0.875] { + if ((cubic_at(&c, t) - center).len() - r).abs() > tol { + return None; + } + } + // The arc from a to b through m runs counter-clockwise when m lies to the right of a→b. + let ccw = chord.x * (m.y - a.y) - chord.y * (m.x - a.x) < 0.0; + let half = (len * 0.5 / r).clamp(-1.0, 1.0).asin(); + // The middle lies on the minor arc, unless it is further from the chord than the radius. + let sag = ((m - a).x * chord.y - (m - a).y * chord.x).abs() / len; + let theta = if sag > r { std::f64::consts::TAU - 2.0 * half } else { 2.0 * half }; + if theta >= std::f64::consts::TAU - 1e-6 { + return None; + } + let bulge = (theta / 4.0).tan(); + Some(if ccw { bulge } else { -bulge }) +} + +impl<'a> Device<'a> for Collector { + fn set_soft_mask(&mut self, mask: Option>) { + if mask.is_some() { + self.approximated("soft masks not applied"); + } + } + fn set_blend_mode(&mut self, mode: BlendMode) { + if mode != BlendMode::Normal { + self.approximated("blend modes not applied"); + } + } + fn draw_path(&mut self, path: &BezPath, transform: Affine, paint: &Paint<'a>, mode: &PathDrawMode) { + if self.failure.is_some() { + return; + } + self.flush_text(); + match mode { + PathDrawMode::Fill(rule) => self.fill(path, transform, paint, rule), + PathDrawMode::Stroke(p) => { + if !p.dash_array.is_empty() { + self.approximated("dashed paths imported as continuous lines"); + } + self.stroke(path, transform, paint, p.line_width); + } + } + } + fn push_clip_path(&mut self, clip: &ClipPath) { + self.flush_text(); + let rect = rect_of(&clip.path); + if rect.is_none() { + self.approximated("clips by a shape other than a rectangle not applied"); + } + self.clips.push(rect); + } + fn push_transparency_group(&mut self, opacity: f32, mask: Option>, mode: BlendMode) { + self.flush_text(); + self.set_soft_mask(mask); + self.set_blend_mode(mode); + if opacity < 1.0 { + self.approximated("translucent groups drawn opaque"); + } + } + fn draw_glyph(&mut self, glyph: &Glyph<'a>, transform: Affine, glyph_transform: Affine, paint: &Paint<'a>, mode: &GlyphDrawMode) { + if matches!(mode, GlyphDrawMode::Fill | GlyphDrawMode::Stroke(_)) { + self.glyph_text(glyph, transform, glyph_transform, paint); + } + } + fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) { + self.flush_text(); + self.left_out(LeftOut::Image); + } + fn pop_clip_path(&mut self) { + self.flush_text(); + self.clips.pop(); + } + fn pop_transparency_group(&mut self) {} +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A one-page PDF, 600 x 800 points, drawing `content`. + fn page(content: &str) -> Vec { + 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() + } + + #[test] + fn many_curves_in_one_path_stop_at_the_vertex_budget() { + // About 500 vertices a curve and 200 curves in one path: some 100 000 vertices against a + // budget of 10 000. The path is refused while its subpaths are built, also when a clip + // would have left all of it out. + let curves = "0 0 m 0 1 1 1 1 0 c ".repeat(200); + let o = PdfImportOptions::default(); + let whole = format!("1000000 0 0 1000000 0 0 cm {curves}S"); + let clipped = format!("q 0 0 1 1 re W n 1000000 0 0 1000000 5000000 5000000 cm {curves}S Q"); + for content in [&whole, &clipped] { + let e = read_within(&page(content), &o, 10_000).unwrap_err().to_string(); + assert!(e.contains("too much geometry on the page"), "{e}"); + } + // Within the budget the same path is read. + let (d, _) = read_within(&page(&whole), &o, MAX_TOTAL_VERTS).unwrap(); + assert_eq!(d.model.iter().count(), 200); + } +} diff --git a/crates/io/src/pdf_read/fill.rs b/crates/io/src/pdf_read/fill.rs new file mode 100644 index 000000000..0db2cd699 --- /dev/null +++ b/crates/io/src/pdf_read/fill.rs @@ -0,0 +1,513 @@ +//! 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 reject spans that would lose useful CAD precision. +const MAX_LOCAL_SPAN: f64 = 1_000_000.0; +/// Maximum points used to approximate one bulge arc for topology checks and tessellation. +const ARC_TOLERANCE: f64 = 0.02; +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. 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, rule: FillRule, max_vertices: usize) -> Result, &'static str> { + if loops.is_empty() { + return Ok(loops); + } + let mut work = 0usize; + let mut sampled = 0usize; + let mut polygons = Vec::new(); + for loop_ in &loops { + let polygon = flatten_loop(loop_, &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 mut depth = vec![0usize; loops.len()]; + containment(&polygons, &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) + } + FillRule::NonZero => { + let sign: Vec = polygons + .iter() + .map(|p| { + let area = signed_area(p); + if p.len() < 3 || area == 0.0 { 0 } else { area.signum() as i64 } + }) + .collect(); + // The winding number just inside each contour. + let mut winding = sign.clone(); + containment(&polygons, &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 = winding.iter().zip(&sign).map(|(&w, &s)| s != 0 && (w != 0) != (w - s != 0)).collect(); + let mut depth = vec![0usize; loops.len()]; + containment(&polygons, &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, work: &mut usize, max_vertices: usize) -> Result, &'static str> { + let n = loop_.vertices.len(); + if n < 3 { + 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 <= ARC_TOLERANCE { std::f64::consts::TAU } else { 2.0 * (1.0 - ARC_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, 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 a point just inside contour `i`. +fn containment(polygons: &[Vec], 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 = interior_probe(polygon); + 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]) -> Option { + let rings: Vec> = polygons + .iter() + .map(|p| { + let mut ring: Vec = 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 longest = polygon.iter().zip(polygon.iter().cycle().skip(1)).take(polygon.len()).max_by(|(a, b), (c, d)| a.dist(**b).total_cmp(&c.dist(**d))); + let Some((a, b)) = longest 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 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::() * 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], sampled_vertices: usize, max_vertices: usize) -> Result, &'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)))); + if max.x - min.x > MAX_LOCAL_SPAN || max.y - min.y > MAX_LOCAL_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::, _>>()?; + 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, + indices: Vec, + 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 { + 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) + } + + fn filled(loops: &[HatchLoop], point: Vec2) -> bool { + loops.iter().filter(|l| contains(&l.vertices.iter().map(|v| v.p).collect::>(), point)).count() % 2 == 1 + } + + #[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).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).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).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).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 as four quarter arcs each, wound opposite ways. + let quarter = (std::f64::consts::PI / 8.0).tan(); + let circle = |r: f64, clockwise: bool| { + 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(), + } + }; + let result = normalize(vec![circle(10.0, false), circle(5.0, true)], FillRule::NonZero, 10_000).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).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).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).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).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))); + } +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 42d3b28fd..3f31133b8 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -59,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; diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs new file mode 100644 index 000000000..a7a21aa83 --- /dev/null +++ b/crates/io/tests/it/pdf_import.rs @@ -0,0 +1,520 @@ +//! 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 { + pages(&[content]) +} + +fn pages(contents: &[&str]) -> Vec { + 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 { + 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 = hatches[0].loops[0].vertices.iter().map(|v| v.p.x).collect(); + let ys: Vec = 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 { + 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(""), 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 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() { + let form = "/X Do /X Do 0 0 m 1 1 l S"; + let pdf = 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() + ); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(read(pdf.as_bytes(), &PdfImportOptions::default()).map(|_| ())); + }); + assert!(rx.recv_timeout(std::time::Duration::from_secs(20)).is_ok(), "the self-calling form was not stopped"); +} + +#[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 = + 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::>()); +} + +/// 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 { + let cmap = format!( + "/CIDInit /ProcSet findresource begin 12 dict begin begincmap\n\ + /CMapName /Test def /CMapType 2 def\n\ + 1 begincodespacerange <00> 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 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 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); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 791d188f5..127e786c0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -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), diff --git a/crates/ui-egui/src/exchange.rs b/crates/ui-egui/src/exchange.rs index 153bbf925..69ed97072 100644 --- a/crates/ui-egui/src/exchange.rs +++ b/crates/ui-egui/src/exchange.rs @@ -26,6 +26,26 @@ pub fn route(app: &mut CadApp, id: &str) -> Result { "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| { + PDF_PENDING.with(|pending| { + *pending.borrow_mut() = Some(PdfImport { + 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 +55,94 @@ pub fn route(app: &mut CadApp, id: &str) -> Result { } } +/// A chosen PDF and the editable content requested from its page. +struct PdfImport { + path: String, + page: u32, + scale: f64, + at: [f64; 2], + password: String, + text: bool, + fills: bool, + lineweights: bool, + focus_page: bool, + error: Option, +} + +thread_local! { + static PDF_PENDING: std::cell::RefCell> = 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); + } + match app.run("pdfimport", params) { + 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 { let msg = format!("{name}: there is no file dialog here; run it with parameters, e.g. {example}"); app.session.echo(msg.clone()); diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 5d5972061..1a2fbe4b0 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1034,6 +1034,7 @@ Not a number or distance: {text} 不是数字或距离:{text} Plotter Manager... 绘图仪管理器... Import... 导入... + Import PDF... 导入 PDF... Export... 导出... Batch Publish... 批量发布... New from Template... 根据样板新建... diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d8e98a42c..6526441e9 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -489,7 +489,9 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { + "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" => { diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 7ff34c0ca..c5927070a 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -31,6 +31,7 @@ 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; diff --git a/crates/ui-egui/tests/it/pdf_import_dialog.rs b/crates/ui-egui/tests/it/pdf_import_dialog.rs new file mode 100644 index 000000000..8b5b4dce1 --- /dev/null +++ b/crates/ui-egui/tests/it/pdf_import_dialog.rs @@ -0,0 +1,100 @@ +//! 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(); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 70cfb3e17..01e111149 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -111,7 +111,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | DWT templates | open, save | NEW/QNEW from `.dwt` and `.dxf` templates, SAVEAS `.dwt` (#552); LAYOUT SAveas writes one layout and the named objects it uses as a `.dwt` (`layout.saveas`) | 0–1 | | DWS standards | open, save, CHECKSTANDARDS | no | 6–10 | | PDF output (PLOT, EXPORTPDF) | multi-sheet, layers, searchable text, hyperlinks | vector PDF with lineweights, real text in embedded TrueType subsets, layers (OCG), several sheets per file and hyperlinks (#567, #571); object transparency as PDF alpha when "Plot transparency" is on (the option isn't saved in DXF/DWG: no public plot layout flag) | 1–2 | -| PDF import (PDFIMPORT) and PDF underlays (PDFATTACH) | yes | no | 15–25 | +| PDF import (PDFIMPORT) and PDF underlays (PDFATTACH) | yes | vector PDF page import as editable lines, polylines, solid fills and text; page, scale and placement controls, CLI conversion and explicit loss reports ([guide](pdf-import.md)). PDF underlays and raster tracing remain unavailable | partial | | Raster images attach (PNG, JPEG, TIFF, BMP …) | yes | **partial** (#956): IMAGEATTACH (JSON form) reads PNG, JPEG, BMP and TIFF; drawn on screen and in PNG output with rotation, clip boundary and fade; reloaded on open, a missing file stays a crossed-out frame. Not yet: PDF and SVG output of the picture, prompts and dialog, detach/reload/unload, IMAGECLIP, IMAGEADJUST, images stored in the drawing | 14–22 | | PNG / JPEG / BMP / TIFF export | PNGOUT, JPGOUT, BMPOUT, TIFOUT | PNG; SVG too (AutoCAD doesn't export SVG) | 1–2 | | DWF/DWFx export, DWF underlay | yes | no | 10–15 | diff --git a/docs/gaps.md b/docs/gaps.md index 13286f9af..891a0b9f8 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -82,7 +82,7 @@ Detail: [file-format-parity.md](file-format-parity.md). | FF7 | Table record and object handles from other programs' files are renumbered on the first save (entity handles are kept; `*D` blocks no longer duplicate and once reopened, CADCraft's own files keep every handle across saves, #495) | Low | 4–6 | | FF8 | SHX shape fonts, big fonts and unifonts are read and drawn (2026-10-22; looked up by file name beside the drawing, in `CADCRAFT_SHXPATH`, via a font map or registered by the web app; FONTALT). Left: no Options entry for the search path or font map; no desktop drag-drop of `.shx`; big-font code page guessed from the file name; vertical text not justified along its column; extended big font box scaling unverified against real files | Medium | 2–4 | | FF9 | `.pc3` plotter configuration files; shape elements in user `.lin` files are dropped on load (DXF/DWG linetype shape elements are drawn since 2026-10-22; templates and `.dwt`, user `.lin`/`.pat` and `.pgp` alias files landed, #552; `.ctb`/`.stb`, #410) | Low-medium | 4–8 | -| FF10 | PDF import and underlays (PDFATTACH). Raster images (#956): IMAGEATTACH from JSON reads PNG, JPEG, BMP and TIFF, the picture is drawn on screen and in PNG exports and plot previews (rotation, clip boundary, fade), sharp at any zoom whatever its size (a pyramid of levels cut into tiles, uploaded as they come into view), and reloaded when the drawing opens; left: PDF and SVG output write only the frame, no prompts, dialog or menu row, no -IMAGE options (detach, reload, unload, path), IMAGECLIP, IMAGEADJUST or IMAGEFRAME, brightness and contrast not applied, images lie under all other objects on screen whatever their draw order, size not taken from the file's resolution, images can't be stored in the drawing. PDF export has real text in embedded TrueType subsets, PDF layers, several sheets per file and hyperlinks (#567, #571) | Medium | 24–40 | +| FF10 | PDF vector import is available ([guide](pdf-import.md)): page selection, editable geometry/fills/text, scale and placement, DXF/DWG conversion. Left: PDF underlays (PDFATTACH), raster tracing/OCR, original layer recovery, exact font and complex clip/compositing preservation. Raster images (#956): IMAGEATTACH from JSON reads PNG, JPEG, BMP and TIFF, the picture is drawn on screen and in PNG exports and plot previews (rotation, clip boundary, fade), sharp at any zoom whatever its size (a pyramid of levels cut into tiles, uploaded as they come into view), and reloaded when the drawing opens; left: PDF and SVG output write only the frame, no prompts, dialog or menu row, no -IMAGE options (detach, reload, unload, path), IMAGECLIP, IMAGEADJUST or IMAGEFRAME, brightness and contrast not applied, images lie under all other objects on screen whatever their draw order, size not taken from the file's resolution, images can't be stored in the drawing. PDF export has real text in embedded TrueType subsets, PDF layers, several sheets per file and hyperlinks (#567, #571) | Medium | 24–40 | | FF11 | DWF/DWFx, DGN, WMF, EPS, ACIS/STL and other exchange formats | Low-medium | 50–100 | | FF12 | DWG in the web build | Medium | 6–10 | | FF13 | R12 binary DXF, pre-R13 DWG | Low | 10–20 | diff --git a/docs/pdf-import.md b/docs/pdf-import.md new file mode 100644 index 000000000..b183ff4c8 --- /dev/null +++ b/docs/pdf-import.md @@ -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`.