Compare commits

..
6 Commits
Author SHA1 Message Date
Tanish Manku 6cc7e0c881 Parity documents stay as on main: the rows PDFIMPORT moves are named in the pull request 2026-11-23 12:36:31 -07:00
Tanish Manku f7f409b2b0 Merge #3375: PDFIMPORT: a page of a PDF imports as editable lines, polylines, solid hatches and text 2026-11-23 12:36:20 -07:00
C00kieMonsta 90d0942548 PDF import test: allow the interpreter's full nested-paint budget for a self-calling form 2026-11-21 22:28:56 +01:00
C00kieMonsta 186e465487 PDF import: fixes from review
- Fill tolerance follows the drawing unit, so arcs are sampled and fills
  split into triangles to the same accuracy in metres as in millimetres.
- Nonzero fills test containment from a point on each contour's edge, so
  an inner contour close to its parent's edge keeps the fill.
- A fill of two arc vertices (a disc) is kept.
- The same text drawn again after a shape or image is kept.
- A clip path that doubles back along an edge is not taken as a rectangle.
- PDF options that are not a JSON object are refused.
- The options window imports into the drawing it was opened for.
- The self-calling form test checks the outcome against a finite form.
2026-11-21 22:02:20 +01:00
C00kieMonsta c79fdde52d PDF import CLI test: format with rustfmt 2026-11-21 21:43:57 +01:00
C00kieMonsta d4fd0dd7a2 PDFIMPORT: a page of a PDF imports as editable lines, polylines, solid hatches and text
PDFIMPORT (File > Import PDF...) adds a chosen page to the current drawing,
with page, scale, insertion point, password and content options. OPEN and
IMPORT take a PDF too; OPEN reads its first page into a new metric drawing,
and cadcraft-cli convert writes it to DXF or DWG.

The mapping is adapted from PR #2787 (MIT OR Apache-2.0) onto craft-pdf's
interpreter. Nonzero fills whose contours don't cross keep their loops and
arcs; crossing contours are split into triangles so the filled area matches.
Content the import leaves out or approximates is named in the read notes,
and a page with no vector content is refused instead of opening empty.
2026-11-21 21:31:15 +01:00
99 changed files with 3314 additions and 3029 deletions
+1 -1
View File
@@ -38,7 +38,7 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
dry-run: ${{ github.event_name == 'schedule' }}
nightly: ${{ github.event_name == 'schedule' }}
app-name: cadcraft
app-title: CADCraft
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
+37 -4
View File
@@ -19,9 +19,7 @@ Generated-in-code assets are original and have no file to list:
- the standard linetype and hatch-pattern libraries (`crates/doc/src/library.rs`; industry-common
names, our own dash/spacing values);
- the colour index palette, generated from its structure (`crates/color/src/lib.rs`);
- the sample drawings (`crates/engine/src/sample.rs`);
- the synthetic two-hexagon hatch logo (`crates/io/tests/it/hatch_loop_flags.rs`, `logo`):
original contributor geometry, generated in code from invented points, under MIT OR Apache-2.0.
- the sample drawings (`crates/engine/src/sample.rs`).
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
@@ -72,7 +70,7 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/bs.tsv` | Nine (@nine-codes) with Claude Code (AI-assisted) | Original Bosnian translations of CADCraft English strings, shared with storytold/craft-i18n `locales/bs/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; not yet reviewed by a native speaker |
| `crates/ui-egui/src/i18n/cs.tsv` | @Losminek (AI-assisted) | Original Czech translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/ru.tsv` | @pechnikov2026-star | Original Russian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star; terminology pass by @YannFR81 | Original French translations of CADCraft English strings; AI-assisted consistency pass (imperative prompts, cote/espace objet/réseau/présentation) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original French translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/zh.tsv` | @mayloglog | Original Simplified Chinese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted); terminology corrections: Andrea Brandi (@starise) with OpenAI Codex (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; targeted Chamfer terminology review by a native speaker |
@@ -83,3 +81,38 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending |
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
## PDF import
The CAD mapping and initial synthetic PDF tests are adapted from CADCraft contributor
@DuukDuul's [PR #2787](https://github.com/storytold/cadcraft/pull/2787), commit
`ec17f63f189d1dccf91357701f9bba243ca88dd5`, under MIT OR Apache-2.0. The mapping has
been changed for the current shared reader, bounded import, fill rules and diagnostics.
PDF test inputs in `crates/io/tests/it/pdf_import.rs`, `crates/io/src/pdf_read.rs`, and
`apps/cadcraft-cli/tests/it/pdf_import.rs` are generated from literal content streams or
CadCraft's own plotter. No customer documents are included.
Enabling `craft-pdf` interpretation uses the following unchanged dependency assets from
`craft-libs` revision `453b0da782ccef39be9a6dac8d27c80b553ef1cc`. Fonts remain in the
shared dependency. Their source and hashes are retained below; notices are in `NOTICE`.
| Asset | Author | Source | Licence | SHA-256 | Notes |
|---|---|---|---|---|---|
| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/pdfcraft/blob/a2ec27b4775f53c40cad3456936d9406611e3a8d/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/pdfcraft/blob/7437bde378f43856eada40af25b983812e615e8a/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
Generated
+123 -18
View File
@@ -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]]
@@ -661,7 +697,6 @@ dependencies = [
"craft-window",
"eframe",
"egui",
"fmv-macos-events",
"hidapi",
"log",
"muda",
@@ -785,6 +820,8 @@ dependencies = [
"craft-pdf",
"craft-svg",
"image",
"kurbo",
"lyon_tessellation",
"miniz_oxide 0.9.1",
"serde",
"serde_json",
@@ -1321,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",
@@ -1343,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",
@@ -2057,17 +2095,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
[[package]]
name = "fmv-macos-events"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55"
dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
]
[[package]]
name = "foldhash"
version = "0.1.5"
@@ -2486,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",
]
@@ -2503,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",
@@ -3909,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"
@@ -3930,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",
@@ -3952,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"
+5
View File
@@ -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" }
+189
View File
@@ -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.
+2 -2
View File
@@ -26,12 +26,12 @@ fn with_formats(cell: &'static std::sync::OnceLock<String>, before: &str, list:
/// The drawing an input argument names.
fn read_help() -> &'static str {
static C: std::sync::OnceLock<String> = std::sync::OnceLock::new();
with_formats(&C, "The drawing to read ", Format::READ, "")
with_formats(&C, "The drawing to read ", Format::READ, ", or a PDF whose first page opens as editable vector content")
}
fn open_help() -> &'static str {
static C: std::sync::OnceLock<String> = std::sync::OnceLock::new();
with_formats(&C, "Drawings to open ", Format::READ, "")
with_formats(&C, "Drawings to open ", Format::READ, ", or PDFs (their first page)")
}
fn write_help() -> &'static str {
+2 -21
View File
@@ -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,
@@ -58,7 +59,6 @@ fn install_io() {
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
}
/// `path` as text, for the engine and io calls that take a file name as a string.
@@ -96,7 +96,7 @@ where
Ok(cli) => cli,
Err(e) => {
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
return match write!(to, "{}", e.render()).and_then(|()| to.flush()) {
return match write!(to, "{}", e.render()) {
Err(w) if w.kind() != std::io::ErrorKind::BrokenPipe => {
let _ = writeln!(err, "error: can't write the output: {w}");
1
@@ -166,25 +166,6 @@ mod tests {
assert_eq!(run(["--help"], &mut FailingWriter(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
}
struct FailingFlush(std::io::ErrorKind);
impl Write for FailingFlush {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Err(self.0.into())
}
}
#[test]
fn a_failed_flush_of_help_exits_1_unless_the_pipe_is_closed() {
let mut err = Vec::new();
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::StorageFull), &mut err), 1);
assert!(String::from_utf8_lossy(&err).starts_with("error: "));
assert_eq!(run(["--help"], &mut FailingFlush(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0);
}
#[test]
fn write_atomic_replaces_file_and_leaves_no_staging_files() {
let dir = scratch_dir("replace");
+1 -1
View File
@@ -58,7 +58,7 @@ pub(crate) fn roundtrip(a: &RoundtripArgs, io: &mut Streams) -> Result {
if a.keep_saved {
opts.keep_saved = Some(out.join("saved"));
}
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| io.errln(format_args!("[{}/{n}] {rel}", i + 1)));
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| eprintln!("[{}/{n}] {rel}", i + 1));
for f in &report.files {
let routes: Vec<String> = f
.routes
+2 -10
View File
@@ -1,7 +1,7 @@
use super::args::{CmdStep, Drawing, RunArgs, Step};
use super::error::Result;
use super::open;
use super::output::{Streams, export, export_framed, export_window, model_views, undrawn_message};
use super::output::{Streams, export, export_framed, export_window, model_views};
use cadcraft_engine::Session;
use cadcraft_engine::doc::Handle;
use serde_json::Value;
@@ -216,15 +216,7 @@ pub(crate) fn run_cmds(a: &RunArgs, io: &mut Streams) -> Result {
export(&s, p, io)?;
}
if let Some(p) = export_to {
let window = if cadcraft_io::is_image(p) {
let window = export_window(&s, framing, Some(&before))?;
if let Some(message) = undrawn_message(s.doc()?, &p.to_string_lossy()) {
io.errln(format_args!("{message}"));
}
window
} else {
None
};
let window = if cadcraft_io::is_image(p) { export_window(&s, framing, Some(&before))? } else { None };
export_framed(&s, p, window, io)?;
}
Ok(())
+1
View File
@@ -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;
+116
View File
@@ -0,0 +1,116 @@
//! A PDF page converted on the command line keeps its geometry and its fill rules through a DXF
//! or DWG save and reopen.
use std::process::{Command, Output};
use serde_json::Value;
const MM_PER_PT: f64 = 25.4 / 72.0;
/// A line, a nonzero fill of two nested squares wound the same way (all of it filled), an
/// even-odd fill of the same squares (the inner one a hole) and a nonzero fill of two
/// overlapping squares (split into triangles).
const CONTENT: &str = "1 0 0 RG 2 w 10 10 m 100 10 l S\n\
0 0 1 rg 200 200 m 300 200 l 300 300 l 200 300 l h 220 220 m 280 220 l 280 280 l 220 280 l h f\n\
0 1 0 rg 400 400 m 500 400 l 500 500 l 400 500 l h 420 420 m 480 420 l 480 480 l 420 480 l h f*\n\
1 0 1 rg 50 600 m 150 600 l 150 700 l 50 700 l h 100 650 m 200 650 l 200 750 l 100 750 l h f\n";
fn page(content: &str) -> Vec<u8> {
format!(
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R >> endobj\n\
4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
trailer << /Root 1 0 R >>\n%%EOF\n",
content.len()
)
.into_bytes()
}
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A fresh scratch directory that is removed on drop, also when an assertion fails.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir(&dir).expect("create scratch dir");
Scratch(dir)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// The model space of `file` with each object's geometry.
fn inspect(file: &str) -> Value {
let out = cli(&["run", file, "--cmd", r#"drawing.inspect {"entities":true}"#]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{file}: {}", String::from_utf8_lossy(&out.stderr));
serde_json::from_str(stdout.lines().last().unwrap_or_default()).unwrap_or_else(|e| panic!("{file}: {e}: {stdout}"))
}
fn inside(ring: &[(f64, f64)], (x, y): (f64, f64)) -> bool {
let mut odd = false;
for (i, &(ax, ay)) in ring.iter().enumerate() {
let (bx, by) = ring[(i + 1) % ring.len()];
if (ay > y) != (by > y) && x < (bx - ax) * (y - ay) / (by - ay) + ax {
odd = !odd;
}
}
odd
}
/// Whether a hatch covers the page point `at` (in PDF points), by odd parity as hatches are drawn.
fn filled(drawing: &Value, at: (f64, f64)) -> bool {
let at = (at.0 * MM_PER_PT, at.1 * MM_PER_PT);
let entities = drawing["entities"].as_array().cloned().unwrap_or_default();
entities.iter().filter(|e| e["type"] == "Hatch").any(|hatch| {
let loops = hatch["geometry"]["loops"].as_array().cloned().unwrap_or_default();
let rings = loops.iter().map(|l| {
l["vertices"]
.as_array()
.into_iter()
.flatten()
.map(|v| (v["p"]["x"].as_f64().unwrap_or(0.0), v["p"]["y"].as_f64().unwrap_or(0.0)))
.collect()
});
rings.filter(|ring: &Vec<(f64, f64)>| inside(ring, at)).count() % 2 == 1
})
}
#[test]
fn a_pdf_page_keeps_its_fills_through_dxf_and_dwg() {
let scratch = Scratch::new("pdf-import");
let pdf = scratch.0.join("plan.pdf");
std::fs::write(&pdf, page(CONTENT)).unwrap();
let pdf = pdf.to_str().unwrap().to_string();
let mut files = vec![pdf.clone()];
for ext in ["dxf", "dwg"] {
let out = scratch.0.join(format!("plan.{ext}"));
let out = out.to_str().unwrap().to_string();
let run = cli(&["convert", &pdf, &out]);
assert!(run.status.success(), "convert to {ext}: {}", String::from_utf8_lossy(&run.stderr));
files.push(out);
}
for file in &files {
let d = inspect(file);
assert_eq!(d["counts"]["Line"], 1, "{file}: {}", d["counts"]);
assert_eq!(d["counts"]["Hatch"], 3, "{file}: {}", d["counts"]);
assert!(filled(&d, (251.3, 247.7)), "{file}: the nonzero fill keeps its centre");
assert!(filled(&d, (210.2, 205.9)), "{file}: the nonzero fill keeps its rim");
assert!(!filled(&d, (451.3, 447.7)), "{file}: the even-odd fill keeps its hole");
assert!(filled(&d, (410.2, 405.9)), "{file}: the even-odd fill keeps its rim");
assert!(!filled(&d, (350.4, 351.7)), "{file}: nothing is filled between the shapes");
assert!(filled(&d, (125.3, 675.2)), "{file}: the overlap of the crossing squares stays filled");
assert!(filled(&d, (60.4, 610.3)) && filled(&d, (190.2, 740.1)), "{file}: both crossing squares stay filled");
assert!(!filled(&d, (60.4, 740.1)), "{file}: the corner beside the crossing squares stays empty");
}
}
+2 -24
View File
@@ -1,5 +1,5 @@
//! Image exports report how many model-space entities they can't draw, by type. The exit code
//! stays 0 (#1208).
//! `convert` to an image says how many model-space entities it can't draw, by type, instead of
//! leaving them out silently (#1208). The exit code stays 0.
use std::process::{Command, Output};
@@ -70,28 +70,6 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() {
assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr));
}
#[test]
fn run_image_export_warns_about_undrawn_entities() {
let scratch = Scratch::new("run-undrawn");
let input = scratch.0.join("proxies.dxf");
std::fs::write(&input, PROXIES).unwrap();
let image = scratch.0.join("out.svg");
let out = cli(&["run", input.to_str().unwrap(), "--export", image.to_str().unwrap()]);
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{:?}: {err}", out.status);
assert!(image.is_file());
assert!(out.stdout.is_empty(), "the warning belongs on stderr");
let warnings: Vec<&str> = err.lines().filter(|l| l.contains("not drawn")).collect();
assert_eq!(warnings, [format!("{}: 3 entities not drawn (PDFUNDERLAY: 1, REGION: 2)", image.display())], "{err}");
let copy = scratch.0.join("copy.dxf");
let out = cli(&["run", input.to_str().unwrap(), "--export", copy.to_str().unwrap()]);
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{:?}: {err}", out.status);
assert!(copy.is_file());
assert!(!err.contains("not drawn"), "{err}");
}
/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it an undrawn entity (#2422); it
/// says once that the OLE content inside the frame is not drawn (review on #2587).
#[test]
-8
View File
@@ -949,11 +949,3 @@ fn json_output_is_pretty_unless_compact() {
assert_eq!(r.stdout.lines().count(), 2, "one line per --cmd result: {}", r.stdout);
assert_eq!(invoke(&["run", "--sample", "--compact"]).code, 2, "run takes no --compact");
}
#[test]
fn roundtrip_progress_uses_the_requested_stderr() {
run_cases(
"roundtrip-progress",
&[case("roundtrip progress", &["roundtrip", "{b}", "--same-format", "--no-census"], 0, Starts("b.dxf: opened;"), Line("[1/1] b.dxf"))],
);
}
+1 -1
View File
@@ -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,
@@ -132,7 +133,6 @@ mod web {
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
let Some(canvas) = app_canvas() else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
+1 -1
View File
@@ -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;
-5
View File
@@ -62,11 +62,6 @@ winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
# in Cargo.lock through eframe.
pollster = "1"
# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C
# handler behind a safe API, without relaxing the workspace's unsafe-code lint.
# Pinned exactly: review the implementation before bumping.
fmv-macos-events = "=0.1.0"
# Rust HID backends: no proprietary SDK or C HID library.
[target.'cfg(target_os = "windows")'.dependencies]
-211
View File
@@ -1,211 +0,0 @@
//! macOS open-documents and quit Apple events (#158).
//!
//! A Finder double-click, Open With, a drop on the Dock icon and `open -a CADCraft plan.dxf` don't
//! put the path in argv: LaunchServices sends the running (or just-launched) app a
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
//! `NSApplicationDelegate`, so AppKit answered "CADCraft cannot open files in the Drawing Exchange
//! Format format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which
//! this workspace forbids. The pinned `fmv-macos-events` crate wraps exactly that, an
//! `NSAppleEventManager` handler registered before Finder's
//! launch event that leaves winit's delegate alone, behind a safe main-thread API.
use std::path::PathBuf;
use cadcraft_ui_egui::CadApp;
#[cfg(target_os = "macos")]
use fmv_macos_events::{Event, Inbox, Registration};
/// The shape of `fmv_macos_events::Event`, so [`dispatch`] and its tests also build and run where
/// that crate is not compiled (PR CI runs on Linux). On macOS the crate's own type is used.
#[cfg(not(target_os = "macos"))]
enum Event {
Open(Vec<PathBuf>),
Quit,
}
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
#[cfg(target_os = "macos")]
pub struct AppleEvents {
_registration: Registration,
inbox: Inbox,
}
#[cfg(target_os = "macos")]
impl AppleEvents {
/// Register the handlers. Call on the main thread before the event loop starts, so the event
/// that launched the app (a Finder double-click) is caught too.
pub fn install() -> Self {
let (registration, inbox) = Registration::install();
Self { _registration: registration, inbox }
}
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
let ctx = ctx.clone();
self.inbox.set_wake(move || ctx.request_repaint());
self.inbox.clone()
}
}
/// The paths to hand to OPEN: UTF-8 and non-empty, each once, in the order they arrived. A second
/// copy of the same path (Finder sends one per selected item, and a drop can repeat) would open
/// the drawing twice.
fn openable(paths: impl IntoIterator<Item = PathBuf>) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for p in paths {
if let Some(s) = p.to_str().filter(|s| !s.is_empty())
&& !out.iter().any(|o| o == s)
{
out.push(s.to_string());
}
}
out
}
/// Dispatch a batch through the regular opening and unsaved-changes paths. Returns whether the
/// window may close now; a queued quit must not bypass the Save / Don't Save / Cancel prompt.
fn dispatch(events: impl IntoIterator<Item = Event>, app: &mut CadApp) -> bool {
let mut quit = false;
for e in events {
match e {
Event::Open(paths) => {
for p in openable(paths) {
app.open_path(std::path::Path::new(&p));
}
}
Event::Quit => quit = true,
}
}
quit && !app.request_quit()
}
/// Drain the inbox each frame; a quit closes the window like Cmd+Q, prompting for unsaved drawings.
#[cfg(target_os = "macos")]
pub fn poll(inbox: &Inbox, app: &mut CadApp, ctx: &egui::Context) {
if dispatch(inbox.drain(), app) {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
#[cfg(test)]
mod tests {
use super::{Event, dispatch, openable};
use cadcraft_engine::Session;
use cadcraft_ui_egui::closing::Choice;
use cadcraft_ui_egui::{CadApp, Services};
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
struct TestDir(PathBuf);
impl TestDir {
fn new() -> Self {
let dir = std::env::temp_dir().join(format!("cadcraft-apple-events-{}-{}", std::process::id(), NEXT_DIR.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
}
impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn app() -> CadApp {
crate::install_io();
// The DWG written and read here is the test's own synthetic file; the app starts its DWG
// worker in `main`, which a test does not run.
cadcraft_io::dwg_worker::allow_in_process();
CadApp::new(Session::new(), Services::default())
}
fn settle(app: &mut CadApp) {
let deadline = Instant::now() + Duration::from_secs(10);
while app.opening.busy() && Instant::now() < deadline {
app.finish_opening();
std::thread::sleep(Duration::from_millis(5));
}
app.finish_opening();
assert!(!app.opening.busy(), "background opening completed");
}
#[test]
fn keeps_order_and_drops_duplicates_and_empty_paths() {
let paths = ["/a/plan.dxf", "", "/b/site.dwg", "/a/plan.dxf"].map(PathBuf::from);
assert_eq!(openable(paths), ["/a/plan.dxf", "/b/site.dwg"]);
assert!(openable(Vec::new()).is_empty());
}
#[cfg(unix)]
#[test]
fn skips_paths_that_are_not_utf8() {
use std::os::unix::ffi::OsStringExt;
let bad = PathBuf::from(std::ffi::OsString::from_vec(vec![b'/', 0xff, b'.', b'd', b'x', b'f']));
assert_eq!(openable([bad, PathBuf::from("/ok.dxf")]), ["/ok.dxf"]);
}
#[test]
fn opens_dwg_and_dxf_without_replacing_an_unsaved_drawing() {
// Writing and opening the DWG here needs the converter in this process: each test is its own.
cadcraft_io::dwg_worker::allow_in_process();
let dir = TestDir::new();
let dxf = dir.0.join("planta com espaços.dxf");
let dwg = dir.0.join("Documentac\u{327}a\u{303}o.dwg");
let bytes = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n10\n0\nENDSEC\n0\nEOF\n";
let drawing = cadcraft_io::read(bytes, "synthetic.dxf").unwrap();
std::fs::write(&dxf, bytes).unwrap();
std::fs::write(&dwg, cadcraft_io::write(&drawing, "synthetic.dwg").unwrap()).unwrap();
let mut app = app();
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
let original = app.session.docs[0].uid;
assert!(app.session.docs[0].is_dirty());
assert!(!dispatch([Event::Open(vec![dxf.clone(), dwg.clone(), dxf.clone(), PathBuf::new()])], &mut app));
settle(&mut app);
assert_eq!(app.session.docs.len(), 3, "each file is opened once alongside the unsaved drawing");
assert_eq!(app.session.docs[0].uid, original);
assert!(app.session.docs[0].is_dirty());
for path in [&dxf, &dwg] {
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == path.to_str()));
}
}
#[test]
fn a_failed_open_reports_the_path_and_keeps_existing_drawings() {
let dir = TestDir::new();
let missing = dir.0.join("missing drawing.dwg");
let mut app = app();
let original = app.session.docs[0].uid;
assert!(!dispatch([Event::Open(vec![missing.clone()])], &mut app));
settle(&mut app);
assert_eq!(app.session.docs.len(), 1);
assert_eq!(app.session.docs[0].uid, original);
assert!(app.session.log.iter().any(|line| line.contains(missing.to_str().unwrap())));
}
#[test]
fn a_quit_event_asks_before_closing_unsaved_work_and_can_be_cancelled() {
let mut app = app();
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
assert!(!dispatch([Event::Quit], &mut app), "must not issue a window close before the answer");
assert!(app.close_prompt().is_some());
assert!(!app.quit_confirmed);
assert!(!app.quit_requested);
app.answer_close(Choice::Cancel);
assert!(app.close_prompt().is_none());
assert!(app.session.docs[0].is_dirty());
assert!(!app.quit_requested);
}
#[test]
fn a_quit_event_can_close_a_clean_session() {
let mut app = app();
assert!(dispatch([Event::Quit], &mut app));
assert!(app.close_prompt().is_none());
}
}
+2 -25
View File
@@ -14,8 +14,6 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(any(target_os = "macos", test))]
mod apple_events;
mod control_server;
mod desktop_theme;
mod env;
@@ -56,9 +54,6 @@ struct App {
/// The `movable` flag last set on the main window.
#[cfg(target_os = "macos")]
movable: Option<bool>,
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
}
impl App {
@@ -107,9 +102,6 @@ impl eframe::App for App {
}
}
}
// Drawings and quit requests from Finder, the Dock and `open -a` (macOS).
#[cfg(target_os = "macos")]
apple_events::poll(&self.apple_events, &mut self.cad, ctx);
// Consume control/open/screenshot queues and time-based autosave, including hidden ticks.
self.cad.guarded_logic(ctx);
// Host frame work runs here, once per frame, and so also on a hidden logic-only tick (which
@@ -175,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,
@@ -184,7 +177,6 @@ pub fn install_io() {
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
}
fn services() -> Services {
@@ -209,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(),
@@ -446,12 +439,6 @@ fn main() -> eframe::Result {
b.with_close_requested_on_terminate(true);
}));
}
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
let apple_events = apple_events::AppleEvents::install();
#[cfg(target_os = "macos")]
let apple_events = &apple_events;
eframe::run_native(
"CADCraft",
options,
@@ -515,14 +502,6 @@ fn main() -> eframe::Result {
for f in &files {
app.open_path(f);
}
// Start reading any launch-time documents before the first frame. Later events use
// this same inbox, including the normal unsaved-changes handling for quit requests.
#[cfg(target_os = "macos")]
let apple_events = {
let inbox = apple_events.connect(&cc.egui_ctx);
apple_events::poll(&inbox, &mut app, &cc.egui_ctx);
inbox
};
if app.session.docs.is_empty() {
// In the units the profile asks for (MEASUREINIT, restored above).
let metric = app.session.settings.measureinit;
@@ -550,8 +529,6 @@ fn main() -> eframe::Result {
menus_in_window: vars.no_native_menu == Switch::On,
#[cfg(target_os = "macos")]
movable: None,
#[cfg(target_os = "macos")]
apple_events,
}))
}),
)
-4
View File
@@ -144,10 +144,6 @@ impl NativeMenu {
self.last_refresh = now;
let typing = menus::text_field_window(ctx).is_some();
for (cmd, _, item) in self.items.values() {
// Open Recent rebuilds this item with the correct enabled state.
if cmd == menus::RECENT_CLEAR {
continue;
}
let en = (typing && menus::edits_text(cmd)) || cadcraft_engine::find_command(cmd).is_none_or(|c| (c.enabled)(&app.session).is_ok());
item.set_enabled(en);
}
-5
View File
@@ -7,11 +7,6 @@ pub struct HatchLoop {
pub vertices: Vec<PolyVertex>,
#[serde(default)]
pub outer: bool,
/// Original DXF group 92 bits. Writing keeps only Derived (4), Textbox (8) and
/// Outermost (16), derives External (1) from `outer`, and sets Polyline (2).
/// None uses the flags of a locally created loop.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub boundary_flags: Option<i64>,
/// The objects the loop was made from (DXF group 97 count, 330 handles): an associative
/// hatch re-fills the loop from them when they change.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
+2 -2
View File
@@ -37,7 +37,7 @@ pub struct RegionProps {
impl Region {
/// A region bounded by one closed loop.
pub fn from_loop(vertices: Vec<PolyVertex>) -> Region {
Region { loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }] }
Region { loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }] }
}
pub fn polylines(&self) -> Vec<Polyline> {
@@ -170,7 +170,7 @@ mod tests {
let mut vertices: Vec<PolyVertex> =
(0..n).map(|k| PolyVertex::new(Vec2::new(c - half + 2.0 * half * k as f64 / n as f64, c - half))).collect();
vertices.extend([Vec2::new(c + half, c - half), Vec2::new(c + half, c + half), Vec2::new(c - half, c + half)].map(PolyVertex::new));
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices, outer, sources: Vec::new() }
}
#[test]
-4
View File
@@ -53,10 +53,6 @@ impl ForeignExtra {
/// Everything of a file CADCraft keeps without modelling it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Foreign {
/// Original two-point text and style, by entity handle and attribute position.
/// Kept with imported metadata so new entities never inherit another entity's fitting.
pub text_fits: BTreeMap<Handle, Vec<(crate::Text, crate::TextStyle)>>,
/// CLASS records (groups after `0 CLASS`) of the kept objects' and entities' types.
pub classes: Vec<Vec<RawTag>>,
/// Classes retain every source position, including duplicate names.
+1 -1
View File
@@ -14,7 +14,7 @@ mod draw;
mod draw2;
mod draworder;
mod edit;
mod exchange;
pub mod exchange;
pub mod file;
mod gripcmds;
mod griphot;
-11
View File
@@ -39,10 +39,6 @@ fn vertex_value(v: &Value) -> Option<PolyVertex> {
Some(PolyVertex { p, bulge: f64_or(v, "bulge", 0.0), start_width: f64_or(v, "startWidth", 0.0), end_width: f64_or(v, "endWidth", 0.0) })
}
fn current_elevation(s: &Session) -> Result<f64> {
Ok(s.doc()?.header.f64("ELEVATION", 0.0))
}
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
for v in raw.into_iter().flatten() {
@@ -57,7 +53,6 @@ pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
let mut k = lwpoly(vs, bool_or(p, "closed", false));
if let EntityKind::LwPolyline(pl) = &mut k {
pl.const_width = width;
pl.elevation = current_elevation(s)?;
}
added(s.add_entity(k)?)
}
@@ -179,7 +174,6 @@ impl Interactive for LineM {
#[derive(Default)]
pub(super) struct PlineM {
verts: Vec<PolyVertex>,
elevation: f64,
arc_mode: bool,
/// Total width at the start and end of the next segment (Width / Halfwidth answers).
start_w: f64,
@@ -197,7 +191,6 @@ impl PlineM {
fn entity(&self, closed: bool) -> EntityKind {
let mut k = lwpoly(self.verts.clone(), closed);
if let EntityKind::LwPolyline(pl) = &mut k {
pl.elevation = self.elevation;
// Every segment the same uniform width: store it as the constant width, as before.
let segs = if closed { pl.vertices.len() } else { pl.vertices.len().saturating_sub(1) };
let w = pl.vertices.first().map_or(0.0, |v| v.start_width);
@@ -266,10 +259,6 @@ impl Interactive for PlineM {
fn name(&self) -> &'static str {
"PLINE"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.elevation = current_elevation(s)?;
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
if self.asking_width > 0 {
let unit = if self.half { "half-width" } else { "width" };
+1 -1
View File
@@ -232,7 +232,7 @@ impl Interactive for MTextM {
None => Prompt::new("Specify first corner", Accept::POINT),
Some(a) if !self.boxed() => Prompt::new("Specify opposite corner", Accept::POINT)
.kw(&["Height", "Justify", "Line spacing", "Rotation", "Style", "Width", "Columns"])
.corner(a),
.base(a),
_ if self.lines.is_empty() => Prompt::new("Enter text (use \\P for new paragraphs)", Accept::TEXT),
_ => Prompt::new("Enter next line of text (empty line to finish)", Accept::TEXT),
}
+165 -17
View File
@@ -1,5 +1,5 @@
//! Moving drawings in and out: EXPORT (DXF, DWG, SVG, PNG or PDF), IMPORT (the objects of another
//! DXF/DWG file), PREVIEW (a picture of the plot) and PUBLISH (plot several sheets at once).
//! DXF/DWG file or a PDF page), PREVIEW (a picture of the plot) and PUBLISH (plot several sheets at once).
//! ATTACH, SHARE and 3DORBIT are registered so the tool bar and command line say they are not
//! available yet.
//!
@@ -35,7 +35,11 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("import", "Import...", run_import)
.menu(&["File", "Import..."])
.alias(&["imp"])
.params("{path | data: base64, name?: \"x.dwg\"} (DXF or DWG), at?: [x,y] (default 0,0), scale?: (default 1) → {imported, handles, layers, styles, blocks}"),
.params("{path | data: base64, name?: \"x.dwg\"} (DXF or DWG; PDF pages can be imported too), at?: [x,y] (default 0,0), scale?: (default 1) → {imported, handles, layers, styles, blocks}"),
CommandSpec::new("pdfimport", "Import PDF...", run_pdfimport)
.menu(&["File", "Import PDF..."])
.alias(&["pdfi"])
.params("{path | data: base64, name?: \"x.pdf\", page?: 1.. (default 1), password?, at?: [x,y] (default 0,0), scale?: (default 1), text?: true, fills?: true, lineweights?: true} → {imported, handles, layers, pages, page, warnings?}: vector paths, fills and supported text become editable objects; raster images and other unsupported content are reported. A scanned PDF has no editable vector content"),
CommandSpec::new("export", "Export...", run_export)
.menu(&["File", "Export..."])
.alias(&["exp"])
@@ -135,28 +139,153 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- IMPORT ----------
fn run_import(s: &mut Session, p: &Value) -> Result<Value> {
let hooks = io().ok_or_else(|| bad("import", "file formats are not available in this build"))?;
/// A PDF page reader installed by the app that links the PDF library.
pub type PdfImportHook = fn(&[u8], &Value) -> std::result::Result<(Drawing, usize), String>;
static PDF_IMPORT: std::sync::OnceLock<PdfImportHook> = std::sync::OnceLock::new();
/// Install the PDF page reader used by OPEN, IMPORT and PDFIMPORT.
pub fn set_pdf_import(hook: PdfImportHook) {
let _ = PDF_IMPORT.set(hook);
}
fn is_pdf(bytes: &[u8]) -> bool {
bytes.starts_with(b"%PDF-")
}
/// Read a PDF's first page as a metric drawing when this host has installed a PDF reader.
pub(super) fn open_pdf(bytes: &[u8]) -> Option<std::result::Result<Drawing, String>> {
if !is_pdf(bytes) {
return None;
}
let read = PDF_IMPORT.get()?;
Some(read(bytes, &json!({ "unit": 25.4 / 72.0 })).and_then(|(drawing, _)| {
if drawing.model.is_empty() {
let notes = drawing.read_notes.join("; ");
let message = if notes.is_empty() {
"PDF page 1 has no editable vector content; scanned drawings need manual tracing".to_string()
} else {
format!("PDF page 1 has no editable vector content; scanned drawings need manual tracing. {notes}")
};
Err(message)
} else {
Ok(drawing)
}
}))
}
/// Read an import source from a path or base64 data.
fn source_file(cmd: &str, p: &Value, default_name: &str) -> Result<(Vec<u8>, String)> {
if let Some(path) = str_param(p, "path") {
return Ok((read_file(path)?, path.to_string()));
}
let data = str_param(p, "data").ok_or_else(|| bad(cmd, "`path` or `data` (base64) is required"))?;
Ok((base64_decode(data).ok_or_else(|| bad(cmd, "invalid base64"))?, str_param(p, "name").unwrap_or(default_name).to_string()))
}
/// Parse the optional insertion point and scale shared by import commands.
fn placement(cmd: &str, p: &Value) -> Result<(Vec2, f64)> {
let at = match p.get("at") {
Some(v) => point_value(v).ok_or_else(|| bad("import", "`at` must be a point [x, y]"))?,
Some(v) => point_value(v).ok_or_else(|| bad(cmd, "`at` must be a point [x, y]"))?,
None => Vec2::ZERO,
};
let scale = match p.get("scale") {
Some(v) => v
.as_f64()
.filter(|k| k.is_finite() && (1e-9..=1e9).contains(&k.abs()))
.ok_or_else(|| bad("import", "`scale` must be a non-zero number"))?,
Some(v) => {
v.as_f64().filter(|k| k.is_finite() && (1e-9..=1e9).contains(&k.abs())).ok_or_else(|| bad(cmd, "`scale` must be a non-zero number"))?
}
None => 1.0,
};
let (bytes, name) = if let Some(path) = str_param(p, "path") {
(read_file(path)?, path.to_string())
} else {
let data = str_param(p, "data").ok_or_else(|| bad("import", "`path` or `data` (base64) is required"))?;
(base64_decode(data).ok_or_else(|| bad("import", "invalid base64"))?, str_param(p, "name").unwrap_or("import.dxf").to_string())
};
Ok((at, scale))
}
fn source_name(name: &str) -> String {
std::path::Path::new(name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default()
}
fn run_import(s: &mut Session, p: &Value) -> Result<Value> {
let (at, scale) = placement("import", p)?;
let (bytes, name) = source_file("import", p, "import.dxf")?;
if is_pdf(&bytes) {
return import_pdf(s, "import", p, &bytes, &name, at, scale);
}
let hooks = io().ok_or_else(|| bad("import", "file formats are not available in this build"))?;
let src = (hooks.read)(&bytes, &name).map_err(|e| bad("import", e))?;
let file = std::path::Path::new(&name).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
import_drawing(s, &src, at, scale, &file)
import_drawing(s, &src, at, scale, &source_name(&name))
}
/// Convert millimetres to the current drawing's `$INSUNITS`.
fn units_per_mm(d: &Drawing) -> f64 {
match d.header.i64("INSUNITS", 4) {
1 => 1.0 / 25.4,
2 => 1.0 / 304.8,
3 => 1.0 / 1_609_344.0,
5 => 0.1,
6 => 0.001,
7 => 1e-6,
8 => 39_370.078_74,
9 => 39.370_078_74,
10 => 1.0 / 914.4,
11 => 1e7,
12 => 1e6,
13 => 1e3,
14 => 0.01,
15 => 1e-4,
16 => 1e-5,
17 => 1e-12,
18 => 1.0 / 1.495_978_707e14,
19 => 1.0 / 9.460_730_472_580_8e18,
20 => std::f64::consts::PI / (648_000.0 * 1.495_978_707e14),
_ => 1.0,
}
}
fn run_pdfimport(s: &mut Session, p: &Value) -> Result<Value> {
let (at, scale) = placement("pdfimport", p)?;
let (bytes, name) = source_file("pdfimport", p, "import.pdf")?;
if !is_pdf(&bytes) {
return Err(bad("pdfimport", format!("{} is not a PDF file", source_name(&name))));
}
import_pdf(s, "pdfimport", p, &bytes, &name, at, scale)
}
fn import_pdf(s: &mut Session, cmd: &str, p: &Value, bytes: &[u8], name: &str, at: Vec2, scale: f64) -> Result<Value> {
let read = PDF_IMPORT.get().ok_or_else(|| bad(cmd, "PDF import is not available in this build"))?;
let unit = 25.4 / 72.0 * units_per_mm(s.doc()?);
let mut options = serde_json::Map::new();
options.insert("unit".into(), json!(unit));
for key in ["page", "password", "text", "fills", "lineweights"] {
if let Some(value) = p.get(key) {
options.insert(key.into(), value.clone());
}
}
let (source, pages) = read(bytes, &Value::Object(options)).map_err(|e| bad(cmd, e))?;
let page = p.get("page").and_then(Value::as_u64).unwrap_or(1);
if source.model.is_empty() {
let detail = source.read_notes.join("; ");
let message = if detail.is_empty() {
"the selected PDF page has no editable vector content; scanned drawings need manual tracing".to_string()
} else {
format!("the selected PDF page has no editable vector content; scanned drawings need manual tracing. {detail}")
};
return Err(bad(cmd, message));
}
let warnings = source.read_notes.clone();
let mut result = import_drawing(s, &source, at, scale, &source_name(name))?;
if let Some(object) = result.as_object_mut() {
object.insert("pages".into(), json!(pages));
object.insert("page".into(), json!(page));
object.insert("warnings".into(), json!(warnings));
let imported = object.get("imported").and_then(Value::as_u64).unwrap_or(0);
let mut message = format!("{imported} objects imported from page {page} of {pages} of {}", source_name(name));
if !source.read_notes.is_empty() {
message.push_str(". Some PDF content was omitted or approximated. See the command history for details.");
for note in &source.read_notes {
s.echo(note.clone());
}
}
object.insert("message".into(), json!(message));
}
Ok(result)
}
/// Copy `src`'s model space into the current space (scaled about the origin, then moved to
@@ -592,6 +721,25 @@ mod tests {
s
}
fn scanned_pdf(_: &[u8], _: &Value) -> std::result::Result<(Drawing, usize), String> {
let mut drawing = Drawing::new_metric();
drawing.read_notes.push("PDF: 1 raster image was not imported".into());
Ok((drawing, 1))
}
#[test]
fn scanned_pdf_does_not_open_or_import_as_an_empty_drawing() {
set_pdf_import(scanned_pdf);
let data = base64_encode(b"%PDF-1.7 synthetic scan");
let mut s = Session::new();
let before = s.doc().unwrap().model.len();
let open = s.execute("open", &json!({ "data": data, "name": "scan.pdf" })).unwrap_err().to_string();
assert!(open.contains("no editable vector content") && open.contains("raster image"), "{open}");
let import = s.execute("pdfimport", &json!({ "data": data, "name": "scan.pdf" })).unwrap_err().to_string();
assert!(import.contains("manual tracing") && import.contains("raster image"), "{import}");
assert_eq!(s.doc().unwrap().model.len(), before, "no empty drawing was opened or imported");
}
fn temp(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("cadcraft-exchange-{}-{name}", std::process::id()))
}
+8 -18
View File
@@ -95,15 +95,6 @@ pub fn set_proxies_lost(f: ProxiesLost) {
let _ = PROXIES_LOST.set(f);
}
/// Version-specific DWG compatibility omissions, counted by the host's actual writer.
pub type DwgCompatLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
static DWG_COMPAT_LOST: OnceLock<DwgCompatLost> = OnceLock::new();
pub fn set_dwg_compat_lost(f: DwgCompatLost) {
let _ = DWG_COMPAT_LOST.set(f);
}
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
@@ -382,11 +373,16 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result<Value> {
/// Parse a drawing's bytes, and search its folder for fonts where the automation roots allow.
fn read_bytes(bytes: &[u8], name: &str, path: Option<String>) -> Result<ReadFile> {
let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?;
let drawing = (hooks.read)(bytes, name).map_err(|e| bad("open", e))?;
let drawing = match super::exchange::open_pdf(bytes) {
Some(result) => result.map_err(|e| bad("open", e))?,
None => {
let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?;
(hooks.read)(bytes, name).map_err(|e| bad("open", e))?
}
};
// A file that isn't a drawing (an imported SVG) gives the drawing no file name: QSAVE then
// asks where to save instead of exporting over the original.
let path = path.filter(|p| is_drawing_file(p));
let path = path.filter(|p| is_drawing_file(p) && !bytes.starts_with(b"%PDF-"));
// The SHX fonts its text styles name are looked for beside the drawing too.
if let Some(dir) = path.as_deref().and_then(|p| std::path::Path::new(p).parent()) {
// A bare file name is in the current folder.
@@ -932,12 +928,6 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
*n = n.saturating_add(1);
}
}
if let Some(compatibility) = DWG_COMPAT_LOST.get() {
for (kind, count) in compatibility(d, version) {
let total = out.entry(kind).or_default();
*total = total.saturating_add(count);
}
}
out
}
+4 -9
View File
@@ -232,7 +232,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
let outer = found.outer;
let ob = Bounds2::from_points(outer.iter().copied());
let sources = handles_of(&owners, &found.outer_sources);
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, sources }];
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, sources }];
// Islands: closed objects entirely inside the outer loop that don't contain the pick point.
if let Some(store) = d.space(&space) {
for e in store.iter() {
@@ -248,7 +248,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
let inside = pts.iter().all(|q| point_in_polygon(&outer, *q) || outer.iter().any(|o| o.near(*q, tol * 10.0)));
let same_as_outer = (cadcraft_geom::shoelace(&pts).abs() - cadcraft_geom::shoelace(&outer).abs()).abs() < tol.max(1e-6) * 1000.0;
if inside && !same_as_outer && !point_in_polygon(&pts, p) {
loops.push(HatchLoop { vertices: vs, outer: false, boundary_flags: None, sources: vec![e.handle] });
loops.push(HatchLoop { vertices: vs, outer: false, sources: vec![e.handle] });
}
}
}
@@ -260,12 +260,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
&& island.sources.iter().all(|&i| owners.get(i).and_then(|h| d.entity(*h)).is_some_and(|e| island_curve(d, e)));
if open_curves {
let sources = handles_of(&owners, &island.sources);
loops.push(HatchLoop {
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
outer: false,
boundary_flags: None,
sources,
});
loops.push(HatchLoop { vertices: island.outline.into_iter().map(PolyVertex::new).collect(), outer: false, sources });
}
}
Ok(loops)
@@ -276,7 +271,7 @@ pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result<Vec<Hatch
let mut loops = Vec::new();
for h in hs {
if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) {
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, sources: vec![*h] });
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), sources: vec![*h] });
}
}
if loops.is_empty() {
+1 -1
View File
@@ -197,7 +197,7 @@ fn follow(before: &Drawing, after: &Drawing, handle: Handle, h: &Hatch, checked:
match refill(from, after, l) {
Refill::Loop(vertices) => {
let sources = l.sources.iter().copied().filter(|s| exists(after, *s)).take(MAX_SOURCES).collect();
loops.push(HatchLoop { vertices, outer: l.outer, boundary_flags: l.boundary_flags, sources });
loops.push(HatchLoop { vertices, outer: l.outer, sources });
}
// An erased island: the hatch fills its area.
Refill::Erased if !l.outer => {}
@@ -41,6 +41,7 @@ pub const FILES: &[&str] = &[
"options",
"pagesetup",
"pdfbook",
"pdfimport",
"plot",
"plotstyle",
"plottermanager",
-13
View File
@@ -454,19 +454,6 @@ fn printing_many_lines_is_linear() {
assert_eq!(s.log.last().map(String::as_str), Some("a"));
}
#[test]
fn lisp_pline_keeps_current_elevation() {
let mut s = session();
ok(&mut s, r#"(setvar "ELEVATION" 800.0)"#);
ok(&mut s, r#"(command "_PLINE" '(0 0) '(1000 0) '(1000 100) "")"#);
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "800.0");
ok(&mut s, r#"(setvar "ELEVATION" -2.5)"#);
s.execute("pline", &serde_json::json!({"vertices": [[0, 0], [10, 0]], "width": 2})).unwrap();
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "-2.5");
assert_eq!(ok(&mut s, "(cdr (assoc 43 (entget (entlast))))"), "2.0");
}
#[test]
fn command_draws_and_one_routine_is_one_undo_step() {
let mut s = session();
+1 -1
View File
@@ -79,7 +79,7 @@ pub struct Prompt {
/// pick arrives as the plain point it was picked at.
pub deferred: bool,
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
/// cell): ortho does not bend the opposite corner, so the rectangle keeps its area.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub corner: bool,
/// The grip this prompt stretches (one hot grip at the STRETCH prompt), as (object, grip
+1 -1
View File
@@ -139,7 +139,7 @@ pub fn bracket() -> Drawing {
EntityKind::Hatch(Hatch {
pattern: "ANSI31".into(),
solid: false,
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, boundary_flags: None, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
+1 -2
View File
@@ -722,7 +722,7 @@ mod hatch_pattern_pick_tests {
fn square(lo: f64, hi: f64, outer: bool) -> HatchLoop {
let vertices = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices, outer, sources: Vec::new() }
}
fn ansi31_hatch(loops: Vec<HatchLoop>) -> Drawing {
@@ -788,7 +788,6 @@ mod hatch_pattern_pick_tests {
let tri = HatchLoop {
vertices: [(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(),
outer: true,
boundary_flags: None,
sources: Vec::new(),
};
let d = solid_hatch(vec![tri], 0);
-1
View File
@@ -192,7 +192,6 @@ impl Session {
}
fn script_lines(&mut self, text: &str) -> Result<()> {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
for line in text.lines() {
// Trailing spaces are inputs (Enter); other trailing whitespace (`\r`) is not.
let line = line.trim_end_matches(|c: char| c.is_whitespace() && c != ' ');
-9
View File
@@ -746,15 +746,6 @@ fn script_runs_commands() {
assert!(matches!(&t.kind, EntityKind::Text(t) if t.value == "Hello world"));
}
#[test]
fn scripts_allow_one_leading_utf8_bom() {
for text in ["\u{feff}LINE 0,0 10,10\n\n", "\u{feff}; first comment\r\nLINE 0,0 10,10\r\n\r\n"] {
let mut s = Session::new();
s.script(text).unwrap();
assert_eq!(kinds(&s), vec!["Line"]);
}
}
#[test]
fn script_splits_line_at_keyword_prompt() {
let mut s = Session::new();
+1 -24
View File
@@ -144,26 +144,6 @@ fn moving_or_copying_the_hatch_alone_ends_the_link() {
assert!(!hatch(&s, &h).associative);
}
#[test]
fn imported_boundary_flags_survive_refill_and_copy() {
let mut session = Session::new();
let boundary = handle(&session.execute("rectang", &json!({ "p1": [0, 0], "p2": [4, 2] })).unwrap());
let hatch_handle = handle(&session.execute("hatch", &json!({ "handles": [boundary.clone()] })).unwrap());
session.doc_mut().unwrap().model.modify(Handle::parse_hex(&hatch_handle).unwrap(), |entity| {
if let EntityKind::Hatch(hatch) = &mut entity.kind {
hatch.loops[0].boundary_flags = Some(7);
}
});
let expected = hatch(&session, &hatch_handle).loops[0].boundary_flags;
session.execute("move", &json!({ "handles": [boundary], "delta": [10, 0] })).unwrap();
assert_eq!(hatch(&session, &hatch_handle).loops[0].boundary_flags, expected);
let count = session.doc().unwrap().model.len();
session.execute("copy", &json!({ "handles": [hatch_handle], "delta": [30, 0] })).unwrap();
let copy = session.doc().unwrap().model.iter().skip(count).find(|entity| matches!(entity.kind, EntityKind::Hatch(_))).unwrap();
let EntityKind::Hatch(copied) = &copy.kind else { panic!("not a hatch") };
assert_eq!(copied.loops[0].boundary_flags, expected);
}
#[test]
fn non_associative_hatch_keeps_no_sources() {
let mut s = Session::new();
@@ -186,10 +166,7 @@ fn hostile_sources_never_panic() {
let k = EntityKind::Hatch(Hatch {
pattern: "ANSI31".into(),
solid: false,
loops: vec![
HatchLoop { vertices: sq, outer: true, boundary_flags: None, sources: sources.clone() },
HatchLoop { vertices: nan, outer: false, boundary_flags: None, sources },
],
loops: vec![HatchLoop { vertices: sq, outer: true, sources: sources.clone() }, HatchLoop { vertices: nan, outer: false, sources }],
scale: 1.0,
angle: 0.0,
associative: true,
-1
View File
@@ -106,7 +106,6 @@ mod mocoro;
mod modify_curves;
mod mtext_columns;
mod mtext_options;
mod mtext_ortho;
mod multiline_attributes;
mod named_viewports;
mod named_views;
-157
View File
@@ -1,157 +0,0 @@
//! MTEXT's opposite corner ignores ortho: the text box keeps its width and proportion (#3388).
use cadcraft_doc::{EntityKind, MText};
use cadcraft_engine::snap::tracking::CursorQuery;
use cadcraft_engine::{Input, Session};
use cadcraft_geom::{Bounds2, Vec2};
use serde_json::json;
/// Move the cursor to `raw` at the current prompt, as the canvas does.
fn hover(s: &mut Session, raw: Vec2) -> Vec2 {
let p = s.current_prompt().unwrap();
let q = CursorQuery { base: p.base, deferred: p.deferred, corner: p.corner, aperture: 1e-6, tol: 1e-6, now: 0.0, shift: false };
let c = s.snap_cursor(raw, &q).point;
s.cursor = c;
c
}
fn session(ortho: bool) -> Session {
let mut s = Session::new();
s.execute("setvar", &json!({ "name": "OSMODE", "value": 0 })).unwrap();
s.execute("setvar", &json!({ "name": "ORTHOMODE", "value": i32::from(ortho) })).unwrap();
s
}
fn last_mtext(s: &Session) -> MText {
match s.doc().unwrap().model.last().map(|e| e.kind.clone()) {
Some(EntityKind::MText(t)) => t,
k => panic!("no mtext: {k:?}"),
}
}
/// Place an MTEXT from `first` to a cursor click at `second`, returning the preview bounds,
/// in-place editor box `(insert, width)` and created entity `(insert, width)`.
fn click_mtext(ortho: bool, first: Vec2, second: Vec2) -> ((Vec2, Vec2), (Vec2, f64), (Vec2, f64)) {
let mut s = session(ortho);
s.cmdline(&format!("mtext {},{}", first.x, first.y)).unwrap();
let p = s.current_prompt().unwrap();
assert_eq!(p.message, "Specify opposite corner");
assert!(p.corner, "MTEXT opposite corner ignores ortho");
let c = hover(&mut s, second);
assert!(c.near(second, 1e-9), "opposite corner stays under the cursor: {c:?}");
let mut pv = Bounds2::EMPTY;
for e in s.preview(c) {
pv = pv.union(&cadcraft_doc::entity_bounds(s.doc().unwrap(), &e, 0));
}
s.input(Input::Point(c)).unwrap();
let ed = s.editing_mtext().unwrap();
s.input(Input::Text("Hello".to_string())).unwrap();
s.input(Input::Enter).unwrap();
assert!(s.current_prompt().is_none(), "MTEXT is done, still at {:?}", s.current_prompt().map(|p| p.message));
let t = last_mtext(&s);
assert_eq!(t.contents, "Hello");
((pv.min, pv.max), (ed.insert.xy(), ed.width), (t.insert.xy(), t.width))
}
#[test]
fn mtext_opposite_corner_ignores_ortho() {
let cases = [
// Wide box (dx > dy)
(Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::new(0.0, 3.0), 10.0),
// Tall box (dy > dx)
(Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::new(0.0, 10.0), 3.0),
// Opposite quadrant (negative dx and dy)
(Vec2::new(10.0, 10.0), Vec2::new(2.0, 4.0), Vec2::new(2.0, 4.0), Vec2::new(10.0, 10.0), Vec2::new(2.0, 10.0), 8.0),
];
for (first, second, min, max, insert, width) in cases {
let on = click_mtext(true, first, second);
assert!(on.0.0.near(min, 1e-9) && on.0.1.near(max, 1e-9), "preview bounds with ortho on: {:?}", on.0);
assert!(on.1.0.near(insert, 1e-9) && (on.1.1 - width).abs() < 1e-9, "editor box with ortho on: {:?}", on.1);
assert!(on.2.0.near(insert, 1e-9) && (on.2.1 - width).abs() < 1e-9, "entity box with ortho on: {:?}", on.2);
let off = click_mtext(false, first, second);
assert_eq!(off, on, "ortho changes nothing");
}
}
#[test]
fn mtext_coordinate_and_direct_distance_input_with_ortho() {
let mut s = session(true);
// Absolute coordinate input for the opposite corner.
s.cmdline("mtext 0,0").unwrap();
s.cmdline("10,3").unwrap();
let ed = s.editing_mtext().unwrap();
assert!(ed.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
assert!((ed.width - 10.0).abs() < 1e-9);
s.input(Input::Text("Abs".to_string())).unwrap();
s.input(Input::Enter).unwrap();
let t = last_mtext(&s);
assert!(t.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
assert!((t.width - 10.0).abs() < 1e-9);
// Relative coordinate input for the opposite corner.
s.cmdline("mtext 2,3").unwrap();
s.cmdline("@4,9").unwrap();
let ed = s.editing_mtext().unwrap();
assert!(ed.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
assert!((ed.width - 4.0).abs() < 1e-9);
s.input(Input::Text("Rel".to_string())).unwrap();
s.input(Input::Enter).unwrap();
let t = last_mtext(&s);
assert!(t.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
assert!((t.width - 4.0).abs() < 1e-9);
// Direct distance entry goes toward the cursor rather than along an axis.
s.cmdline("mtext 0,0").unwrap();
let c = hover(&mut s, Vec2::new(3.0, 4.0));
assert!(c.near(Vec2::new(3.0, 4.0), 1e-9));
s.cmdline("5").unwrap();
let ed = s.editing_mtext().unwrap();
assert!(ed.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
assert!((ed.width - 3.0).abs() < 1e-9);
s.input(Input::Text("Dir".to_string())).unwrap();
s.input(Input::Enter).unwrap();
let t = last_mtext(&s);
assert!(t.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
assert!((t.width - 3.0).abs() < 1e-9);
}
#[test]
fn mtext_escape_cancels_cleanly_with_ortho() {
let mut s = session(true);
// Cancel at the opposite-corner prompt.
s.cmdline("mtext 0,0").unwrap();
let c = hover(&mut s, Vec2::new(10.0, 3.0));
assert!(c.near(Vec2::new(10.0, 3.0), 1e-9));
s.cancel();
assert!(s.current_prompt().is_none());
assert!(s.editing_mtext().is_none());
assert!(s.doc().unwrap().model.is_empty());
// Cancel after picking the opposite corner (at the text prompt).
s.cmdline("mtext 0,0").unwrap();
let c = hover(&mut s, Vec2::new(10.0, 3.0));
s.input(Input::Point(c)).unwrap();
assert!(s.editing_mtext().is_some());
s.cancel();
assert!(s.current_prompt().is_none());
assert!(s.editing_mtext().is_none());
assert!(s.doc().unwrap().model.is_empty());
}
#[test]
fn line_and_pline_still_obey_ortho() {
let mut s = session(true);
s.cmdline("line 0,0").unwrap();
let p = s.current_prompt().unwrap();
assert!(!p.corner, "LINE next point is constrained by ortho");
let c = hover(&mut s, Vec2::new(10.0, 3.0));
assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps LINE horizontal: {c:?}");
s.cancel();
s.cmdline("pline 0,0").unwrap();
let p = s.current_prompt().unwrap();
assert!(!p.corner, "PLINE next point is constrained by ortho");
let c = hover(&mut s, Vec2::new(3.0, 10.0));
assert!(c.near(Vec2::new(0.0, 10.0), 1e-9), "ortho keeps PLINE vertical: {c:?}");
s.cancel();
}
@@ -22,7 +22,6 @@ fn install() {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
set_proxies_lost(cadcraft_io::proxies_lost);
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
}
/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes.
@@ -88,35 +87,6 @@ fn not_saved(r: &Value) -> Value {
r.get("notSaved").cloned().unwrap_or(Value::Null)
}
#[test]
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn legacy_visualstyles_warn_only_for_2007_dwg() {
install();
cadcraft_io::dwg_worker::allow_in_process();
let source = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1021\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic\n350\n21\n\
0\nVISUALSTYLE\n5\n21\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic\n70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\
74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n\
170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n0\nENDSEC\n0\nEOF\n";
let drawing = cadcraft_io::read_dxf(source.as_bytes()).unwrap();
let mut session = Session::empty();
session.open_drawing(drawing, "styles.dxf", None);
assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&session, "styles.dwg").get("VISUALSTYLE"), Some(&1));
for (format, version) in [("dwg", 2007), ("dwg", 2013), ("dxf", 2007)] {
let start = session.log.len();
let result = session.execute("document.bytes", &json!({"format": format, "version": version})).unwrap();
if format == "dwg" && version == 2007 {
assert_eq!(not_saved(&result), json!({"VISUALSTYLE": 1}));
assert!(session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
} else {
assert_eq!(not_saved(&result), Value::Null);
assert!(!session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
}
}
}
#[test]
fn a_proxy_no_version_writes_is_not_reported() {
install();
+21 -40
View File
@@ -649,41 +649,31 @@ fn frame(font: &TextFont, s: &str, p: &TextParams) -> (Vec2, Vec2, f64, Vec2) {
(origin, justify_offset(font, &sh, height, p.h, p.v), rot, mirror)
}
/// Resolve Aligned/Fit dimensions with the same shaping direction as [`place`].
/// Missing, coincident or nonfinite points leave the parameters unchanged.
pub fn fit_params(font: &TextFont, s: &str, p: &TextParams) -> TextParams {
let mut fitted = *p;
if !matches!(p.h, Align::Aligned | Align::Fit) {
return fitted;
}
let Some(second) = p.align_pt else { return fitted };
let distance = p.insert.dist(second);
if !distance.is_finite() || distance <= 1e-12 {
return fitted;
}
fitted.rotation = p.insert.angle_to(second);
let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
let width = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL).width;
if width.is_finite() && width > 1e-12 {
let scale = distance / width;
if p.h == Align::Aligned {
fitted.height = height * scale;
} else {
fitted.width_factor *= scale;
}
}
fitted
}
/// Place a single-line TEXT in world coordinates with any font. Returns the shaped text and its
/// bounding box.
pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) {
let fitted = fit_params(font, s, p);
let p = &fitted;
let height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
let rot = if p.rotation.is_finite() { p.rotation } else { 0.0 };
let mut height = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 };
let mut wf = p.width_factor;
let mut rot = if p.rotation.is_finite() { p.rotation } else { 0.0 };
let insert = p.insert;
let mut sh = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL);
if matches!(p.h, Align::Aligned | Align::Fit)
&& let Some(p2) = p.align_pt
{
let len = insert.dist(p2);
rot = insert.angle_to(p2);
// Measured as it is placed, left to right: the stroke font's trailing gap follows the
// glyph that ends the line.
let w = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL).width;
if w > 1e-12 && len > 1e-12 {
let k = len / w;
if p.h == Align::Aligned {
height *= k;
} else {
wf *= k;
}
}
}
let mut sh = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL);
let width = sh.width;
// Every justification but baseline-left (and aligned/fit, which span both points) is placed by
// its alignment point (DXF group 11); the insertion point (group 10) is then a computed point.
@@ -750,15 +740,6 @@ mod tests {
assert!((text.width - 10.0).abs() < 1e-9, "{}", text.width);
}
#[test]
fn two_point_middle_vertical_spans_points() {
for h in [Align::Aligned, Align::Fit] {
let p = TextParams { h, v: VAlign::Middle, align_pt: Some(Vec2::new(12.0, 5.0)), ..TextParams::new(Vec2::ZERO, 2.0) };
let (shaped, _) = place(&TextFont::Stroke, "SYNTHETIC", &p);
assert!((shaped.width - p.insert.dist(p.align_pt.unwrap())).abs() < 1e-9);
}
}
#[test]
fn every_ascii_printable_has_a_glyph() {
for c in ' '..='~' {
-4
View File
@@ -102,9 +102,6 @@ pub struct MTextLayout {
/// Geometry by colour run (strokes plus fillable glyph outlines).
pub pieces: Vec<MTextPiece>,
pub bounds: Bounds2,
/// The box of each column, in the order the text flows through them, measured like `bounds`
/// but without the gutters and to each column's own height. One column: `bounds`.
pub column_bounds: Vec<Bounds2>,
/// Plain text of each laid-out line.
pub lines: Vec<String>,
/// Whether the geometry stops short: the layout reached its allowance of retained points
@@ -734,7 +731,6 @@ pub fn layout_mtext_with(contents: &str, p: &MTextParams) -> MTextLayout {
out.bounds = Bounds2::from_points(
[Vec2::new(x0, top), Vec2::new(x0 + block_w, top), Vec2::new(x0 + block_w, top - block_h), Vec2::new(x0, top - block_h)].map(xf),
);
out.column_bounds = vec![out.bounds];
out
}
-8
View File
@@ -700,14 +700,6 @@ pub(super) fn layout(contents: &str, params: &MTextParams, base: &Fmt) -> MTextL
[Vec2::new(box_x0, top), Vec2::new(box_x0 + total_w, top), Vec2::new(box_x0 + total_w, top - block_h), Vec2::new(box_x0, top - block_h)]
.map(xf),
);
out.column_bounds = (0..n_cols)
.map(|column| {
let h = col_bottom.get(column).copied().unwrap_or(0.0).max(col_height(column));
let slot = if reversed { n_cols.saturating_sub(1).saturating_sub(column) } else { column };
let x0 = box_x0 + slot as f64 * (col_w + gutter);
Bounds2::from_points([Vec2::new(x0, top), Vec2::new(x0 + col_w, top), Vec2::new(x0 + col_w, top - h), Vec2::new(x0, top - h)].map(xf))
})
.collect();
out
}
-60
View File
@@ -109,66 +109,6 @@ fn reversed_columns_run_right_to_left() {
assert!(first > 0 && second > 0 && min_x(&l) >= 0.0);
}
/// The geometry points inside `b`.
fn points_in(l: &MTextLayout, b: &cadcraft_geom::Bounds2) -> usize {
l.strokes.iter().flatten().filter(|p| b.contains(**p)).count()
}
#[test]
fn each_column_has_its_own_box_without_the_gutter() {
let two = lay(&"word ".repeat(12), 10.0, Some(MTextColumnSpec { count: 2, gutter: 2.0, height: 6.0, ..Default::default() }));
let [a, b] = two.column_bounds.as_slice() else { panic!("{:?}", two.column_bounds) };
assert!(two.bounds.contains_box(a) && two.bounds.contains_box(b));
assert!(a.max.x < b.min.x, "the gutter lies between the columns: {a:?} {b:?}");
assert!(a.width() + b.width() < two.bounds.width());
let total = two.strokes.iter().map(Vec::len).sum::<usize>();
assert!(points_in(&two, a) > 0 && points_in(&two, b) > 0);
assert_eq!(points_in(&two, a) + points_in(&two, b), total, "every point is in its column's box");
// Three static columns, the text filling two and a half: the half-full column keeps the
// column height; text past the last column lengthens only that one.
let spec = MTextColumnSpec { count: 3, gutter: 2.0, height: 6.0, ..Default::default() };
let three = lay(&"word ".repeat(20), 10.0, Some(spec.clone()));
assert_eq!(three.column_bounds.len(), 3);
assert!(three.column_bounds.windows(2).all(|w| w[0].max.x < w[1].min.x && (w[0].height() - w[1].height()).abs() < 1e-9));
let over = lay(&"word ".repeat(40), 10.0, Some(spec));
let [first, .., last] = over.column_bounds.as_slice() else { panic!("{:?}", over.column_bounds) };
assert!(last.height() > first.height() && (last.height() - over.bounds.height()).abs() < 1e-9);
// Manual heights: each column as tall as its own height.
let manual = lay("one\\Ntwo", 5.0, Some(MTextColumnSpec { dynamic: true, heights: vec![3.0, 5.0], ..Default::default() }));
let [a, b] = manual.column_bounds.as_slice() else { panic!("{:?}", manual.column_bounds) };
assert!(a.height() < b.height());
}
#[test]
fn an_empty_column_keeps_its_place() {
let l = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 3, gutter: 1.0, height: 4.0, ..Default::default() }));
let [a, b, c] = l.column_bounds.as_slice() else { panic!("{:?}", l.column_bounds) };
assert!(a.max.x < b.min.x && b.max.x < c.min.x);
assert!(points_in(&l, a) > 0 && points_in(&l, b) > 0 && points_in(&l, c) == 0);
assert!((c.max.x - l.bounds.max.x).abs() < 1e-9 && (c.height() - a.height()).abs() < 1e-9);
// Reversed: the column the text starts in is the rightmost.
let r = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 2, height: 1.0, reversed: true, ..Default::default() }));
let [a, b] = r.column_bounds.as_slice() else { panic!("{:?}", r.column_bounds) };
assert!(a.min.x > b.max.x - 1e-9);
}
#[test]
fn one_column_is_the_whole_box() {
let rotated = |p: MTextParams| MTextParams { rotation: 0.4, attach: 5, insert: Vec2::new(3.0, -2.0), ..p };
for (s, width, columns) in [
("plain text that wraps a few times", 6.0, None),
("\\pxl1;paragraph text that wraps\\Pagain", 6.0, None),
("no width\\Pat all", 0.0, None),
(&*"word ".repeat(30), 10.0, Some(MTextColumnSpec { count: 1, gutter: 5.0, height: 3.0, ..Default::default() })),
("one\\Ptwo", 10.0, Some(MTextColumnSpec { dynamic: true, gutter: 5.0, height: 30.0, ..Default::default() })),
] {
let l = layout_mtext_with(s, &rotated(MTextParams { width, columns, ..MTextParams::new(Vec2::ZERO, 1.0) }));
assert_eq!(l.column_bounds, vec![l.bounds], "{s}");
}
}
#[test]
fn hostile_paragraph_codes_do_not_panic() {
let huge_tabs = format!("\\pt{};a\tb", (0..100_000).map(|i| i.to_string()).collect::<Vec<_>>().join(","));
+4 -2
View File
@@ -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"
-18
View File
@@ -212,7 +212,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
// Every record is placed now, and an object holding a reserved handle keeps it from new
// objects by itself. Kept, the set would be copied with every undo step of the drawing.
d.reserved_handles.clear();
remember_text_fits(&mut d);
Ok(d)
}
@@ -245,23 +244,6 @@ fn number_unknown_viewport_ids(d: &mut Drawing, sheet_dropped: &std::collections
}
}
/// Capture after all tables and entity fixups, including files whose tables follow entities.
fn remember_text_fits(d: &mut Drawing) {
let mut fits = std::collections::BTreeMap::new();
for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())) {
let texts: Vec<&Text> = match &e.kind {
EntityKind::Text(t) => vec![t],
EntityKind::AttDef(a) => vec![&a.text],
EntityKind::Insert(i) => i.attribs.iter().map(|a| &a.text).collect(),
_ => continue,
};
if texts.iter().any(|t| matches!(t.halign, HAlign::Aligned | HAlign::Fit)) {
fits.insert(e.handle, texts.into_iter().map(|t| (t.clone(), d.text_style(&t.style).cloned().unwrap_or_default())).collect());
}
}
std::sync::Arc::make_mut(&mut d.foreign).text_fits = fits;
}
/// An entity from the groups of a DXF record of type `kind` (without its `0` group), as the
/// reader makes it, with plain strings as [`crate::entity_groups`] gives them (not the file's
/// `^ ` escapes). AutoLISP's `entmake` and `entmod` are built on it.
+1 -1
View File
@@ -73,7 +73,7 @@ pub(super) fn hatch(tags: &[Tag], t: &T, curves: &mut CurvePoints) -> Option<Ent
verts.pop();
}
let sources = boundary_sources(tags, &mut i);
loops.push(HatchLoop { vertices: verts, outer, boundary_flags: Some(flags), sources });
loops.push(HatchLoop { vertices: verts, outer, sources });
}
curves.left = curves.left.saturating_sub(start_left.saturating_sub(budget.left));
if budget.cut {
+2 -3
View File
@@ -70,8 +70,7 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option<EntityKind>
let list = xdata_list(x, "REGION");
let fin = |v: &PolyVertex| v.p.is_finite() && v.bulge.is_finite();
let first_outer = list.iter().find(|t| t.code == 1070).is_none_or(|t| t.i64() != 0);
let mut loops =
vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, boundary_flags: None, sources: Vec::new() }];
let mut loops = vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, sources: Vec::new() }];
let mut total = 0usize;
let mut cur: Option<HatchLoop> = None;
let mut expect_flag = false;
@@ -82,7 +81,7 @@ pub(crate) fn from_polyline(tags: &[Tag], pl: LwPolyline) -> Option<EntityKind>
if loops.len() >= MAX_REGION_LOOPS {
break;
}
cur = Some(HatchLoop { vertices: Vec::new(), outer: false, boundary_flags: None, sources: Vec::new() });
cur = Some(HatchLoop { vertices: Vec::new(), outer: false, sources: Vec::new() });
expect_flag = true;
}
1070 if expect_flag => {
+3 -49
View File
@@ -165,56 +165,10 @@ fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::Hash
/// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG
/// version's (MULTILEADER from 2007).
pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> (String, craft_dwg::Unwritten) {
let (mut tags, kept) = sections::tags_kept_for(d, Version::R2000, dwg, false, true);
let mut unwritten = craft_dwg::Unwritten::new();
if dwg == Version::R2007 {
let omitted = legacy_visualstyles_kept(d, &kept);
if omitted != 0 {
let mut source = d.clone();
std::sync::Arc::make_mut(&mut source.foreign).objects.retain(|object| !legacy_visual_style(object));
tags = tags_for(&source, Version::R2000, dwg, false);
unwritten.insert("VISUALSTYLE".into(), omitted);
}
}
pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> String {
let mut tags = tags_for(d, Version::R2000, dwg, false);
bridge_markers(&mut tags);
(craft_dxf::write_ascii(&tags), unwritten)
}
/// Version-specific DWG compatibility omissions, counted from the actual saved view.
/// Hosts use this before saving and when reporting saves through their byte-only I/O hooks.
pub fn dwg_compat_lost(d: &Drawing, version: Version) -> craft_dwg::Unwritten {
let mut lost = craft_dwg::Unwritten::new();
if version == Version::R2007 && d.foreign.objects.iter().any(legacy_visual_style) {
let (_, kept) = sections::tags_kept_for(d, Version::R2000, version, false, true);
let omitted = legacy_visualstyles_kept(d, &kept);
if omitted != 0 {
lost.insert("VISUALSTYLE".into(), omitted);
}
}
lost
}
fn legacy_visualstyles_kept(d: &Drawing, kept: &HashSet<cadcraft_doc::Handle>) -> usize {
d.foreign.objects.iter().filter(|object| kept.contains(&object.handle) && legacy_visual_style(object)).count()
}
/// The fixed-property VISUALSTYLE layout in the 2007/2010 DXF Reference has no 176/177
/// property pairs. The bridge cannot faithfully save this layout as a 2007 DWG.
fn legacy_visual_style(object: &cadcraft_doc::foreign::ForeignObject) -> bool {
if !object.kind.trim().eq_ignore_ascii_case("VISUALSTYLE") {
return false;
}
let mut properties = object.tags.iter().skip_while(|tag| tag.code != 100 || tag.value.trim() != "AcDbVisualStyle");
properties.next();
let mut fixed = false;
for tag in properties.take_while(|tag| tag.code != 100 && tag.code < 1000) {
if matches!(tag.code, 176 | 177) {
return false;
}
fixed |= matches!(tag.code, 40 | 71);
}
fixed
craft_dxf::write_ascii(&tags)
}
/// Proxy type names and lookup-parameter subclass names must match the bridge reader's spelling.
+1 -62
View File
@@ -254,69 +254,8 @@ fn computed_text_insert(d: &Drawing, t: &Text) -> Vec3 {
if q.is_finite() { Vec3::new(q.x, q.y, t.insert.z) } else { t.insert }
}
fn relative_match(a: f64, b: f64) -> bool {
a.is_finite() && b.is_finite() && (a - b).abs() <= 1e-9 * a.abs().max(b.abs())
}
// A fitted dimension depends on the point distance, independently of position and direction.
fn imported_fit_scale(original: &Text, current: &Text) -> Option<f64> {
let (Some(first), Some(second)) = (original.align_pt, current.align_pt) else {
return None;
};
let before = original.insert.xy().dist(first.xy());
let after = current.insert.xy().dist(second.xy());
if !before.is_finite() || !after.is_finite() || before <= 0.0 || after <= 0.0 {
return None;
}
if relative_match(before, after) {
return Some(1.0);
}
let scale = after / before;
(scale.is_finite() && scale > 0.0).then_some(scale)
}
/// `attdef_prompt` is `Some` for an ATTDEF (its prompt, which may be empty) and `None` for an ATTRIB.
pub(super) fn text_tags(
w: &mut W,
d: &Drawing,
t: &Text,
attrib: Option<(&Attrib, Version)>,
attdef_prompt: Option<&str>,
source: (cadcraft_doc::Handle, usize),
) {
let fitted;
let t = if matches!(t.halign, HAlign::Aligned | HAlign::Fit) {
let mut resolved = t.clone();
// Imported dimensions use the originating font's measurements. A substituted font
// must not replace them while the fitting inputs still match the read-time snapshot.
if let Some((original, style)) = d.foreign.text_fits.get(&source.0).and_then(|texts| texts.get(source.1))
&& original.value == t.value
&& let Some(scale) = imported_fit_scale(original, t)
&& original.style == t.style
&& *style == d.text_style(&t.style).cloned().unwrap_or_default()
&& original.halign == t.halign
&& original.valign == t.valign
&& original.oblique == t.oblique
&& original.width_factor == t.width_factor
&& (t.halign != HAlign::Fit || relative_match(t.height, original.height * scale))
{
if t.halign == HAlign::Aligned && !t.value.is_empty() {
resolved.height = original.height * scale;
}
if let Some(second) = t.align_pt {
let distance = t.insert.xy().dist(second.xy());
if distance.is_finite() && distance > 1e-12 {
resolved.rotation = t.insert.xy().angle_to(second.xy());
}
}
} else {
resolved = cadcraft_render::fitted_text_entity(d, t, &t.value);
}
fitted = resolved;
&fitted
} else {
t
};
pub(super) fn text_tags(w: &mut W, d: &Drawing, t: &Text, attrib: Option<(&Attrib, Version)>, attdef_prompt: Option<&str>) {
let attdef = attdef_prompt.is_some();
// An attribute definition with no default value is drawn as its tag, whatever its prompt: the
// baseline start AutoCAD stored is judged against the tag's width too. A stored point that is
+5 -5
View File
@@ -292,7 +292,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo
w.s(0, "TEXT");
common(w, e, owner, paper, "AcDbText");
thickness(w, e);
text_tags(w, d, t, None, None, (e.handle, 0));
text_tags(w, d, t, None, None);
}
// Closed polylines, one per loop (`dxf_region`): REGION's own data is ACIS.
EntityKind::Region(r) => {
@@ -312,7 +312,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo
EntityKind::AttDef(a) => {
w.s(0, "ATTDEF");
common(w, e, owner, paper, "AcDbText");
text_tags(w, d, &a.text, Some((a, cx.target)), Some(&a.prompt), (e.handle, 0));
text_tags(w, d, &a.text, Some((a, cx.target)), Some(&a.prompt));
if cx.target >= Version::R2007 {
multiline_tags(w, a, true);
}
@@ -372,7 +372,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
w.f(45, i.row_spacing);
}
if !i.attribs.is_empty() {
for (index, a) in i.attribs.iter().enumerate() {
for a in &i.attribs {
let ah = w.h();
w.s(0, "ATTRIB");
w.s(5, ah);
@@ -385,7 +385,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
w.i(60, 1);
}
w.s(100, "AcDbText");
text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index));
text_tags(w, d, &a.text, Some((a, cx.target)), None);
if cx.target >= Version::R2007 {
multiline_tags(w, a, false);
}
@@ -627,7 +627,7 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
w.i(71, i64::from(h.associative));
w.i(91, h.loops.len() as i64);
for l in &h.loops {
w.i(92, 2 | i64::from(l.outer) | (l.boundary_flags.unwrap_or(0) & (4 | 8 | 16)));
w.i(92, 2 | if l.outer { 1 } else { 0 });
let has_bulge = l.vertices.iter().any(|v| v.bulge != 0.0);
w.i(72, i64::from(has_bulge));
w.i(73, 1);
+1 -3
View File
@@ -26,7 +26,6 @@ const HEADER_VARS: &[(&str, i32)] = &[
("CELTSCALE", 40),
("DIMSCALE", 40),
("DIMSTYLE", 2),
("DIMASSOC", 280),
("LUNITS", 70),
("LUPREC", 70),
("AUNITS", 70),
@@ -125,7 +124,6 @@ fn dim_header_vars(w: &mut W, d: &Drawing) {
}
}
/// Write modelled HEADER variables with their declared DXF group types, then dimension style variables.
pub(super) fn header_vars(w: &mut W, d: &Drawing) {
for (name, code) in HEADER_VARS {
let Some(v) = d.header.get(name) else { continue };
@@ -155,7 +153,7 @@ pub(super) fn header_vars(w: &mut W, d: &Drawing) {
w.f(c, f);
}
}
(c @ (62 | 70 | 280 | 290 | 370), v) => {
(c @ (62 | 70 | 290 | 370), v) => {
if let Some(i) = v.as_i64() {
w.s(9, format!("${name}"));
w.i(c, i);
+3 -11
View File
@@ -411,28 +411,22 @@ struct LayoutWriteData<'a> {
ucs: Option<&'a Ucs>,
/// The layout's limits as read (`None`: the default 0,0 to 12,9).
limits: Option<(Vec2, Vec2)>,
/// Whether this is the Model layout (block record *Model_Space).
model: bool,
}
/// The plot layout flags (AcDbPlotSettings group 70) for `page`. The bits CADCraft models come
/// from the page: 2 display plot styles, 4 centred, 128 lineweights, and 16 standard scale where
/// the scale decides it (scaled to fit: set; a custom scale: clear). The rest are kept as the file
/// had them (#3227); a page CADCraft made gets 512 (plot paper space last) and 32 (plot with plot
/// styles), and 16 when its scale is standard. 1024 ("ModelType", DXF Reference, PLOTSETTINGS
/// group 70) follows the layout: set for the Model layout, cleared for a paper-space layout even
/// when the file had it, since it would mark that layout as model space.
fn plot_layout_flags(page: &PageSetup, standard: bool, model: bool) -> i64 {
/// styles), and 16 when its scale is standard.
fn plot_layout_flags(page: &PageSetup, standard: bool) -> i64 {
const MODELED: i64 = 2 | 4 | 128;
const STANDARD_SCALE: i64 = 16;
const MODEL_TYPE: i64 = 1024;
let kept = match page.file_plot_flags {
Some(f) if page.scale_to_fit => (f & !MODELED) | STANDARD_SCALE,
Some(f) if !standard => f & !MODELED & !STANDARD_SCALE,
Some(f) => f & !MODELED,
None => 512 | 32 | if standard { STANDARD_SCALE } else { 0 },
};
let kept = if model { kept | MODEL_TYPE } else { kept & !MODEL_TYPE };
kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 }
}
@@ -452,7 +446,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
// The file's standard scale (such as 1:50) while the scale is still the one read with it.
let file_standard = page.file_standard_scale.filter(|&(_, s)| !page.scale_to_fit && s == scale).map(|(code, _)| code);
let standard = page.scale_to_fit || scale == 1.0 || file_standard.is_some();
let plot_flags = plot_layout_flags(page, standard, data.model);
let plot_flags = plot_layout_flags(page, standard);
let plot_type = match page.plot_area.as_str() {
"display" => 0,
"extents" => 1,
@@ -616,7 +610,6 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
view: None,
ucs: None,
limits: None,
model: true,
},
);
for (i, (_, brh, l)) in ps_brs.iter().enumerate() {
@@ -634,7 +627,6 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
view: l.view,
ucs: l.ucs.as_ref(),
limits: l.limits,
model: false,
},
);
}
+5 -9
View File
@@ -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;
@@ -37,7 +38,7 @@ pub use cadcraft_doc::Format;
pub use craft_dxf::Version;
pub use dxf_raw::{ObjectRecord, object_records};
pub use dxf_read::entity_from_groups;
pub use dxf_write::{dwg_compat_lost, entity_groups, proxies_lost};
pub use dxf_write::{entity_groups, proxies_lost};
pub use pdf::{PdfOptions, pdf, plot};
/// How a drawing is saved as DXF or DWG.
@@ -164,13 +165,8 @@ pub fn write_noted(d: &Drawing, name: impl AsRef<Path>, opts: &SaveOptions) -> R
/// file they came from (`Foreign::version`, not `$ACADVER`, which SAVEAS changes), and the bridge
/// reads them as that version.
fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec<u8>, craft_dwg::Unwritten)> {
let (bridge, omitted) = dxf_write::dwg_bridge(d, version);
let (bytes, mut unwritten) = craft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(dwg_error)?;
for (kind, omitted) in omitted {
let count = unwritten.entry(kind).or_default();
*count = count.saturating_add(omitted);
}
Ok((bytes, unwritten))
let bridge = dxf_write::dwg_bridge(d, version);
craft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(dwg_error)
}
/// Like [`write`], but image formats (PNG, SVG, PDF) show `window` (a model-space rectangle in
File diff suppressed because it is too large Load Diff
+569
View File
@@ -0,0 +1,569 @@
//! Preserve the PDF fill rule when PDF paths become CAD hatch boundaries.
//!
//! Hatch rendering uses even-odd parity. A nonzero PDF fill whose contours neither cross nor touch
//! keeps the contours where the winding number changes between zero and non-zero, so its loops
//! and bulge arcs survive import. Crossing contours are resolved into disjoint triangles by
//! Lyon's tessellator.
use cadcraft_doc::HatchLoop;
use cadcraft_geom::{PolyVertex, Vec2};
use craft_pdf::interpret::FillRule;
use lyon_tessellation::geometry_builder::{FillGeometryBuilder, GeometryBuilder, GeometryBuilderError};
use lyon_tessellation::math::point;
use lyon_tessellation::path::Path;
use lyon_tessellation::{FillOptions, FillTessellator, FillVertex, VertexId};
/// Work charged to input sampling and containment checks.
const MAX_WORK: usize = 20_000_000;
/// Bounding-box tests between contours before a fill is refused.
const MAX_BOX_CHECKS: usize = 50_000_000;
/// Edge pairs compared when looking for crossings; past this a nonzero fill is tessellated.
const MAX_EDGE_PAIRS: usize = 20_000_000;
/// Sampled points above which a nonzero fill is tessellated without looking for crossings.
const MAX_TOPOLOGY_POINTS: usize = 1_000_000;
/// Lyon uses `f32`; work in a local frame and refuse a fill wider than this many tolerances.
const MAX_SPAN_OVER_TOLERANCE: f64 = 5.0e7;
/// Most points one bulge arc is sampled into.
const MAX_ARC_STEPS: usize = 10_000;
/// Convert PDF boundaries to hatch boundaries that keep the PDF's fill rule.
///
/// `max_vertices` covers sampled input points and output triangle vertices. `tolerance` is how far,
/// in drawing units, a sampled arc may leave the real one. Even-odd loops and nonzero loops that
/// don't cross retain their original curves. Crossing nonzero contours are tessellated into
/// disjoint triangles, each represented by one hatch loop.
pub(super) fn normalize(mut loops: Vec<HatchLoop>, rule: FillRule, max_vertices: usize, tolerance: f64) -> Result<Vec<HatchLoop>, &'static str> {
if loops.is_empty() {
return Ok(loops);
}
if !tolerance.is_finite() || tolerance <= 0.0 {
return Err("PDF fill tolerance is not usable");
}
let mut work = 0usize;
let mut sampled = 0usize;
let mut polygons = Vec::new();
for loop_ in &loops {
let polygon = flatten_loop(loop_, tolerance, &mut work, max_vertices.saturating_sub(sampled))?;
sampled = sampled.checked_add(polygon.len()).ok_or("PDF fill exceeds vertex limit")?;
polygons.push(polygon);
}
match rule {
FillRule::EvenOdd => {
let probes: Vec<Vec2> = polygons.iter().map(|p| interior_probe(p)).collect();
let mut depth = vec![0usize; loops.len()];
containment(&polygons, &probes, &mut work, |i, _| depth[i] += 1)?;
for (loop_, depth) in loops.iter_mut().zip(depth) {
loop_.outer = depth.is_multiple_of(2);
}
Ok(loops)
}
FillRule::NonZero if sampled > MAX_TOPOLOGY_POINTS || edges_meet(&polygons).unwrap_or(true) => {
tessellate_nonzero(&polygons, sampled, max_vertices, tolerance)
}
FillRule::NonZero => {
let sign: Vec<i64> = polygons
.iter()
.map(|p| {
let area = signed_area(p);
if p.len() < 3 || area == 0.0 { 0 } else { area.signum() as i64 }
})
.collect();
// No two contours meet, so a contour lies inside another exactly when a point of its
// own boundary does.
let probes: Vec<Vec2> = polygons.iter().map(|p| longest_edge(p).map_or(Vec2::ZERO, |(a, b)| (a + b) * 0.5)).collect();
// The winding number just inside each contour.
let mut winding = sign.clone();
containment(&polygons, &probes, &mut work, |i, j| winding[i] += sign[j])?;
// A contour bounds the fill where the winding number changes between zero and non-zero.
let keep: Vec<bool> = winding.iter().zip(&sign).map(|(&w, &s)| s != 0 && (w != 0) != (w - s != 0)).collect();
let mut depth = vec![0usize; loops.len()];
containment(&polygons, &probes, &mut work, |i, j| {
if keep[i] && keep[j] {
depth[i] += 1;
}
})?;
Ok(loops
.into_iter()
.enumerate()
.filter(|(i, _)| keep[*i])
.map(|(i, mut loop_)| {
loop_.outer = depth[i].is_multiple_of(2);
loop_
})
.collect())
}
}
}
fn flatten_loop(loop_: &HatchLoop, tolerance: f64, work: &mut usize, max_vertices: usize) -> Result<Vec<Vec2>, &'static str> {
let n = loop_.vertices.len();
// Two vertices enclose an area only through an arc.
if n < 2 || (n == 2 && loop_.vertices.iter().all(|v| v.bulge.abs() < 1e-12)) {
return Ok(Vec::new());
}
let mut points = Vec::new();
for i in 0..n {
let vertex = loop_.vertices[i];
if !vertex.p.is_finite() || !vertex.bulge.is_finite() {
return Err("PDF fill contains invalid coordinates");
}
push_bounded(&mut points, vertex.p, max_vertices)?;
let next = loop_.vertices[(i + 1) % n].p;
if vertex.bulge.abs() < 1e-12 || vertex.p == next {
continue;
}
// A polyline bulge is tan(sweep/4). Sampling is used only for containment and lyon's
// topology. Even-odd output keeps the original circular arc vertices.
let dx = next.x - vertex.p.x;
let dy = next.y - vertex.p.y;
let bulge = vertex.bulge;
let center = Vec2::new(
(vertex.p.x + next.x) * 0.5 - dy * (1.0 - bulge * bulge) / (4.0 * bulge),
(vertex.p.y + next.y) * 0.5 + dx * (1.0 - bulge * bulge) / (4.0 * bulge),
);
let start = (vertex.p.y - center.y).atan2(vertex.p.x - center.x);
let sweep = 4.0 * bulge.atan();
let radius = vertex.p.dist(center);
if !radius.is_finite() {
return Err("PDF fill contains invalid coordinates");
}
let max_angle = if radius <= tolerance { std::f64::consts::TAU } else { 2.0 * (1.0 - tolerance / radius).clamp(-1.0, 1.0).acos() };
let steps = (sweep.abs() / max_angle.max(1e-12)).ceil().max(1.0) as usize;
if steps > MAX_ARC_STEPS {
return Err("PDF fill arc exceeds sampling limit");
}
for step in 1..steps {
let angle = start + sweep * step as f64 / steps as f64;
let point = Vec2::new(center.x + radius * angle.cos(), center.y + radius * angle.sin());
if !point.is_finite() {
return Err("PDF fill contains invalid coordinates");
}
push_bounded(&mut points, point, max_vertices)?;
}
}
*work = work.checked_add(points.len()).ok_or("PDF fill exceeds work limit")?;
if *work > MAX_WORK {
return Err("PDF fill exceeds work limit");
}
Ok(points)
}
fn push_bounded(points: &mut Vec<Vec2>, point: Vec2, max_vertices: usize) -> Result<(), &'static str> {
if points.len() >= max_vertices {
return Err("PDF fill exceeds vertex limit");
}
points.push(point);
Ok(())
}
/// Call `found(i, j)` for each contour `j` that contains `probes[i]`, the point standing for contour `i`.
fn containment(polygons: &[Vec<Vec2>], probes: &[Vec2], work: &mut usize, mut found: impl FnMut(usize, usize)) -> Result<(), &'static str> {
let boxes: Vec<(Vec2, Vec2)> = polygons.iter().map(|p| bounds(p)).collect();
let mut checks = 0usize;
for (i, polygon) in polygons.iter().enumerate() {
if polygon.len() < 3 {
continue;
}
let probe = probes[i];
for (j, other) in polygons.iter().enumerate() {
if i == j || other.len() < 3 {
continue;
}
checks += 1;
if checks > MAX_BOX_CHECKS {
return Err("PDF fill exceeds work limit");
}
let (lo, hi) = boxes[j];
if probe.x < lo.x || probe.x > hi.x || probe.y < lo.y || probe.y > hi.y {
continue;
}
*work = work.checked_add(other.len()).ok_or("PDF fill exceeds work limit")?;
if *work > MAX_WORK {
return Err("PDF fill exceeds work limit");
}
if contains(other, probe) {
found(i, j);
}
}
}
Ok(())
}
fn bounds(points: &[Vec2]) -> (Vec2, Vec2) {
let first = points.first().copied().unwrap_or(Vec2::ZERO);
points.iter().fold((first, first), |(lo, hi), p| (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))))
}
/// Whether two contours cross or touch, or one crosses, touches or folds back on itself. `None`
/// when the search would compare more than [`MAX_EDGE_PAIRS`] edge pairs.
fn edges_meet(polygons: &[Vec<Vec2>]) -> Option<bool> {
let rings: Vec<Vec<Vec2>> = polygons
.iter()
.map(|p| {
let mut ring: Vec<Vec2> = Vec::with_capacity(p.len());
for &q in p {
if ring.last() != Some(&q) {
ring.push(q);
}
}
while ring.len() > 1 && ring.first() == ring.last() {
ring.pop();
}
ring
})
.collect();
let edge = |r: usize, k: usize| (rings[r][k], rings[r][(k + 1) % rings[r].len()]);
// Each edge by its smallest x, so only edges whose x ranges overlap are compared.
let mut edges: Vec<(f64, usize, usize)> = Vec::new();
for (r, ring) in rings.iter().enumerate() {
if ring.len() < 3 {
continue;
}
for k in 0..ring.len() {
let (a, b) = edge(r, k);
edges.push((a.x.min(b.x), r, k));
}
}
edges.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut pairs = 0usize;
for (n, &(_, r, k)) in edges.iter().enumerate() {
let (a, b) = edge(r, k);
let right = a.x.max(b.x);
for &(left, s, m) in &edges[n + 1..] {
if left > right {
break;
}
pairs += 1;
if pairs > MAX_EDGE_PAIRS {
return None;
}
let (c, d) = edge(s, m);
if a.y.max(b.y) < c.y.min(d.y) || c.y.max(d.y) < a.y.min(b.y) {
continue;
}
if r == s {
let len = rings[r].len();
// Neighbouring edges share a vertex; they only meet elsewhere by folding back.
if (k + 1) % len == m {
if folds_back(a, b, d) {
return Some(true);
}
continue;
}
if (m + 1) % len == k {
if folds_back(c, d, b) {
return Some(true);
}
continue;
}
}
if segments_meet(a, b, c, d) {
return Some(true);
}
}
}
Some(false)
}
/// Whether the path a to b to c turns straight back over itself at b.
fn folds_back(a: Vec2, b: Vec2, c: Vec2) -> bool {
(b - a).cross(c - b) == 0.0 && (b.x - a.x) * (c.x - b.x) + (b.y - a.y) * (c.y - b.y) < 0.0
}
/// Whether the closed segments a to b and c to d share a point.
fn segments_meet(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> bool {
let side = |p: Vec2, q: Vec2, r: Vec2| (q - p).cross(r - p);
let within = |p: Vec2, q: Vec2, r: Vec2| r.x >= p.x.min(q.x) && r.x <= p.x.max(q.x) && r.y >= p.y.min(q.y) && r.y <= p.y.max(q.y);
let (d1, d2, d3, d4) = (side(c, d, a), side(c, d, b), side(a, b, c), side(a, b, d));
if ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0)) && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0)) {
return true;
}
(d1 == 0.0 && within(c, d, a)) || (d2 == 0.0 && within(c, d, b)) || (d3 == 0.0 && within(a, b, c)) || (d4 == 0.0 && within(a, b, d))
}
/// Find a point slightly inside the longest edge. The scan across edges handles concave loops
/// without relying on their vertex average being inside.
fn interior_probe(polygon: &[Vec2]) -> Vec2 {
let area = signed_area(polygon);
let sign = if area >= 0.0 { 1.0 } else { -1.0 };
let Some((a, b)) = longest_edge(polygon) else { return Vec2::ZERO };
let edge = b - a;
let len = edge.len().max(1e-30);
let mut epsilon = (len * 1e-6).max(1e-12);
for _ in 0..32 {
let probe = Vec2::new((a.x + b.x) * 0.5 - sign * edge.y / len * epsilon, (a.y + b.y) * 0.5 + sign * edge.x / len * epsilon);
if contains(polygon, probe) {
return probe;
}
epsilon *= 0.5;
}
Vec2::new((a.x + b.x) * 0.5, (a.y + b.y) * 0.5)
}
fn longest_edge(polygon: &[Vec2]) -> Option<(Vec2, Vec2)> {
polygon
.iter()
.copied()
.zip(polygon.iter().copied().cycle().skip(1))
.take(polygon.len())
.max_by(|(a, b), (c, d)| a.dist(*b).total_cmp(&c.dist(*d)))
}
fn signed_area(polygon: &[Vec2]) -> f64 {
polygon.iter().zip(polygon.iter().cycle().skip(1)).take(polygon.len()).map(|(a, b)| a.x * b.y - b.x * a.y).sum::<f64>() * 0.5
}
fn contains(polygon: &[Vec2], point: Vec2) -> bool {
let mut inside = false;
for (a, b) in polygon.iter().zip(polygon.iter().cycle().skip(1)).take(polygon.len()) {
if (a.y > point.y) != (b.y > point.y) && point.x < (b.x - a.x) * (point.y - a.y) / (b.y - a.y) + a.x {
inside = !inside;
}
}
inside
}
fn tessellate_nonzero(polygons: &[Vec<Vec2>], sampled_vertices: usize, max_vertices: usize, tolerance: f64) -> Result<Vec<HatchLoop>, &'static str> {
let Some(origin) = polygons.iter().flatten().next().copied() else { return Ok(Vec::new()) };
let (min, max) = polygons
.iter()
.flatten()
.fold((origin, origin), |(lo, hi), p| (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))));
let span = tolerance * MAX_SPAN_OVER_TOLERANCE;
if max.x - min.x > span || max.y - min.y > span {
return Err("PDF fill is too large for stable vector conversion");
}
let mut path = Path::builder();
for polygon in polygons {
let Some(first) = polygon.first() else { continue };
path.begin(point((first.x - origin.x) as f32, (first.y - origin.y) as f32));
for p in polygon.iter().skip(1) {
path.line_to(point((p.x - origin.x) as f32, (p.y - origin.y) as f32));
}
path.end(true);
}
let mut output = CappedGeometry::new(max_vertices.saturating_sub(sampled_vertices));
FillTessellator::new().tessellate_path(&path.build(), &FillOptions::non_zero(), &mut output).map_err(|_| "PDF fill tessellation failed")?;
if output.exceeded || output.indices.len().checked_add(sampled_vertices).is_none_or(|n| n > max_vertices) {
return Err("PDF fill exceeds vertex limit");
}
if !output.indices.len().is_multiple_of(3) {
return Err("PDF fill tessellation returned invalid triangles");
}
output
.indices
.as_chunks::<3>()
.0
.iter()
.map(|triangle| {
let vertices = triangle
.iter()
.map(|&index| {
output
.vertices
.get(index as usize)
.copied()
.map(|p| PolyVertex::new(Vec2::new(p.x + origin.x, p.y + origin.y)))
.ok_or("PDF fill tessellation returned an invalid index")
})
.collect::<Result<Vec<_>, _>>()?;
Ok(HatchLoop { vertices, outer: true, sources: Vec::new() })
})
.collect()
}
/// Lyon's triangle callback cannot report a capacity error. This builder caps both buffers and
/// records rejected triangles so extraction remains bounded even for pathological intersections.
struct CappedGeometry {
vertices: Vec<Vec2>,
indices: Vec<u32>,
limit: usize,
exceeded: bool,
}
impl CappedGeometry {
fn new(limit: usize) -> Self {
Self { vertices: Vec::new(), indices: Vec::new(), limit, exceeded: false }
}
}
impl GeometryBuilder for CappedGeometry {
fn add_triangle(&mut self, a: VertexId, b: VertexId, c: VertexId) {
if self.indices.len().saturating_add(3) > self.limit {
self.exceeded = true;
return;
}
self.indices.extend([a.0, b.0, c.0]);
}
}
impl FillGeometryBuilder for CappedGeometry {
fn add_fill_vertex(&mut self, vertex: FillVertex<'_>) -> Result<VertexId, GeometryBuilderError> {
if self.vertices.len() >= self.limit {
self.exceeded = true;
return Err(GeometryBuilderError::TooManyVertices);
}
let id = u32::try_from(self.vertices.len()).map_err(|_| GeometryBuilderError::TooManyVertices)?;
let p = vertex.position();
self.vertices.push(Vec2::new(f64::from(p.x), f64::from(p.y)));
Ok(VertexId(id))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn polygon(points: &[(f64, f64)]) -> HatchLoop {
HatchLoop { vertices: points.iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(), outer: false, sources: Vec::new() }
}
fn square(x0: f64, y0: f64, x1: f64, y1: f64, clockwise: bool) -> HatchLoop {
let points = if clockwise { vec![(x0, y0), (x0, y1), (x1, y1), (x1, y0)] } else { vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1)] };
polygon(&points)
}
/// The arc tolerance of a drawing in millimetres.
const TOL: f64 = 0.02;
fn filled(loops: &[HatchLoop], point: Vec2) -> bool {
loops.iter().filter(|l| contains(&l.vertices.iter().map(|v| v.p).collect::<Vec<_>>(), point)).count() % 2 == 1
}
/// A circle about the origin as four quarter arcs.
fn circle(r: f64, clockwise: bool) -> HatchLoop {
let quarter = (std::f64::consts::PI / 8.0).tan();
let turn = if clockwise { -1.0 } else { 1.0 };
HatchLoop {
vertices: [(r, 0.0), (0.0, r * turn), (-r, 0.0), (0.0, -r * turn)]
.iter()
.map(|&(x, y)| PolyVertex { bulge: quarter * turn, ..PolyVertex::new(Vec2::new(x, y)) })
.collect(),
outer: false,
sources: Vec::new(),
}
}
#[test]
fn a_small_circle_keeps_its_curve_when_tessellated_in_a_large_unit() {
// A circle of radius 5 mm in a drawing in metres, crossed by a bar so the fill is
// tessellated. Its arcs are sampled to the given tolerance, not cut to their four vertices.
let r = 0.005;
let metres = 0.02 * 25.4 / 72.0 / 1000.0;
let bar = square(0.5 * r, -0.2 * r, 2.0 * r, 0.2 * r, false);
let result = normalize(vec![circle(r, false), bar], FillRule::NonZero, 100_000, metres).expect("valid contours");
assert!(result.len() > 3, "tessellated into triangles");
assert!(filled(&result, Vec2::new(0.65 * r, 0.65 * r)), "the arc between two vertices stays filled");
}
#[test]
fn a_disc_of_two_half_circles_is_kept() {
let half = |x: f64| PolyVertex { bulge: 1.0, ..PolyVertex::new(Vec2::new(x, 0.0)) };
let disc = HatchLoop { vertices: vec![half(-1.0), half(1.0)], outer: false, sources: Vec::new() };
for rule in [FillRule::EvenOdd, FillRule::NonZero] {
let result = normalize(vec![disc.clone()], rule, 10_000, TOL).expect("valid contour");
assert_eq!(result.len(), 1);
assert!(result[0].outer);
assert_eq!(result[0].vertices, disc.vertices, "the arcs are kept");
}
}
#[test]
fn nonzero_contour_hugging_its_parents_edge_keeps_the_fill() {
// The inner square runs 1e-7 from the outer one's left edge, closer than a point nudged
// inside that edge: each contour is placed by a point of its own boundary.
let input = vec![square(0.0, 0.0, 10.0, 10.0, false), square(1e-7, 4.0, 1.0, 6.0, false)];
let result = normalize(input, FillRule::NonZero, 1000, TOL).expect("valid contours");
assert!(filled(&result, Vec2::new(5.0, 5.0)) && filled(&result, Vec2::new(0.5, 5.0)), "{result:?}");
assert!(result.iter().all(|l| l.vertices.len() == 4), "kept as drawn, not split into triangles");
}
#[test]
fn even_odd_disconnected_contours_are_both_outer() {
let input = vec![square(0.0, 0.0, 2.0, 2.0, false), square(4.0, 0.0, 6.0, 2.0, false)];
let result = normalize(input, FillRule::EvenOdd, 100, TOL).expect("valid contours");
assert!(result.iter().all(|loop_| loop_.outer));
assert!(filled(&result, Vec2::new(1.0, 1.0)));
assert!(filled(&result, Vec2::new(5.0, 1.0)));
}
#[test]
fn nonzero_nested_same_direction_contours_keep_the_center_filled() {
let result = normalize(vec![square(0.0, 0.0, 10.0, 10.0, false), square(2.0, 2.0, 8.0, 8.0, false)], FillRule::NonZero, 1000, TOL)
.expect("valid contours");
assert!(filled(&result, Vec2::new(5.0, 5.0)));
assert!(filled(&result, Vec2::new(1.0, 1.0)));
assert!(result.iter().all(|l| l.vertices.len() == 4), "the outer square is kept, not split into triangles");
}
#[test]
fn nonzero_nested_opposite_direction_contours_leave_a_hole() {
let result = normalize(vec![square(0.0, 0.0, 10.0, 10.0, false), square(2.0, 2.0, 8.0, 8.0, true)], FillRule::NonZero, 1000, TOL)
.expect("valid contours");
assert!(!filled(&result, Vec2::new(5.0, 5.0)));
assert!(filled(&result, Vec2::new(1.0, 1.0)));
assert!(result.iter().all(|l| l.vertices.len() == 4), "both squares are kept as drawn");
assert!(result.iter().any(|l| l.outer) && result.iter().any(|l| !l.outer));
}
#[test]
fn nonzero_concave_contour_stays_one_loop() {
let points = [(0.0, 0.0), (10.0, 0.0), (10.0, 3.0), (3.0, 3.0), (3.0, 10.0), (0.0, 10.0)];
let result = normalize(vec![polygon(&points)], FillRule::NonZero, 1000, TOL).expect("valid contour");
assert_eq!(result.len(), 1);
assert_eq!(result[0].vertices, polygon(&points).vertices);
assert!(result[0].outer);
}
#[test]
fn nonzero_curved_nested_contours_keep_their_arcs() {
// Circles of radius 10 and 5, wound opposite ways.
let result = normalize(vec![circle(10.0, false), circle(5.0, true)], FillRule::NonZero, 10_000, TOL).expect("valid contours");
assert_eq!(result.len(), 2);
assert!(result.iter().all(|l| l.vertices.iter().all(|v| v.bulge != 0.0)), "the arcs are kept");
}
#[test]
fn nonzero_overlapping_contours_keep_the_overlap_filled() {
let result = normalize(vec![square(0.0, 0.0, 6.0, 6.0, false), square(3.0, 0.0, 9.0, 6.0, false)], FillRule::NonZero, 1000, TOL)
.expect("valid contours");
assert!(filled(&result, Vec2::new(4.0, 3.0)));
assert!(filled(&result, Vec2::new(1.0, 3.0)));
assert!(filled(&result, Vec2::new(8.0, 3.0)));
}
#[test]
fn nonzero_self_crossing_contour_is_split_into_triangles() {
let points = [(0.0, 0.0), (10.0, 10.0), (0.0, 10.0), (6.0, 0.0), (3.0, 8.0)];
let result = normalize(vec![polygon(&points)], FillRule::NonZero, 1000, TOL).expect("valid contour");
assert!(result.len() > 1);
assert!(filled(&result, Vec2::new(4.0, 5.0)));
}
#[test]
fn nonzero_tessellation_keeps_coordinates_away_from_the_local_origin() {
let shift = 50_000.0;
// The third square crosses the first, so the fill is tessellated.
let input = vec![
square(shift, shift, shift + 10.0, shift + 10.0, false),
square(shift + 2.0, shift + 2.0, shift + 8.0, shift + 8.0, true),
square(shift + 9.0, shift + 4.0, shift + 12.0, shift + 6.0, false),
];
let result = normalize(input, FillRule::NonZero, 1000, TOL).expect("valid translated contours");
assert!(result.len() > 3, "tessellated into triangles");
assert!(!filled(&result, Vec2::new(shift + 5.0, shift + 5.0)));
assert!(filled(&result, Vec2::new(shift + 1.0, shift + 1.0)));
assert!(filled(&result, Vec2::new(shift + 11.0, shift + 5.1)));
}
#[test]
fn even_odd_nested_contours_are_classified_by_depth() {
let result = normalize(vec![square(0.0, 0.0, 10.0, 10.0, false), square(2.0, 2.0, 8.0, 8.0, false)], FillRule::EvenOdd, 1000, TOL)
.expect("valid contours");
assert!(result[0].outer);
assert!(!result[1].outer);
assert!(!filled(&result, Vec2::new(5.0, 5.0)));
assert!(filled(&result, Vec2::new(1.0, 1.0)));
}
}
+1 -510
View File
@@ -111,7 +111,6 @@ fn sample() -> Drawing {
loops: vec![HatchLoop {
vertices: vec![PolyVertex::new(Vec2::ZERO), PolyVertex::new(Vec2::new(2.0, 0.0)), PolyVertex::new(Vec2::new(2.0, 2.0))],
outer: true,
boundary_flags: Some(3),
sources: Vec::new(),
}],
scale: 1.0,
@@ -2030,514 +2029,6 @@ fn intl_text(value: &str) -> Text {
}
}
fn two_point_text_sample() -> Drawing {
let mut drawing = Drawing::new_metric();
let mut block = Block::new("Labels");
let mut attribs = Vec::new();
for (index, halign) in [HAlign::Aligned, HAlign::Fit].into_iter().enumerate() {
for multiplier in [1.0, 2.0] {
let text =
Text { insert: Vec3::ZERO, align_pt: Some(Vec3::new(30.0 * multiplier, 4.0 * multiplier, 0.0)), halign, ..intl_text("SYNTHETIC") };
drawing.add(&Space::Model, Common::default(), EntityKind::Text(text.clone())).unwrap();
let attribute = Attrib {
tag: format!("LABEL{index}_{multiplier}"),
text,
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
block.entities.push(Entity::new(Handle(0x500 + attribs.len() as u64), EntityKind::AttDef(attribute.clone())));
attribs.push(attribute);
}
}
drawing.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
drawing
.add(
&Space::Model,
Common::default(),
EntityKind::Insert(Insert {
block: "Labels".into(),
insert: Vec3::ZERO,
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs,
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}),
)
.unwrap();
drawing
}
fn two_point_texts(drawing: &Drawing) -> Vec<&Text> {
let mut texts = Vec::new();
for entity in drawing.model.iter() {
match &entity.kind {
EntityKind::Text(text) => texts.push(text),
EntityKind::Insert(insert) => texts.extend(insert.attribs.iter().map(|attribute| &attribute.text)),
_ => {}
}
}
texts.extend(
drawing
.block("Labels")
.unwrap()
.entities
.iter()
.filter_map(|entity| if let EntityKind::AttDef(attribute) = &entity.kind { Some(&attribute.text) } else { None }),
);
texts
}
fn edit_two_point_texts(d: &mut Drawing, edit: impl Fn(&mut Text)) {
fn store(store: &mut EntityStore, edit: &impl Fn(&mut Text)) {
for handle in store.handles() {
store.modify(handle, |e| match &mut e.kind {
EntityKind::Text(t) => edit(t),
EntityKind::AttDef(a) => edit(&mut a.text),
EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| edit(&mut a.text)),
_ => {}
});
}
}
store(&mut d.model, &edit);
for block in d.blocks.values_mut() {
store(&mut std::sync::Arc::make_mut(block).entities, &edit);
}
}
// Original synthetic DXF records with measurements deliberately different from our stroke font.
fn imported_two_point_text_sample() -> Drawing {
let tags = craft_dxf::parse(write_dxf(&two_point_text_sample()).as_bytes()).unwrap();
let mut altered = tags.clone();
// Work on complete records, including their leading group 0.
let starts: Vec<usize> = tags.iter().enumerate().filter_map(|(i, t)| (t.code == 0).then_some(i)).chain([tags.len()]).collect();
for pair in starts.windows(2) {
let record = &tags[pair[0]..pair[1]];
if !matches!(record[0].str().as_ref(), "TEXT" | "ATTDEF" | "ATTRIB") {
continue;
}
let number = |code| record.iter().find(|t| t.code == code).map(|t| t.str().parse::<f64>().unwrap()).unwrap_or(0.0);
let distance = Vec2::new(number(10), number(20)).dist(Vec2::new(number(11), number(21)));
let width = cadcraft_fonts::shape_stroke("SYNTHETIC", 2.5, 1.0, 0.0).width;
let aligned = number(72) == 3.0;
let code = if aligned { 40 } else { 41 };
let dimension = if aligned { 2.5 } else { 1.0 } * distance / width * 1.15;
for tag in &mut altered[pair[0]..pair[1]] {
if tag.code == code {
*tag = craft_dxf::Tag::new(code, craft_dxf::Value::Real(dimension));
}
if tag.code == 50 {
*tag = craft_dxf::Tag::new(50, craft_dxf::Value::Real(0.0));
}
}
}
read_dxf(craft_dxf::write_ascii(&altered).as_bytes()).unwrap()
}
fn check_two_point_save(d: &Drawing, name: &str, recompute: bool, rotation: bool) {
let saved = read(&write(d, name).unwrap(), name).unwrap();
let before = two_point_texts(d);
let after = two_point_texts(&saved);
assert_eq!(after.len(), before.len());
for (original, text) in before.into_iter().zip(&after) {
if rotation {
assert!((text.rotation - text.insert.xy().angle_to(text.align_pt.unwrap().xy())).abs() < 1e-10, "{name}: {text:?}");
}
if recompute {
let width =
cadcraft_fonts::shape_stroke_dir(&original.value, original.height, original.width_factor, original.oblique, Some(false)).width;
let scale = original.insert.xy().dist(original.align_pt.unwrap().xy()) / width;
let (height, factor) = if original.halign == HAlign::Aligned {
(original.height * scale, original.width_factor)
} else {
(original.height, original.width_factor * scale)
};
assert!((text.height / height - 1.0).abs() < 1e-12, "height: {name}");
assert!((text.width_factor / factor - 1.0).abs() < 1e-12, "width factor: {name}");
} else {
assert!((text.height - original.height).abs() < 1e-10, "{name}");
assert!((text.width_factor - original.width_factor).abs() < 1e-10, "{name}");
}
}
let again = read(&write(&saved, name).unwrap(), name).unwrap();
for (first, second) in after.into_iter().zip(two_point_texts(&again)) {
assert!((first.rotation - second.rotation).abs() < 1e-10, "{name}");
assert!((first.height - second.height).abs() < 1e-10, "{name}");
assert!((first.width_factor - second.width_factor).abs() < 1e-10, "{name}");
}
}
fn two_point_formats() -> [&'static str; 2] {
crate::dwg_worker::allow_in_process();
["fit.dxf", "fit.dwg"]
}
#[test]
fn two_point_imported_measurements_survive_save() {
for name in two_point_formats() {
check_two_point_save(&imported_two_point_text_sample(), name, false, false);
}
}
#[test]
fn two_point_imported_rotation_follows_points() {
for name in two_point_formats() {
check_two_point_save(&imported_two_point_text_sample(), name, false, true);
}
}
fn transform_two_point_sample(d: &mut Drawing, matrix: cadcraft_geom::Mat3) {
// Transform the reference itself so attached attributes follow the production path.
for handle in d.model.handles() {
d.model.modify(handle, |entity| entity.kind.transform(&matrix));
}
}
#[test]
fn two_point_imported_measurements_survive_move() {
let mut d = imported_two_point_text_sample();
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::translate(Vec2::new(47.0, -19.0)));
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_imported_measurements_survive_rotate() {
let mut d = imported_two_point_text_sample();
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::rotate_about(Vec2::new(7.0, -3.0), 0.73));
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_imported_measurements_follow_uniform_scale() {
let mut d = imported_two_point_text_sample();
let imported = d.clone();
transform_two_point_sample(&mut d, cadcraft_geom::Mat3::scale_about(Vec2::new(7.0, -3.0), 2.0));
for (before, scaled) in two_point_texts(&imported).into_iter().zip(two_point_texts(&d)).take(8) {
assert!((scaled.height - before.height * 2.0).abs() < 1e-10);
assert!((scaled.width_factor - before.width_factor).abs() < 1e-10);
}
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_changed_fit_height_recomputes_measurements() {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| t.height *= 1.4);
for name in two_point_formats() {
// Aligned height is derived from distance, so editing it alone preserves the import.
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for (before, after) in two_point_texts(&d).into_iter().zip(two_point_texts(&saved)) {
if before.halign == HAlign::Fit {
let expected = cadcraft_render::fitted_text_entity(&d, before, &before.value);
assert!((after.width_factor / expected.width_factor - 1.0).abs() < 1e-12);
}
}
}
}
#[test]
fn two_point_imported_distance_uses_relative_tolerance() {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| {
let point = t.align_pt.as_mut().unwrap();
point.x *= 1.0 + 0.5e-9;
point.y *= 1.0 + 0.5e-9;
});
for name in two_point_formats() {
check_two_point_save(&d, name, false, true);
}
}
#[test]
fn two_point_changed_fitting_inputs_recompute_measurements() {
for input in ["style", "oblique", "width factor"] {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| match input {
"style" => t.style = "Replacement".into(),
"oblique" => t.oblique += 0.2,
_ => t.width_factor *= 1.2,
});
for name in two_point_formats() {
check_two_point_save(&d, name, true, true);
}
}
}
#[test]
fn two_point_changed_string_recomputes_measurements() {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| t.value.push_str(" EDITED"));
for name in two_point_formats() {
check_two_point_save(&d, name, true, false);
}
}
#[test]
fn two_point_changed_distance_scales_aligned_and_recomputes_fit() {
let mut d = imported_two_point_text_sample();
let imported = d.clone();
edit_two_point_texts(&mut d, |t| t.align_pt.as_mut().unwrap().x *= 1.8);
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for ((before, edited), after) in two_point_texts(&imported).into_iter().zip(two_point_texts(&d)).zip(two_point_texts(&saved)) {
if before.halign == HAlign::Aligned {
let ratio = edited.insert.xy().dist(edited.align_pt.unwrap().xy()) / before.insert.xy().dist(before.align_pt.unwrap().xy());
assert!((after.height / (before.height * ratio) - 1.0).abs() < 1e-12, "{name}");
} else {
let expected = cadcraft_render::fitted_text_entity(&d, edited, &edited.value);
assert!((after.width_factor / expected.width_factor - 1.0).abs() < 1e-12, "{name}");
}
}
check_two_point_save(&saved, name, false, true);
}
}
#[test]
fn two_point_authored_text_recomputes_measurements() {
for name in two_point_formats() {
check_two_point_save(&two_point_text_sample(), name, true, false);
}
}
#[test]
fn two_point_text_save_keeps_degenerate_and_unrelated_values() {
for halign in [HAlign::Left, HAlign::Center, HAlign::Right, HAlign::Middle, HAlign::Aligned, HAlign::Fit] {
for valign in [VAlign::Baseline, VAlign::Bottom] {
for align_pt in [None, Some(Vec3::ZERO), Some(Vec3::new(30.0, 4.0, 0.0))] {
if matches!(halign, HAlign::Aligned | HAlign::Fit) && align_pt.is_some_and(|point| point != Vec3::ZERO) {
continue;
}
let text = Text { insert: Vec3::ZERO, align_pt, halign, valign, rotation: 0.7, width_factor: 0.8, ..intl_text("SYNTHETIC") };
let mut drawing = Drawing::new_metric();
drawing.add(&Space::Model, Common::default(), EntityKind::Text(text.clone())).unwrap();
let saved = read(&write(&drawing, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let back = first(&saved, |kind| if let EntityKind::Text(text) = kind { Some(text.clone()) } else { None });
assert!((text.rotation - back.rotation).abs() < 1e-12);
assert!((text.height - back.height).abs() < 1e-10);
assert!((text.width_factor - back.width_factor).abs() < 1e-10);
}
}
}
}
#[test]
fn two_point_imported_degenerate_geometry_keeps_edited_height() {
for missing in [false, true] {
let mut d = imported_two_point_text_sample();
let handle = d.model.handles()[0];
d.model.modify(handle, |entity| {
if let EntityKind::Text(t) = &mut entity.kind {
t.insert = Vec3::ZERO;
t.align_pt = if missing { None } else { Some(Vec3::ZERO) };
t.height = 2.0;
}
});
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
snapshot.insert = Vec3::ZERO;
snapshot.align_pt = if missing { None } else { Some(Vec3::ZERO) };
snapshot.height = 2.0;
let mut d = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let handle = d.model.handles()[0];
let imported = first(&d, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
assert_eq!(imported.align_pt, if missing { None } else { Some(Vec3::ZERO) });
d.model.modify(handle, |entity| {
if let EntityKind::Text(t) = &mut entity.kind {
t.height = 4.0;
}
});
let saved = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let text = first(&saved, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
assert!((text.height - 4.0).abs() < 1e-10, "missing: {missing}");
}
}
#[test]
fn two_point_imported_nonfinite_geometry_keeps_edited_height() {
let mut d = imported_two_point_text_sample();
let handle = d.model.handles()[0];
d.model.modify(handle, |entity| {
if let EntityKind::Text(t) = &mut entity.kind {
assert_eq!(t.halign, HAlign::Aligned);
t.insert = Vec3::ZERO;
t.align_pt = Some(Vec3::new(f64::INFINITY, 0.0, 0.0));
t.height = 4.0;
}
});
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
snapshot.insert = Vec3::ZERO;
snapshot.align_pt = Some(Vec3::new(f64::INFINITY, 0.0, 0.0));
snapshot.height = 2.0;
let saved = read(&write(&d, "edge.dxf").unwrap(), "edge.dxf").unwrap();
let text = first(&saved, |kind| if let EntityKind::Text(t) = kind { Some(t.clone()) } else { None });
assert!((text.height - 4.0).abs() < 1e-10);
}
#[test]
fn two_point_imported_empty_attdef_keeps_dimensions_when_points_move() {
let mut d = imported_two_point_text_sample();
let block = std::sync::Arc::make_mut(d.blocks.get_mut("Labels").unwrap());
let handle = block.entities.handles()[0];
block.entities.modify(handle, |entity| {
if let EntityKind::AttDef(a) = &mut entity.kind {
a.text.value.clear();
a.text.insert = Vec3::ZERO;
a.text.align_pt = Some(Vec3::new(10.0, 0.0, 0.0));
a.text.height = 2.0;
a.text.width_factor = 0.8;
}
});
let snapshot = &mut std::sync::Arc::make_mut(&mut d.foreign).text_fits.get_mut(&handle).unwrap()[0].0;
snapshot.value.clear();
snapshot.insert = Vec3::ZERO;
snapshot.align_pt = Some(Vec3::new(10.0, 0.0, 0.0));
snapshot.height = 2.0;
snapshot.width_factor = 0.8;
let mut d = read(&write(&d, "empty.dxf").unwrap(), "empty.dxf").unwrap();
let block = std::sync::Arc::make_mut(d.blocks.get_mut("Labels").unwrap());
let handle = block.entities.handles()[0];
block.entities.modify(handle, |entity| {
if let EntityKind::AttDef(a) = &mut entity.kind {
a.text.align_pt = Some(Vec3::new(0.0, 20.0, 0.0));
}
});
let saved = read(&write(&d, "empty.dxf").unwrap(), "empty.dxf").unwrap();
let entity = saved.block("Labels").unwrap().entities.iter().next().unwrap();
let EntityKind::AttDef(a) = &entity.kind else { panic!("expected ATTDEF") };
assert!((a.text.height - 2.0).abs() < 1e-10);
assert!((a.text.width_factor - 0.8).abs() < 1e-10);
assert!((a.text.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-10);
}
#[test]
fn two_point_changed_style_definition_recomputes_measurements() {
let mut d = imported_two_point_text_sample();
d.text_styles.iter_mut().find(|style| style.name.eq_ignore_ascii_case("Standard")).unwrap().backwards = true;
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for (before, after) in two_point_texts(&d).into_iter().zip(two_point_texts(&saved)) {
let expected = cadcraft_render::fitted_text_entity(&d, before, &before.value);
assert!((after.height - expected.height).abs() < 1e-9, "{name}");
assert!((after.width_factor - expected.width_factor).abs() < 1e-9, "{name}");
}
}
}
#[test]
fn two_point_changed_justification_recomputes_measurements() {
for horizontal in [true, false] {
let mut d = imported_two_point_text_sample();
edit_two_point_texts(&mut d, |t| {
if horizontal {
t.halign = if t.halign == HAlign::Fit { HAlign::Aligned } else { HAlign::Fit };
} else {
t.valign = VAlign::Middle;
}
});
for name in two_point_formats() {
check_two_point_save(&d, name, true, true);
}
}
}
#[test]
fn two_point_dwg_source_preserves_imported_measurements() {
let imported = imported_two_point_text_sample();
crate::dwg_worker::allow_in_process();
let dwg = write(&imported, "source.dwg").unwrap();
let reopened = read(&dwg, "source.dwg").unwrap();
assert!(!reopened.foreign.text_fits.is_empty());
for name in two_point_formats() {
check_two_point_save(&reopened, name, false, true);
}
}
#[test]
fn two_point_block_layout_and_empty_default() {
let mut d = Drawing::new_metric();
let mut block = Block::new("Labels");
for (index, halign) in [HAlign::Aligned, HAlign::Fit].into_iter().enumerate() {
let text = Text { halign, valign: VAlign::Middle, align_pt: Some(Vec3::new(30.0, 4.0, 0.0)), ..intl_text("SYNTHETIC") };
block.entities.push(Entity::new(Handle(0x500 + index as u64), EntityKind::Text(text.clone())));
d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Text(text)).unwrap();
let empty = Text { halign, align_pt: Some(Vec3::new(30.0, 4.0, 0.0)), ..intl_text("") };
block.entities.push(Entity::new(
Handle(0x510 + index as u64),
EntityKind::AttDef(Attrib {
tag: "LABEL".into(),
text: empty,
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
}),
));
}
d.blocks.insert(block.name.clone(), std::sync::Arc::new(block));
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
for (before, after) in d.block("Labels").unwrap().entities.iter().zip(saved.block("Labels").unwrap().entities.iter()) {
match (&before.kind, &after.kind) {
(EntityKind::Text(a), EntityKind::Text(b)) => {
let expected = cadcraft_render::fitted_text_entity(&d, a, &a.value);
assert!((b.height - expected.height).abs() < 1e-9);
assert!((b.width_factor - expected.width_factor).abs() < 1e-9);
}
(EntityKind::AttDef(a), EntityKind::AttDef(b)) => {
assert!((a.text.height - b.text.height).abs() < 1e-9);
assert!((a.text.width_factor - b.text.width_factor).abs() < 1e-9);
assert!((b.text.rotation - b.text.insert.xy().angle_to(b.text.align_pt.unwrap().xy())).abs() < 1e-9);
}
_ => panic!("unexpected block entity"),
}
}
let before = &d.layout("Layout1").unwrap().entities;
let after = &saved.layout("Layout1").unwrap().entities;
for (a, b) in before.iter().zip(after.iter()) {
if let (EntityKind::Text(a), EntityKind::Text(b)) = (&a.kind, &b.kind) {
let expected = cadcraft_render::fitted_text_entity(&d, a, &a.value);
assert!((b.height - expected.height).abs() < 1e-9);
assert!((b.width_factor - expected.width_factor).abs() < 1e-9);
}
}
assert_eq!(before.len(), after.len());
}
}
#[test]
fn two_point_nonuniform_insert_keeps_attribute_fit_in_its_stored_coordinates() {
let mut d = two_point_text_sample();
for h in d.model.handles() {
d.model.modify(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
i.scale = Vec3::new(2.0, 0.5, 1.0);
}
});
}
for name in two_point_formats() {
let saved = read(&write(&d, name).unwrap(), name).unwrap();
let insert = saved.model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i) } else { None }).unwrap();
let fit = insert.attribs.iter().find(|a| a.text.halign == HAlign::Fit).unwrap();
let width = cadcraft_fonts::shape_stroke_dir(&fit.text.value, fit.text.height, fit.text.width_factor, fit.text.oblique, Some(false)).width;
assert!((width - fit.text.insert.xy().dist(fit.text.align_pt.unwrap().xy())).abs() < 1e-9);
assert!((insert.scale.x - 2.0).abs() < 1e-9 && (insert.scale.y - 0.5).abs() < 1e-9);
}
}
fn intl_sample() -> Drawing {
let mut d = Drawing::new_metric();
let layer = format!("层 {INTL}");
@@ -2952,7 +2443,7 @@ fn gradient_sample() -> (Drawing, Vec<Option<Gradient>>) {
let h = Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices: square.clone(), outer: true, boundary_flags: Some(3), sources: Vec::new() }],
loops: vec![HatchLoop { vertices: square.clone(), outer: true, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
-48
View File
@@ -1,48 +0,0 @@
//! DIMASSOC is a drawing variable, written as HEADER group 280, independently of DIMSTYLE.
use cadcraft_doc::Drawing;
use cadcraft_io::{SaveOptions, Version, read_dxf, write, write_with};
/// Extract every DIMASSOC HEADER entry so duplicate or mistyped values fail the assertions.
fn dimassoc_groups(bytes: &[u8]) -> Vec<(i32, i64)> {
let tags = craft_dxf::parse(bytes).unwrap();
let header = craft_dxf::sections(&tags).into_iter().find(|s| s.name == "HEADER").unwrap();
let mut found = Vec::new();
for pair in header.tags.windows(2) {
if pair[0].code == 9 && pair[0].str() == "$DIMASSOC" {
found.push((pair[1].code, pair[1].i64()));
}
}
found
}
/// All supported modes use group 280 and survive each tested DXF version and encoding.
#[test]
fn new_drawing_modes_use_group_280_in_ascii_and_binary_dxf() {
for mode in [0, 1, 2] {
let mut d = Drawing::new_metric();
d.header.set_i64("DIMASSOC", mode);
for version in [Version::R2000, Version::R2004, Version::R2007, Version::R2018] {
for binary in [false, true] {
let bytes = write_with(&d, "setting.dxf", &SaveOptions { version: Some(version), binary }).unwrap();
assert_eq!(dimassoc_groups(&bytes), [(280, mode)], "{version:?}, binary{binary}");
let back = read_dxf(&bytes).unwrap();
assert_eq!(back.header.i64("DIMASSOC", -1), mode);
}
}
}
}
/// Editing an imported mode replaces its stored value without emitting a second HEADER entry.
#[test]
fn an_imported_mode_can_be_changed_without_a_stale_or_duplicate_header() {
let source = b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$DIMASSOC\n280\n1\n0\nENDSEC\n0\nEOF\n";
let mut d = read_dxf(source).unwrap();
assert_eq!(d.header.i64("DIMASSOC", -1), 1);
for mode in [1, 0, 2] {
d.header.set_i64("DIMASSOC", mode);
let bytes = write(&d, "edited.dxf").unwrap();
assert_eq!(dimassoc_groups(&bytes), [(280, mode)]);
d = read_dxf(&bytes).unwrap();
assert_eq!(d.header.i64("DIMASSOC", -1), mode);
}
}
+1 -1
View File
@@ -118,7 +118,7 @@ fn hatch(pattern: &str, gradient: Option<Gradient>) -> Hatch {
Hatch {
pattern: pattern.into(),
solid: pattern == "SOLID",
loops: vec![HatchLoop { vertices: square(10.0), outer: true, boundary_flags: None, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: square(10.0), outer: true, sources: Vec::new() }],
scale: 2.0,
angle: 0.25,
associative: false,
+5 -5
View File
@@ -41,8 +41,8 @@ fn source_boundary_objects_roundtrip() {
let outer = poly(&mut d, square(0.0, 20.0));
let island = poly(&mut d, square(5.0, 5.0));
let loops = vec![
HatchLoop { vertices: square(0.0, 20.0), outer: true, boundary_flags: None, sources: vec![outer] },
HatchLoop { vertices: square(5.0, 5.0), outer: false, boundary_flags: None, sources: vec![island] },
HatchLoop { vertices: square(0.0, 20.0), outer: true, sources: vec![outer] },
HatchLoop { vertices: square(5.0, 5.0), outer: false, sources: vec![island] },
];
d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(loops.clone(), true))).expect("add");
// A non-associative hatch writes no sources; a source that is gone isn't written.
@@ -79,7 +79,7 @@ fn join(p: &[(i32, String)]) -> String {
fn sources_after_spline_fit_data_and_hostile_counts() {
let mut d = Drawing::new_imperial();
let outer = poly(&mut d, square(0.0, 20.0));
let loops = vec![HatchLoop { vertices: square(0.0, 20.0), outer: true, boundary_flags: None, sources: vec![outer] }];
let loops = vec![HatchLoop { vertices: square(0.0, 20.0), outer: true, sources: vec![outer] }];
d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(loops, true))).expect("add");
let p = pairs(&write_dxf(&d));
let start = p.iter().position(|(c, v)| *c == 0 && v == "HATCH").expect("HATCH");
@@ -127,11 +127,11 @@ fn a_hatch_in_a_block_keeps_its_boundary_and_the_boundary_its_reactor() {
let fill = d.new_handle();
let k = EntityKind::LwPolyline(LwPolyline { vertices: square(0.0, 10.0), closed: true, const_width: 0.0, elevation: 0.0, plinegen: false });
b.entities.push(Entity::new(outline, k));
let loops = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, boundary_flags: None, sources: vec![outline] }];
let loops = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, sources: vec![outline] }];
b.entities.push(Entity::new(fill, EntityKind::Hatch(hatch(loops, true))));
d.blocks.insert("Tag".into(), std::sync::Arc::new(b));
// A model-space hatch whose source is in the block is not linked to it.
let stray = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, boundary_flags: None, sources: vec![outline] }];
let stray = vec![HatchLoop { vertices: square(0.0, 10.0), outer: true, sources: vec![outline] }];
let other = d.add(&Space::Model, Common::default(), EntityKind::Hatch(hatch(stray, true))).expect("add");
let p = pairs(&write_dxf(&d));
let poly = record(&p, "LWPOLYLINE", outline);
-145
View File
@@ -1,145 +0,0 @@
use cadcraft_doc::{Drawing, EntityKind, HatchLoop, Region};
use cadcraft_io::{read_dxf, write_dxf};
fn boundary(points: &[(f64, f64)], flags: i64) -> String {
let mut text = format!("92\n{flags}\n");
if flags & 2 != 0 {
text.push_str(&format!("72\n0\n73\n1\n93\n{}\n", points.len()));
for (point_x, point_y) in points {
text.push_str(&format!("10\n{point_x}\n20\n{point_y}\n"));
}
} else {
text.push_str(&format!("93\n{}\n", points.len()));
for (start, end) in points.iter().zip(points.iter().cycle().skip(1)) {
text.push_str(&format!("72\n1\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n", start.0, start.1, end.0, end.1));
}
}
text.push_str("97\n0\n");
text
}
fn logo(flags: [i64; 4]) -> String {
let hexagon = [(-10.0, 0.0), (-5.0, -8.0), (5.0, -8.0), (10.0, 0.0), (5.0, 8.0), (-5.0, 8.0)];
let letter = [(-3.0, -4.0), (3.0, -4.0), (3.0, -2.0), (-1.0, -2.0), (-1.0, 4.0), (-3.0, 4.0)];
let right: Vec<_> = hexagon.iter().map(|(point_x, point_y)| (point_x + 28.0, *point_y)).collect();
let hole: Vec<_> = hexagon.iter().map(|(point_x, point_y)| (point_x * 0.6 + 28.0, point_y * 0.6)).collect();
let mut text = String::from("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n");
for (index, loops) in
[[(&hexagon[..], flags[0]), (&letter[..], flags[1])], [(&right[..], flags[2]), (&hole[..], flags[3])]].into_iter().enumerate()
{
text.push_str(&format!(
"0\nHATCH\n5\n{:X}\n100\nAcDbEntity\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n1\n2\nSOLID\n70\n1\n71\n0\n91\n2\n",
0x100 + index
));
for (points, flags) in loops {
text.push_str(&boundary(points, flags));
}
text.push_str("75\n1\n76\n1\n98\n0\n");
}
text.push_str("0\nENDSEC\n0\nEOF\n");
text
}
fn flags_written(drawing: &Drawing) -> Vec<i64> {
let text = write_dxf(drawing);
let lines: Vec<_> = text.lines().collect();
let mut hatch = false;
lines
.as_chunks::<2>()
.0
.iter()
.filter_map(|pair| {
let code: i32 = pair[0].trim().parse().unwrap();
if code == 0 {
hatch = pair[1].trim() == "HATCH";
}
if hatch && code == 92 { Some(pair[1].trim().parse().unwrap()) } else { None }
})
.collect()
}
#[test]
fn boundary_flags_survive_dxf_open_and_save() {
for flags in [[7, 22, 7, 6], [7, 22, 6, 20], [0, 9, 16, 31]] {
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
let expected = flags.map(|flag| flag | 2);
assert_eq!(flags_written(&drawing), expected);
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
assert_eq!(flags_written(&back), expected);
for entity in back.model.iter() {
if let EntityKind::Hatch(hatch) = &entity.kind {
let json = serde_json::to_vec(&hatch.loops).unwrap();
let restored: Vec<HatchLoop> = serde_json::from_slice(&json).unwrap();
assert_eq!(restored, hatch.loops);
}
}
}
}
#[test]
fn reclassified_loops_write_current_external_bit() {
for imported in [7, 23] {
let mut drawing = read_dxf(logo([7, imported, 7, 6]).as_bytes()).unwrap();
let handle = drawing.model.iter().next().unwrap().handle;
drawing.model.modify(handle, |entity| {
let EntityKind::Hatch(hatch) = &mut entity.kind else { panic!("expected hatch") };
assert!(hatch.loops[1].outer);
let mut region = Region { loops: hatch.loops.clone() };
assert!(region.renest());
hatch.loops = region.loops;
assert!(!hatch.loops[1].outer);
assert_eq!(hatch.loops[1].boundary_flags, Some(imported));
});
let written = flags_written(&drawing)[1];
assert_eq!(written & 1, 0);
assert_eq!(written & (4 | 16), imported & (4 | 16));
assert_ne!(written & 2, 0);
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
assert_eq!(flags_written(&back), flags_written(&drawing));
}
}
#[test]
fn undocumented_boundary_bits_are_not_written_back() {
let flags = [i64::MAX, -1, 32 | 7, i64::MIN | 22];
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
let expected = flags.map(|flag| (flag & 31) | 2);
assert_eq!(flags_written(&drawing), expected);
let back = read_dxf(write_dxf(&drawing).as_bytes()).unwrap();
assert_eq!(flags_written(&back), expected);
}
#[test]
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn boundary_flags_survive_dwg_open_and_both_save_formats() {
cadcraft_io::dwg_worker::allow_in_process();
for flags in [[7, 22, 7, 6], [7, 22, 6, 20]] {
let drawing = read_dxf(logo(flags).as_bytes()).unwrap();
let bytes = cadcraft_io::write(&drawing, "logo.dwg").unwrap();
let back = cadcraft_io::read(&bytes, "logo.dwg").unwrap();
let expected = flags.map(|flag| flag | 2);
assert_eq!(flags_written(&back), expected);
let again = cadcraft_io::write(&back, "logo.dwg").unwrap();
assert_eq!(flags_written(&cadcraft_io::read(&again, "logo.dwg").unwrap()), expected);
}
}
#[test]
fn old_serialized_loops_keep_locally_created_flags() {
let mut drawing = read_dxf(logo([7, 22, 6, 20]).as_bytes()).unwrap();
let mut expected = Vec::new();
let handles: Vec<_> = drawing.model.iter().map(|entity| entity.handle).collect();
for handle in handles {
drawing.model.modify(handle, |entity| {
if let EntityKind::Hatch(hatch) = &mut entity.kind {
for boundary in &mut hatch.loops {
let mut json = serde_json::to_value(&*boundary).unwrap();
json.as_object_mut().unwrap().remove("boundary_flags");
*boundary = serde_json::from_value::<HatchLoop>(json).unwrap();
expected.push(2 | i64::from(boundary.outer));
}
}
});
}
assert_eq!(flags_written(&drawing), expected);
}
+1 -1
View File
@@ -8,7 +8,7 @@ use cadcraft_io::{read_dxf, write_dxf};
fn square() -> HatchLoop {
let v = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].into_iter().map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
HatchLoop { vertices: v, outer: true, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices: v, outer: true, sources: Vec::new() }
}
fn hatch(pattern: &str, scale: f64, angle: f64, origin: Vec2, lines: Vec<PatternLine>) -> Hatch {
-38
View File
@@ -72,41 +72,3 @@ fn the_page_still_decides_the_bits_cadcraft_models() {
d.layouts.last_mut().unwrap().page = PageSetup::default();
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128 | 32 | 16));
}
/// Each LAYOUT object's name and plot layout flags (the AcDbLayout group 1 and the
/// AcDbPlotSettings group 70) in DXF text.
fn layout_plot_flags(text: &str) -> Vec<(String, i64)> {
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut out = Vec::new();
let (mut inside, mut subclass, mut name, mut flags) = (false, "", None, None);
for pair in lines.chunks(2) {
let [code, value] = pair else { break };
match *code {
"0" => {
if let (true, Some(n), Some(f)) = (inside, name.take(), flags.take()) {
out.push((n, f));
}
(inside, subclass, name, flags) = (*value == "LAYOUT", "", None, None);
}
"100" if inside => subclass = value,
"70" if inside && subclass == "AcDbPlotSettings" => flags = value.parse().ok(),
"1" if inside && subclass == "AcDbLayout" => name = Some(value.to_string()),
_ => {}
}
}
out
}
#[test]
fn only_the_model_layout_carries_the_model_type_flag() {
// 1024 is "ModelType" (DXF Reference, PLOTSETTINGS group 70): the plot settings of model space.
// The Model layout carries it; a paper layout does not, even when it was read with it.
for read in [688, 688 | 1024] {
let bytes = write(&drawing(read), "sheet.dxf").unwrap();
let layouts = layout_plot_flags(&String::from_utf8_lossy(&bytes));
let flags = |name: &str| layouts.iter().find(|(n, _)| n == name).map(|&(_, f)| f);
let (model, sheet) = (flags("Model").unwrap(), flags("SHEET").unwrap());
assert_ne!(model & 1024, 0, "Model, SHEET read with {read}: {layouts:?}");
assert_eq!(sheet & 1024, 0, "SHEET read with {read}: {layouts:?}");
}
}
+1 -3
View File
@@ -31,7 +31,6 @@ mod exhausted_handseed;
mod followups_626;
mod groups_roundtrip;
mod hatch_assoc_roundtrip;
mod hatch_loop_flags;
mod hatch_pattern_def;
mod helix_roundtrip;
mod layer_states_acad;
@@ -60,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;
@@ -91,7 +91,5 @@ mod user_lin_pat_roundtrip;
mod view_tables_roundtrip;
mod view_target;
mod viewport_clip_roundtrip;
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod visualstyle_dwg;
mod xclip_roundtrip;
mod xref_roundtrip;
+553
View File
@@ -0,0 +1,553 @@
//! PDFIMPORT: the vector content of a PDF page as editable objects. The PDFs are written here by
//! hand (a content stream and the standard Helvetica) or by CADCraft's own plotter.
use cadcraft_color::{Color, Rgb};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, HAlign, Line, Lineweight, Space, Text};
use cadcraft_geom::Vec3;
use cadcraft_io::pdf_read::{MM_PER_PT, PdfImportOptions, read};
use serde_json::json;
/// A one-page PDF, 600 × 800 points, drawing `content` with Helvetica as `/F1`.
fn page(content: &str) -> Vec<u8> {
pages(&[content])
}
fn pages(contents: &[&str]) -> Vec<u8> {
pages_by(contents, Some("(Autodesk AutoCAD 2024 DWG To PDF)"))
}
/// Like [`pages`], with the `/Producer` value (a PDF string) the file's information names, or none.
fn pages_by(contents: &[&str], producer: Option<&str>) -> Vec<u8> {
let n = contents.len();
let kids: String = (0..n).map(|i| format!("{} 0 R ", 10 + 2 * i)).collect();
let mut pdf = format!(
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [{kids}] /Count {n} >> endobj\n\
3 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\n"
);
for (i, c) in contents.iter().enumerate() {
pdf.push_str(&format!(
"{} 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents {} 0 R /Resources << /Font << /F1 3 0 R >> >> >> endobj\n\
{} 0 obj << /Length {} >> stream\n{c}\nendstream endobj\n",
10 + 2 * i,
11 + 2 * i,
11 + 2 * i,
c.len()
));
}
match producer {
Some(p) => pdf.push_str(&format!("4 0 obj << /Producer {p} >> endobj\ntrailer << /Root 1 0 R /Info 4 0 R >>\n%%EOF\n")),
None => pdf.push_str("trailer << /Root 1 0 R >>\n%%EOF\n"),
}
pdf.into_bytes()
}
fn import(content: &str) -> Drawing {
read(&page(content), &PdfImportOptions::default()).unwrap().0
}
fn kinds(d: &Drawing) -> Vec<&Entity> {
d.model.iter().map(|e| &**e).collect()
}
fn near(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-6
}
#[test]
fn a_stroked_line_is_a_line_with_its_colour_weight_and_layer() {
let d = import("1 0 0 RG 2 w 10 20 m 110 20 l S");
let all = kinds(&d);
assert_eq!(all.len(), 1);
let e = all[0];
let EntityKind::Line(l) = &e.kind else { panic!("{:?}", e.kind) };
assert!(near(l.a.x, 10.0 * MM_PER_PT) && near(l.a.y, 20.0 * MM_PER_PT), "{l:?}");
assert!(near(l.b.x, 110.0 * MM_PER_PT) && near(l.b.y, 20.0 * MM_PER_PT), "{l:?}");
assert_eq!(e.common.color, Color::True(Rgb(255, 0, 0)));
assert_eq!(e.common.layer, "PDF_Geometry");
// 2 pt = 0.7 mm.
assert_eq!(e.common.lineweight, Lineweight::Mm100(70));
}
#[test]
fn black_is_the_automatic_colour() {
let d = import("0 G 0 0 m 10 10 l S");
assert_eq!(kinds(&d)[0].common.color, Color::Index(7));
}
#[test]
fn a_rectangle_is_a_closed_polyline() {
let d = import("10 10 50 30 re S");
let EntityKind::LwPolyline(p) = &kinds(&d)[0].kind else { panic!() };
assert!(p.closed);
assert_eq!(p.vertices.len(), 4);
assert!(p.vertices.iter().all(|v| v.bulge == 0.0));
}
#[test]
fn a_circle_drawn_as_beziers_keeps_its_arcs() {
let k = 0.552_284_75 * 50.0;
let c = format!(
"100 100 m 100 {a} {b} 150 150 150 c {c} 150 200 {a} 200 100 c 200 {d} {c} 50 150 50 c {b} 50 100 {d} 100 100 c h S",
a = 100.0 + k,
b = 150.0 - k,
c = 150.0 + k,
d = 100.0 - k + 0.0
);
// Four quarter arcs: out of the first point, counter-clockwise.
let content = format!(
"150 100 m 150 {k1} {k2} 150 100 150 c {k3} 150 50 {k1} 50 100 c 50 {k4} {k3} 50 100 50 c {k2} 50 150 {k4} 150 100 c h S",
k1 = 100.0 + k,
k2 = 100.0 + k,
k3 = 100.0 - k,
k4 = 100.0 - k
);
let _ = c;
let d = import(&content);
let all = kinds(&d);
assert_eq!(all.len(), 1);
let EntityKind::LwPolyline(p) = &all[0].kind else { panic!("{:?}", all[0].kind) };
assert!(p.closed);
assert_eq!(p.vertices.len(), 4, "{:?}", p.vertices);
for v in &p.vertices {
assert!((v.bulge - (std::f64::consts::PI / 8.0).tan()).abs() < 1e-3, "counter-clockwise quarter arcs: {v:?}");
}
}
#[test]
fn a_filled_shape_is_a_solid_hatch_and_a_white_one_is_left_out() {
let d = import("0 0 1 rg 0 0 100 50 re f 1 1 1 rg 200 200 40 40 re f");
let all = kinds(&d);
assert_eq!(all.len(), 1);
let EntityKind::Hatch(h) = &all[0].kind else { panic!("{:?}", all[0].kind) };
assert!(h.solid && h.loops.len() == 1 && h.loops[0].vertices.len() == 4);
assert_eq!(all[0].common.color, Color::True(Rgb(0, 0, 255)));
assert_eq!(all[0].common.layer, "PDF_Solid Fills");
assert!(d.read_notes.iter().any(|n| n.contains("1 white or near-white fill")), "{:?}", d.read_notes);
}
#[test]
fn a_near_white_fill_is_left_out_like_a_white_one() {
// 245, 245, 245 table shading is left out; a light grey (230) is a fill.
let d = import("0.96 0.96 0.96 rg 0 0 50 50 re f 0.9 0.9 0.9 rg 100 100 50 50 re f");
let all = kinds(&d);
assert_eq!(all.len(), 1, "{all:?}");
assert_eq!(all[0].common.color, Color::True(Rgb(230, 230, 230)));
assert!(d.read_notes.iter().any(|n| n.contains("1 white or near-white fill")), "{:?}", d.read_notes);
}
#[test]
fn a_hole_stays_a_second_loop() {
let d = import("0 0 1 rg 0 0 100 100 re 25 25 50 50 re f*");
let EntityKind::Hatch(h) = &kinds(&d)[0].kind else { panic!() };
assert_eq!(h.loops.len(), 2);
}
#[test]
fn text_is_one_text_object_per_baseline() {
let d = import("BT /F1 12 Tf 100 200 Td (Hello World) Tj ET");
let all = kinds(&d);
assert_eq!(all.len(), 1, "{all:?}");
let EntityKind::Text(t) = &all[0].kind else { panic!("{:?}", all[0].kind) };
assert_eq!(t.value, "Hello World");
assert!(near(t.insert.x, 100.0 * MM_PER_PT) && near(t.insert.y, 200.0 * MM_PER_PT), "{t:?}");
assert!(near(t.height, 12.0 * MM_PER_PT * 0.72), "{t:?}");
assert!(t.rotation.abs() < 1e-9);
assert_eq!(t.halign, HAlign::Fit);
let end = t.align_pt.unwrap();
assert!(end.x > t.insert.x + 10.0 * MM_PER_PT && near(end.y, t.insert.y), "{t:?}");
assert_eq!(all[0].common.layer, "PDF_Text");
}
#[test]
fn rotated_text_keeps_its_angle() {
// A 90 degree text matrix.
let d = import("BT /F1 10 Tf 0 1 -1 0 300 300 Tm (Up) Tj ET");
let EntityKind::Text(t) = &kinds(&d)[0].kind else { panic!() };
assert_eq!(t.value, "Up");
assert!((t.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{t:?}");
}
#[test]
fn words_far_apart_on_a_line_are_separate_texts() {
let d = import("BT /F1 10 Tf 50 100 Td (Left) Tj 400 0 Td (Right) Tj ET");
let texts: Vec<_> = kinds(&d).into_iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.value.clone()) } else { None }).collect();
assert_eq!(texts, ["Left", "Right"]);
}
#[test]
fn options_leave_out_text_fills_and_weights() {
let bytes = page("BT /F1 12 Tf 10 10 Td (Hi) Tj ET 0 0 1 rg 0 0 5 5 re f 2 w 0 0 m 9 9 l S");
let (d, pages) = read(&bytes, &PdfImportOptions { text: false, fills: false, lineweights: false, ..Default::default() }).unwrap();
assert_eq!(pages, 1);
let all = kinds(&d);
assert_eq!(all.len(), 1);
assert_eq!(all[0].common.lineweight, Lineweight::ByLayer);
}
#[test]
fn a_rectangular_clip_cuts_a_line_and_drops_what_lies_outside() {
let d = import("q 100 100 100 100 re W n 0 150 m 300 150 l S 0 0 m 10 10 l S Q");
let all = kinds(&d);
assert_eq!(all.len(), 1, "{all:?}");
let EntityKind::Line(l) = &all[0].kind else { panic!("{:?}", all[0].kind) };
assert!(near(l.a.x, 100.0 * MM_PER_PT) && near(l.b.x, 200.0 * MM_PER_PT), "{l:?}");
assert!(near(l.a.y, 150.0 * MM_PER_PT) && near(l.b.y, 150.0 * MM_PER_PT), "{l:?}");
}
#[test]
fn a_rectangular_clip_cuts_a_fill_to_its_corners() {
let d = import("q 100 100 100 100 re W n 0 0 1 rg 50 50 200 200 re f Q 0 1 0 rg 0 0 10 10 re f");
let hatches: Vec<_> = kinds(&d).into_iter().filter_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h) } else { None }).collect();
assert_eq!(hatches.len(), 2);
let xs: Vec<f64> = hatches[0].loops[0].vertices.iter().map(|v| v.p.x).collect();
let ys: Vec<f64> = hatches[0].loops[0].vertices.iter().map(|v| v.p.y).collect();
assert!(xs.iter().all(|x| *x >= 100.0 * MM_PER_PT - 1e-6 && *x <= 200.0 * MM_PER_PT + 1e-6), "{xs:?}");
assert!(ys.iter().all(|y| *y >= 100.0 * MM_PER_PT - 1e-6 && *y <= 200.0 * MM_PER_PT + 1e-6), "{ys:?}");
// After the clip is restored, the next fill is whole again.
assert_eq!(hatches[1].loops[0].vertices.len(), 4);
}
fn texts(d: &Drawing) -> Vec<String> {
kinds(d).into_iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.value.clone()) } else { None }).collect()
}
#[test]
fn text_starting_on_a_clip_edge_is_kept() {
// A cell clipped to a box whose left side runs a hair right of the text's start, as a plotter
// draws it: a viewer shows the whole word.
let d = import("q 100.001 200 200 14 re W n BT /F1 10 Tf 100 202 Td (MATERIAL) Tj ET Q");
assert_eq!(texts(&d), ["MATERIAL"]);
// A label turned to read downwards with its start just off a page clip.
let d = import("q 0.12 0.12 599 799 re W n BT /F1 10 Tf 0 -1 1 0 -0.5 300 Tm (B) Tj ET Q");
assert_eq!(texts(&d), ["B"]);
// Text wholly outside the clip is still left out, and a glyph is cut at the clip.
let d = import("q 100 200 200 14 re W n BT /F1 10 Tf 400 202 Td (Gone) Tj ET BT /F1 10 Tf 88 202 Td (XYZ) Tj ET Q");
assert_eq!(texts(&d), ["Z"]);
}
#[test]
fn a_shape_outside_its_clip_is_left_out() {
let d = import("q 100 100 50 50 re W n 0 0 m 10 10 l S Q");
assert_eq!(kinds(&d).len(), 0);
}
#[test]
fn another_clip_shape_is_not_applied_and_the_read_note_says_so() {
let d = import("q 100 100 m 200 100 l 150 200 l h W n 0 0 m 300 300 l S Q");
assert_eq!(kinds(&d).len(), 1);
assert!(d.read_notes.iter().any(|n| n.contains("clips by a shape other than a rectangle")), "{:?}", d.read_notes);
}
#[test]
fn the_unit_sets_the_scale() {
let (d, _) = read(&page("0 0 m 72 0 l S"), &PdfImportOptions { unit: 1.0 / 72.0, ..Default::default() }).unwrap();
let EntityKind::Line(l) = &kinds(&d)[0].kind else { panic!() };
assert!(near(l.b.x, 1.0), "{l:?}");
}
#[test]
fn a_page_is_chosen_by_number() {
let bytes = pages(&["0 0 m 10 0 l S", "0 0 m 20 0 l S", "0 0 m 30 0 l S"]);
let (d, n) = read(&bytes, &PdfImportOptions { page: 2, ..Default::default() }).unwrap();
assert_eq!(n, 3);
let EntityKind::Line(l) = &kinds(&d)[0].kind else { panic!() };
assert!(near(l.b.x, 20.0 * MM_PER_PT));
let e = read(&bytes, &PdfImportOptions { page: 4, ..Default::default() }).unwrap_err().to_string();
assert!(e.contains("page 4") && e.contains("3 pages"), "{e}");
assert!(read(&bytes, &PdfImportOptions { page: 0, ..Default::default() }).is_err());
}
#[test]
fn a_file_that_is_not_a_pdf_is_an_error_not_a_panic() {
assert!(read(b"%PDF-1.7 garbage", &PdfImportOptions::default()).is_err());
assert!(read(b"", &PdfImportOptions::default()).is_err());
assert!(read(&page("0 0 m 1 1 l S"), &PdfImportOptions { unit: 0.0, ..Default::default() }).is_err());
}
#[test]
fn any_pdf_is_imported_whatever_made_it() {
// A plot that another program merged or printed again no longer names the CAD program.
let content = ["0 0 m 10 10 l S"];
for producer in [Some("(Skia/PDF m120)"), Some("(Example PDF Tool)"), Some("<FEFF004400570047>"), None] {
let (d, _) = read(&pages_by(&content, producer), &PdfImportOptions::default()).unwrap();
assert_eq!(kinds(&d).len(), 1, "{producer:?}");
}
}
#[test]
fn nonsense_content_does_not_panic() {
for c in ["q q q", "1 2 3 re re re f", "BT (x) Tj ET", "0 0 m 1e300 1e300 l 1e300 -1e300 l S", "Q Q Q h h S"] {
let _ = read(&page(c), &PdfImportOptions::default());
}
}
#[test]
fn a_truncated_or_damaged_file_is_never_a_panic() {
let whole = page("1 0 0 RG 2 w 10 20 m 110 20 l S 0 0 1 rg 0 0 50 50 re f BT /F1 12 Tf 100 200 Td (Hello) Tj ET");
for len in (0..whole.len()).step_by(3) {
let _ = read(&whole[..len], &PdfImportOptions::default());
}
for at in (0..whole.len()).step_by(2) {
for byte in [0x00, 0xFF, b'<', b'0'] {
let mut damaged = whole.clone();
damaged[at] = byte;
let _ = read(&damaged, &PdfImportOptions::default());
}
}
}
#[test]
fn a_page_with_a_great_many_objects_is_read_or_refused_not_hung() {
let content = "0 0 m 1 1 l S ".repeat(60_000);
let (d, _) = read(&page(&content), &PdfImportOptions::default()).unwrap();
assert_eq!(d.model.iter().count(), 60_000);
}
#[test]
fn the_general_reader_does_not_take_a_pdf() {
// INSERT, XREF, COMPARE, RECOVER and templates read drawings through `read`; a PDF is taken
// only by the engine's OPEN, IMPORT and PDFIMPORT, through `pdf_read`.
let e = cadcraft_io::read(&page("0 0 m 10 10 l S"), "plan.pdf").unwrap_err().to_string();
assert!(e.contains("unsupported file type"), "{e}");
}
/// A one-page PDF whose page draws the form `/X` once; the form's content is `form`, and it may
/// draw `/X` itself.
fn form_page(form: &str) -> String {
format!(
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [10 0 R] /Count 1 >> endobj\n\
10 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 11 0 R /Resources << /XObject << /X 5 0 R >> >> >> endobj\n\
11 0 obj << /Length 5 >> stream\n/X Do\nendstream endobj\n\
5 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 600 800] /Resources << /XObject << /X 5 0 R >> >> /Length {} >> stream\n{form}\nendstream endobj\n\
4 0 obj << /Producer (AutoCAD) >> endobj\n\
trailer << /Root 1 0 R /Info 4 0 R >>\n%%EOF\n",
form.len()
)
}
fn lines_of(d: &Drawing) -> usize {
kinds(d).iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count()
}
/// A form that draws itself twice asks for about 2^50 nested interpretations unless the interpreter
/// limits how often forms nest (craft-libs' patched hayro-interpret does).
#[test]
fn a_form_that_draws_itself_twice_is_stopped() {
// The same page with a form that doesn't call itself draws its line once.
let (d, _) = read(form_page("0 0 m 1 1 l S").as_bytes(), &PdfImportOptions::default()).unwrap();
assert_eq!(lines_of(&d), 1);
let pdf = form_page("/X Do /X Do 0 0 m 1 1 l S");
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(read(pdf.as_bytes(), &PdfImportOptions::default()).map(|(d, _)| lines_of(&d)));
});
let result = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("the self-calling form was not stopped");
// The page still reads, with the form's own line drawn and the nesting cut off.
let lines = result.unwrap_or_else(|e| panic!("{e}"));
// The top-level form plus 50_000 nested paints (`MAX_NESTED_PAINTS` in craft-libs' hayro-interpret).
assert!((1..=50_001).contains(&lines), "{lines} lines");
}
#[test]
fn a_huge_curve_is_bounded_and_an_out_of_range_one_is_left_out() {
// A million points across: its flattening is capped, not millions of segments.
let d = import("1000000 0 0 1000000 0 0 cm 0 0 m 0 1 1 1 1 0 c S");
let verts: usize = kinds(&d).iter().map(|e| if let EntityKind::LwPolyline(p) = &e.kind { p.vertices.len() } else { 2 }).sum();
assert!(verts < 5_000, "{verts} vertices");
// 1e20 points across: out of any drawing's range, named in a read note, and nothing runs away.
let d = import("100000000000000000000 0 0 100000000000000000000 0 0 cm 0 0 m 0 1 1 1 1 0 c S");
assert_eq!(kinds(&d).len(), 0);
assert!(d.read_notes.iter().any(|n| n.contains("out-of-range")), "{:?}", d.read_notes);
}
#[test]
fn text_drawn_as_fill_and_stroke_is_one_text() {
// Render mode 2 draws each glyph twice at one origin: fill, then stroke.
let d = import("BT /F1 12 Tf 100 200 Td 2 Tr (Hello) Tj ET");
let texts: Vec<String> =
kinds(&d).into_iter().filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.value.clone()) } else { None }).collect();
assert_eq!(texts, ["Hello"]);
}
#[test]
fn a_plot_of_a_drawing_imports_back_as_its_geometry() {
let mut d = Drawing::new_metric();
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(100.0, 0.0, 0.0) })).unwrap();
d.add(
&Space::Model,
Common::default(),
EntityKind::Text(Text {
insert: Vec3::new(10.0, 20.0, 0.0),
align_pt: None,
height: 5.0,
value: "Plan".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: HAlign::Left,
valign: Default::default(),
}),
)
.unwrap();
let pdf = cadcraft_io::plot(&d, &Space::Model, &json!({ "compress": false, "paper": "A4", "fit": true })).unwrap();
let (back, _) = read(&pdf, &PdfImportOptions::default()).unwrap();
let lines = back.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_) | EntityKind::LwPolyline(_))).count();
assert!(lines >= 1, "{:?}", back.model.iter().map(|e| &e.kind).collect::<Vec<_>>());
}
/// A one-page PDF drawing `content` with Helvetica as `/F1`, whose ToUnicode CMap maps the code
/// `<41>` to `to` (a hex string of UTF-16 code units).
fn page_with_to_unicode(content: &str, to: &str) -> Vec<u8> {
let cmap = format!(
"/CIDInit /ProcSet findresource begin 12 dict begin begincmap\n\
/CMapName /Test def /CMapType 2 def\n\
1 begincodespacerange <00> <FF> endcodespacerange\n\
1 beginbfchar <41> <{to}> endbfchar\n\
endcmap CMapName currentdict /CMap defineresource pop end end"
);
format!(
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [10 0 R] /Count 1 >> endobj\n\
3 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding /ToUnicode 5 0 R >> endobj\n\
5 0 obj << /Length {} >> stream\n{cmap}\nendstream endobj\n\
10 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 11 0 R /Resources << /Font << /F1 3 0 R >> >> >> endobj\n\
11 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
trailer << /Root 1 0 R >>\n%%EOF\n",
cmap.len(),
content.len()
)
.into_bytes()
}
#[test]
fn one_glyph_gives_at_most_32_characters_and_a_page_a_bounded_text() {
// `<41>` (an A) stands for 16 000 Bs.
let long = "0042".repeat(16_000);
let d = read(&page_with_to_unicode("BT /F1 12 Tf 100 200 Td (A) Tj ET", &long), &PdfImportOptions::default()).unwrap().0;
assert_eq!(texts(&d), ["B".repeat(32)]);
// 125 000 of them, each kerned back onto the one before: more text than a page may hold, so
// the import stops with a reason instead of growing the text.
let content = format!("BT /F1 12 Tf 100 200 Td [{}] TJ ET", "(A) 667 ".repeat(125_000));
let e = read(&page_with_to_unicode(&content, &long), &PdfImportOptions::default()).unwrap_err().to_string();
assert!(e.contains("characters of text on the page"), "{e}");
}
#[test]
fn text_with_a_scale_too_large_for_numbers_is_skipped_not_added() {
// Ten times 1e30 makes 1e300; a larger font size pushes the em square past what a number holds,
// and a horizontal scaling of 1000 % its width alone (the baseline's direction).
let big = "1000000000000000000000000000000 0 0 1000000000000000000000000000000 0 0 cm ".repeat(10);
for (size, scaling) in [1, 100, 10_000, 1_000_000, 100_000_000].into_iter().flat_map(|s| [(s, 100), (s, 1000)]) {
let r = read(&page(&format!("{big} BT /F1 {size} Tf {scaling} Tz (AB) Tj ET")), &PdfImportOptions::default());
let (d, _) = r.unwrap_or_else(|e| panic!("size {size}, scaling {scaling}: {e}"));
for e in kinds(&d) {
if let EntityKind::Text(t) = &e.kind {
let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite();
assert!(finite(t.insert) && t.align_pt.is_none_or(finite) && t.rotation.is_finite() && t.height.is_finite(), "{t:?}");
}
}
}
}
#[test]
fn a_curve_after_a_close_starts_where_the_subpath_did() {
let d = import("0 0 m 100 0 l 100 100 l h 0 50 50 100 100 100 c S");
let all = kinds(&d);
assert_eq!(all.len(), 2, "{all:?}");
let EntityKind::LwPolyline(p) = &all[1].kind else { panic!("{:?}", all[1].kind) };
let (first, last) = (p.vertices.first().unwrap().p, p.vertices.last().unwrap().p);
assert!(near(first.x, 0.0) && near(first.y, 0.0), "{first:?}");
assert!(near(last.x, 100.0 * MM_PER_PT) && near(last.y, 100.0 * MM_PER_PT), "{last:?}");
}
#[test]
fn crop_origin_user_units_and_page_rotation_are_applied() {
let pdf = String::from_utf8(page("100 200 m 150 200 l S")).unwrap();
let pdf = pdf.replace("/MediaBox [0 0 600 800]", "/MediaBox [0 0 600 800] /CropBox [100 200 300 400] /UserUnit 2 /Rotate 90");
let (d, _) = read(pdf.as_bytes(), &PdfImportOptions::default()).unwrap();
let all = kinds(&d);
assert_eq!(all.len(), 1);
let EntityKind::Line(line) = &all[0].kind else { panic!("expected a line") };
assert!(near(line.a.x, line.b.x), "rotation makes the line vertical: {line:?}");
assert!(near((line.b.y - line.a.y).abs(), 100.0 * MM_PER_PT), "UserUnit doubles the length: {line:?}");
assert!(line.a.x >= 0.0 && line.a.y >= 0.0 && line.b.x >= 0.0 && line.b.y >= 0.0);
}
#[test]
fn the_page_boundary_and_nested_clips_both_limit_the_import() {
let d = import("q -100 -100 800 1000 re W n q 10 10 40 40 re W n -50 30 m 100 30 l S Q -100 60 m 700 60 l S Q");
let all = kinds(&d);
assert_eq!(all.len(), 2);
let lines: Vec<_> = all.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l) } else { None }).collect();
assert!(lines[0].a.x > lines[1].a.x && lines[0].b.x < lines[1].b.x, "inner clip narrows the first line");
assert!(near(lines[1].a.x, 0.0) && near(lines[1].b.x, 600.0 * MM_PER_PT), "page clips the restored outer line");
}
#[test]
fn text_and_shapes_keep_their_paint_order() {
let d = import("BT /F1 12 Tf 20 20 Td (Below) Tj ET 1 0 0 rg 10 10 100 40 re f BT /F1 12 Tf 20 80 Td (Above) Tj ET");
let all = kinds(&d);
assert!(matches!(all[0].kind, EntityKind::Text(_)));
assert!(matches!(all[1].kind, EntityKind::Hatch(_)));
assert!(matches!(all[2].kind, EntityKind::Text(_)));
assert!(d.read_notes.iter().any(|n| n.contains("Standard font")));
}
#[test]
fn the_same_text_drawn_again_over_a_shape_is_kept() {
// A label, a fill over it, then the label again on top: the second one is what shows.
let d = import("BT /F1 12 Tf 20 20 Td (Label) Tj ET 1 0 0 rg 10 10 100 40 re f BT /F1 12 Tf 20 20 Td (Label) Tj ET");
assert_eq!(texts(&d), ["Label", "Label"]);
assert!(matches!(kinds(&d).last().map(|e| &e.kind), Some(EntityKind::Text(_))));
}
#[test]
fn diagonal_edges_are_not_mistaken_for_a_rectangular_clip() {
let d = import("q 0 0 m 100 100 l 100 0 l 0 100 l h W n 0 50 m 150 50 l S Q");
assert!(d.read_notes.iter().any(|n| n.contains("clips by a shape other than a rectangle")));
}
#[test]
fn a_path_that_doubles_back_along_an_edge_is_not_a_rectangular_clip() {
// Every point lies on the box's edges, but the corner at (0, 100) is never reached.
let d = import("q 0 0 m 100 0 l 100 100 l 100 0 l h W n 0 50 m 150 50 l S Q");
assert!(d.read_notes.iter().any(|n| n.contains("clips by a shape other than a rectangle")), "{:?}", d.read_notes);
let EntityKind::Line(line) = &kinds(&d)[0].kind else { panic!("expected a line") };
assert!(line.b.x > 100.0 * MM_PER_PT, "the line was cut at the box: {line:?}");
}
#[test]
fn raster_only_pages_are_identified_without_fabricated_geometry() {
let d = import("q 100 0 0 100 0 0 cm BI /W 1 /H 1 /CS /RGB /BPC 8 /F /AHx ID FF0000> EI Q");
assert!(d.model.is_empty());
assert!(d.read_notes.iter().any(|n| n.contains("raster image")), "{:?}", d.read_notes);
}
#[test]
fn form_transforms_and_bounding_boxes_are_respected() {
let form = "0 0 m 100 0 l S";
let mut pdf = String::from_utf8(page("/Fm Do"))
.unwrap()
.replace("/Resources << /Font << /F1 3 0 R >> >>", "/Resources << /Font << /F1 3 0 R >> /XObject << /Fm 6 0 R >> >>");
let object = format!(
"6 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Matrix [2 0 0 2 10 30] /Length {} >> stream\n{form}\nendstream endobj\n",
form.len()
);
pdf = pdf.replace("trailer <<", &format!("{object}trailer <<"));
let (d, _) = read(pdf.as_bytes(), &PdfImportOptions::default()).unwrap();
let all = kinds(&d);
assert_eq!(all.len(), 1);
let EntityKind::Line(line) = &all[0].kind else { panic!("expected a line") };
assert!(near(line.a.x, 10.0 * MM_PER_PT) && near(line.b.x, 50.0 * MM_PER_PT), "{line:?}");
assert!(near(line.a.y, 30.0 * MM_PER_PT) && near(line.b.y, line.a.y), "{line:?}");
}
#[test]
fn changed_dash_appearance_is_reported() {
let d = import("[5 3] 0 d 10 10 m 100 10 l S");
assert!(!d.model.is_empty());
assert!(d.read_notes.iter().any(|n| n.contains("dashed paths")), "{:?}", d.read_notes);
}
+1 -2
View File
@@ -19,7 +19,7 @@ fn regions(d: &Drawing) -> Vec<Region> {
fn square(x: f64, y: f64, s: f64, outer: bool) -> HatchLoop {
let v = |a: f64, b: f64| PolyVertex::new(Vec2::new(a, b));
HatchLoop { vertices: vec![v(x, y), v(x + s, y), v(x + s, y + s), v(x, y + s)], outer, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices: vec![v(x, y), v(x + s, y), v(x + s, y + s), v(x, y + s)], outer, sources: Vec::new() }
}
#[test]
@@ -29,7 +29,6 @@ fn region_with_islands_survives_save_and_reopen() {
let hole = HatchLoop {
vertices: vec![PolyVertex::with_bulge(Vec2::new(3.0, 5.0), 1.0), PolyVertex::with_bulge(Vec2::new(7.0, 5.0), 1.0)],
outer: false,
boundary_flags: None,
sources: Vec::new(),
};
let r = Region { loops: vec![square(0.0, 0.0, 10.0, true), hole, square(4.5, 4.5, 1.0, true), square(20.0, 0.0, 2.0, true)] };
@@ -226,7 +226,7 @@ pub(crate) fn hatches() -> Vec<Case> {
EntityKind::Hatch(Hatch {
pattern: "SOLID".into(),
solid: true,
loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, boundary_flags: Some(3), sources: Vec::new() }],
loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
-50
View File
@@ -373,53 +373,3 @@ fn angle_tolerance_does_not_hide_real_changes_or_nonfinite_values() {
assert!(std::panic::catch_unwind(|| angle(0.7, actual, "self-test", "angle")).is_err());
}
}
/// Authored two-point text saves the dimensions of its measured span. Expectations come from
/// shaping and geometry, independently of the save fitting helper; all field assertions remain.
pub(super) fn authored_text_dimensions(d: &Drawing) -> Drawing {
fn fit(d: &Drawing, t: &mut Text) {
use cadcraft_doc::HAlign;
if !matches!(t.halign, HAlign::Aligned | HAlign::Fit) {
return;
}
let Some(second) = t.align_pt else { return };
let distance = t.insert.xy().dist(second.xy());
if !distance.is_finite() || distance <= 1e-12 {
return;
}
t.rotation = t.insert.xy().angle_to(second.xy());
let style = d.text_style(&t.style).cloned().unwrap_or_default();
let font = cadcraft_render::style_font(&style);
let width = cadcraft_fonts::shape_line_dir(&font, &t.value, t.height, t.width_factor, t.oblique, Some(false)).width;
if width.is_finite() && width > 1e-12 {
if t.halign == HAlign::Aligned {
t.height *= distance / width;
} else {
t.width_factor *= distance / width;
}
}
}
fn store(d: &Drawing, entities: &mut EntityStore) {
for h in entities.handles() {
// Read-time measurements already have their own preservation contract.
if d.foreign.text_fits.contains_key(&h) {
continue;
}
entities.modify(h, |e| match &mut e.kind {
EntityKind::Text(t) => fit(d, t),
EntityKind::AttDef(a) => fit(d, &mut a.text),
EntityKind::Insert(i) => i.attribs.iter_mut().for_each(|a| fit(d, &mut a.text)),
_ => {}
});
}
}
let mut expected = d.clone();
store(d, &mut expected.model);
for layout in &mut expected.layouts {
store(d, &mut layout.entities);
}
for block in expected.blocks.values_mut() {
store(d, &mut std::sync::Arc::make_mut(block).entities);
}
expected
}
-2
View File
@@ -57,8 +57,6 @@ fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, versio
}
fn check_version_using(case: &str, original: &Drawing, expected: &Drawing, version: Version, verify: impl Fn(&Drawing, &Drawing, &str)) {
let expected_dimensions = compare::authored_text_dimensions(expected);
let expected = &expected_dimensions;
cadcraft_io::dwg_worker::allow_in_process();
let options = SaveOptions { version: Some(version), binary: false };
let mut current = original.clone();
-2
View File
@@ -33,8 +33,6 @@ fn check_version(case: &str, original: &Drawing, expected: &Drawing, version: Ve
}
fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, version: Version, extra: impl Fn(&Drawing, &Drawing, &str)) {
let expected_dimensions = compare::authored_text_dimensions(expected);
let expected = &expected_dimensions;
for binary in [false, true] {
let options = SaveOptions { version: Some(version), binary };
let mut current = original.clone();
+1 -1
View File
@@ -19,7 +19,7 @@ fn user_linetypes_and_patterns_survive_dxf() {
let h = Hatch {
pattern: steps.name.clone(),
solid: false,
loops: vec![HatchLoop { vertices: square, outer: true, boundary_flags: None, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: square, outer: true, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
-95
View File
@@ -1,95 +0,0 @@
//! Original synthetic geometry, style values and xdata, licensed with the repository.
//! The fixed fields follow Autodesk's 2010 DXF Reference, VISUALSTYLE, pp. 208-210:
//! https://images.autodesk.com/adsk/files/acad_dxf1.pdf
use cadcraft_doc::EntityKind;
use cadcraft_io::{SaveOptions, Version};
fn source(version: &str) -> String {
let mut text = format!(
"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\n{version}\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nAPPID\n5\n10\n100\nAcDbSymbolTable\n70\n1\n\
0\nAPPID\n5\n11\n330\n10\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n2\nACAD\n70\n0\n0\nENDTAB\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic0\n350\n21\n3\nSynthetic1\n350\n22\n"
);
for index in 0..2 {
text.push_str(&format!(
"0\nVISUALSTYLE\n5\n{:X}\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic{index}\n\
70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\
74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n\
76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n\
1001\nACAD\n1000\nAcRTDxfName\n1000\nVISUALSTYLE\n",
0x21 + index
));
}
text.push_str("0\nENDSEC\n0\nEOF\n");
text
}
#[test]
fn legacy_visualstyles_are_reported_and_left_out_of_2007_dwg_only() {
cadcraft_io::dwg_worker::allow_in_process();
for from in ["AC1021", "AC1024"] {
let drawing = cadcraft_io::read_dxf(source(from).as_bytes()).unwrap();
let styles = || drawing.foreign.objects.iter().filter(|object| object.kind == "VISUALSTYLE").count();
assert_eq!(styles(), 2);
for version in [Version::R2007, Version::R2013] {
let options = SaveOptions { version: Some(version), binary: false };
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
assert!(back.model.iter().any(|entity| matches!(entity.kind, EntityKind::Line(_))));
let retained = back
.foreign
.objects
.iter()
.any(|object| object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 2 && tag.value.starts_with("Synthetic")));
if version == Version::R2007 {
assert_eq!(report.get("VISUALSTYLE"), Some(&styles()));
assert!(!retained);
} else {
assert!(!report.contains_key("VISUALSTYLE"));
assert!(retained);
}
let (dxf, report) = cadcraft_io::write_noted(&drawing, "styles.dxf", &options).unwrap();
assert!(report.is_empty());
let back = cadcraft_io::read_dxf(&dxf).unwrap();
assert_eq!(back.foreign.objects.iter().filter(|object| object.kind == "VISUALSTYLE").count(), styles());
}
assert_eq!(styles(), 2);
}
}
#[test]
fn orphaned_legacy_visualstyles_are_not_reported_as_compatibility_omissions() {
cadcraft_io::dwg_worker::allow_in_process();
let mut drawing = cadcraft_io::read_dxf(source("AC1021").as_bytes()).unwrap();
let foreign = std::sync::Arc::make_mut(&mut drawing.foreign);
let orphan = foreign.objects.iter_mut().find(|object| object.kind == "VISUALSTYLE").unwrap();
orphan.tags.iter_mut().find(|tag| tag.code == 330).unwrap().value = "FF".into();
let options = SaveOptions { version: Some(Version::R2007), binary: false };
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
assert!(back.model.iter().any(|entity| matches!(entity.kind, EntityKind::Line(_))));
assert_eq!(report.get("VISUALSTYLE"), Some(&1));
}
#[test]
fn newer_visualstyle_properties_are_kept_in_2007_dwg() {
cadcraft_io::dwg_worker::allow_in_process();
let document = acadrust::DxfReader::from_reader(std::io::Cursor::new(source("AC1027").into_bytes())).unwrap().read().unwrap();
let modern = acadrust::DxfWriter::new(&document).write_to_vec().unwrap();
let drawing = cadcraft_io::read_dxf(&modern).unwrap();
assert!(drawing.foreign.objects.iter().any(|object| object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 176)));
let options = SaveOptions { version: Some(Version::R2007), binary: false };
let (bytes, report) = cadcraft_io::write_noted(&drawing, "styles.dwg", &options).unwrap();
assert!(!report.contains_key("VISUALSTYLE"));
let back = cadcraft_io::read(&bytes, "styles.dwg").unwrap();
assert!(
back.foreign
.objects
.iter()
.any(|object| { object.kind == "VISUALSTYLE" && object.tags.iter().any(|tag| tag.code == 2 && tag.value.starts_with("Synthetic")) })
);
}
-1
View File
@@ -684,7 +684,6 @@ mod tests {
PolyVertex::new(Vec2::new(0.0, 10.0)),
],
outer: true,
boundary_flags: None,
sources: vec![],
};
let loop2 = loop1.clone();
+1 -1
View File
@@ -438,7 +438,7 @@ pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER,
pub use pipeline::{Options, build, build_entities, build_plot};
use props::{default_lineweight, resolve_common};
use text_entity::text_style;
pub use text_entity::{fitted_text_entity, layout_mtext_entity, place_text_entity, style_font, text_align};
pub use text_entity::{layout_mtext_entity, place_text_entity, style_font, text_align};
use viewports::{Clip, append_clipped_keep};
pub use viewports::{clip_list, viewport_clip, viewport_content};
+3 -4
View File
@@ -82,7 +82,7 @@ fn hatch_pattern_and_solid() {
let h = Hatch {
pattern: "ANSI31".into(),
solid: false,
loops: vec![HatchLoop { vertices: sq.clone(), outer: true, boundary_flags: None, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: sq.clone(), outer: true, sources: Vec::new() }],
scale: 1.0,
angle: 0.0,
associative: false,
@@ -514,7 +514,7 @@ fn pattern_hatch(pattern: &str, scale: f64, (x0, y0, x1, y1): (f64, f64, f64, f6
Hatch {
pattern: pattern.into(),
solid: false,
loops: vec![HatchLoop { vertices: sq.to_vec(), outer: true, boundary_flags: None, sources: Vec::new() }],
loops: vec![HatchLoop { vertices: sq.to_vec(), outer: true, sources: Vec::new() }],
scale,
angle: 0.0,
associative: false,
@@ -1371,7 +1371,7 @@ fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() {
}
}
v.rotate_left(rot);
HatchLoop { vertices: v, outer: true, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices: v, outer: true, sources: Vec::new() }
};
let mut h = pattern_hatch("SOLID", 1.0, (0.0, 0.0, 1.0, 1.0));
h.loops = vec![ring(0, false), ring(2, false), ring(1, true), ring(3, true)];
@@ -1380,7 +1380,6 @@ fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() {
h.loops.push(HatchLoop {
vertices: ring(0, false).vertices.into_iter().map(|q| PolyVertex { bulge: 0.0, ..q }).collect(),
outer: true,
boundary_flags: None,
sources: Vec::new(),
});
assert_eq!(loops_of(&h).len(), 2);
+1 -13
View File
@@ -13,18 +13,6 @@ pub fn style_font(ts: &cadcraft_doc::TextStyle) -> cadcraft_fonts::TextFont {
/// Shape a TEXT / ATTRIB / ATTDEF with its style's font and generation flags.
pub fn place_text_entity(d: &Drawing, t: &cadcraft_doc::Text, value: &str) -> (cadcraft_fonts::Shaped, Bounds2) {
let (font, params) = text_params(d, t);
cadcraft_fonts::place(&font, value, &params)
}
/// The dimensions used to display a two-point TEXT, ATTRIB or ATTDEF, for file writers.
pub fn fitted_text_entity(d: &Drawing, t: &cadcraft_doc::Text, value: &str) -> cadcraft_doc::Text {
let (font, params) = text_params(d, t);
let fitted = cadcraft_fonts::fit_params(&font, value, &params);
cadcraft_doc::Text { height: fitted.height, rotation: fitted.rotation, width_factor: fitted.width_factor, ..t.clone() }
}
fn text_params(d: &Drawing, t: &cadcraft_doc::Text) -> (cadcraft_fonts::TextFont, cadcraft_fonts::TextParams) {
let ts = text_style(d, &t.style);
let font = style_font(&ts);
let (h, v) = align(t.halign, t.valign);
@@ -40,7 +28,7 @@ fn text_params(d: &Drawing, t: &cadcraft_doc::Text) -> (cadcraft_fonts::TextFont
backwards: ts.backwards,
upside_down: ts.upside_down,
};
(font, p)
cadcraft_fonts::place(&font, value, &p)
}
/// Lay out an MTEXT with its style's font.
+1 -1
View File
@@ -9,7 +9,7 @@ use cadcraft_render::{DisplayList, Kind, Options, build};
fn square(lo: f64, hi: f64) -> HatchLoop {
let v = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)].into_iter().map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect();
HatchLoop { vertices: v, outer: lo == 0.0, boundary_flags: None, sources: Vec::new() }
HatchLoop { vertices: v, outer: lo == 0.0, sources: Vec::new() }
}
fn hatch(pattern: &str, loops: Vec<HatchLoop>) -> Hatch {
+1 -1
View File
@@ -1562,7 +1562,7 @@ mod tests {
let d = Drawing::new_metric();
assert!(too_much(&d, EntityKind::Wipeout(Wipeout { boundary: points.clone() })));
assert!(too_much(&d, EntityKind::MLine(MLine::new(&MLineStyle::default(), &points, false, MLineJust::default(), 1.0))));
let region = Region { loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, boundary_flags: None, sources: Vec::new() }] };
let region = Region { loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, sources: Vec::new() }] };
assert!(too_much(&d, EntityKind::Region(region)));
// An object with nothing in it still takes a visit, for each cell of an array.
let mut empty = Block::new("EMPTY");
+9 -14
View File
@@ -2,11 +2,10 @@
//! the spot where it went down, however fast the mouse is moving. Where the pointer goes while the
//! button is held only decides whether the press also becomes a drag:
//!
//! - holding still, or staying within the press tolerance, never makes a drag;
//! - holding still, or staying within [`TOLERANCE`] of the press, never makes a drag;
//! - once the pointer leaves the tolerance a timer starts; a button still down [`DRAG_DELAY`]
//! later is a drag (a selection window the press opened closes where the button comes up);
//! - returning within the selection-window tolerance resets the timer; a button that comes up
//! there or before the delay was a click (the window waits for the next press).
//! - a button that comes up sooner was a click (the window waits for the next press).
//!
//! The timer starts on leaving the tolerance, not on the press: pressing, holding still and then
//! moving and letting go quickly is still a click, as in AutoCAD.
@@ -19,16 +18,15 @@ use egui::{Modifiers, Pos2};
/// How far (points) the pointer may wander from the press before the timer starts.
pub(crate) const TOLERANCE: f32 = 6.0;
/// Extra room to click the first corner of a window without committing it by accident.
const WINDOW_TOLERANCE: f32 = 12.0;
/// How long (seconds) the button must stay down outside the tolerance for the press to be a drag.
/// How long (seconds) the button must stay down after the pointer left [`TOLERANCE`] for the
/// press to be a drag.
pub(crate) const DRAG_DELAY: f64 = 0.25;
/// A primary-button press being held.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Press {
origin: Pos2,
/// When the pointer went outside the press tolerance (seconds).
/// When the pointer first went further than [`TOLERANCE`] from `origin` (seconds).
left_at: Option<f64>,
/// The press opened a selection window (set its first corner).
pub(crate) opened_window: bool,
@@ -62,11 +60,8 @@ impl Press {
/// The pointer is at `pos` at time `now`.
pub(crate) fn moved(&mut self, pos: Pos2, now: f64) {
let tolerance = if self.opened_window { WINDOW_TOLERANCE } else { TOLERANCE };
if pos.distance(self.origin) > tolerance {
self.left_at.get_or_insert(now);
} else if self.opened_window {
self.left_at = None;
if self.left_at.is_none() && pos.distance(self.origin) > TOLERANCE {
self.left_at = Some(now);
}
}
@@ -114,7 +109,7 @@ mod tests {
#[test]
fn letting_go_soon_after_leaving_the_tolerance_is_a_click() {
let mut p = Press::new(pos2(100.0, 100.0), true);
p.moved(pos2(115.0, 100.0), 1.0);
p.moved(pos2(112.0, 100.0), 1.0);
assert!(!p.released_as_drag(pos2(130.0, 100.0), 1.0 + DRAG_DELAY / 2.0));
}
@@ -129,7 +124,7 @@ mod tests {
#[test]
fn a_button_still_down_after_the_delay_is_a_drag() {
let mut p = Press::new(pos2(100.0, 100.0), true);
p.moved(pos2(115.0, 100.0), 1.0);
p.moved(pos2(110.0, 100.0), 1.0);
p.moved(pos2(200.0, 150.0), 1.1);
assert!(p.released_as_drag(pos2(250.0, 160.0), 1.0 + DRAG_DELAY));
}
+1
View File
@@ -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),
+118
View File
@@ -26,6 +26,28 @@ pub fn route(app: &mut CadApp, id: &str) -> Result<Value, String> {
"import" | "imp" => app
.pick_then(Pick::Open, |app, path| app.run("import", json!({ "path": path })))
.unwrap_or_else(|| no_picker(app, "IMPORT", r#"import {"path": "parts.dxf"}"#)),
"pdfimport" | "pdfi" => app
.pick_then(Pick::Open, |app, path| {
let doc = app.session.state().ok().map(|s| s.uid);
PDF_PENDING.with(|pending| {
*pending.borrow_mut() = Some(PdfImport {
doc,
path,
page: 1,
scale: 1.0,
at: [0.0, 0.0],
password: String::new(),
text: true,
fills: true,
lineweights: true,
focus_page: true,
error: None,
});
});
app.ui.dialog = Some("pdfimport".into());
Ok(Value::Null)
})
.unwrap_or_else(|| no_picker(app, "PDFIMPORT", r#"pdfimport {"path": "plan.pdf", "page": 1}"#)),
"publish" => app
.pick_then(Pick::Save(format!("{stem}.pdf")), |app, path| app.run("publish", json!({ "path": path })))
.unwrap_or_else(|| no_picker(app, "PUBLISH", "publish {}")),
@@ -35,6 +57,102 @@ pub fn route(app: &mut CadApp, id: &str) -> Result<Value, String> {
}
}
/// A chosen PDF and the editable content requested from its page.
struct PdfImport {
/// The drawing the window was opened for; the page goes there even if another is shown now.
doc: Option<u64>,
path: String,
page: u32,
scale: f64,
at: [f64; 2],
password: String,
text: bool,
fills: bool,
lineweights: bool,
focus_page: bool,
error: Option<String>,
}
thread_local! {
static PDF_PENDING: std::cell::RefCell<Option<PdfImport>> = const { std::cell::RefCell::new(None) };
}
/// Show page and content options before adding the selected PDF page to the drawing.
pub fn pdf_dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
let Some(mut state) = PDF_PENDING.with(|pending| pending.borrow_mut().take()) else {
*open = false;
return;
};
let name = std::path::Path::new(&state.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let (mut import, mut cancel) = (false, false);
egui::Window::new(crate::tl!("Import PDF")).id(egui::Id::unique("cc_pdf_import")).open(open).collapsible(false).resizable(false).show(
ctx,
|ui| {
ui.label(&name);
ui.horizontal(|ui| {
let label = ui.label(crate::tl!("Page number"));
let page = ui.add(egui::DragValue::new(&mut state.page).range(1..=100_000)).labelled_by(label.id);
if state.focus_page {
page.request_focus();
state.focus_page = false;
}
});
ui.horizontal(|ui| {
let label = ui.label(crate::tl!("Scale factor"));
ui.add(egui::DragValue::new(&mut state.scale).speed(0.1).range(1e-9..=1e9).clamp_existing_to_range(false)).labelled_by(label.id);
});
ui.horizontal(|ui| {
let label = ui.label(crate::tl!("Insertion X"));
ui.add(egui::DragValue::new(&mut state.at[0]).speed(1.0).range(-1e9..=1e9).clamp_existing_to_range(false)).labelled_by(label.id);
let label = ui.label(crate::tl!("Insertion Y"));
ui.add(egui::DragValue::new(&mut state.at[1]).speed(1.0).range(-1e9..=1e9).clamp_existing_to_range(false)).labelled_by(label.id);
});
ui.horizontal(|ui| {
let label = ui.label(crate::tl!("Password"));
ui.add(egui::TextEdit::singleline(&mut state.password).password(true)).labelled_by(label.id);
});
ui.checkbox(&mut state.text, crate::tl!("Import text as TEXT"));
ui.checkbox(&mut state.fills, crate::tl!("Import filled shapes as solid hatches"));
ui.checkbox(&mut state.lineweights, crate::tl!("Use the PDF's line widths"));
if let Some(error) = &state.error {
let t = crate::theme::Tokens::get();
let shown = ui.label(egui::RichText::new(crate::tf!("Import failed: {error}", error = error)).color(t.warn));
// Focus stays on the Import button, so the failure is announced.
ui.ctx().accesskit_node_builder(shown.id, |node| node.set_live(egui::accesskit::Live::Assertive));
}
ui.horizontal(|ui| {
import = ui.button(crate::tl!("Import Page")).clicked();
cancel = ui.button(crate::tl!("Cancel")).clicked();
});
},
);
if ctx.input(|input| input.key_pressed(egui::Key::Escape)) {
cancel = true;
}
if import {
let mut params = json!({ "path": state.path, "page": state.page, "scale": state.scale, "at": state.at, "text": state.text, "fills": state.fills, "lineweights": state.lineweights });
if !state.password.is_empty() {
params["password"] = json!(state.password);
}
let index = state.doc.and_then(|uid| app.session.docs.iter().position(|d| d.uid == uid));
let result = match index {
None => Err(crate::tl!("The drawing this window was opened for is closed; nothing was imported.").to_string()),
Some(i) if i != app.session.active => app.run("document.switch", json!({ "index": i })).and_then(|_| app.run("pdfimport", params)),
Some(_) => app.run("pdfimport", params),
};
match result {
Ok(_) => *open = false,
Err(error) => state.error = Some(error),
}
}
if cancel {
*open = false;
}
if *open {
PDF_PENDING.with(|pending| *pending.borrow_mut() = Some(state));
}
}
fn no_picker(app: &mut CadApp, name: &str, example: &str) -> Result<Value, String> {
let msg = format!("{name}: there is no file dialog here; run it with parameters, e.g. {example}");
app.session.echo(msg.clone());
+8 -8
View File
@@ -406,7 +406,7 @@
Grip Option خيار المقبض
Grip Rotate تدوير بالمقبض
Grip Scale تحجيم بالمقبض
Grip Stretch تمطيط بالمقبض
Grip Stretch تمديد بالمقبض
Grip size حجم المقبض
Group تجميع
Group Edit تحرير المجموعة
@@ -703,7 +703,7 @@
Plotter Manager مدير الطابعات
Plotter Manager... مدير الطابعات...
Plus/minus زائد/ناقص
Point نقطة
Point تأشير
Point Filters مرشحات النقطة
Point Style... نمط النقطة...
Polar (distance < angle) قطبي (المسافة < الزاوية)
@@ -872,15 +872,15 @@
Select object حدد كائناً
Select object to dimension حدد كائناً لتأشيره
Select object to divide حدد كائناً لتقسيمه
Select object to extend or shift-select to trim حدد كائناً لتمديده أو حدد مع Shift للتشذيب
Select object to extend or shift-select to trim حدد كائناً لتمديده أو حدد مع Shift للقص
Select object to measure حدد كائناً لقياسه
Select object to offset حدد كائناً لإزاحته
Select object to trim or shift-select to extend حدد كائناً لتشذيبه أو حدد مع Shift للتمديد
Select object to trim or shift-select to extend حدد كائناً لقصه أو حدد مع Shift للتمديد
Select objects حدد كائنات
Select objects (crossing window first corner) حدد كائنات (الزاوية الأولى لنافذة التقاطع)
Select objects first, then choose a command حدد الكائنات أولاً ثم اختر أمراً
Select objects to array. حدد كائنات لتكوين مصفوفة.
Select objects to stretch by crossing-window or crossing-polygon... حدد كائنات لتمطيطها بنافذة التقاطع أو مضلع التقاطع...
Select objects to stretch by crossing-window or crossing-polygon... حدد كائنات لتمديدها بنافذة التقاطع أو مضلع التقاطع...
Select objects: حدد كائنات:
Select one polyline (Multiple is available through the JSON form). حدد متعدد خطوط واحداً (يتوفر الوضع المتعدد عبر نموذج JSON).
Select path curve حدد منحنى المسار
@@ -1084,8 +1084,8 @@
Start, End, Radius بداية، نهاية، نصف قطر
Status الحالة
Status Bar شريط الحالة
Stretch تمطيط
Stretch Vertex تمطيط رأس
Stretch تمديد
Stretch Vertex تمديد رأس
Style: Standard النمط: Standard
Subtract طرح
Sweep كنس
@@ -1134,7 +1134,7 @@
Track orthogonally only تعقب متعامد فقط
Track using all polar angle settings تعقب باستخدام كل إعدادات الزوايا القطبية
Transparency شفافية
Trim تشذيب
Trim حدود التشذيب
True Color لون حقيقي
Turn All Layers On تشغيل كل الطبقات
Turn Off Layer إيقاف طبقة
1 # CADCraft Arabic interface catalog — original translations.
406
407
408
409
410
411
412
703
704
705
706
707
708
709
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
1084
1085
1086
1087
1088
1089
1090
1091
1134
1135
1136
1137
1138
1139
1140
+101 -101
View File
@@ -1,4 +1,4 @@
# CADCraft French interface catalog — original translations by @pechnikov2026-star; terminology review by @YannFR81.
# CADCraft French interface catalog — original translations by @pechnikov2026-star.
# License: MIT OR Apache-2.0 (the repository LICENSE-MIT and LICENSE-APACHE).
# Written from CADCraft's English strings; no proprietary translations were copied.
# UTF-8: context<TAB>English source<TAB>French translation.
@@ -160,7 +160,7 @@
Delete Supprimer
Delete Column Supprimer la colonne
Delete Constraints Supprimer les contraintes
Delete Dimension Style Supprimer le style de cote
Delete Dimension Style Supprimer le style de cotation
Delete Duplicate Objects Supprimer les objets en double
Delete Layer Supprimer le calque
Delete Layer State Supprimer l'état des calques
@@ -172,17 +172,17 @@
Description Description
Deselect All Désélectionner tout
Diameter Diamètre
Dim style Style de cote
Dim style Style de cotation
Dimension Cotation
Dimension Space Espacer les cotes
Dimension Style Override Remplacement de style de cote
Dimension Style... Style de cote...
Dimension Text Edit Modifier le texte de cote
Dimension style Style de cote
Dimension Space Espace entre cotations
Dimension Style Override Substitution de style de cotation
Dimension Style... Style de cotation...
Dimension Text Edit Modifier le texte de cotation
Dimension style Style de cotation
Dimensional Constraint Contrainte dimensionnelle
Dimensional Constraint Parameters Paramètres de contraintes dimensionnelles
Dimensional Constraints Contraintes dimensionnelles
Disassociate Dimensions Dissocier les cotes
Disassociate Dimensions Dissocier les cotations
Display name Nom d'affichage
Distance Distance
Divide Diviser
@@ -200,7 +200,7 @@
Drawing Limits Limites du dessin
Drawing Utilities Utilitaires de dessin
Drawings (DWG, DXF) Dessins (DWG, DXF)
Dynamic Dimensions Cotes dynamiques
Dynamic Dimensions Cotations dynamiques
Dynamic Input Saisie dynamique
Dynamic Input (F12) Saisie dynamique (F12)
E Est
@@ -233,9 +233,9 @@
Enter degree of spline Entrez le degré de la spline
Enter delta angle Entrez l'écart d'angle
Enter delta length Entrez l'écart de longueur
Enter dimension text Entrez le texte de cote
Enter dimension text (<> = measurement) Entrez le texte de cote (<> = mesure)
Enter dimension value or [name=expression] Entrez la valeur de cote ou [name=expression]
Enter dimension text Entrez le texte de cotation
Enter dimension text (<> = measurement) Entrez le texte de cotation (<> = mesure)
Enter dimension value or [name=expression] Entrez la valeur de cotation ou [name=expression]
Enter dimension variable name to override Entrez le nom de la variable de cotation à substituer
Enter justification type Entrez le type de justification
Enter leader text Entrez le texte du repère
@@ -254,10 +254,10 @@
Enter rectangle length Entrez la longueur du rectangle
Enter rectangle width Entrez la largeur du rectangle
Enter scale factor Entrez le facteur d'échelle
Enter text Entrez le texte
Enter text (use \P for new paragraphs) Entrez le texte (utilisez \P pour les nouveaux paragraphes)
Enter the number of segments Entrez le nombre de segments
Enter twist direction of helix Entrez le sens de vrillage de l'hélice
Enter text Entrer le texte
Enter text (use \P for new paragraphs) Entrer le texte (utilisez \P pour les nouveaux paragraphes)
Enter the number of segments Entrer le nombre de segments
Enter twist direction of helix Entrer le sens de vrillage de l'hélice
Entire drawing Tout le dessin
Equal Égalité
Erase Effacer
@@ -482,8 +482,8 @@
Object Snap Accrochage aux objets
Object Snap (F3) Accrochage aux objets (F3)
Object Snap On (F3) Activer l'accrochage aux objets (F3)
Object Snap Tracking Repérage d'accrochage aux objets
Object Snap Tracking (F11) Repérage d'accrochage aux objets (F11)
Object Snap Tracking Suivi de l'accrochage aux objets
Object Snap Tracking (F11) Suivi de l'accrochage aux objets (F11)
Object type: Type d'objet :
Off Désactivé
Offset Décalage
@@ -539,7 +539,7 @@
New STB Nouvelle STB
New style Nouveau style
Reset Panel Layout Réinitialiser la disposition des panneaux
Use for this layout Utiliser pour cette présentation
Use for this layout Utiliser pour cet espace
Display plot styles Afficher les styles de tracé
No plot style tables. Aucune table de styles de tracé.
A built-in table: editing it keeps an edited copy in the drawing. Table intégrée : sa modification conserve une copie modifiée dans le dessin.
@@ -560,9 +560,9 @@
Point Filters Filtres de points
Point Style... Style de point...
Polar Array Réseau polaire
Polar Tracking Repérage polaire
Polar Tracking (F10) Repérage polaire (F10)
Polar Tracking On (F10) Activer le repérage polaire (F10)
Polar Tracking Recherche polaire
Polar Tracking (F10) Recherche polaire (F10)
Polar Tracking On (F10) Activer la recherche polaire (F10)
Polar: {distance} < {angle}° Polaire : {distance} < {angle}°
Polygon Polygone
Polygonal Polygonal
@@ -645,77 +645,77 @@
Search for parameter Rechercher un paramètre
Second and next points: Deuxième point et points suivants :
Select Sélectionner
Select 2D polyline Sélectionnez une polyligne 2D
Select 2D polyline Sélectionner une polyligne 2D
Select All Sélectionner tout
Select Objects Sélectionner les objets
Select a 2D polyline. Sélectionnez une polyligne 2D.
Select a block reference. Sélectionnez une référence de bloc.
Select a circle or arc. Sélectionnez un cercle ou un arc.
Select a closed polyline Sélectionnez une polyligne fermée
Select a closed polyline, circle, ellipse or closed spline. Sélectionnez une polyligne fermée, un cercle, une ellipse ou une spline fermée.
Select a closed polyline. Sélectionnez une polyligne fermée.
Select a curve as the path. Sélectionnez une courbe comme trajectoire.
Select a dimension constraint type Sélectionnez un type de contrainte dimensionnelle
Select a line object Sélectionnez une ligne
Select a line object. Sélectionnez une ligne.
Select a line or an arc. Sélectionnez une ligne ou un arc.
Select a line or polyline segment Sélectionnez une ligne ou un segment de polyligne
Select a line, arc or open polyline. Sélectionnez une ligne, un arc ou une polyligne ouverte.
Select a line, arc, circle, polyline, ellipse or spline as the path. Sélectionnez une ligne, un arc, un cercle, une polyligne, une ellipse ou une spline comme trajectoire.
Select a line, circle, arc or polyline segment. Sélectionnez une ligne, un cercle, un arc ou un segment de polyligne.
Select a line. Sélectionnez une ligne.
Select a 2D polyline. Sélectionner une polyligne 2D.
Select a block reference. Sélectionner une référence de bloc.
Select a circle or arc. Sélectionner un cercle ou un arc.
Select a closed polyline Sélectionner une polyligne fermée
Select a closed polyline, circle, ellipse or closed spline. Sélectionner une polyligne fermée, un cercle, une ellipse ou une spline fermée.
Select a closed polyline. Sélectionner une polyligne fermée.
Select a curve as the path. Sélectionner une courbe comme trajectoire.
Select a dimension constraint type Sélectionner un type de contrainte dimensionnelle
Select a line object Sélectionner une ligne
Select a line object. Sélectionner une ligne.
Select a line or an arc. Sélectionner une ligne ou un arc.
Select a line or polyline segment Sélectionner une ligne ou un segment de polyligne
Select a line, arc or open polyline. Sélectionner une ligne, un arc ou une polyligne ouverte.
Select a line, arc, circle, polyline, ellipse or spline as the path. Sélectionner une ligne, un arc, un cercle, une polyligne, une ellipse ou une spline comme trajectoire.
Select a line, circle, arc or polyline segment. Sélectionner une ligne, un cercle, un arc ou un segment de polyligne.
Select a line. Sélectionner une ligne.
Add to Working Set Ajouter au jeu de travail
Edit Reference In-Place Modifier la référence sur place
Save Reference Edits Enregistrer les modifications de la référence
Working Set Jeu de travail
Xref and Block In-place Editing Édition sur place des xrefs et des blocs
Select a polyline. Sélectionnez une polyligne.
Select a text, mtext, attribute definition or dimension. Sélectionnez un texte, un texte multiligne, une définition d'attribut ou une cote.
Select an annotation object Sélectionnez un objet d'annotation
Select an arc or circle Sélectionnez un arc ou un cercle
Select an arc. Sélectionnez un arc.
Select an object Sélectionnez un objet
Select an object to change Sélectionnez un objet à modifier
Select an object to measure Sélectionnez un objet à mesurer
Select an object. Sélectionnez un objet.
Select an open curve. Sélectionnez une courbe ouverte.
Select an open line, arc, polyline, ellipse arc or spline. Sélectionnez une ligne, un arc, une polyligne, un arc elliptique ou une spline ouverts.
Select arc or circle Sélectionnez un arc ou un cercle
Select arc or polyline arc segment Sélectionnez un arc ou un segment d'arc de polyligne
Select arc style Sélectionnez un style d'arc
Select arc, circle, line Sélectionnez un arc, un cercle, une ligne
Select at least two objects to join. Sélectionnez au moins deux objets à joindre.
Select circle or arc to add center mark Sélectionnez un cercle ou un arc pour ajouter une marque de centre
Select closed objects (regions, closed polylines, circles). Sélectionnez des objets fermés (régions, polylignes fermées, cercles).
Select first line Sélectionnez la première ligne
Select first line or arc Sélectionnez la première ligne ou le premier arc
Select first object Sélectionnez le premier objet
Select first point Sélectionnez le premier point
Select nested objects to copy Sélectionnez des objets imbriqués à copier
Select object Sélectionnez un objet
Select object to dimension Sélectionnez un objet à coter
Select object to divide Sélectionnez un objet à diviser
Select object to extend or shift-select to trim Sélectionnez un objet à prolonger ou sélectionnez avec Maj pour rogner
Select object to measure Sélectionnez un objet à mesurer
Select object to offset Sélectionnez un objet à décaler
Select object to trim or shift-select to extend Sélectionnez un objet à rogner ou sélectionnez avec Maj pour prolonger
Select objects Sélectionnez les objets
Select objects (crossing window first corner) Sélectionnez les objets (premier coin de la fenêtre de capture)
Select objects to array. Sélectionnez les objets à répartir en réseau.
Select objects to stretch by crossing-window or crossing-polygon... Sélectionnez les objets à étirer par fenêtre de capture ou polygone de capture...
Select objects: Sélectionnez les objets :
Select one polyline (Multiple is available through the JSON form). Sélectionnez une polyligne (l'option Multiple est disponible via le formulaire JSON).
Select path curve Sélectionnez la courbe de trajectoire
Select point or object Sélectionnez un point ou un objet
Select polyline Sélectionnez une polyligne
Select second line Sélectionnez la deuxième ligne
Select second line or shift-select to apply corner Sélectionnez la deuxième ligne ou sélectionnez avec Maj pour former le coin
Select second object Sélectionnez le deuxième objet
Select second object or shift-select to apply corner Sélectionnez le deuxième objet ou sélectionnez avec Maj pour former le coin
Select second point Sélectionnez le deuxième point
Select spline Sélectionnez une spline
Select symmetry line Sélectionnez l'axe de symétrie
Select two points Sélectionnez deux points
Select a polyline. Sélectionner une polyligne.
Select a text, mtext, attribute definition or dimension. Sélectionner un texte, un texte multiligne, une définition d'attribut ou une cote.
Select an annotation object Sélectionner un objet d'annotation
Select an arc or circle Sélectionner un arc ou un cercle
Select an arc. Sélectionner un arc.
Select an object Sélectionner un objet
Select an object to change Sélectionner un objet à modifier
Select an object to measure Sélectionner un objet à mesurer
Select an object. Sélectionner un objet.
Select an open curve. Sélectionner une courbe ouverte.
Select an open line, arc, polyline, ellipse arc or spline. Sélectionner une ligne, un arc, une polyligne, un arc elliptique ou une spline ouverts.
Select arc or circle Sélectionner un arc ou un cercle
Select arc or polyline arc segment Sélectionner un arc ou un segment d'arc de polyligne
Select arc style Sélectionner un style d'arc
Select arc, circle, line Sélectionner un arc, un cercle, une ligne
Select at least two objects to join. Sélectionner au moins deux objets à joindre.
Select circle or arc to add center mark Sélectionner un cercle ou un arc pour ajouter une marque de centre
Select closed objects (regions, closed polylines, circles). Sélectionner des objets fermés (régions, polylignes fermées, cercles).
Select first line Sélectionner la première ligne
Select first line or arc Sélectionner la première ligne ou le premier arc
Select first object Sélectionner le premier objet
Select first point Sélectionner le premier point
Select nested objects to copy Sélectionner des objets imbriqués à copier
Select object Sélectionner un objet
Select object to dimension Sélectionner un objet à coter
Select object to divide Sélectionner un objet à diviser
Select object to extend or shift-select to trim Sélectionner un objet à prolonger ou sélectionner avec Maj pour rogner
Select object to measure Sélectionner un objet à mesurer
Select object to offset Sélectionner un objet à décaler
Select object to trim or shift-select to extend Sélectionner un objet à rogner ou sélectionner avec Maj pour prolonger
Select objects Sélectionner les objets
Select objects (crossing window first corner) Sélectionner les objets (premier coin de la fenêtre de capture)
Select objects to array. Sélectionner les objets à répartir en réseau.
Select objects to stretch by crossing-window or crossing-polygon... Sélectionner les objets à étirer par fenêtre de capture ou polygone de capture...
Select objects: Sélectionner les objets :
Select one polyline (Multiple is available through the JSON form). Sélectionner une polyligne (l'option Multiple est disponible via le formulaire JSON).
Select path curve Sélectionner la courbe de trajectoire
Select point or object Sélectionner un point ou un objet
Select polyline Sélectionner une polyligne
Select second line Sélectionner la deuxième ligne
Select second line or shift-select to apply corner Sélectionner la deuxième ligne ou sélectionner avec Maj pour former le coin
Select second object Sélectionner le deuxième objet
Select second object or shift-select to apply corner Sélectionner le deuxième objet ou sélectionner avec Maj pour former le coin
Select second point Sélectionner le deuxième point
Select spline Sélectionner une spline
Select symmetry line Sélectionner l'axe de symétrie
Select two points Sélectionner deux points
Selection Cycling Cycle de sélection
Send to Back Envoyer à l'arrière-plan
Set Current Définir comme courant
@@ -747,18 +747,18 @@
Snap and Grid Accrochage et grille
Solid Solide
Sort Trier
Specify a point Spécifiez un point
Specify a scale for the hatch pattern Spécifiez une échelle pour le motif de hachures
Specify a second extension line origin Spécifiez l'origine de la deuxième ligne d'attache
Specify an angle for the hatch pattern Spécifiez un angle pour le motif de hachures
Specify angle end point Spécifiez le point final de l'angle
Specify angle of dimension line Spécifiez l'angle de la ligne de cote
Specify angle of dimension text Spécifiez l'angle du texte de cote
Specify angle start point Spécifiez le point de départ de l'angle
Specify angle vertex Spécifiez le sommet de l'angle
Specify angle vertex point Spécifiez le point du sommet de l'angle
Specify arc length dimension location Spécifiez l'emplacement de la cote de longueur d'arc
Specify axis endpoint of ellipse Spécifiez l'extrémité de l'axe de l'ellipse
Specify a point Spécifier un point
Specify a scale for the hatch pattern Spécifier une échelle pour le motif de hachures
Specify a second extension line origin Spécifier l'origine de la deuxième ligne d'attache
Specify an angle for the hatch pattern Spécifier un angle pour le motif de hachures
Specify angle end point Spécifier le point final de l'angle
Specify angle of dimension line Spécifier l'angle de la ligne de cote
Specify angle of dimension text Spécifier l'angle du texte de cote
Specify angle start point Spécifier le point de départ de l'angle
Specify angle vertex Spécifier le sommet de l'angle
Specify angle vertex point Spécifier le point du sommet de l'angle
Specify arc length dimension location Spécifier l'emplacement de la cote de longueur d'arc
Specify axis endpoint of ellipse Spécifier l'extrémité de l'axe de l'ellipse
Specify base diameter Spécifiez le diamètre de la base
Specify base point Spécifiez le point de base
Specify base point or displacement (drag with the middle mouse button for realtime pan) Spécifiez le point de base ou le déplacement (faites glisser avec le bouton central de la souris pour un panoramique en temps réel)
@@ -768,7 +768,7 @@
Specify center of polygon Spécifiez le centre du polygone
Specify center point for circle Spécifiez le point central du cercle
Specify center point of arc Spécifiez le point central de l'arc
Specify center point of array Spécifiez le point central du réseau
Specify center point of array Spécifiez le point central de la matrice
Specify center point of base Spécifiez le point central de la base
Specify corner of viewport Spécifiez le coin de la fenêtre
Specify corner of window, enter a scale factor (nX or nXP) Spécifiez le coin de la fenêtre, entrez un facteur d'échelle (nX ou nXP)
@@ -894,7 +894,7 @@
Sweep Balayage
Switch Drawing Changer de dessin
Switch Layout Changer de présentation
Switch between model space in a viewport and paper space Basculer entre l'espace objet dans une fenêtre et l'espace papier
Switch between model space in a viewport and paper space Basculer entre l'espace modèle dans une fenêtre et l'espace papier
Symmetric Symétrie
Synchronize Attributes Synchroniser les attributs
Toggle PICKADD (off: each pick replaces the selection) Basculer PICKADD (désactivé : chaque sélection remplace la sélection existante)
1 # CADCraft French interface catalog — original translations by @pechnikov2026-star; terminology review by @YannFR81. # CADCraft French interface catalog — original translations by @pechnikov2026-star.
2 # License: MIT OR Apache-2.0 (the repository LICENSE-MIT and LICENSE-APACHE).
3 # Written from CADCraft's English strings; no proprietary translations were copied.
4 # UTF-8: context<TAB>English source<TAB>French translation.
160
161
162
163
164
165
166
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
200
201
202
203
204
205
206
233
234
235
236
237
238
239
240
241
254
255
256
257
258
259
260
261
262
263
482
483
484
485
486
487
488
489
539
540
541
542
543
544
545
560
561
562
563
564
565
566
567
568
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
768
769
770
771
772
773
774
894
895
896
897
898
899
900
+4 -59
View File
@@ -340,7 +340,7 @@
Exclude from new selection set ახალი მონიშნულიდან გამორიცხვა
Explode დაშლა
Explode Attributes to Text ატრიბუტების ტექსტად დაშლა
Export ექსპორტირება
Export ექსპორტი
Export Table ცხრილის ექსპორტი
Export to PDF... PDF-ად ექსპორტი...
Express Tools Express Tools
@@ -707,8 +707,8 @@
Previous Change წინა ცვლილება
Previous Layer წინა შრე
Primitives პრიმიტივები
Print ბეჭდვა
Print... ბეჭდვა...
Print დაბეჭდვა
Print... დაბეჭდვა...
Properties თვისებები
Properties Inspector თვისებების ინსპექტორი
Properties: თვისებები:
@@ -1242,7 +1242,7 @@
Animation effects ანიმაციის ეფექტები
Interface scale ინტერფეისის მასშტაბი
Import... იმპორტი...
Export... ექსპორტირება...
Export... ექსპორტი...
Batch Publish... პაკეტური გამოქვეყნება...
Scale List... მასშტაბების სია...
Annotative Object Scale ანოტაციური ობიექტის მასშტაბი
@@ -1472,26 +1472,6 @@ menu View ხედი
Text to find მოსაძებნი ტექსტი
Whole words მთლიანი სიტყვები
Nothing found ვერაფერი მოიძებნა
Multiple Insert მრავალჯერადი ჩასმა
Ctrl+Enter to apply გამოსაყენებლად: Ctrl+Enter
Edit Text ტექსტის რედაქტირება
The drawing changed. Close the window and open it again. ნახაზი შეიცვალა. დახურეთ ფანჯარა და ხელახლა გახსენით.
DView დინამიკური ხედი
Raster Image Reference... რასტრული გამოსახულების მიმართვა...
Raster Images რასტრული გამოსახულებები
Clip Xref გარე მიმართვის მოჭრა
Xref გარე მიმართვა
Xref Clip Frame გარე მიმართვის მოჭრის ჩარჩო
Backup copies are off, so the current file will be replaced. სარეზერვო ასლები გამორთულია, ამიტომ მიმდინარე ფაილი ჩანაცვლდება.
DXF 2010 and earlier keep them. Use Save As to keep them in the drawing. DXF 2010 და უფრო ძველი ვერსიები მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“.
DXF keeps them. Use Save As to keep them in the drawing. DXF მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“.
Save Anyway მაინც შენახვა
Save cancelled: {path} was not changed. შენახვა გაუქმდა: {path} არ შეცვლილა.
Saving {name} will remove content ფაილში {name} შენახვისას შიგთავსის ნაწილი წაიშლება
The current file doesn't look whole, so {name} stays as it is and the current file will be replaced. მიმდინარე ფაილი არასრული ჩანს, ამიტომ {name} უცვლელი რჩება, მიმდინარე ფაილი კი ჩანაცვლდება.
The current file is kept as {name} until the next save. მიმდინარე ფაილი შემდეგ შენახვამდე შენარჩუნდება სახელით {name}.
This format can't keep these objects yet: {objects}. ეს ფორმატი ამ ობიექტებს ჯერ ვერ ინახავს: {objects}.
{count} more types კიდევ {count} ტიპი
Add a drawing file as a block library ნახაზის ფაილის დამატება ბლოკების ბიბლიოთეკად
Add a folder of drawings or a drawing file to use its blocks. დაამატეთ ნახაზების საქაღალდე ან ნახაზის ფაილი მისი ბლოკების გამოსაყენებლად.
Block Libraries ბლოკების ბიბლიოთეკები
@@ -1522,38 +1502,3 @@ menu View ხედი
# ArtCraft feature naming
Additional Tools დამატებითი ხელსაწყოები
# Keyboard Shortcuts, Right-Click Customization, alias import
Keyboard Shortcuts... კლავიატურის მალსახმობები...
Keyboard Shortcuts კლავიატურის მალსახმობები
Replaces the shortcut of {commands} ჩაანაცვლებს ამ ბრძანებების მალსახმობს: {commands}
Needs Ctrl, Alt or a function key საჭიროა Ctrl, Alt ან ფუნქციური კლავიში
Press the keys დააჭირეთ კლავიშებს
Back to CADCraft's shortcut CADCraft-ის მალსახმობზე დაბრუნება
A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. თქვენ მიერ მინიჭებულ მალსახმობს უპირატესობა აქვს CADCraft-ის საკუთარზე. ცვლილებები მაშინვე მოქმედებს და შემდეგი ჯერისთვისაც ინახება.
Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode. გამორთვისას ბრძანების შესრულების დროს მარჯვენა დაწკაპება იმას აკეთებს, რაც „მარჯვენა დაწკაპების მორგებაში“ ბრძანების რეჟიმისთვის არის არჩეული.
Right-Click Customization... მარჯვენა დაწკაპების მორგება...
Right-Click Customization მარჯვენა დაწკაპების მორგება
Turn on time-sensitive right-click დროზე დამოკიდებული მარჯვენა დაწკაპების ჩართვა
Longer click duration: გრძელი დაწკაპების ხანგრძლივობა:
milliseconds მილიწამი
While a command runs, a quick click is Enter and a longer click opens the shortcut menu. ბრძანების შესრულების დროს მოკლე დაწკაპება Enter-ია, გრძელი დაწკაპება კი კონტექსტურ მენიუს ხსნის.
Default Mode ნაგულისხმევი რეჟიმი
No objects selected and no command running: არაფერია მონიშნული და არცერთი ბრძანება არ სრულდება:
Edit Mode რედაქტირების რეჟიმი
Objects selected and no command running: ობიექტები მონიშნულია და არცერთი ბრძანება არ სრულდება:
Repeat last command ბოლო ბრძანების გამეორება
Shortcut Menu კონტექსტური მენიუ
Command Mode ბრძანების რეჟიმი
While a command runs: ბრძანების შესრულების დროს:
ENTER ENTER
Shortcut Menu: always enabled კონტექსტური მენიუ: ყოველთვის ჩართული
Shortcut Menu: enabled when command options are present კონტექსტური მენიუ: ჩართული, როცა ბრძანებას ვარიანტები აქვს
Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter. იმპორტი: აქ ფაილის არჩევის დიალოგი არ არის; გაუშვით ALIASEDIT და ფაილის შიგთავსი გადაეცით მის text პარამეტრს.
Aliases are saved in your CADCraft profile and survive restarts. ფსევდონიმები თქვენს CADCraft-ის პროფილში ინახება და გადატვირთვის შემდეგაც რჩება.
Import… იმპორტი…
Run ALIASEDIT with the file's contents using its text parameter. გაუშვით ALIASEDIT და ფაილის შიგთავსი გადაეცით მის text პარამეტრს.
Importing a file replaces your {n} aliases, and any changes not applied yet. ფაილის იმპორტი ჩაანაცვლებს თქვენს ფსევდონიმებს ({n}) და ჯერ გამოუყენებელ ცვლილებებს.
Import and replace იმპორტი და ჩანაცვლება
Keep my aliases ჩემი ფსევდონიმების შენარჩუნება
{n} more warnings; see the command line. კიდევ {n} გაფრთხილება; იხილეთ ბრძანების სტრიქონი.
Can't render this file because it contains an unexpected character in line 10 and column 14.
-705
View File
@@ -1511,711 +1511,6 @@ menu Modify Ändra
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Ritningen har ändrats. Stäng fönstret och öppna det igen.
DView DView
Keyboard Shortcuts... Kortkommandon...
Multiple Insert Infoga flera
Raster Image Reference... Rasterbildsreferens...
Raster Images Rasterbilder
Clip Xref Beskär xref
Xref Xref
Xref Clip Frame Beskärningsram för xref
A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. Ett kortkommando du anger går före CADCrafts eget. Ändringar gäller direkt och sparas till nästa gång.
Alias files (PGP) Aliasfiler (PGP)
Aliases are saved in your CADCraft profile and survive restarts. Alias sparas i din CADCraft-profil och finns kvar efter omstart.
Back to CADCraft's shortcut Tillbaka till CADCrafts kortkommando
Command Mode Kommandoläge
Default Mode Standardläge
Edit Mode Redigeringsläge
ENTER ENTER
Import and replace Importera och ersätt
Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter. Importera: det finns ingen fildialogruta här; kör ALIASEDIT med filens innehåll i dess textparameter.
Importing a file replaces your {n} aliases, and any changes not applied yet. Om du importerar en fil ersätts dina {n} alias och alla ändringar du inte har använt än.
Import… Importera…
Keep my aliases Behåll mina alias
Keyboard Shortcuts Kortkommandon
Longer click duration: Längd för längre klick:
milliseconds millisekunder
Needs Ctrl, Alt or a function key Kräver Ctrl, Alt eller en funktionstangent
No objects selected and no command running: Inga objekt markerade och inget kommando körs:
Objects selected and no command running: Objekt markerade och inget kommando körs:
Press the keys Tryck på tangenterna
Repeat last command Upprepa senaste kommandot
Replaces the shortcut of {commands} Ersätter kortkommandot för {commands}
Right-Click Customization Anpassning av högerklick
Right-Click Customization... Anpassning av högerklick...
Run ALIASEDIT with the file's contents using its text parameter. Kör ALIASEDIT med filens innehåll i dess textparameter.
Shortcut Menu Snabbmeny
Shortcut Menu: always enabled Snabbmeny: alltid aktiverad
Shortcut Menu: enabled when command options are present Snabbmeny: aktiverad när det finns kommandoalternativ
Turn on time-sensitive right-click Slå på tidskänsligt högerklick
Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode. När det är avstängt gör ett högerklick under ett pågående kommando det som Anpassning av högerklick anger för kommandoläget.
While a command runs, a quick click is Enter and a longer click opens the shortcut menu. Medan ett kommando körs är ett snabbt klick Enter och ett längre klick öppnar snabbmenyn.
While a command runs: Medan ett kommando körs:
{n} more warnings; see the command line. {n} varningar till; se kommandoraden.
# ArtCraft feature naming
Additional Tools Ytterligare verktyg
Grid Rutnät
Ortho Orto
Workspace Arbetslayout
Settings Inställningar
Preferences Inställningar
Current: Aktuell:
Continuous Kontinuerlig
Displayed layers Visade lager
Black Svart
Gray Grå
Grey Grå
Orange Orange
Purple Lila
Brown Brun
Pink Rosa
Rename Byt namn
Select Color Välj färg
Layer filters Lagerfilter
Dashed Streckad
Dotted Prickad
Dashdot Streckprickad
Hidden Dold
Phantom Fantom
Clear selection Rensa markering
Model Space Modellrymd
Plot Settings Plottinställningar
Perimeter Omkrets
Polar Polär
Lineweight Display Visning av linjetjocklek
Annotation Anteckning
Annotative Annotativ
Insertion point Insättningspunkt
Base point Baspunkt
Scale factor Skalfaktor
Rotation angle Rotationsvinkel
X coordinate X-koordinat
Y coordinate Y-koordinat
Z coordinate Z-koordinat
Cancel operation Avbryt åtgärden
Reset Återställ
Update Fields Uppdatera fält
Edit Xref in Place Redigera xref på plats
New UCS Nytt UCS
World Världen
Face Yta
Origin Origo
LwPolyline LwPolyline
New Sheet Set... Ny ritningsuppsättning...
Open Sheet Set... Öppna ritningsuppsättning...
Clear Menu Rensa meny
Attach... Koppla...
Export Layout to Model... Exportera layout till modell...
Package Drawing... Paketera ritning...
DWG Compare... DWG-jämförelse...
Markup Import... Importera kommentarer...
Share... Dela...
Undo Group of commands Ångra kommandogrupp
Constrained Orbit Begränsad kretsning
Free Orbit Fri kretsning
Camera Kamera
Adjust Distance Justera avstånd
Swivel Svängning
3D Views 3D-vyer
Viewpoint Vypunkt
Plan View Planvy
Current UCS Aktuellt UCS
World UCS Världs-UCS
Named UCS Namngivna UCS
Bottom Nederkant
Front Framifrån
Back Tillbaka
SW Isometric SV-isometrisk
SE Isometric Isometrisk SO
NE Isometric Isometrisk NO
NW Isometric Isometrisk NV
Hide Dölj
Visual Styles Visuella stilar
2D Wireframe 2D-trådram
Wireframe Trådram
Realistic Realistisk
Conceptual Konceptuell
Shaded Skuggad
Shaded with Edges Skuggad med kanter
Shades of Gray Gråtoner
Sketchy Skissartad
X-Ray Genomskinlig
Render Rendera
New Point Light Nytt punktljus
New Spotlight Ny strålkastare
New Distant Light Nytt avlägset ljus
Light Glyphs Ljusglyfer
Materials Browser Materialbläddrare
Enter Full Screen Visa i helskärm
PDF Underlay... PDF-underlägg...
Field... Fält...
Layout from Template... Layout från mall...
ACIS File... ACIS-fil...
Drawing Exchange Binary... Drawing Exchange Binary...
Spelling Stavning
Linetype Manager Linjetypshanterare
Color Selector Färgväljare
Object Properties Objektegenskaper
Width Bredd
Position Position
Object Snap Settings Inställningar för objektfäste
Polar Tracking Settings Inställningar för polär spårning
Explode Block Lös upp block
Block Name Blocknamn
Coordinate Koordinat
Coordinates Koordinater
Properties Palette Egenskapspalett
Save Changes Spara ändringar
Discard Changes Ignorera ändringar
Are you sure? Är du säker?
Create Skapa
Fit Anpassa
Specify center point Ange centrumpunkt
Align block with object? Justera blocket mot objektet?
Guide crosshairs along cloud path Led hårkorset längs molnets bana
Erase polyline? Radera polylinje?
Calculate rectangle dimensions based on Beräkna rektangelns mått utifrån
Erase source objects? Radera källobjekt?
Object selected is not a polyline. Do you want to turn it into one? Det markerade objektet är inte en polylinje. Vill du göra om det till en?
Scale objects based on alignment points? Skala objekt utifrån justeringspunkter?
Specify radius Ange radie
Specify diameter Ange diameter
Specify opposite corner point Ange motsatt hörnpunkt
Pick internal point Välj inre punkt
{n} commit {n} commit
{n} contributor {n} bidragsgivare
(1, 2, 4, 8, 16, 32, 64, 128, or 256) (1, 2, 4, 8, 16, 32, 64, 128 eller 256)
<Offset> <Förskjutning>
>> Expression >> Uttryck
Associate the hatch with the new boundary? Associera skrafferingen med den nya gränsen?
Associative dimension priority Prioritet för associativa mått
Breakline extension distance Förlängningsavstånd för brytlinje
Breakline symbol size Symbolstorlek för brytlinje
Choose mode for selected object conversion Välj läge för konvertering av markerade objekt
Combine collinear objects that meet end to end Kombinera kolinjära objekt som möts ände mot ände
Combine collinear objects that partially overlap Kombinera kolinjära objekt som delvis överlappar
Combine identical rows? Kombinera identiska rader?
Combine layer property changes into one undo step? Kombinera ändringar av lageregenskaper till ett ångringssteg?
Combine text into a single MTEXT? Kombinera text till en enda MTEXT?
Combine zooms and pans into one undo step? Kombinera zoomningar och panoreringar till ett ångringssteg?
Constant? Konstant?
Convert Lines and Arcs to polylines Konvertera linjer och bågar till polylinjer
Create associative array Skapa associativ array
Delete old boundary(s)? Ta bort gamla gräns(er)?
Drafting mode? Ritläge?
Edit attributes one at a time? Redigera attributen ett i taget?
Edit only attributes visible on screen? Redigera endast attribut som syns på skärmen?
Edit path for which xref(s) Redigera sökväg för vilka xref:ar
Enter Trim mode option Ange alternativ för trimningsläge
Enter UNDO Auto mode Ange UNDO Auto-läge
Enter X scale factor, specify opposite corner Ange X-skalfaktor, ange motsatt hörn
Enter a boundary loop number to remove (starting at 1) Ange numret på gränsloopen som ska tas bort (börjar på 1)
Enter a configuration option Ange ett konfigurationsalternativ
Enter a default viewport visibility option Ange ett alternativ för standardsynlighet i vyfönster
Enter a group description Ange en gruppbeskrivning
Enter a group name Ange ett gruppnamn
Enter a group option Ange ett gruppalternativ
Enter a hatch option Ange ett skrafferingsalternativ
Enter a loaded linetype name Ange namnet på en inläst linjetyp
Enter a name for the new plotter Ange ett namn på den nya plottern
Enter a new name for the group Ange ett nytt namn på gruppen
Enter a plotter option Ange ett plotteralternativ
Enter a plotting preference Ange en plottningsinställning
Enter a projection option Ange ett projektionsalternativ
Enter a property to turn on or off Ange en egenskap att slå på eller av
Enter a scale factor (nX or nXP) Ange en skalfaktor (nX eller nXP)
Enter a text edit mode option Ange ett alternativ för textredigeringsläge
Enter an UNDO control option Ange ett alternativ för UNDO-kontroll
Enter an annotation option Ange ett anteckningsalternativ
Enter an implied edge extension mode Ange ett läge för underförstådd kantförlängning
Enter an option [Add/Remove] <Add> Ange ett alternativ [Add/Remove] <Add>
Enter an option to change Ange ett alternativ att ändra
Enter array type Ange arraytyp
Enter attribute tag Ange attributtagg
Enter attribute tag specification Ange specifikation för attributtagg
Enter attribute value specification Ange specifikation för attributvärde
Enter attribute visibility setting Ange inställning för attributsynlighet
Enter block name or select a block reference Ange blocknamn eller markera en blockreferens
Enter block name or select a block reference [?] Ange blocknamn eller markera en blockreferens [?]
Enter block name specification Ange specifikation för blocknamn
Enter block(s) to list Ange block att lista
Enter choice, 1 to 5 Ange val, 1 till 5
Enter clipping option Ange klippningsalternativ
Enter color name or number (1-255) Ange färgnamn eller -nummer (1-255)
Enter column type Ange kolumntyp
Enter decimal places of accuracy (0 to 16) Ange noggrannhet i antal decimaler (0 till 16)
Enter distance between rows or specify unit cell (---) Ange avstånd mellan rader eller ange enhetscell (---)
Enter file name Ange filnamn
Enter first angle constraint Ange första vinkelvillkor
Enter first line of annotation text or Ange första raden av kommentarstexten eller
Enter first tolerance value Ange första toleransvärde
Enter fit tolerance Ange anpassningstolerans
Enter fuzz distance Ange fuzz-avstånd
Enter group description Ange gruppbeskrivning
Enter group name Ange gruppnamn
Enter group name(s) to list Ange gruppnamn att lista
Enter inspection rate Ange granskningshastighet
Enter inspection shape Ange granskningsform
Enter justification Ange justering
Enter knot parameterization Ange knutparametrisering
Enter label (press ENTER for none) Ange etikett (tryck på ENTER för ingen)
Enter layer description Ange lagerbeskrivning
Enter layer name Ange lagernamn
Enter layer name to make current Ange namnet på lagret som ska bli aktuellt
Enter layer name(s) to change default viewport visibility Ange lagernamn för att ändra standardsynlighet i vyfönster
Enter layer name(s) to list Ange lagernamn att lista
Enter layer option for offset objects Ange lageralternativ för förskjutna objekt
Enter layout name for copy Ange layoutnamn för kopian
Enter layout name(s) to list Ange layoutnamn att lista
Enter layout option Ange layoutalternativ
Enter layout to make current Ange layout som ska bli aktuell
Enter layout to rename Ange layout att byta namn på
Enter layout to save to template Ange layout att spara som mall
Enter leader format option Ange formatalternativ för hänvisningslinje
Enter line spacing factor or distance Ange radavståndsfaktor eller avstånd
Enter line spacing type Ange typ av radavstånd
Enter linetype(s) to load Ange linjetyp(er) att läsa in
Enter lineweight (0.0mm - 2.11mm) Ange linjetjocklek (0,0 mm - 2,11 mm)
Enter magnification or height Ange förstoring eller höjd
Enter maximum part height Ange maximal delhöjd
Enter mline editing option Ange redigeringsalternativ för multilinje
Enter mline style name or [?] Ange namn på multilinjestil eller [?]
Enter name for new layer (becomes the current layer) Ange namn på nytt lager (blir aktuellt lager)
Enter name for new scale Ange namn på ny skala
Enter name for new viewport configuration Ange namn på ny vyfönsterkonfiguration
Enter name list for new layer(s) Ange namnlista för nya lager
Enter name of block to manage Ange namn på block att hantera
Enter name of block to sync Ange namn på block att synkronisera
Enter name of breakline symbol block (. for the built-in symbol) Ange namn på block för brytlinjesymbol (. för den inbyggda symbolen)
Enter name of drawing file to recover Ange namn på ritningsfil att återställa
Enter name of existing block Ange namn på befintligt block
Enter name of layout to copy Ange namn på layout att kopiera
Enter name of layout to delete Ange namn på layout att ta bort
Enter name of linetype file Ange namn på linjetypsfil
Enter name of new layout Ange namn på ny layout
Enter name of output file Ange namn på utdatafil
Enter name of scale to delete Ange namn på skala att ta bort
Enter name of script file Ange namn på skriptfil
Enter name of viewport configuration to restore Ange namn på vyfönsterkonfiguration att återställa
Enter name(s) of new layers frozen in all viewports Ange namn på nya lager som är frusna i alla vyfönster
Enter name(s) of viewport configurations to delete Ange namn på vyfönsterkonfigurationer att ta bort
Enter name(s) of viewport configurations to list Ange namn på vyfönsterkonfigurationer att lista
Enter name(s) to purge Ange namn att rensa
Enter named scale to add Ange namngiven skala att lägga till
Enter named scale to delete Ange namngiven skala att ta bort
Enter new color Ange ny färg
Enter new default value Ange nytt standardvärde
Enter new group name Ange nytt gruppnamn
Enter new layer name Ange nytt lagernamn
Enter new layout name Ange nytt layoutnamn
Enter new linetype name Ange nytt linjetypsnamn
Enter new linetype scale factor Ange ny linjetypsskalfaktor
Enter new lineweight Ange ny linjetjocklek
Enter new order Ange ny ordning
Enter new prompt Ange ny ledtext
Enter new string Ange ny sträng
Enter new tag Ange ny tagg
Enter new text style Ange ny textstil
Enter new value for CONSTRAINTINFER Ange nytt värde för CONSTRAINTINFER
Enter new value for PICKSTYLE Ange nytt värde för PICKSTYLE
Enter new value for THICKNESS Ange nytt värde för THICKNESS
Enter new value for XCLIPFRAME Ange nytt värde för XCLIPFRAME
Enter next line of annotation text Ange nästa rad med kommentarstext
Enter next line of text (empty line to finish) Ange nästa textrad (tom rad för att slutföra)
Enter number of actions Ange antal åtgärder
Enter number of columns (|||) Ange antal kolumner (|||)
Enter number of digits to right of decimal point (0 to 8) Ange antal siffror till höger om decimaltecknet (0 till 8)
Enter number of fractional places for display of angles (0 to 8) Ange antal decimaler för visning av vinklar (0 till 8)
Enter number of items in array Ange antal objekt i arrayen
Enter number of rows (---) Ange antal rader (---)
Enter object ordering option Ange alternativ för objektordning
Enter object type to rename Ange objekttyp att byta namn på
Enter obliquing angle (press ENTER for none) Ange lutningsvinkel (tryck på ENTER för ingen)
Enter old group name Ange gammalt gruppnamn
Enter old layer name Ange gammalt lagernamn
Enter option Ange alternativ
Enter option [Save/Discard reference changes] <Save> Ange alternativ [Spara/Släng referensändringar] <Spara>
Enter properties to match (SELECTSIMILARMODE bit code) Ange egenskaper att matcha (bitkod för SELECTSIMILARMODE)
Enter property to change Ange egenskap att ändra
Enter scale ratio (paper units:drawing units) Ange skalkvot (pappersenheter:ritningsenheter)
Enter second angle constraint Ange andra vinkelvillkoret
Enter second tolerance value Ange andra toleransvärdet
Enter spline creation method Ange metod för att skapa spline
Enter string to change Ange sträng att ändra
Enter style name Ange stilnamn
Enter symbol type to bind Ange symboltyp att bädda in
Enter target layer name Ange namn på mållager
Enter template file name Ange namn på mallfil
Enter the distance between rows or specify unit cell (---) Ange avståndet mellan rader eller ange enhetscell (---)
Enter the drawing to compare with (an open drawing's name or a file path) Ange ritningen att jämföra med (namnet på en öppen ritning eller en sökväg)
Enter the maximum points for leader line Ange största antal punkter för hänvisningslinjen
Enter the name of the block to replace Ange namnet på blocket som ska ersättas
Enter the number of columns (|||) Ange antal kolumner (|||)
Enter the number of items in the array Ange antal objekt i arrayen
Enter the number of levels Ange antal nivåer
Enter the number of operations to undo Ange antal åtgärder att ångra
Enter the number of rows Ange antal rader
Enter the number of rows (---) Ange antal rader (---)
Enter the output Ange utdata
Enter the paper name Ange pappersnamnet
Enter the paper width,height in mm Ange pappersbredd,höjd i mm
Enter the plotter to add a paper size to Ange plottern som en pappersstorlek ska läggas till för
Enter the plotter to delete Ange plottern att ta bort
Enter the type of array Ange typ av array
Enter tolerance location Ange toleransens placering
Enter transparency value Ange genomskinlighetsvärde
Enter transparency value (0-90) Ange genomskinlighetsvärde (0-90)
Enter trim method Ange trimningsmetod
Enter type of dimension editing Ange typ av måttredigering
Enter type of unused objects to purge Ange typ av oanvända objekt att rensa
Enter type of value modification Ange typ av värdeändring
Enter value Ange värde
Enter variable name Ange variabelnamn
Enter view name to restore Ange namn på vy att återställa
Enter view name to save Ange namn på vy att spara
Enter view name(s) to delete Ange namn på vyer att ta bort
Enter view name(s) to list Ange namn på vyer att lista
Enter viewport arrangement Ange vyfönsterarrangemang
Enter viewport configuration name Ange namn på vyfönsterkonfiguration
Enter what to pick Ange vad som ska väljas
Enter xref(s) to list Ange xref att lista
Erase source object after offsetting? Radera källobjektet efter förskjutning?
First point of mid Första punkt för mittpunkt
First tracking point Första spårningspunkt
Fix any errors detected? Åtgärda upptäckta fel?
Get from the drawing or [Point/Distance/Angle/Intersection] Hämta från ritningen eller [Punkt/Avstånd/Vinkel/Skärningspunkt]
Indicate dimension point to add Ange måttpunkt att lägga till
Indicate dimension point to remove Ange måttpunkt att ta bort
Internal error; press Enter to end the command Internt fel; tryck på Enter för att avsluta kommandot
Invisible? Osynlig?
Island detection style Stil för identifiering av öar
Keep associative objects Behåll associativa objekt
Lock the view of viewports? Lås vyn i vyfönster?
Measure angles clockwise? Mäta vinklar medurs?
New color Ny färg
Next point (Press ENTER to end tracking) Nästa punkt (tryck på ENTER för att avsluta spårning)
No mark: undo everything? Inget märke: ångra allt?
Number of objects to move Antal objekt att flytta
Optimize segments within polylines Optimera segment i polylinjer
Pick a table cell Välj en tabellcell
Pick an internal point for the new boundary Välj en inre punkt för den nya gränsen
Red, Green, Blue Röd, grön, blå
Red,Green,Blue Röd,grön,blå
Reset the scale list to the defaults? Återställ skallistan till standardvärdena?
Rotate arrayed items? Rotera objekten i arrayen?
Rotate arrayed objects? Rotera arrayobjekten?
Save changes to array? Spara ändringar i arrayen?
Save layer settings with views? Spara lagerinställningar med vyer?
Second point of mid Andra punkt för mittpunkt
Select a block Markera ett block
Select a content type Välj en innehållstyp
Select a leader type Välj en typ av hänvisningslinje
Select a multileader Markera en multihänvisningslinje
Select a table Markera en tabell
Select a viewport Markera ett vyfönster
Select an item in array to replace Markera ett objekt i arrayen som ska ersättas
Select an object to copy Markera ett objekt att kopiera
Select array Markera array
Select attributes Markera attribut
Select base dimension Markera basmått
Select base point of replacement objects Markera baspunkt för ersättningsobjekten
Select boundary objects (Enter finds them) Markera gränsobjekt (Enter hittar dem)
Select clipping object Markera beskärningsobjekt
Select closed boundary objects to add Markera slutna gränsobjekt att lägga till
Select destination object(s) Markera målobjekt
Select dimension Markera mått
Select dimension to add jog Markera mått att lägga till knäck på
Select dimension to add/remove break Markera mått för att lägga till/ta bort brytning
Select dimensions to space Markera mått att fördela
Select grip to edit array Markera grepp för att redigera arrayen
Select group Markera grupp
Select hatch object Markera skrafferingsobjekt
Select item in array Markera objekt i arrayen
Select jog to remove Markera knäck att ta bort
Select mline Markera multilinje
Select multileader to align to or [Options] Markera multihänvisningslinje att justera mot eller [Alternativ]
Select new datum point Markera ny referenspunkt
Select object on target layer Markera objekt på mållagret
Select object to break dimension Markera objekt som ska bryta måttet
Select object to clip viewport Markera objekt att beskära vyfönstret med
Select object to count or [List/Spaces] Markera objekt att räkna eller [Lista/Blanksteg]
Select objects to add to the group Markera objekt att lägga till i gruppen
Select objects to erase or Markera objekt att radera eller
Select objects to remove from the group Markera objekt att ta bort från gruppen
Select reference objects Markera referensobjekt
Select replacement objects Markera ersättningsobjekt
Select source object Markera källobjekt
Select viewport to clip Markera vyfönster att beskära
Select viewports Markera vyfönster
Sort text top-down? Sortera text uppifrån och ned?
Specify Z scale factor or Ange skalfaktor för Z eller
Specify a fit tolerance Ange en anpassningstolerans
Specify a point on the spline <exit> Ange en punkt på splinen <avsluta>
Specify a precision Ange en precision
Specify base point of objects Ange objektens baspunkt
Specify block attachment Ange blockets anslutning
Specify center location override Ange åsidosatt placering för centrum
Specify center of isocircle Ange isocirkelns centrum
Specify center of view box Ange vyrutans centrum
Specify chamfer angle from the first line Ange fasvinkel från första linjen
Specify chamfer length on the first line Ange faslängd på första linjen
Specify change point Ange ändringspunkt
Specify clipping boundary or select invert option Ange beskärningsgräns eller välj alternativet Invertera
Specify collected multileader location or [Vertical/Horizontal/Wrap] Ange placering för samlad multihänvisningslinje eller [Lodrät/Vågrät/Radbryt]
Specify column height Ange kolumnhöjd
Specify control point <exit> Ange styrpunkt <avsluta>
Specify direction Ange riktning
Specify direction (first point) Ange riktning (första punkten)
Specify direction (second point) Ange riktning (andra punkten)
Specify direction of chord for arc Ange kordans riktning för bågen
Specify direction of vertex tangent Ange riktning för hörnpunktens tangent
Specify displacement Ange förskjutning
Specify displacement base point Ange baspunkt för förskjutning
Specify distance between columns (|||) Ange avstånd mellan kolumner (|||)
Specify end tangent Ange sluttangent
Specify existing fit point <exit> Ange befintlig anpassningspunkt <avsluta>
Specify first break point Ange första brytpunkten
Specify first corner of the unit cell Ange enhetscellens första hörn
Specify first fence point Ange första staketpunkten
Specify first point for arc length dimension Ange första punkten för båglängdsmått
Specify first point for breakline Ange första punkten för brytlinje
Specify first point or [Options] Ange första punkten eller [Alternativ]
Specify fourth point or Ange fjärde punkten eller
Specify gutter width Ange bredd på spaltmellanrum
Specify included angle for arc Ange medelpunktsvinkel för bågen
Specify insertion point of the table Ange tabellens insättningspunkt
Specify jog location Ange placering för knäcken
Specify jog location (or press ENTER) Ange placering för knäcken (eller tryck på ENTER)
Specify leader arrowhead location or [Remove leaders] Ange placering för hänvisningslinjens pilspets eller [Ta bort hänvisningslinjer]
Specify leader start point Ange hänvisningslinjens startpunkt
Specify leaders to remove Ange hänvisningslinjer att ta bort
Specify leaders to remove or [Add leaders] Ange hänvisningslinjer att ta bort eller [Lägg till hänvisningslinjer]
Specify length of line Ange linjens längd
Specify linetype name Ange linjetypens namn
Specify location for break symbol Ange placering för brytsymbol
Specify location of the text Ange textens placering
Specify new angle Ange ny vinkel
Specify new block insertion point Ange blockets nya insättningspunkt
Specify new block rotation angle Ange blockets nya rotationsvinkel
Specify new circle radius Ange cirkelns nya radie
Specify new elevation Ange nytt höjdläge
Specify new fit point <exit> Ange ny anpassningspunkt <avsluta>
Specify new height Ange ny höjd
Specify new length Ange ny längd
Specify new linetype scale Ange ny linjetypsskala
Specify new location Ange ny placering
Specify new location for dimension text Ange ny placering för måttal
Specify new point on spline <exit> Ange ny punkt på splinen <avsluta>
Specify new text insertion point Ange textens nya insättningspunkt
Specify new thickness Ange ny tjocklek
Specify next fence point Ange nästa staketpunkt
Specify number of columns Ange antal kolumner
Specify other corner Ange andra hörnet
Specify quadrant Ange kvadrant
Specify reference angle Ange referensvinkel
Specify reference length Ange referenslängd
Specify rotation around major axis Ange rotation kring storaxeln
Specify scale factor for XYZ axes Ange skalfaktor för XYZ-axlarna
Specify second point for arc length dimension Ange andra punkten för båglängdsmått
Specify second point for breakline Ange andra punkten för brytlinje
Specify size of view box Ange vyrutans storlek
Specify spacing Ange avstånd
Specify temporary OTRACK point Ange tillfällig OTRACK-punkt
Specify text height Ange texthöjd
Specify the angle between items Ange vinkeln mellan objekten
Specify the angle to fill (+=ccw, -=cw) Ange vinkel att fylla (+=moturs, -=medurs)
Specify the distance between columns (|||) Ange avståndet mellan kolumner (|||)
Specify the incrementing elevation between rows Ange höjdökningen mellan rader
Specify the new angle Ange den nya vinkeln
Specify the pattern origin Ange mönstrets origo
Specify the reference angle Ange referensvinkeln
Specify third point Ange tredje punkten
Specify tolerance Ange tolerans
Specify view twist angle Ange vyns vridningsvinkel
Specify width Ange bredd
Specify zoom scale factor Ange skalfaktor för zoom
Type of boundary object Typ av gränsobjekt
Type something to find Skriv något att söka efter
Use landing Använd anslutningslinje
Verify each name to be purged? Bekräfta varje namn som ska rensas?
Where should the data go? Var ska data hamna?
Word-wrap text? Radbryt text?
Remove objects Ta bort objekt
Select geometry to dimension Markera geometri att måttsätta
Select annotative objects Markera annotativa objekt
Specify total width Ange total bredd
Specify column width Ange kolumnbredd
Specify control point Ange styrpunkt
<style overrides> <lokala stiländringar>
A dimension style with this name already exists. Det finns redan en måttstil med det här namnet.
Above Ovanför
Above text Ovanför text
All properties of {style} Alla egenskaper för {style}
All styles Alla stilar
Alt enabled Alt. enheter aktiverade
Alt format Alt. format
Alt precision Alt. precision
Alt prefix Alt. prefix
Alt prefix and suffix Alt. prefix och suffix
Alt round Alt. avrundning
Alt scale factor Alt. skalfaktor
Alt suffix Alt. suffix
Alt zero suppression Alt. nollundertryckning
Alternate Units Alternativa enheter
Angle format Vinkelformat
Angle precision Vinkelprecision
Angular zero suppression Nollundertryckning för vinkelmått
Arc length symbol Båglängdssymbol
Architectural stacked Arkitektonisk, staplad
Architectural tick Arkitektoniskt snedstreck
Arrow 1 Pil 1
Arrow 2 Pil 2
Arrowheads Pilspetsar
Arrows Pilar
At Ext Line 1 Vid måttgränslinje 1
At Ext Line 2 Vid måttgränslinje 2
At least Minst
Baseline spacing Baslinjeavstånd
Before text Före text
Below Nedanför
Best fit Bästa anpassning
Bottom center Nere i mitten
Box blank Låda, tom
Box filled Låda, fylld
Center mark size Centrummarkeringens storlek
Closed blank Sluten, tom
Closed filled Sluten, fylld
Columns Kolumner
Comma Komma
Compare Jämför
Compare Dimension Styles Jämför måttstilar
Compare... Jämför...
Create New Dimension Style Skapa ny måttstil
Current dimension style: {style} Aktuell måttstil: {style}
Datum triangle Referenstriangel
Datum triangle filled Referenstriangel, fylld
Decimal separator Decimalavgränsare
Degrees Minutes Seconds Grader minuter sekunder
Diagonal stacking Diagonal stapling
Dim line color Måttlinjens färg
Dim line ext Måttlinjens förlängning
Dim line forced Tvingad måttlinje
Dim line linetype Måttlinjens linjetyp
Dim line lineweight Måttlinjens linjetjocklek
Dim prefix Måttprefix
Dim roundoff Måttavrundning
Dim scale linear Linjär måttskala
Dim suffix Måttsuffix
Dim units Måttenheter
Dimension Style Måttstil
Dimension Style Manager Hantera måttstilar
Dimension Style Overrides Lokala ändringar av måttstil
Dot Punkt
Dot blank Punkt, tom
Dot small Punkt, liten
Exactly Exakt
Ext line 1 linetype Linjetyp för måttgränslinje 1
Ext line 2 linetype Linjetyp för måttgränslinje 2
Ext line color Måttgränslinjens färg
Ext line ext Måttgränslinjens förlängning
Ext line fixed Fast längd på måttgränslinje
Ext line length Måttgränslinjens längd
Ext line lineweight Måttgränslinjens linjetjocklek
Ext line offset Måttgränslinjens förskjutning
Fraction format Bråkformat
Fractional stacked Bråk, staplat
Gradians Gon
Hide dim line 1 Dölj måttlinje 1
Hide dim line 2 Dölj måttlinje 2
Hide ext line 1 Dölj måttgränslinje 1
Hide ext line 2 Dölj måttgränslinje 2
Horizontal stacking Vågrät stapling
Integral Integral
JIS JIS
Jog angle Brytvinkel
Justification Justering
Keep dim line with text Håll ihop måttlinje och text
Leader arrow Hänvisningspil
Leading Inledande
Line space distance Radavståndsvärde
Line space factor Radavståndsfaktor
Line space style Radavståndsstil
Lines Linjer
Lines & Arrows Linjer och pilar
Lower tolerance Nedre tolerans
Measurement Mätning
Middle I mitten
Middle center I mitten, centrerat
Middle left I mitten till vänster
Middle right I mitten till höger
Misc Övrigt
Modify Dimension Style: {style} Ändra måttstil: {style}
Modify... Ändra...
Move text, add leader Flytta text, lägg till hänvisningslinje
Move text, no leader Flytta text, ingen hänvisningslinje
New Dimension Style: {style} Ny måttstil: {style}
New style name Namn på ny stil
New... Ny...
Not stacked Inte staplat
Obliquing Snedställning
Open 30 Öppen 30
Open arrow Öppen pil
Origin indicator Origoindikator
Origin indicator 2 Origoindikator 2
Outside Utanför
Over Ext Line 1 Över måttgränslinje 1
Over Ext Line 2 Över måttgränslinje 2
Override Current Style: {style} Åsidosätt aktuell stil: {style}
Override... Åsidosätt...
Overrides the dimension style. Right-click to use the style's value. Åsidosätter måttstilen. Högerklicka för att använda stilens värde.
Period Punkt
Prefix and suffix Prefix och suffix
Preview of: {style} Förhandsvisning av: {style}
Preview of: {style} (overrides) Förhandsvisning av: {style} (lokala ändringar)
Primary Units Primära enheter
Remove Style Overrides Ta bort lokala ändringar av stilen
Right angle Rät vinkel
Save as New Style... Spara som ny stil...
Save to current style Spara i aktuell stil
Set by text style "{style}", which has a fixed height. Give the style a height of 0 to use the dimension text height. Styrs av textstilen "{style}", som har fast höjd. Ge stilen höjden 0 för att använda måttalets höjd.
Small Liten
Some of these dimensions take their text height from a fixed-height text style. Några av dessa mått får sin texthöjd från en textstil med fast höjd.
Space Space
Start with Börja med
Style Stil
Styles Stilar
Styles in use Stilar som används
Suppress arrows Utelämna pilar
Symbols and Arrows Symboler och pilar
Text alignment X Textjustering X
Text alignment Y Textjustering Y
Text and arrows Text och pilar
Text inside Text inuti
Text inside align Justering av text inuti
Text movement Textförflyttning
Text offset Textförskjutning
Text outside align Justering av text utanför
Text pos hor Textpos. vågr.
Text pos vert Textpos. lodr.
Text position X Textposition X
Text position Y Textposition Y
Text rotation Textrotation
Text vertical position Lodrät textposition
Tick size Storlek på snedstreck
Tolerance height Toleranshöjd
Tolerance pos vert Tolerans pos. lodr.
Tolerance precision Toleransprecision
Tolerance zero suppression Nollundertryckning för tolerans
Tolerances Toleranser
Top Ovan
Top center Uppe i mitten
Trailing Avslutande
Upper tolerance Övre tolerans
Use the style's value Använd stilens värde
Variable Variabel
Windows desktop Windows-skrivbord
With Med
Zero suppression Nollundertryckning
{count} differences {count} skillnader
{property}: that value can't be used here. {property}: det värdet kan inte användas här.
Can't render this file because it contains an unexpected character in line 1500 and column 24.
-21
View File
@@ -732,24 +732,3 @@ fn polish_plural_forms() {
assert_eq!(plural_pl(n), expected, "n={n}");
}
}
/// Arabic gives Stretch, Trim and Point words of their own: Stretch read «تمديد» like Extend,
/// Trim's prompts said «قص» like Cut, and Point read «تأشير», the catalog's word for dimensioning.
#[test]
fn arabic_tells_stretch_trim_and_point_from_their_neighbours() {
// The words themselves: a pair that merely differs also differs when a row is missing and both
// fall back to English, and Point and Dimension already differed before.
for (key, word) in [("Stretch", "تمطيط"), ("Trim", "تشذيب"), ("Point", "نقطة")] {
assert_eq!(tr("ar", key), word, "{key}");
}
for (a, b) in [("Stretch", "Extend"), ("Trim", "Cut"), ("Point", "Dimension")] {
assert_ne!(tr("ar", a), tr("ar", b), "{a} and {b} share a word");
}
for (prompt, verb) in [
("Select object to trim or shift-select to extend", "تشذيب"),
("Select object to extend or shift-select to trim", "تشذيب"),
("Select objects to stretch by crossing-window or crossing-polygon...", "تمطيط"),
] {
assert!(tr("ar", prompt).contains(verb), "{prompt}");
}
}
+1
View File
@@ -1034,6 +1034,7 @@
Not a number or distance: {text} 不是数字或距离:{text}
Plotter Manager... 绘图仪管理器...
Import... 导入...
Import PDF... 导入 PDF...
Export... 导出...
Batch Publish... 批量发布...
New from Template... 根据样板新建...
1 # CADCraft Simplified Chinese interface catalog — original translations.
1034
1035
1036
1037
1038
1039
1040
+1 -25
View File
@@ -775,8 +775,7 @@ impl CadApp {
/// Open the drawing at `path`. Natively the file is read on a worker thread while an
/// "Opening ..." card shows ([`opening`]); [`Self::finish_opening`] adds it when ready. On the
/// web it opens at once. An already open drawing is selected without re-reading it, retaining
/// its unsaved edits and view; window drops and Open Recent use this same entry point.
/// web it opens at once.
pub fn open_path(&mut self, path: &Path) {
// A LISP file (dropped on the window): loaded as APPLOAD loads it.
if is_lisp_file(path) {
@@ -786,9 +785,6 @@ impl CadApp {
}
return;
}
if self.select_open_drawing(path) {
return;
}
#[cfg(not(target_arch = "wasm32"))]
{
self.opening.start(path);
@@ -819,10 +815,6 @@ impl CadApp {
/// OPEN is reported. Called every frame.
pub fn finish_opening(&mut self) {
for (path, outcome) in self.opening.poll() {
// A drawing may have been opened or saved at this path while the read was pending.
if self.select_open_drawing(&path) {
continue;
}
// A recent file that is gone can never be opened again: drop it from the list. A path
// whose existence can't be checked (a folder that denies access) stays.
if outcome.is_err() && matches!(path.try_exists(), Ok(false)) {
@@ -840,22 +832,6 @@ impl CadApp {
}
}
/// Reuse the existing document through the normal tab-switch command, including symlink paths.
fn select_open_drawing(&mut self, path: &Path) -> bool {
let existing = self.session.docs.iter().position(|d| d.path.as_deref().is_some_and(|p| opening::same_path(Path::new(p), path)));
let Some(index) = existing else { return false };
match self.run("document.switch", json!({"index": index})) {
Ok(_) => {
self.ui.start_tab = false;
if let Some(path) = self.session.docs.get(index).and_then(|d| d.path.clone()) {
self.remember_recent(path);
}
}
Err(error) => self.open_failed(error),
}
true
}
/// Load a LISP file: its routine runs and may wait for the user (APPLOAD typed or from the
/// menu runs this way too).
fn load_lisp(&mut self, name: &str, text: &str) {
+5 -20
View File
@@ -73,7 +73,7 @@ pub const OPEN_RECENT: &str = "Open Recent";
/// The last item of File ▸ Open Recent.
pub const CLEAR_RECENT: &str = "Clear Recent Files";
const RECENT_ITEM: &str = "ui.recent.";
pub const RECENT_CLEAR: &str = "ui.recent.clear";
const RECENT_CLEAR: &str = "ui.recent.clear";
/// UI-only commands: (id, label, menu path, shortcut).
pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
@@ -459,13 +459,7 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Re
.unwrap_or(Ok(Value::Null)),
"ui.saveas" | "saveas" if no_path => {
let title = app.session.state().map(|s| s.title.clone()).ok();
// `format` ("dxf" or "dwg") is only this dialog's suggestion. Without it, Save As uses
// the user's default format, and neither call changes that default.
let format = match suggested_save_format(params, app.ui.save_format) {
Ok(format) => format,
Err(e) => return Some(Err(e)),
};
let name = format.suggested_name(title.as_deref());
let name = app.ui.save_format.suggested_name(title.as_deref());
// Bound to this drawing: the answer saves it, not whichever drawing is active then.
app.pick_then(Pick::Save(name), |app, p| {
app.session.execute("saveas", &saveas_params(&app.ui, &app.session, &p)).map_err(|e| e.to_string())
@@ -495,7 +489,9 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Re
app.ui.start_tab = false;
Ok(Value::Null)
}
"export" | "exp" | "import" | "imp" | "publish" | "preview" | "pre" if params.is_null() && app.session.state().is_ok() => {
"export" | "exp" | "import" | "imp" | "pdfimport" | "pdfi" | "publish" | "preview" | "pre"
if params.is_null() && app.session.state().is_ok() =>
{
return Some(crate::exchange::route(app, id));
}
"ui.hidepalettes" => {
@@ -614,17 +610,6 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Re
Some(r)
}
/// The format a Save dialog suggests: `format` when the call names `dxf` or `dwg`, otherwise the
/// user's default. Naming one does not change the default.
fn suggested_save_format(params: &Value, default: crate::SaveFormat) -> Result<crate::SaveFormat, String> {
let Some(v) = params.get("format").filter(|v| !v.is_null()) else { return Ok(default) };
let Some(name) = v.as_str() else { return Err("save format must be \"dxf\" or \"dwg\"".into()) };
crate::SaveFormat::parse(name).ok_or_else(|| {
let shown: String = name.chars().take(40).collect();
format!("unknown save format \"{shown}\" (dxf or dwg)")
})
}
/// SAVEAS parameters for a path picked in the Save dialog: a drawing that has no file yet is saved
/// in the default save version; one opened from a file keeps that file's version.
fn saveas_params(ui: &crate::UiState, session: &cadcraft_engine::Session, path: &str) -> Value {
-20
View File
@@ -13,22 +13,6 @@ use crate::theme::Tokens;
type Outcome = Result<ReadFile, String>;
/// Compare file paths without requiring the file to still exist. Native aliases are resolved so
/// a symlink and its target share a drawing; web paths can only be compared directly.
pub(crate) fn same_path(a: &Path, b: &Path) -> bool {
if a == b {
return true;
}
#[cfg(not(target_arch = "wasm32"))]
{
a.canonicalize().ok().zip(b.canonicalize().ok()).is_some_and(|(a, b)| a == b)
}
#[cfg(target_arch = "wasm32")]
{
false
}
}
struct Job {
path: PathBuf,
started: Instant,
@@ -44,10 +28,6 @@ pub struct Opening {
impl Opening {
/// Start reading `path` on a worker thread.
pub fn start(&mut self, path: &Path) {
// Repeated events can arrive before the first background read completes.
if self.jobs.iter().any(|j| same_path(&j.path, path)) {
return;
}
let (tx, rx) = channel();
let p = path.to_path_buf();
let spawned = std::thread::Builder::new().name("cadcraft-open".into()).spawn(move || {
+3 -10
View File
@@ -2,10 +2,8 @@
//! another program keeps (`cadcraft_engine::cmd::file::not_saved`), a DXF can't hold every solid
//! or proxy of every version (`cadcraft_engine::cmd::file::loss_on_save`), and QSAVE replaces the file
//! that still has it, so File ▸ Save, its shortcut or typing QSAVE says what would go first:
//! Save Anyway / Save As... / Cancel. Save As from a DWG warning suggests DXF, which keeps the
//! objects; File ▸ Save As suggests the user's default format. Agreeing lasts for that same loss
//! on that same file, so later saves in the session don't ask again; the file no longer holds
//! what was agreed to.
//! Save Anyway / Save As... / Cancel. Agreeing lasts for that same loss on that same file, so
//! later saves in the session don't ask again; the file no longer holds what was agreed to.
//!
//! Programmatic saves (`engine.execute`, the control channel, MCP, scripts) never ask: they keep
//! reporting the loss in the result's `notSaved` and on the command line.
@@ -96,12 +94,7 @@ impl CadApp {
(Choice::Cancel, _) | (_, None) => self.session.echo(crate::tf!("Save cancelled: {path} was not changed.", path = loss.path)),
(Choice::SaveAs, Some(i)) => {
self.activate_doc(i);
// A DWG warning says DXF keeps the objects, so this dialog suggests DXF. A DXF
// warning is about an older version, and File ▸ Save As passes no format, so both
// keep suggesting the user's default.
let dxf = std::path::Path::new(&loss.path).extension().is_some_and(|e| e.eq_ignore_ascii_case("dxf"));
let params = if dxf { Value::Null } else { json!({ "format": "dxf" }) };
let _ = self.run("ui.saveas", params);
let _ = self.run("ui.saveas", Value::Null);
}
(Choice::SaveAnyway, Some(i)) => {
self.activate_doc(i);
+1
View File
@@ -32,6 +32,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;
@@ -0,0 +1,119 @@
//! PDF import exposes named placement controls and gives the page field initial keyboard focus.
use cadcraft_engine::Session;
use cadcraft_engine::cmd::exchange::set_pdf_import;
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
use cadcraft_engine::geom::Vec3;
use cadcraft_ui_egui::{CadApp, Services};
use egui::accesskit::{Action, ActionData, ActionRequest, Live, Role};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT_FILE: AtomicUsize = AtomicUsize::new(0);
fn read_pdf(_: &[u8], options: &serde_json::Value) -> Result<(Drawing, usize), String> {
if options["page"].as_u64() != Some(2) {
return Err("expected page 2".into());
}
let mut drawing = Drawing::new_metric();
drawing
.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) }))
.map_err(|e| e.to_string())?;
Ok((drawing, 4))
}
fn harness(path: String) -> Harness<'static, CadApp> {
let services = Services { pick_open: Some(Box::new(move || Some(path.clone()))), ..Services::default() };
let mut app = CadApp::new(Session::new(), services);
app.start("pdfimport");
Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
)
}
fn set_number(h: &mut Harness<'_, CadApp>, name: &str, value: f64) {
let (target_node, target_tree) = h.get_by_role_and_label(Role::SpinButton, name).accesskit_node().locate();
h.event(egui::Event::AccessKitActionRequest(ActionRequest {
action: Action::SetValue,
target_node,
target_tree,
data: Some(ActionData::NumericValue(value)),
}));
h.run_steps(2);
}
fn pdf_path() -> (std::path::PathBuf, String) {
let name = format!("cadcraft-import-{}-{}.pdf", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed));
let path = std::env::temp_dir().join(name);
std::fs::write(&path, b"%PDF-1.7\nsynthetic\n").unwrap();
(path.clone(), path.to_string_lossy().into_owned())
}
#[test]
fn page_focus_placement_acceptance_and_escape_cancellation_work() {
set_pdf_import(read_pdf);
let (path, name) = pdf_path();
let mut h = harness(name.clone());
h.run_steps(3);
assert!(h.get_by_role_and_label(Role::SpinButton, "Page number").is_focused());
for label in ["Page number", "Scale factor", "Insertion X", "Insertion Y"] {
h.get_by_role_and_label(Role::SpinButton, label);
}
h.get_by_role_and_label(Role::PasswordInput, "Password");
for label in ["Import text as TEXT", "Import filled shapes as solid hatches", "Use the PDF's line widths"] {
h.get_by_role_and_label(Role::CheckBox, label);
}
h.get_by_role_and_label(Role::Button, "Import Page");
h.get_by_role_and_label(Role::Button, "Cancel");
// The reader refuses page 1: the window stays open and announces the failure.
h.get_by_role_and_label(Role::Button, "Import Page").click();
h.run_steps(3);
assert!(h.state().ui.dialog.is_some(), "a failed import keeps the options window open");
assert_eq!(h.get_by_label_contains("Import failed").accesskit_node().live(), Live::Assertive);
set_number(&mut h, "Page number", 2.0);
set_number(&mut h, "Scale factor", 2.0);
set_number(&mut h, "Insertion X", 10.0);
set_number(&mut h, "Insertion Y", 20.0);
h.get_by_role_and_label(Role::Button, "Import Page").click();
h.run_steps(3);
let drawing = h.state().session.doc().unwrap();
let Some(entity) = drawing.model.iter().next() else { panic!("the page was imported") };
let EntityKind::Line(line) = &entity.kind else { panic!("the line remains editable geometry") };
assert_eq!(line.a, Vec3::new(10.0, 20.0, 0.0));
assert_eq!(line.b, Vec3::new(30.0, 20.0, 0.0));
assert!(h.state().ui.dialog.is_none(), "successful import closes the options window");
let mut cancelled = harness(name);
cancelled.run_steps(3);
cancelled.key_press(egui::Key::Escape);
cancelled.run_steps(3);
assert!(cancelled.state().ui.dialog.is_none(), "Escape closes the PDF options window");
assert!(cancelled.state().session.doc().unwrap().model.is_empty(), "cancelling leaves the drawing unchanged");
std::fs::remove_file(path).unwrap();
}
#[test]
fn the_page_goes_to_the_drawing_the_window_was_opened_for() {
set_pdf_import(read_pdf);
let (path, name) = pdf_path();
let mut h = harness(name);
h.run_steps(3);
// Another drawing is made active while the window is still open.
h.state_mut().run("new", serde_json::json!({ "template": "." })).unwrap();
h.run_steps(2);
assert_eq!(h.state().session.active, 1);
set_number(&mut h, "Page number", 2.0);
h.get_by_role_and_label(Role::Button, "Import Page").click();
h.run_steps(3);
let docs = &h.state().session.docs;
assert!(!docs[0].doc.model.is_empty(), "the page went into the drawing that asked for it");
assert!(docs[1].doc.model.is_empty(), "the drawing shown meanwhile is unchanged");
std::fs::remove_file(path).unwrap();
}
@@ -124,27 +124,6 @@ fn both_corners_of_a_click_click_window_count_while_the_mouse_moves() {
assert_eq!(h.state().session.selection().len(), 1);
}
#[test]
fn pointer_drift_at_the_first_corner_does_not_commit_the_window() {
for (drift, release) in [(9.0, 9.0), (30.0, 4.0)] {
let mut h = harness();
let first = screen(&h, Vec2::new(10.0, 10.0));
h.event(Event::PointerMoved(first));
button(&mut h, first, true);
h.event(Event::PointerMoved(first + vec2(drift, 0.0)));
h.run_steps(30);
let at_release = first + vec2(release, 0.0);
h.event(Event::PointerMoved(at_release));
button(&mut h, at_release, false);
h.run_steps(2);
assert!(h.state().session.pending_window.is_some(), "drift {drift}, release {release}: still waiting for the second corner");
quick_moving_click(&mut h, Vec2::new(70.0, 30.0));
assert!(h.state().session.pending_window.is_none());
assert_eq!(h.state().session.selection().len(), 1);
}
}
#[test]
fn holding_the_button_while_moving_drags_a_window() {
let mut h = harness();
+2 -2
View File
@@ -70,11 +70,11 @@ fn opened_drawings_are_listed_newest_first_and_survive_a_restart() {
let labels: Vec<_> = items.iter().map(|(l, _)| l.as_str()).collect();
assert_eq!(labels, ["plan.dxf", "section.dwg", "Clear Recent Files"]);
// Choosing an already open item selects its tab and moves it to the top.
// Choosing an item opens that file and moves it to the top.
let before = app.session.docs.len();
menus::activate(&mut app, &items[1].1);
settle(&mut app);
assert_eq!(app.session.docs.len(), before);
assert_eq!(app.session.docs.len(), before + 1);
assert_eq!(app.session.state().ok().and_then(|s| s.path.clone()), Some(section.clone()));
assert_eq!(app.ui.recent_files, [section.clone(), plan.clone()]);
-153
View File
@@ -1,153 +0,0 @@
//! Reopening a path selects the existing drawing, preserving edits, even across Finder events.
#![cfg(not(target_arch = "wasm32"))]
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io};
use cadcraft_engine::doc::Drawing;
use cadcraft_ui_egui::{CadApp, Services};
use serde_json::json;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
struct Files(PathBuf);
impl Files {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = std::env::temp_dir().join(format!("cadcraft-reopen-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir(&root).unwrap();
set_io(IoHooks { read: |_, _| Ok(Drawing::new_metric()), write: |_, _| Ok(Vec::new()), plot: None });
Self(root)
}
fn drawing(&self, name: &str) -> PathBuf {
let path = self.0.join(name);
// Synthetic input: the test reader returns an empty drawing for any bytes.
std::fs::write(&path, b"0\nEOF\n").unwrap();
path
}
}
impl Drop for Files {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn app() -> CadApp {
CadApp::new(Session::empty(), Services::default())
}
fn open(app: &mut CadApp, path: &Path) {
app.open_path(path);
}
fn settle(app: &mut CadApp) {
let deadline = Instant::now() + Duration::from_secs(10);
while app.opening.busy() {
app.finish_opening();
assert!(Instant::now() < deadline, "background OPEN did not finish");
std::thread::sleep(Duration::from_millis(1));
}
}
#[test]
fn reopening_dwg_and_dxf_preserves_edits_view_and_recent_files() {
let files = Files::new();
for name in ["检查井 成果.dwg", "管网 检测.dxf"] {
let path = files.drawing(name);
let mut app = app();
open(&mut app, &path);
settle(&mut app);
app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap();
let before = app.session.state().unwrap().clone();
app.run("new", json!({})).unwrap();
let count = app.session.docs.len();
app.ui.start_tab = true;
open(&mut app, &path);
assert!(!app.opening.busy(), "an existing drawing must not be re-read");
let after = app.session.state().unwrap();
assert_eq!(after.uid, before.uid);
assert_eq!(after.doc, before.doc);
assert_eq!(after.view(), before.view());
assert_eq!(after.undo.len(), before.undo.len());
assert!(after.is_dirty());
assert_eq!(app.session.docs.len(), count);
assert!(!app.ui.start_tab);
assert_eq!(app.ui.recent_files.first().map(String::as_str), path.to_str());
}
}
#[test]
fn reopening_a_deleted_file_keeps_the_unsaved_drawing() {
let files = Files::new();
let path = files.drawing("deleted.dxf");
let mut app = app();
open(&mut app, &path);
settle(&mut app);
app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap();
let uid = app.session.state().unwrap().uid;
std::fs::remove_file(&path).unwrap();
app.run("new", json!({})).unwrap();
open(&mut app, &path);
assert!(!app.opening.busy());
assert_eq!(app.session.state().unwrap().uid, uid);
assert!(app.session.state().unwrap().is_dirty());
}
#[test]
fn repeated_requests_while_loading_add_one_tab_per_file() {
let files = Files::new();
let first = files.drawing("first.dxf");
let second = files.drawing("second.dwg");
let mut app = app();
open(&mut app, &first);
open(&mut app, &first);
open(&mut app, &second);
open(&mut app, &first);
settle(&mut app);
assert_eq!(app.session.docs.len(), 2);
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == first.to_str()));
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == second.to_str()));
}
#[cfg(unix)]
#[test]
fn symlinks_share_both_pending_reads_and_existing_dirty_tabs() {
let files = Files::new();
let path = files.drawing("drawing.dxf");
let alias = files.0.join("alias.dxf");
std::os::unix::fs::symlink(&path, &alias).unwrap();
let mut app = app();
open(&mut app, &path);
open(&mut app, &alias);
settle(&mut app);
assert_eq!(app.session.docs.len(), 1);
app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap();
let uid = app.session.state().unwrap().uid;
app.run("new", json!({})).unwrap();
open(&mut app, &alias);
assert!(!app.opening.busy());
assert_eq!(app.session.docs.len(), 2);
assert_eq!(app.session.state().unwrap().uid, uid);
assert!(app.session.state().unwrap().is_dirty());
}
#[test]
fn a_read_finishing_after_the_path_is_opened_keeps_existing_edits() {
let files = Files::new();
let path = files.drawing("pending.dxf");
let mut app = app();
open(&mut app, &path);
// Simulate another OPEN/Save As assigning this path before the UI polls the background read.
app.run("new", json!({})).unwrap();
app.session.state_mut().unwrap().path = path.to_str().map(str::to_string);
app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap();
let uid = app.session.state().unwrap().uid;
settle(&mut app);
assert_eq!(app.session.docs.len(), 1);
assert_eq!(app.session.state().unwrap().uid, uid);
assert!(app.session.state().unwrap().is_dirty());
assert_eq!(app.session.doc().unwrap().entity_count(), 1);
}
-21
View File
@@ -93,27 +93,6 @@ fn programmatic_saves_never_ask() {
cleanup(&path);
}
/// Save As from a DWG warning suggests DXF, which the warning says keeps the objects. The user's
/// default format stays what File ▸ Save As suggests.
#[test]
fn save_as_from_the_dwg_warning_suggests_dxf_and_leaves_the_default() {
let (mut app, path) = opened("suggest", &["MLINE"]);
let suggested = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let seen = suggested.clone();
app.services.pick_save = Some(Box::new(move |name: &str| {
seen.lock().unwrap().push(name.to_string());
None
}));
app.run("ui.saveformat", json!({ "format": "dwg" })).unwrap();
menus::activate(&mut app, "qsave");
app.answer_save_loss(Choice::SaveAs);
app.run("ui.saveas", json!(null)).unwrap();
assert_eq!(suggested.lock().unwrap().as_slice(), ["Plan.dxf", "Plan.dwg"]);
assert_eq!(app.ui.save_format, cadcraft_ui_egui::SaveFormat::Dwg);
assert_eq!(std::fs::read(&path).unwrap(), ORIGINAL, "cancelling the dialog writes nothing");
cleanup(&path);
}
/// Type names come from the file: however many, however long, the warning stays readable.
#[test]
fn a_hostile_list_of_types_is_capped() {
+65
View File
@@ -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`.
+2 -5
View File
@@ -79,9 +79,6 @@
</dict>
</dict>
</array>
<!-- With AutoCAD or LibreOffice installed, .dwg and .dxf files carry their exported types
(com.autodesk.autocad.dwg, org.libreoffice.dxf-document) instead of ours, so those are
claimed too. Otherwise Finder never offers CADCraft in Open With. -->
<key>CFBundleDocumentTypes</key>
<array>
<dict>
@@ -92,7 +89,7 @@
<key>LSHandlerRank</key>
<string>Alternate</string>
<key>LSItemContentTypes</key>
<array><string>ai.storyteller.cadcraft.dxf</string><string>org.libreoffice.dxf-document</string></array>
<array><string>ai.storyteller.cadcraft.dxf</string></array>
<key>CFBundleTypeIconFile</key>
<string>CADCraft</string>
</dict>
@@ -104,7 +101,7 @@
<key>LSHandlerRank</key>
<string>Alternate</string>
<key>LSItemContentTypes</key>
<array><string>ai.storyteller.cadcraft.dwg</string><string>com.autodesk.autocad.dwg</string></array>
<array><string>ai.storyteller.cadcraft.dwg</string></array>
<key>CFBundleTypeIconFile</key>
<string>CADCraft</string>
</dict>