mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-24 21:09:40 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6cc7e0c881 | ||
|
|
f7f409b2b0 | ||
|
|
90d0942548 | ||
|
|
186e465487 | ||
|
|
c79fdde52d | ||
|
|
d4fd0dd7a2 |
@@ -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
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
# Accessibility
|
||||
|
||||
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
|
||||
|
||||
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
|
||||
|
||||
## Supported environments and how accessibility works
|
||||
|
||||
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
|
||||
|
||||
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
|
||||
- **macOS:** NSAccessibility (VoiceOver)
|
||||
- **Linux and FreeBSD:** AT-SPI (Orca)
|
||||
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
|
||||
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
|
||||
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
|
||||
|
||||
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
|
||||
|
||||
## Known limitations and workarounds
|
||||
|
||||
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
|
||||
|
||||
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
|
||||
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
|
||||
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
|
||||
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
|
||||
|
||||
See [This application](#this-application) below for repository-specific links and details.
|
||||
|
||||
## Reporting an accessibility barrier
|
||||
|
||||
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
|
||||
|
||||
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
|
||||
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
|
||||
- **Helpful details to share (when convenient):**
|
||||
- What you were trying to do, what happened, and what you expected
|
||||
- Application version (or commit) and operating system or browser
|
||||
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
|
||||
|
||||
## How we respond
|
||||
|
||||
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
|
||||
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
|
||||
|
||||
## Note for contributors and coding agents
|
||||
|
||||
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
|
||||
|
||||
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
|
||||
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
|
||||
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
|
||||
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
|
||||
|
||||
## Ownership
|
||||
|
||||
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
|
||||
|
||||
## This application
|
||||
|
||||
**CADCraft** (`storytold/cadcraft`) is an open-source computer-aided design and drafting application written in pure Rust.
|
||||
|
||||
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
|
||||
- **Command-line and automation interface:** `cadcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
|
||||
- **Report an accessibility barrier:** [Open an issue in `storytold/cadcraft`](https://github.com/storytold/cadcraft/issues/new)
|
||||
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/cadcraft`](https://github.com/storytold/cadcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
|
||||
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/cadcraft`](https://github.com/storytold/cadcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
|
||||
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
|
||||
+37
-4
@@ -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
@@ -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"
|
||||
|
||||
@@ -48,6 +48,8 @@ thiserror = "2"
|
||||
same-file = "1"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip", "raw_value"] }
|
||||
# Geometry types shared with the PDF interpreter.
|
||||
kurbo = "0.13"
|
||||
log = "0.4"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
@@ -116,6 +118,9 @@ debug = 0
|
||||
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -172,3 +172,192 @@ Original src/avx2/fdct.rs opening notice
|
||||
* Based on the x86 SIMD extension for IJG JPEG library
|
||||
* Copyright (C) 1999-2006, MIYASAKA Masaru.
|
||||
*/
|
||||
|
||||
|
||||
PDF import dependency notices
|
||||
=============================
|
||||
|
||||
The PDF import mapping and synthetic tests derive from CADCraft PR #2787,
|
||||
commit ec17f63f189d1dccf91357701f9bba243ca88dd5 (MIT OR Apache-2.0).
|
||||
Local adaptations retain the project licences.
|
||||
|
||||
Standard PDF font programs (PDFium, BSD-3-Clause)
|
||||
|
||||
// Copyright 2014 PDFium Authors. All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
CMYK profile (CC0-1.0)
|
||||
|
||||
CC0 1.0 Universal
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator and
|
||||
subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for the
|
||||
purpose of contributing to a commons of creative, cultural and scientific
|
||||
works ("Commons") that the public can reliably and without fear of later
|
||||
claims of infringement build upon, modify, incorporate in other works, reuse
|
||||
and redistribute as freely as possible in any form whatsoever and for any
|
||||
purposes, including without limitation commercial purposes. These owners may
|
||||
contribute to the Commons to promote the ideal of a free culture and the
|
||||
further production of creative, cultural and scientific works, or to gain
|
||||
reputation or greater distribution for their Work in part through the use and
|
||||
efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any expectation
|
||||
of additional consideration or compensation, the person associating CC0 with a
|
||||
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
|
||||
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
|
||||
and publicly distribute the Work under its terms, with knowledge of his or her
|
||||
Copyright and Related Rights in the Work and the meaning and intended legal
|
||||
effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not limited
|
||||
to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display, communicate,
|
||||
and translate a Work;
|
||||
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
|
||||
iii. publicity and privacy rights pertaining to a person's image or likeness
|
||||
depicted in a Work;
|
||||
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data in
|
||||
a Work;
|
||||
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation thereof,
|
||||
including any amended or successor version of such directive); and
|
||||
|
||||
vii. other similar, equivalent or corresponding rights throughout the world
|
||||
based on applicable law or treaty, and any national implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention of,
|
||||
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
|
||||
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
|
||||
and Related Rights and associated claims and causes of action, whether now
|
||||
known or unknown (including existing as well as future claims and causes of
|
||||
action), in the Work (i) in all territories worldwide, (ii) for the maximum
|
||||
duration provided by applicable law or treaty (including future time
|
||||
extensions), (iii) in any current or future medium and for any number of
|
||||
copies, and (iv) for any purpose whatsoever, including without limitation
|
||||
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
|
||||
the Waiver for the benefit of each member of the public at large and to the
|
||||
detriment of Affirmer's heirs and successors, fully intending that such Waiver
|
||||
shall not be subject to revocation, rescission, cancellation, termination, or
|
||||
any other legal or equitable action to disrupt the quiet enjoyment of the Work
|
||||
by the public as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason be
|
||||
judged legally invalid or ineffective under applicable law, then the Waiver
|
||||
shall be preserved to the maximum extent permitted taking into account
|
||||
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
|
||||
is so judged Affirmer hereby grants to each affected person a royalty-free,
|
||||
non transferable, non sublicensable, non exclusive, irrevocable and
|
||||
unconditional license to exercise Affirmer's Copyright and Related Rights in
|
||||
the Work (i) in all territories worldwide, (ii) for the maximum duration
|
||||
provided by applicable law or treaty (including future time extensions), (iii)
|
||||
in any current or future medium and for any number of copies, and (iv) for any
|
||||
purpose whatsoever, including without limitation commercial, advertising or
|
||||
promotional purposes (the "License"). The License shall be deemed effective as
|
||||
of the date CC0 was applied by Affirmer to the Work. Should any part of the
|
||||
License for any reason be judged legally invalid or ineffective under
|
||||
applicable law, such partial invalidity or ineffectiveness shall not
|
||||
invalidate the remainder of the License, and in such case Affirmer hereby
|
||||
affirms that he or she will not (i) exercise any of his or her remaining
|
||||
Copyright and Related Rights in the Work or (ii) assert any associated claims
|
||||
and causes of action with respect to the Work, in either case contrary to
|
||||
Affirmer's express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
|
||||
b. Affirmer offers the Work as-is and makes no representations or warranties
|
||||
of any kind concerning the Work, express, implied, statutory or otherwise,
|
||||
including without limitation warranties of title, merchantability, fitness
|
||||
for a particular purpose, non infringement, or the absence of latent or
|
||||
other defects, accuracy, or the present or absence of errors, whether or not
|
||||
discoverable, all to the greatest extent permissible under applicable law.
|
||||
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without limitation
|
||||
any person's Copyright and Related Rights in the Work. Further, Affirmer
|
||||
disclaims responsibility for obtaining any necessary consents, permissions
|
||||
or other rights required for any use of the Work.
|
||||
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to this
|
||||
CC0 or use of the Work.
|
||||
|
||||
For more information, please see
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
|
||||
PDF character maps: LICENSE.txt
|
||||
|
||||
Copyright 1990-2023 Adobe. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
Neither the name of Adobe nor the names of its contributors may be
|
||||
used to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
@@ -26,12 +26,12 @@ fn with_formats(cell: &'static std::sync::OnceLock<String>, before: &str, list:
|
||||
/// The drawing an input argument names.
|
||||
fn read_help() -> &'static str {
|
||||
static C: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
with_formats(&C, "The drawing to read ", Format::READ, "")
|
||||
with_formats(&C, "The drawing to read ", Format::READ, ", or a PDF whose first page opens as editable vector content")
|
||||
}
|
||||
|
||||
fn open_help() -> &'static str {
|
||||
static C: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
with_formats(&C, "Drawings to open ", Format::READ, "")
|
||||
with_formats(&C, "Drawings to open ", Format::READ, ", or PDFs (their first page)")
|
||||
}
|
||||
|
||||
fn write_help() -> &'static str {
|
||||
|
||||
@@ -49,6 +49,7 @@ fn install_io() {
|
||||
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
|
||||
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
|
||||
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
|
||||
groups: cadcraft_io::entity_groups,
|
||||
@@ -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");
|
||||
|
||||
@@ -58,7 +58,7 @@ pub(crate) fn roundtrip(a: &RoundtripArgs, io: &mut Streams) -> Result {
|
||||
if a.keep_saved {
|
||||
opts.keep_saved = Some(out.join("saved"));
|
||||
}
|
||||
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| io.errln(format_args!("[{}/{n}] {rel}", i + 1)));
|
||||
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| eprintln!("[{}/{n}] {rel}", i + 1));
|
||||
for f in &report.files {
|
||||
let routes: Vec<String> = f
|
||||
.routes
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::args::{CmdStep, Drawing, RunArgs, Step};
|
||||
use super::error::Result;
|
||||
use super::open;
|
||||
use super::output::{Streams, export, export_framed, export_window, model_views, undrawn_message};
|
||||
use super::output::{Streams, export, export_framed, export_window, model_views};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Handle;
|
||||
use serde_json::Value;
|
||||
@@ -216,15 +216,7 @@ pub(crate) fn run_cmds(a: &RunArgs, io: &mut Streams) -> Result {
|
||||
export(&s, p, io)?;
|
||||
}
|
||||
if let Some(p) = export_to {
|
||||
let window = if cadcraft_io::is_image(p) {
|
||||
let window = export_window(&s, framing, Some(&before))?;
|
||||
if let Some(message) = undrawn_message(s.doc()?, &p.to_string_lossy()) {
|
||||
io.errln(format_args!("{message}"));
|
||||
}
|
||||
window
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let window = if cadcraft_io::is_image(p) { export_window(&s, framing, Some(&before))? } else { None };
|
||||
export_framed(&s, p, window, io)?;
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -2,6 +2,7 @@ mod cli;
|
||||
mod drafting_spacing;
|
||||
mod help;
|
||||
mod mcp_connect;
|
||||
mod pdf_import;
|
||||
mod skipped_records;
|
||||
mod undrawn_entities;
|
||||
mod usage;
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! A PDF page converted on the command line keeps its geometry and its fill rules through a DXF
|
||||
//! or DWG save and reopen.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
const MM_PER_PT: f64 = 25.4 / 72.0;
|
||||
|
||||
/// A line, a nonzero fill of two nested squares wound the same way (all of it filled), an
|
||||
/// even-odd fill of the same squares (the inner one a hole) and a nonzero fill of two
|
||||
/// overlapping squares (split into triangles).
|
||||
const CONTENT: &str = "1 0 0 RG 2 w 10 10 m 100 10 l S\n\
|
||||
0 0 1 rg 200 200 m 300 200 l 300 300 l 200 300 l h 220 220 m 280 220 l 280 280 l 220 280 l h f\n\
|
||||
0 1 0 rg 400 400 m 500 400 l 500 500 l 400 500 l h 420 420 m 480 420 l 480 480 l 420 480 l h f*\n\
|
||||
1 0 1 rg 50 600 m 150 600 l 150 700 l 50 700 l h 100 650 m 200 650 l 200 750 l 100 750 l h f\n";
|
||||
|
||||
fn page(content: &str) -> Vec<u8> {
|
||||
format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R >> endobj\n\
|
||||
4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF\n",
|
||||
content.len()
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
/// A fresh scratch directory that is removed on drop, also when an assertion fails.
|
||||
struct Scratch(std::path::PathBuf);
|
||||
|
||||
impl Scratch {
|
||||
fn new(tag: &str) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir(&dir).expect("create scratch dir");
|
||||
Scratch(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The model space of `file` with each object's geometry.
|
||||
fn inspect(file: &str) -> Value {
|
||||
let out = cli(&["run", file, "--cmd", r#"drawing.inspect {"entities":true}"#]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(out.status.success(), "{file}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
serde_json::from_str(stdout.lines().last().unwrap_or_default()).unwrap_or_else(|e| panic!("{file}: {e}: {stdout}"))
|
||||
}
|
||||
|
||||
fn inside(ring: &[(f64, f64)], (x, y): (f64, f64)) -> bool {
|
||||
let mut odd = false;
|
||||
for (i, &(ax, ay)) in ring.iter().enumerate() {
|
||||
let (bx, by) = ring[(i + 1) % ring.len()];
|
||||
if (ay > y) != (by > y) && x < (bx - ax) * (y - ay) / (by - ay) + ax {
|
||||
odd = !odd;
|
||||
}
|
||||
}
|
||||
odd
|
||||
}
|
||||
|
||||
/// Whether a hatch covers the page point `at` (in PDF points), by odd parity as hatches are drawn.
|
||||
fn filled(drawing: &Value, at: (f64, f64)) -> bool {
|
||||
let at = (at.0 * MM_PER_PT, at.1 * MM_PER_PT);
|
||||
let entities = drawing["entities"].as_array().cloned().unwrap_or_default();
|
||||
entities.iter().filter(|e| e["type"] == "Hatch").any(|hatch| {
|
||||
let loops = hatch["geometry"]["loops"].as_array().cloned().unwrap_or_default();
|
||||
let rings = loops.iter().map(|l| {
|
||||
l["vertices"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|v| (v["p"]["x"].as_f64().unwrap_or(0.0), v["p"]["y"].as_f64().unwrap_or(0.0)))
|
||||
.collect()
|
||||
});
|
||||
rings.filter(|ring: &Vec<(f64, f64)>| inside(ring, at)).count() % 2 == 1
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pdf_page_keeps_its_fills_through_dxf_and_dwg() {
|
||||
let scratch = Scratch::new("pdf-import");
|
||||
let pdf = scratch.0.join("plan.pdf");
|
||||
std::fs::write(&pdf, page(CONTENT)).unwrap();
|
||||
let pdf = pdf.to_str().unwrap().to_string();
|
||||
let mut files = vec![pdf.clone()];
|
||||
for ext in ["dxf", "dwg"] {
|
||||
let out = scratch.0.join(format!("plan.{ext}"));
|
||||
let out = out.to_str().unwrap().to_string();
|
||||
let run = cli(&["convert", &pdf, &out]);
|
||||
assert!(run.status.success(), "convert to {ext}: {}", String::from_utf8_lossy(&run.stderr));
|
||||
files.push(out);
|
||||
}
|
||||
for file in &files {
|
||||
let d = inspect(file);
|
||||
assert_eq!(d["counts"]["Line"], 1, "{file}: {}", d["counts"]);
|
||||
assert_eq!(d["counts"]["Hatch"], 3, "{file}: {}", d["counts"]);
|
||||
assert!(filled(&d, (251.3, 247.7)), "{file}: the nonzero fill keeps its centre");
|
||||
assert!(filled(&d, (210.2, 205.9)), "{file}: the nonzero fill keeps its rim");
|
||||
assert!(!filled(&d, (451.3, 447.7)), "{file}: the even-odd fill keeps its hole");
|
||||
assert!(filled(&d, (410.2, 405.9)), "{file}: the even-odd fill keeps its rim");
|
||||
assert!(!filled(&d, (350.4, 351.7)), "{file}: nothing is filled between the shapes");
|
||||
assert!(filled(&d, (125.3, 675.2)), "{file}: the overlap of the crossing squares stays filled");
|
||||
assert!(filled(&d, (60.4, 610.3)) && filled(&d, (190.2, 740.1)), "{file}: both crossing squares stay filled");
|
||||
assert!(!filled(&d, (60.4, 740.1)), "{file}: the corner beside the crossing squares stays empty");
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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"))],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -62,11 +62,6 @@ winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
|
||||
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
|
||||
# in Cargo.lock through eframe.
|
||||
pollster = "1"
|
||||
# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a
|
||||
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C
|
||||
# handler behind a safe API, without relaxing the workspace's unsafe-code lint.
|
||||
# Pinned exactly: review the implementation before bumping.
|
||||
fmv-macos-events = "=0.1.0"
|
||||
|
||||
# Rust HID backends: no proprietary SDK or C HID library.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
//! macOS open-documents and quit Apple events (#158).
|
||||
//!
|
||||
//! A Finder double-click, Open With, a drop on the Dock icon and `open -a CADCraft plan.dxf` don't
|
||||
//! put the path in argv: LaunchServices sends the running (or just-launched) app a
|
||||
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
|
||||
//! `NSApplicationDelegate`, so AppKit answered "CADCraft cannot open files in the Drawing Exchange
|
||||
//! Format format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which
|
||||
//! this workspace forbids. The pinned `fmv-macos-events` crate wraps exactly that, an
|
||||
//! `NSAppleEventManager` handler registered before Finder's
|
||||
//! launch event that leaves winit's delegate alone, behind a safe main-thread API.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use cadcraft_ui_egui::CadApp;
|
||||
#[cfg(target_os = "macos")]
|
||||
use fmv_macos_events::{Event, Inbox, Registration};
|
||||
|
||||
/// The shape of `fmv_macos_events::Event`, so [`dispatch`] and its tests also build and run where
|
||||
/// that crate is not compiled (PR CI runs on Linux). On macOS the crate's own type is used.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
enum Event {
|
||||
Open(Vec<PathBuf>),
|
||||
Quit,
|
||||
}
|
||||
|
||||
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub struct AppleEvents {
|
||||
_registration: Registration,
|
||||
inbox: Inbox,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl AppleEvents {
|
||||
/// Register the handlers. Call on the main thread before the event loop starts, so the event
|
||||
/// that launched the app (a Finder double-click) is caught too.
|
||||
pub fn install() -> Self {
|
||||
let (registration, inbox) = Registration::install();
|
||||
Self { _registration: registration, inbox }
|
||||
}
|
||||
|
||||
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
|
||||
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
|
||||
let ctx = ctx.clone();
|
||||
self.inbox.set_wake(move || ctx.request_repaint());
|
||||
self.inbox.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths to hand to OPEN: UTF-8 and non-empty, each once, in the order they arrived. A second
|
||||
/// copy of the same path (Finder sends one per selected item, and a drop can repeat) would open
|
||||
/// the drawing twice.
|
||||
fn openable(paths: impl IntoIterator<Item = PathBuf>) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for p in paths {
|
||||
if let Some(s) = p.to_str().filter(|s| !s.is_empty())
|
||||
&& !out.iter().any(|o| o == s)
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Dispatch a batch through the regular opening and unsaved-changes paths. Returns whether the
|
||||
/// window may close now; a queued quit must not bypass the Save / Don't Save / Cancel prompt.
|
||||
fn dispatch(events: impl IntoIterator<Item = Event>, app: &mut CadApp) -> bool {
|
||||
let mut quit = false;
|
||||
for e in events {
|
||||
match e {
|
||||
Event::Open(paths) => {
|
||||
for p in openable(paths) {
|
||||
app.open_path(std::path::Path::new(&p));
|
||||
}
|
||||
}
|
||||
Event::Quit => quit = true,
|
||||
}
|
||||
}
|
||||
quit && !app.request_quit()
|
||||
}
|
||||
|
||||
/// Drain the inbox each frame; a quit closes the window like Cmd+Q, prompting for unsaved drawings.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn poll(inbox: &Inbox, app: &mut CadApp, ctx: &egui::Context) {
|
||||
if dispatch(inbox.drain(), app) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Event, dispatch, openable};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::closing::Choice;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct TestDir(PathBuf);
|
||||
|
||||
impl TestDir {
|
||||
fn new() -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-apple-events-{}-{}", std::process::id(), NEXT_DIR.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn app() -> CadApp {
|
||||
crate::install_io();
|
||||
// The DWG written and read here is the test's own synthetic file; the app starts its DWG
|
||||
// worker in `main`, which a test does not run.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
CadApp::new(Session::new(), Services::default())
|
||||
}
|
||||
|
||||
fn settle(app: &mut CadApp) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while app.opening.busy() && Instant::now() < deadline {
|
||||
app.finish_opening();
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
app.finish_opening();
|
||||
assert!(!app.opening.busy(), "background opening completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_order_and_drops_duplicates_and_empty_paths() {
|
||||
let paths = ["/a/plan.dxf", "", "/b/site.dwg", "/a/plan.dxf"].map(PathBuf::from);
|
||||
assert_eq!(openable(paths), ["/a/plan.dxf", "/b/site.dwg"]);
|
||||
assert!(openable(Vec::new()).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn skips_paths_that_are_not_utf8() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let bad = PathBuf::from(std::ffi::OsString::from_vec(vec![b'/', 0xff, b'.', b'd', b'x', b'f']));
|
||||
assert_eq!(openable([bad, PathBuf::from("/ok.dxf")]), ["/ok.dxf"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_dwg_and_dxf_without_replacing_an_unsaved_drawing() {
|
||||
// Writing and opening the DWG here needs the converter in this process: each test is its own.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let dir = TestDir::new();
|
||||
let dxf = dir.0.join("planta com espaços.dxf");
|
||||
let dwg = dir.0.join("Documentac\u{327}a\u{303}o.dwg");
|
||||
let bytes = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n10\n0\nENDSEC\n0\nEOF\n";
|
||||
let drawing = cadcraft_io::read(bytes, "synthetic.dxf").unwrap();
|
||||
std::fs::write(&dxf, bytes).unwrap();
|
||||
std::fs::write(&dwg, cadcraft_io::write(&drawing, "synthetic.dwg").unwrap()).unwrap();
|
||||
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!dispatch([Event::Open(vec![dxf.clone(), dwg.clone(), dxf.clone(), PathBuf::new()])], &mut app));
|
||||
settle(&mut app);
|
||||
|
||||
assert_eq!(app.session.docs.len(), 3, "each file is opened once alongside the unsaved drawing");
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
for path in [&dxf, &dwg] {
|
||||
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == path.to_str()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_open_reports_the_path_and_keeps_existing_drawings() {
|
||||
let dir = TestDir::new();
|
||||
let missing = dir.0.join("missing drawing.dwg");
|
||||
let mut app = app();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(!dispatch([Event::Open(vec![missing.clone()])], &mut app));
|
||||
settle(&mut app);
|
||||
assert_eq!(app.session.docs.len(), 1);
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.log.iter().any(|line| line.contains(missing.to_str().unwrap())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_asks_before_closing_unsaved_work_and_can_be_cancelled() {
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
assert!(!dispatch([Event::Quit], &mut app), "must not issue a window close before the answer");
|
||||
assert!(app.close_prompt().is_some());
|
||||
assert!(!app.quit_confirmed);
|
||||
assert!(!app.quit_requested);
|
||||
app.answer_close(Choice::Cancel);
|
||||
assert!(app.close_prompt().is_none());
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!app.quit_requested);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_can_close_a_clean_session() {
|
||||
let mut app = app();
|
||||
assert!(dispatch([Event::Quit], &mut app));
|
||||
assert!(app.close_prompt().is_none());
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -123,11 +123,6 @@ sync_github_name = true
|
||||
[people.helenkwok]
|
||||
real_name = "Helen Kwok"
|
||||
|
||||
[people.whaslbeck]
|
||||
real_name = "Walter Haslbeck"
|
||||
display_name = "Walter Haslbeck"
|
||||
sync_github_name = false
|
||||
|
||||
[people.V1dalTheAbidal]
|
||||
sync_github_name = true
|
||||
|
||||
|
||||
@@ -43,7 +43,6 @@ mod curves;
|
||||
mod dim;
|
||||
mod fill;
|
||||
mod layout;
|
||||
mod proxy;
|
||||
mod text;
|
||||
mod wipeout;
|
||||
|
||||
@@ -53,18 +52,12 @@ pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, Polyface
|
||||
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
|
||||
pub use fill::{Gradient, Hatch, HatchLoop};
|
||||
pub use layout::{Image, Table, TableCell, Viewport};
|
||||
pub use proxy::{ProxyTables, proxy_entities};
|
||||
pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign};
|
||||
pub use wipeout::Wipeout;
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Unknown {
|
||||
pub dxf_type: String,
|
||||
pub tags: Vec<RawTag>,
|
||||
/// What an ACAD_PROXY_ENTITY draws: its proxy graphics as read-only entities, made when the
|
||||
/// drawing is read (the graphics refer to table rows by their place in the file). Drawn and
|
||||
/// measured like block contents; saving writes `tags` unchanged.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub graphics: Vec<Entity>,
|
||||
}
|
||||
|
||||
impl Unknown {
|
||||
@@ -271,8 +264,7 @@ impl EntityKind {
|
||||
EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())],
|
||||
EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())],
|
||||
EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())],
|
||||
// What its proxy graphics draw, so a proxy can be picked and snapped to.
|
||||
EntityKind::Unknown(u) => u.graphics.iter().flat_map(|g| g.kind.prims()).collect(),
|
||||
EntityKind::Unknown(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -1,717 +0,0 @@
|
||||
//! The proxy graphics an ACAD_PROXY_ENTITY carries (DXF groups 92/160 and 310): the picture
|
||||
//! the owning application left for programs that don't have it, drawn as AutoCAD draws it with
|
||||
//! PROXYSHOW 1. The layout follows the Open Design Alliance's public DWG specification
|
||||
//! ("Proxy Entity Graphics"): a header (total size, chunk count), then chunks of (size, type,
|
||||
//! data), sizes in bytes including the 8-byte chunk header, all little-endian.
|
||||
//!
|
||||
//! The picture becomes ordinary, read-only entities: drawn and measured like the contents of a
|
||||
//! block, with layer 0, ByBlock colour, linetype and lineweight standing for the proxy's own
|
||||
//! until a chunk sets them. Chunks CADCraft doesn't decode (meshes, shells, lightweight
|
||||
//! polylines, materials) are skipped.
|
||||
|
||||
use super::{Arc, Circle, Common, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown};
|
||||
use cadcraft_color::{Color, Rgb};
|
||||
use cadcraft_geom::{PolyVertex, Vec2, Vec3};
|
||||
|
||||
/// Bytes of proxy graphics read at most from one entity.
|
||||
const MAX_BYTES: usize = 16 << 20;
|
||||
/// Entities made at most from one entity's proxy graphics.
|
||||
const MAX_ENTITIES: usize = 100_000;
|
||||
/// Vertices read at most from one polyline or polygon chunk.
|
||||
const MAX_VERTICES: usize = 1_000_000;
|
||||
/// Matrices pushed at most.
|
||||
const MAX_MATRICES: usize = 64;
|
||||
|
||||
/// The table names proxy graphics refer to by index, in the order of the file's tables.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ProxyTables {
|
||||
/// LAYER records in file order.
|
||||
pub layers: Vec<String>,
|
||||
/// LTYPE records in file order, without ByBlock and ByLayer (indices count only the others).
|
||||
pub linetypes: Vec<String>,
|
||||
/// Text styles (name, font file) in file order: a text chunk names its font, and the first
|
||||
/// style with that font draws it.
|
||||
pub styles: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Unknown {
|
||||
/// The proxy graphics bytes of an ACAD_PROXY_ENTITY: the 310 groups after its size group
|
||||
/// (92, or 160 in newer files), cut to that size. Empty for other records, for an entity
|
||||
/// without graphics and for one whose data isn't hex.
|
||||
pub fn proxy_graphics_bytes(&self) -> Vec<u8> {
|
||||
if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(at) = self.tags.iter().position(|t| t.code == 92 || t.code == 160) else { return Vec::new() };
|
||||
let size = self.tags.get(at).and_then(|t| t.value.trim().parse::<usize>().ok()).unwrap_or(0).min(MAX_BYTES);
|
||||
let mut out = Vec::with_capacity(size);
|
||||
for t in self.tags.iter().skip(at + 1).take_while(|t| t.code == 310) {
|
||||
// Damaged data draws nothing rather than a picture cut at a guess.
|
||||
if !push_hex(&mut out, &t.value) {
|
||||
return Vec::new();
|
||||
}
|
||||
if out.len() >= size {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out.truncate(size);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Append the bytes of hex string `s`. False on a character that isn't a hex digit.
|
||||
fn push_hex(out: &mut Vec<u8>, s: &str) -> bool {
|
||||
let digits: Vec<u8> = s.trim().bytes().collect();
|
||||
for pair in digits.chunks(2) {
|
||||
let (Some(&hi), Some(&lo)) = (pair.first(), pair.get(1)) else { return false };
|
||||
let (Some(hi), Some(lo)) = ((hi as char).to_digit(16), (lo as char).to_digit(16)) else { return false };
|
||||
out.push((hi * 16 + lo) as u8);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The entities the proxy graphics `bytes` draw, all with `handle` (the proxy's): selecting one
|
||||
/// selects the proxy.
|
||||
pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec<Entity> {
|
||||
let mut r = Decoder {
|
||||
tables,
|
||||
handle,
|
||||
pen: Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..Common::default() },
|
||||
fill: false,
|
||||
matrices: Vec::new(),
|
||||
out: Vec::new(),
|
||||
};
|
||||
let mut at = 8;
|
||||
while let (Some(size), Some(kind)) = (u32_at(bytes, at), u32_at(bytes, at + 4)) {
|
||||
let size = size as usize;
|
||||
if size < 8 || r.out.len() >= MAX_ENTITIES {
|
||||
break;
|
||||
}
|
||||
let Some(data) = bytes.get(at + 8..at.saturating_add(size)) else { break };
|
||||
r.chunk(kind, data);
|
||||
at += size;
|
||||
}
|
||||
r.out
|
||||
}
|
||||
|
||||
struct Decoder<'a> {
|
||||
tables: &'a ProxyTables,
|
||||
handle: Handle,
|
||||
/// Layer, colour, linetype and lineweight for the entities that follow.
|
||||
pen: Common,
|
||||
fill: bool,
|
||||
/// Model transforms pushed by PUSH_MATRIX, innermost last (row-major 3x4 of the 4x4).
|
||||
matrices: Vec<[f64; 12]>,
|
||||
out: Vec<Entity>,
|
||||
}
|
||||
|
||||
impl Decoder<'_> {
|
||||
/// Decode one chunk of type `kind`: draw it, or change the pen for what follows.
|
||||
fn chunk(&mut self, kind: u32, data: &[u8]) {
|
||||
let mut b = Bytes { data, at: 0 };
|
||||
match kind {
|
||||
// CIRCLE: centre, radius, normal.
|
||||
2 => {
|
||||
if let (Some(c), Some(r)) = (b.point(), b.f64()) {
|
||||
self.circle(c, r);
|
||||
}
|
||||
}
|
||||
// CIRCLE_3P: three points on it.
|
||||
3 => {
|
||||
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point())
|
||||
&& let Some((c, r)) = circle_through(self.xy(p1), self.xy(p2), self.xy(p3))
|
||||
{
|
||||
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
|
||||
}
|
||||
}
|
||||
// CIRCULAR_ARC: centre, radius, normal, start vector, sweep angle (around the normal).
|
||||
4 => {
|
||||
if let (Some(c), Some(r), Some(n), Some(v), Some(sweep)) = (b.point(), b.f64(), b.point(), b.point(), b.f64()) {
|
||||
self.arc(c, r, n, v, sweep);
|
||||
}
|
||||
}
|
||||
// CIRCULAR_ARC_3P: start, a point on the arc, end.
|
||||
5 => {
|
||||
if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point()) {
|
||||
self.arc_3p(self.xy(p1), self.xy(p2), self.xy(p3));
|
||||
}
|
||||
}
|
||||
// POLYLINE and POLYGON: a count, then the points.
|
||||
6 | 7 => {
|
||||
let Some(n) = b.u32() else { return };
|
||||
let n = (n as usize).min(MAX_VERTICES);
|
||||
let pts: Vec<Vec2> = (0..n).map_while(|_| b.point()).map(|p| self.xy(p)).collect();
|
||||
self.polyline(pts, kind == 7);
|
||||
}
|
||||
// TEXT: position, normal, direction, height, width factor, oblique, string.
|
||||
10 => {
|
||||
if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) {
|
||||
let s = b.string();
|
||||
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() });
|
||||
}
|
||||
}
|
||||
// TEXT2: position, normal, direction, string, length (the characters drawn), raw
|
||||
// flag, height, width factor, oblique, tracking, five style flags, font, big font.
|
||||
11 => {
|
||||
if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) {
|
||||
let s = b.string();
|
||||
let s = first_chars(s, b.u32());
|
||||
b.skip(4);
|
||||
if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) {
|
||||
b.skip(8 + 20);
|
||||
let font = b.string();
|
||||
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font });
|
||||
}
|
||||
}
|
||||
}
|
||||
// UNICODE_TEXT: as TEXT with a UTF-16 string.
|
||||
36 => {
|
||||
if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) {
|
||||
let s = b.unicode();
|
||||
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() });
|
||||
}
|
||||
}
|
||||
// UNICODE_TEXT2: as TEXT2 with UTF-16 strings, and bold, italic, charset, pitch and
|
||||
// the typeface before the font file.
|
||||
38 => {
|
||||
if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) {
|
||||
let s = b.unicode();
|
||||
let s = first_chars(s, b.u32());
|
||||
b.skip(4);
|
||||
if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) {
|
||||
b.skip(8 + 20 + 16);
|
||||
let _typeface = b.unicode();
|
||||
let font = b.unicode();
|
||||
self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font });
|
||||
}
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_COLOR: ACI, 0 ByBlock, 256 ByLayer.
|
||||
14 => {
|
||||
if let Some(c) = b.u32() {
|
||||
self.pen.color = Color::from_aci(i16::try_from(c).unwrap_or(256));
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_LAYER: index into the layer table; an index past it leaves the layer.
|
||||
16 => {
|
||||
if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)) {
|
||||
self.pen.layer = name.clone();
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_LINETYPE: index into the linetypes other than ByBlock and ByLayer;
|
||||
// 32766 is ByBlock, 32767 and anything past the table ByLayer.
|
||||
18 => {
|
||||
if let Some(i) = b.u32() {
|
||||
self.pen.linetype = match i {
|
||||
32766 => "ByBlock".into(),
|
||||
_ => self.tables.linetypes.get(i as usize).cloned().unwrap_or_else(|| "ByLayer".into()),
|
||||
};
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_FILL: the next polygon is filled.
|
||||
20 => self.fill = b.u32().is_some_and(|f| f != 0),
|
||||
// ATTRIBUTE_TRUE_COLOR: a colour with its method in the top byte.
|
||||
22 => {
|
||||
if let Some(v) = b.u32() {
|
||||
self.pen.color = match v >> 24 {
|
||||
0xC0 => Color::ByLayer,
|
||||
0xC1 => Color::ByBlock,
|
||||
0xC2 => Color::True(Rgb::from_u32(v & 0x00FF_FFFF)),
|
||||
0xC3 => Color::from_aci((v & 0xFF) as i16),
|
||||
_ => self.pen.color,
|
||||
};
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_LINEWEIGHT: hundredths of a millimetre, or -1 ByLayer, -2 ByBlock,
|
||||
// -3 the default.
|
||||
23 => {
|
||||
if let Some(v) = b.u32() {
|
||||
self.pen.lineweight = Lineweight::from_dxf(i16::try_from(v as i32).unwrap_or(-1));
|
||||
}
|
||||
}
|
||||
// ATTRIBUTE_LTSCALE.
|
||||
24 => {
|
||||
if let Some(s) = b.f64().filter(|s| s.is_finite() && *s > 0.0) {
|
||||
self.pen.ltscale = s;
|
||||
}
|
||||
}
|
||||
// PUSH_MATRIX, PUSH_MATRIX2: a 4x4 model transform for what follows; POP_MATRIX.
|
||||
29 | 30 => {
|
||||
let m: Vec<f64> = (0..16).map_while(|_| b.f64()).collect();
|
||||
if let Some(m) = m.get(..12).and_then(|m| <[f64; 12]>::try_from(m).ok())
|
||||
&& m.iter().all(|x| x.is_finite())
|
||||
&& self.matrices.len() < MAX_MATRICES
|
||||
{
|
||||
self.matrices.push(m);
|
||||
}
|
||||
}
|
||||
31 => {
|
||||
self.matrices.pop();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add an entity drawn with the current pen (up to [`MAX_ENTITIES`]).
|
||||
fn push(&mut self, kind: EntityKind) {
|
||||
if self.out.len() < MAX_ENTITIES {
|
||||
self.out.push(Entity { handle: self.handle, common: self.pen.clone(), kind });
|
||||
}
|
||||
}
|
||||
|
||||
/// `p` through the pushed matrices, innermost first, in the XY plane.
|
||||
fn xy(&self, p: Vec3) -> Vec2 {
|
||||
let mut p = p;
|
||||
for m in self.matrices.iter().rev() {
|
||||
p = Vec3::new(
|
||||
m[0] * p.x + m[1] * p.y + m[2] * p.z + m[3],
|
||||
m[4] * p.x + m[5] * p.y + m[6] * p.z + m[7],
|
||||
m[8] * p.x + m[9] * p.y + m[10] * p.z + m[11],
|
||||
);
|
||||
}
|
||||
p.xy()
|
||||
}
|
||||
|
||||
/// How much the pushed matrices scale lengths (1 without any).
|
||||
fn scale(&self) -> f64 {
|
||||
self.matrices.iter().map(|m| (m[0] * m[5] - m[1] * m[4]).abs().sqrt()).product()
|
||||
}
|
||||
|
||||
/// A full circle around `c`, through the pushed matrices.
|
||||
fn circle(&mut self, c: Vec3, r: f64) {
|
||||
let r = r * self.scale();
|
||||
let c = self.xy(c);
|
||||
if r.is_finite() && r > 0.0 && c.is_finite() {
|
||||
self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r }));
|
||||
}
|
||||
}
|
||||
|
||||
/// An arc around `c` from the direction `start`, turned by `sweep` around `normal`.
|
||||
fn arc(&mut self, c: Vec3, r: f64, normal: Vec3, start: Vec3, sweep: f64) {
|
||||
if !(r.is_finite() && r > 0.0 && sweep.is_finite() && sweep != 0.0) || start.xy().len() < 1e-12 {
|
||||
return;
|
||||
}
|
||||
// The start point and the end point (the start vector turned by the sweep around the
|
||||
// normal: clockwise in plan for a normal pointing down), through the matrices.
|
||||
let dir = if normal.z < 0.0 { -1.0 } else { 1.0 };
|
||||
let a0 = start.y.atan2(start.x);
|
||||
let a1 = a0 + dir * sweep;
|
||||
let on = |a: f64| c + Vec3::new(r * a.cos(), r * a.sin(), 0.0);
|
||||
let mid = on((a0 + a1) / 2.0);
|
||||
if sweep.abs() >= std::f64::consts::TAU - 1e-9 {
|
||||
return self.circle(c, r);
|
||||
}
|
||||
self.arc_3p(self.xy(on(a0)), self.xy(mid), self.xy(on(a1)));
|
||||
}
|
||||
|
||||
/// The arc from `p1` through `p2` to `p3`.
|
||||
fn arc_3p(&mut self, p1: Vec2, p2: Vec2, p3: Vec2) {
|
||||
let Some((c, r)) = circle_through(p1, p2, p3) else {
|
||||
return self.polyline(vec![p1, p3], false);
|
||||
};
|
||||
let ang = |p: Vec2| (p.y - c.y).atan2(p.x - c.x);
|
||||
let (a1, a2, a3) = (ang(p1), ang(p2), ang(p3));
|
||||
let ccw = |from: f64, to: f64| (to - from).rem_euclid(std::f64::consts::TAU);
|
||||
// Counter-clockwise from p1 to p3 when p2 lies on that way, else from p3 to p1.
|
||||
let (start, end) = if ccw(a1, a2) <= ccw(a1, a3) { (a1, a3) } else { (a3, a1) };
|
||||
self.push(EntityKind::Arc(Arc { center: c.to3(0.0), radius: r, start, end }));
|
||||
}
|
||||
|
||||
/// A polyline, or a closed polygon: filled (a solid hatch) when ATTRIBUTE_FILL asked for it,
|
||||
/// which applies to this one polygon only.
|
||||
fn polyline(&mut self, pts: Vec<Vec2>, polygon: bool) {
|
||||
let fill = std::mem::take(&mut self.fill);
|
||||
if pts.iter().any(|p| !p.is_finite()) || pts.is_empty() {
|
||||
return;
|
||||
}
|
||||
if polygon && fill && pts.len() >= 3 {
|
||||
let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
|
||||
return self.push(EntityKind::Hatch(Hatch {
|
||||
pattern: "SOLID".into(),
|
||||
solid: true,
|
||||
loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, sources: Vec::new() }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: false,
|
||||
style: 0,
|
||||
elevation: 0.0,
|
||||
gradient: None,
|
||||
origin: Vec2::ZERO,
|
||||
background: None,
|
||||
pattern_lines: Vec::new(),
|
||||
}));
|
||||
}
|
||||
match pts.as_slice() {
|
||||
[a, b] if !polygon => self.push(EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })),
|
||||
_ => {
|
||||
let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
|
||||
self.push(EntityKind::LwPolyline(LwPolyline { vertices, closed: polygon, const_width: 0.0, elevation: 0.0, plinegen: false }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A single-line text, its style the first one whose font file the chunk names.
|
||||
fn text(&mut self, t: TextChunk) {
|
||||
let TextChunk { p, dir, height, width, oblique, value, font } = t;
|
||||
let font = font.as_str();
|
||||
let height = height * self.scale();
|
||||
if !(height.is_finite() && height > 0.0) || value.is_empty() {
|
||||
return;
|
||||
}
|
||||
let at = self.xy(p);
|
||||
if !at.is_finite() {
|
||||
return;
|
||||
}
|
||||
let towards = self.xy(p + dir) - at;
|
||||
let rotation = if towards.len() > 1e-12 { towards.y.atan2(towards.x) } else { 0.0 };
|
||||
let stem = |f: &str| f.trim().rsplit(['/', '\\']).next().unwrap_or_default().split('.').next().unwrap_or_default().to_ascii_lowercase();
|
||||
let style = self
|
||||
.tables
|
||||
.styles
|
||||
.iter()
|
||||
.find(|(_, f)| !font.is_empty() && stem(f) == stem(font))
|
||||
.map(|(n, _)| n.clone())
|
||||
.unwrap_or_else(|| "Standard".into());
|
||||
self.push(EntityKind::Text(Text {
|
||||
insert: at.to3(0.0),
|
||||
align_pt: None,
|
||||
height,
|
||||
value,
|
||||
rotation,
|
||||
width_factor: if width.is_finite() && width > 0.0 { width } else { 1.0 },
|
||||
oblique: if oblique.is_finite() { oblique } else { 0.0 },
|
||||
style,
|
||||
halign: Default::default(),
|
||||
valign: Default::default(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The first `length` characters of `s`: a text chunk may carry more text than it draws (the
|
||||
/// rest of a note, drawn by the chunks after it). No length, or one past the end, keeps it all.
|
||||
fn first_chars(s: String, length: Option<u32>) -> String {
|
||||
match length.map(|n| n as usize) {
|
||||
Some(n) if n > 0 && n < s.chars().count() => s.chars().take(n).collect(),
|
||||
_ => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// A text chunk: position, direction, height, width factor, oblique, string and font file.
|
||||
struct TextChunk {
|
||||
p: Vec3,
|
||||
dir: Vec3,
|
||||
height: f64,
|
||||
width: f64,
|
||||
oblique: f64,
|
||||
value: String,
|
||||
font: String,
|
||||
}
|
||||
|
||||
/// The circle through three points (centre, radius), if they aren't on one line.
|
||||
fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> {
|
||||
let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
|
||||
if !d.is_finite() || d.abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let (a2, b2, c2) = (a.x * a.x + a.y * a.y, b.x * b.x + b.y * b.y, c.x * c.x + c.y * c.y);
|
||||
let center =
|
||||
Vec2::new((a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d);
|
||||
let r = (a - center).len();
|
||||
(center.is_finite() && r.is_finite() && r > 0.0).then_some((center, r))
|
||||
}
|
||||
|
||||
/// The little-endian u32 at `at`, if `bytes` holds one there.
|
||||
fn u32_at(bytes: &[u8], at: usize) -> Option<u32> {
|
||||
bytes.get(at..at.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)
|
||||
}
|
||||
|
||||
/// A reader over one chunk's data. Strings are padded to four bytes.
|
||||
struct Bytes<'a> {
|
||||
data: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl Bytes<'_> {
|
||||
/// The next `n` bytes, if there are that many.
|
||||
fn take(&mut self, n: usize) -> Option<&[u8]> {
|
||||
let s = self.data.get(self.at..self.at.checked_add(n)?)?;
|
||||
self.at += n;
|
||||
Some(s)
|
||||
}
|
||||
/// Pass over `n` bytes (reads after the end then find nothing).
|
||||
fn skip(&mut self, n: usize) {
|
||||
self.at = self.at.saturating_add(n);
|
||||
}
|
||||
/// A little-endian u32.
|
||||
fn u32(&mut self) -> Option<u32> {
|
||||
self.take(4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)
|
||||
}
|
||||
/// A little-endian double.
|
||||
fn f64(&mut self) -> Option<f64> {
|
||||
self.take(8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes)
|
||||
}
|
||||
/// Three doubles, if all are finite.
|
||||
fn point(&mut self) -> Option<Vec3> {
|
||||
let p = Vec3::new(self.f64()?, self.f64()?, self.f64()?);
|
||||
(p.x.is_finite() && p.y.is_finite() && p.z.is_finite()).then_some(p)
|
||||
}
|
||||
/// Move on to the next multiple of four bytes, where padded strings end.
|
||||
fn align(&mut self) {
|
||||
self.at = self.at.saturating_add((4 - self.at % 4) % 4);
|
||||
}
|
||||
/// A zero-terminated string in the drawing's code page; bytes above 0x7F as Latin-1.
|
||||
fn string(&mut self) -> String {
|
||||
let rest = self.data.get(self.at..).unwrap_or_default();
|
||||
let end = rest.iter().position(|&c| c == 0).unwrap_or(rest.len());
|
||||
let s: String = rest.iter().take(end).map(|&c| c as char).collect();
|
||||
self.at += end + 1;
|
||||
self.align();
|
||||
s
|
||||
}
|
||||
/// A UTF-16 string ended by a zero code unit.
|
||||
fn unicode(&mut self) -> String {
|
||||
let rest = self.data.get(self.at..).unwrap_or_default();
|
||||
let (pairs, _) = rest.as_chunks::<2>();
|
||||
let units: Vec<u16> = pairs.iter().map(|&p| u16::from_le_bytes(p)).take_while(|&u| u != 0).collect();
|
||||
self.at += units.len() * 2 + 2;
|
||||
self.align();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::RawTag;
|
||||
|
||||
/// A chunk of type `kind`, its data padded to four bytes.
|
||||
fn chunk(kind: u32, data: &[u8]) -> Vec<u8> {
|
||||
let mut d = data.to_vec();
|
||||
d.resize(d.len().div_ceil(4) * 4, 0);
|
||||
let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec();
|
||||
out.extend(kind.to_le_bytes());
|
||||
out.extend(d);
|
||||
out
|
||||
}
|
||||
/// Proxy graphics: the header (total size, chunk count), then the chunks.
|
||||
fn graphics(chunks: &[Vec<u8>]) -> Vec<u8> {
|
||||
let body: Vec<u8> = chunks.concat();
|
||||
let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec();
|
||||
out.extend((chunks.len() as u32).to_le_bytes());
|
||||
out.extend(body);
|
||||
out
|
||||
}
|
||||
/// A point in the XY plane as three doubles.
|
||||
fn pt(x: f64, y: f64) -> Vec<u8> {
|
||||
[x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect()
|
||||
}
|
||||
/// Two layers, two linetypes and two text styles.
|
||||
fn tables() -> ProxyTables {
|
||||
ProxyTables {
|
||||
layers: vec!["0".into(), "BALLOONS".into()],
|
||||
linetypes: vec!["Continuous".into(), "DASHED".into()],
|
||||
styles: vec![("Standard".into(), "txt".into()), ("ISO".into(), "isocp.shx".into())],
|
||||
}
|
||||
}
|
||||
|
||||
/// A balloon as AutoCAD Mechanical stores one: layer, colour, a circle, the leader and the
|
||||
/// number as TEXT2.
|
||||
#[test]
|
||||
fn a_balloon_becomes_circle_line_and_text() {
|
||||
let mut text2 = pt(173.0, 112.0);
|
||||
text2.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter()));
|
||||
text2.extend(pt(1.0, 0.0));
|
||||
text2.extend(b"12\0\0");
|
||||
text2.extend(2i32.to_le_bytes());
|
||||
text2.extend(0i32.to_le_bytes());
|
||||
for v in [6.0f64, 1.0, 0.0, 0.0] {
|
||||
text2.extend(v.to_le_bytes());
|
||||
}
|
||||
text2.extend([0u8; 20]);
|
||||
text2.extend(b"ISOCP.SHX\0\0\0\0\0");
|
||||
let mut circle = pt(175.0, 115.0);
|
||||
circle.extend(6.0f64.to_le_bytes());
|
||||
circle.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter()));
|
||||
let mut leader = 2u32.to_le_bytes().to_vec();
|
||||
leader.extend(pt(170.0, 111.0));
|
||||
leader.extend(pt(150.0, 90.0));
|
||||
let g = graphics(&[chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text2)]);
|
||||
let es = proxy_entities(&g, &tables(), Handle(0x35));
|
||||
assert_eq!(es.len(), 3);
|
||||
assert!(es.iter().all(|e| e.handle == Handle(0x35) && e.common.layer == "BALLOONS" && e.common.color == Color::Index(1)));
|
||||
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(175.0, 115.0, 0.0) && c.radius == 6.0));
|
||||
assert!(matches!(&es[1].kind, EntityKind::Line(l) if l.b == Vec3::new(150.0, 90.0, 0.0)));
|
||||
assert!(matches!(&es[2].kind, EntityKind::Text(t) if t.value == "12" && t.height == 6.0 && t.style == "ISO" && t.rotation == 0.0));
|
||||
}
|
||||
|
||||
/// A TEXT2 chunk draws only as many characters as its length says.
|
||||
#[test]
|
||||
fn text2_draws_its_length() {
|
||||
let text2 = |value: &[u8], length: i32| {
|
||||
let mut t = pt(0.0, 0.0);
|
||||
t.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
t.extend(pt(1.0, 0.0));
|
||||
t.extend(value);
|
||||
t.extend(vec![0u8; 4 - value.len() % 4]);
|
||||
t.extend(length.to_le_bytes());
|
||||
t.extend(1i32.to_le_bytes());
|
||||
for v in [2.5f64, 1.0, 0.0, 0.0] {
|
||||
t.extend(v.to_le_bytes());
|
||||
}
|
||||
t.extend([0u8; 20]);
|
||||
t.extend(b"txt\0");
|
||||
let es = proxy_entities(&graphics(&[chunk(11, &t)]), &tables(), Handle(1));
|
||||
match es.first().map(|e| &e.kind) {
|
||||
Some(EntityKind::Text(t)) => t.value.clone(),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
};
|
||||
assert_eq!(text2(b"two lines\\Pof text", 9), "two lines");
|
||||
assert_eq!(text2(b"whole", 0), "whole");
|
||||
assert_eq!(text2(b"whole", 99), "whole");
|
||||
}
|
||||
|
||||
/// Without layer and colour chunks the picture takes the proxy's own (layer 0, ByBlock).
|
||||
#[test]
|
||||
fn unset_traits_are_the_proxys() {
|
||||
let mut leader = 3u32.to_le_bytes().to_vec();
|
||||
for (x, y) in [(0.0, 0.0), (10.0, 0.0), (10.0, 5.0)] {
|
||||
leader.extend(pt(x, y));
|
||||
}
|
||||
let es = proxy_entities(
|
||||
&graphics(&[chunk(6, &leader), chunk(16, &u32::MAX.to_le_bytes()), chunk(18, &32766u32.to_le_bytes())]),
|
||||
&tables(),
|
||||
Handle(1),
|
||||
);
|
||||
let e = es.first().expect("polyline");
|
||||
assert_eq!(
|
||||
(e.common.layer.as_str(), e.common.color, e.common.linetype.as_str(), e.common.lineweight),
|
||||
("0", Color::ByBlock, "ByBlock", Lineweight::ByBlock)
|
||||
);
|
||||
assert!(matches!(&e.kind, EntityKind::LwPolyline(p) if p.vertices.len() == 3 && !p.closed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filled_polygon_is_a_solid_hatch_and_fill_applies_once() {
|
||||
let mut tri = 3u32.to_le_bytes().to_vec();
|
||||
for (x, y) in [(0.0, 0.0), (4.0, 0.0), (2.0, 3.0)] {
|
||||
tri.extend(pt(x, y));
|
||||
}
|
||||
let es = proxy_entities(&graphics(&[chunk(20, &1u32.to_le_bytes()), chunk(7, &tri), chunk(7, &tri)]), &tables(), Handle(1));
|
||||
assert!(matches!(&es[0].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3));
|
||||
assert!(matches!(&es[1].kind, EntityKind::LwPolyline(p) if p.closed));
|
||||
}
|
||||
|
||||
/// A quarter arc counter-clockwise from 0°, and the same sweep around a downward normal,
|
||||
/// which runs clockwise in plan (from 0° to -90°).
|
||||
#[test]
|
||||
fn arcs_follow_their_normal() {
|
||||
let arc = |nz: f64| {
|
||||
let mut a = pt(0.0, 0.0);
|
||||
a.extend(2.0f64.to_le_bytes());
|
||||
a.extend([0.0f64, 0.0, nz].iter().flat_map(|v| v.to_le_bytes()));
|
||||
a.extend(pt(1.0, 0.0));
|
||||
a.extend(std::f64::consts::FRAC_PI_2.to_le_bytes());
|
||||
a.extend(0u32.to_le_bytes());
|
||||
match proxy_entities(&graphics(&[chunk(4, &a)]), &tables(), Handle(1)).first().map(|e| e.kind.clone()) {
|
||||
Some(EntityKind::Arc(a)) => (a.start, a.end, a.radius),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
};
|
||||
let (s, e, r) = arc(1.0);
|
||||
assert!(s.abs() < 1e-9 && (e - std::f64::consts::FRAC_PI_2).abs() < 1e-9 && (r - 2.0).abs() < 1e-9);
|
||||
let (s, e, _) = arc(-1.0);
|
||||
assert!((s + std::f64::consts::FRAC_PI_2).abs() < 1e-9 && e.abs() < 1e-9, "{s} {e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pushed_matrix_moves_what_follows_until_popped() {
|
||||
let mut m = [0.0f64; 16];
|
||||
(m[0], m[5], m[10], m[15], m[3], m[7]) = (2.0, 2.0, 1.0, 1.0, 100.0, 50.0);
|
||||
let mut circle = pt(1.0, 1.0);
|
||||
circle.extend(1.0f64.to_le_bytes());
|
||||
circle.extend(pt(0.0, 0.0));
|
||||
let push: Vec<u8> = m.iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(31, &[]), chunk(2, &circle)]), &tables(), Handle(1));
|
||||
assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(102.0, 52.0, 0.0) && c.radius == 2.0));
|
||||
assert!(matches!(&es[1].kind, EntityKind::Circle(c) if c.center == Vec3::new(1.0, 1.0, 0.0) && c.radius == 1.0));
|
||||
}
|
||||
|
||||
/// A finite matrix can still move a point past the largest float: a circle or a text that
|
||||
/// would land there is left out, as a polyline is, so no infinity reaches the extents.
|
||||
#[test]
|
||||
fn what_a_matrix_moves_out_of_range_is_left_out() {
|
||||
let mut m = [0.0f64; 16];
|
||||
(m[0], m[5], m[10], m[15], m[3]) = (1.0, 1.0, 1.0, 1.0, 1.7e308);
|
||||
let push: Vec<u8> = m.iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
let mut circle = pt(1e308, 0.0);
|
||||
circle.extend(1.0f64.to_le_bytes());
|
||||
circle.extend(pt(0.0, 0.0));
|
||||
let mut text = pt(1e308, 0.0);
|
||||
text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
text.extend(pt(1.0, 0.0));
|
||||
text.extend(b"far\0");
|
||||
text.extend(0i32.to_le_bytes());
|
||||
text.extend(1i32.to_le_bytes());
|
||||
for v in [2.5f64, 1.0, 0.0, 0.0] {
|
||||
text.extend(v.to_le_bytes());
|
||||
}
|
||||
text.extend([0u8; 20]);
|
||||
text.extend(b"txt\0");
|
||||
let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(11, &text)]), &tables(), Handle(1));
|
||||
assert!(es.is_empty(), "{es:?}");
|
||||
// The same text without the matrix is drawn: the chunk itself is sound.
|
||||
assert_eq!(proxy_entities(&graphics(&[chunk(11, &text)]), &tables(), Handle(1)).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bytes_come_from_the_310_groups_after_the_size() {
|
||||
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
|
||||
let u = Unknown {
|
||||
dxf_type: "ACAD_PROXY_ENTITY".into(),
|
||||
tags: vec![tag(90, "498"), tag(92, "5"), tag(310, "0102"), tag(310, "030405FF"), tag(93, "0")],
|
||||
graphics: Vec::new(),
|
||||
};
|
||||
assert_eq!(u.proxy_graphics_bytes(), [1, 2, 3, 4, 5]);
|
||||
let other = Unknown { dxf_type: "ACAD_PROXY_OBJECT".into(), ..u.clone() };
|
||||
assert!(other.proxy_graphics_bytes().is_empty());
|
||||
let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u };
|
||||
assert!(bad.proxy_graphics_bytes().is_empty());
|
||||
}
|
||||
|
||||
/// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and
|
||||
/// never panic.
|
||||
#[test]
|
||||
fn hostile_graphics_do_not_panic() {
|
||||
let mut huge = u32::MAX.to_le_bytes().to_vec();
|
||||
huge.extend(pt(1.0, 1.0));
|
||||
let mut nan = pt(f64::NAN, 0.0);
|
||||
nan.extend(1.0f64.to_le_bytes());
|
||||
let cases: Vec<Vec<u8>> = vec![
|
||||
Vec::new(),
|
||||
vec![0; 7],
|
||||
graphics(&[chunk(6, &huge)]),
|
||||
graphics(&[chunk(2, &nan)]),
|
||||
graphics(&[chunk(11, &[0xFF; 30])]),
|
||||
graphics(&[chunk(38, &[0x41; 77])]),
|
||||
graphics(&[chunk(29, &[1; 40])]),
|
||||
graphics(&[chunk(31, &[]), chunk(31, &[])]),
|
||||
[graphics(&[chunk(2, &pt(0.0, 0.0))]), vec![0xFF; 9]].concat(),
|
||||
{
|
||||
let mut g = graphics(&[]);
|
||||
g.extend(4u32.to_le_bytes());
|
||||
g.extend(2u32.to_le_bytes());
|
||||
g
|
||||
},
|
||||
{
|
||||
let mut g = graphics(&[]);
|
||||
g.extend(1_000u32.to_le_bytes());
|
||||
g.extend(2u32.to_le_bytes());
|
||||
g
|
||||
},
|
||||
];
|
||||
for g in cases {
|
||||
let _ = proxy_entities(&g, &tables(), Handle(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -371,28 +371,6 @@ fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blo
|
||||
bounds_in(d, e, depth, blocks, off_counts)
|
||||
}
|
||||
|
||||
/// The bounds of a record kept as read that draws something: a proxy as its proxy graphics draw
|
||||
/// (layer 0 in them is the proxy's layer), each at the next depth as a block's contents are, and an
|
||||
/// OLE2FRAME as its frame.
|
||||
fn unknown_bounds<'a>(
|
||||
d: &'a Drawing,
|
||||
u: &crate::Unknown,
|
||||
depth: usize,
|
||||
blocks: &mut HashMap<(&'a str, usize), Bounds2>,
|
||||
off_counts: bool,
|
||||
) -> Bounds2 {
|
||||
if u.graphics.is_empty() {
|
||||
return ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points);
|
||||
}
|
||||
if depth >= MAX_BLOCK_DEPTH {
|
||||
return Bounds2::EMPTY;
|
||||
}
|
||||
u.graphics
|
||||
.iter()
|
||||
.filter(|g| in_block_visible(d, g, off_counts))
|
||||
.fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, off_counts)))
|
||||
}
|
||||
|
||||
/// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed,
|
||||
/// by block name and depth: every further reference to a block at that depth reuses them instead of
|
||||
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
|
||||
@@ -538,9 +516,8 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
|
||||
Bounds2::from_points([o, o + u, o + v, o + u + v])
|
||||
}
|
||||
EntityKind::LwPolyline(p) => lwpolyline_bounds(p),
|
||||
// A proxy measures as its proxy graphics draw. An OLE object's content is not drawn, but its
|
||||
// frame is, so the frame counts (#2422).
|
||||
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, off_counts),
|
||||
// An OLE object's content is not drawn, but its frame is, so the frame counts (#2422).
|
||||
EntityKind::Unknown(u) if u.is_ole_frame() => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points),
|
||||
kind => {
|
||||
let mut b = Bounds2::EMPTY;
|
||||
for p in kind.prims() {
|
||||
@@ -741,15 +718,12 @@ mod tests {
|
||||
#[test]
|
||||
fn ole_frame_counts_in_extents() {
|
||||
let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() };
|
||||
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
|
||||
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags });
|
||||
let b = bounds(frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")]));
|
||||
assert_eq!((b.min, b.max), (Vec2::new(30.0, -22.0), Vec2::new(35.0, -19.0)));
|
||||
assert!(bounds(frame(vec![tag(10, "1"), tag(20, "2")])).is_empty(), "one corner is not a frame");
|
||||
assert!(bounds(frame(vec![tag(10, "NaN"), tag(20, "0"), tag(11, "1"), tag(21, "inf")])).is_empty());
|
||||
assert!(
|
||||
bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")], graphics: Vec::new() }))
|
||||
.is_empty()
|
||||
);
|
||||
assert!(bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")] })).is_empty());
|
||||
}
|
||||
|
||||
/// Groups 10/20 inside an application-defined `102 {...}` group belong to the application, not
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -57,10 +57,6 @@ impl EntityStore {
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Arc<Entity>> + '_ {
|
||||
self.chunks.iter().flat_map(|c| c.items.iter())
|
||||
}
|
||||
/// Iterate from the top of the draw order down.
|
||||
pub fn iter_rev(&self) -> impl Iterator<Item = &Arc<Entity>> + '_ {
|
||||
self.chunks.iter().rev().flat_map(|c| c.items.iter().rev())
|
||||
}
|
||||
pub fn handles(&self) -> Vec<Handle> {
|
||||
self.iter().map(|e| e.handle).collect()
|
||||
}
|
||||
@@ -350,7 +346,6 @@ mod tests {
|
||||
}
|
||||
assert!(s.move_next_to(Handle(1), Handle(3), true));
|
||||
assert_eq!(order(&s), [2, 3, 1, 4, 5]);
|
||||
assert_eq!(s.iter_rev().map(|e| e.handle.0).collect::<Vec<_>>(), [5, 4, 1, 3, 2], "top down");
|
||||
assert!(s.move_next_to(Handle(5), Handle(2), false));
|
||||
assert_eq!(order(&s), [5, 2, 3, 1, 4]);
|
||||
assert!(!s.move_next_to(Handle(5), Handle(5), true));
|
||||
|
||||
@@ -14,7 +14,7 @@ mod draw;
|
||||
mod draw2;
|
||||
mod draworder;
|
||||
mod edit;
|
||||
mod exchange;
|
||||
pub mod exchange;
|
||||
pub mod file;
|
||||
mod gripcmds;
|
||||
mod griphot;
|
||||
|
||||
@@ -60,9 +60,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
attedit::dash_attedit_spec(),
|
||||
wblock::wblock_spec(),
|
||||
wblock::dash_wblock_spec(),
|
||||
CommandSpec::new("wblockpick", "Write Block Pick", run_wblockpick)
|
||||
.params("{mode: \"objects\"|\"base\"}")
|
||||
.interactive(|_| Ok(Box::new(WblockPickM::default()))),
|
||||
CommandSpec::new("base", "Base", run_base).menu(&["Draw", "Block", "Base"]).params("{at: [x,y]}"),
|
||||
CommandSpec::new("blocks.dynamic", "Dynamic Block Data", run_dynamic)
|
||||
.params("{name (a block, or \"*Model_Space\" for a drawing that is a dynamic block's own)} → {parameters, actions, other} | null (not a dynamic block)")
|
||||
@@ -716,88 +713,6 @@ impl BlockM {
|
||||
}
|
||||
}
|
||||
|
||||
// ── WBLOCKPICK ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// The result kept for the Write Block dialog after a WBLOCKPICK session ends.
|
||||
pub struct WblockPicks {
|
||||
/// Selected handles (mode "objects") — empty for a "base" pick.
|
||||
pub handles: Vec<Handle>,
|
||||
/// Base point picked (mode "base") — `None` for an "objects" pick.
|
||||
pub base: Option<Vec2>,
|
||||
}
|
||||
|
||||
fn run_wblockpick(_s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Which pick session WBLOCKPICK is running.
|
||||
#[derive(Default)]
|
||||
enum WblockPickMode {
|
||||
/// Waiting for the mode keyword ("objects" or "base").
|
||||
#[default]
|
||||
Waiting,
|
||||
Objects(SelectPhase),
|
||||
Base,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct WblockPickM {
|
||||
mode: WblockPickMode,
|
||||
}
|
||||
|
||||
impl Interactive for WblockPickM {
|
||||
fn name(&self) -> &'static str {
|
||||
"WBLOCKPICK"
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
match &self.mode {
|
||||
WblockPickMode::Waiting => Prompt::new("Enter pick mode", Accept::TEXT).kw(&["Objects", "Base"]),
|
||||
WblockPickMode::Objects(sel) => sel.prompt(),
|
||||
WblockPickMode::Base => Prompt::new("Specify insertion base point", Accept::POINT),
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
match &mut self.mode {
|
||||
WblockPickMode::Waiting => {
|
||||
match &i {
|
||||
Input::Keyword(k) | Input::Text(k) => {
|
||||
let k = k.to_ascii_lowercase();
|
||||
if k.starts_with('o') {
|
||||
self.mode = WblockPickMode::Objects(SelectPhase::default());
|
||||
} else {
|
||||
self.mode = WblockPickMode::Base;
|
||||
}
|
||||
}
|
||||
Input::Cancel | Input::Enter => return Ok(Step::Cancel),
|
||||
_ => {}
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
WblockPickMode::Objects(sel) => {
|
||||
if matches!(i, Input::Cancel) {
|
||||
return Ok(Step::Cancel);
|
||||
}
|
||||
match sel.feed(s, &i)? {
|
||||
SelOutcome::More => Ok(Step::Continue),
|
||||
SelOutcome::Empty => Ok(Step::Cancel),
|
||||
SelOutcome::Done(hs) => {
|
||||
s.wblock_picks = Some(WblockPicks { handles: hs, base: None });
|
||||
Ok(Step::Done)
|
||||
}
|
||||
}
|
||||
}
|
||||
WblockPickMode::Base => match i {
|
||||
Input::Cancel => Ok(Step::Cancel),
|
||||
Input::Point(p) => {
|
||||
s.wblock_picks = Some(WblockPicks { handles: Vec::new(), base: Some(p) });
|
||||
Ok(Step::Done)
|
||||
}
|
||||
_ => Ok(Step::Continue),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod insert_file;
|
||||
pub(crate) mod library;
|
||||
pub(crate) mod xref;
|
||||
|
||||
@@ -16,9 +16,7 @@ use super::insert_file::stem;
|
||||
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
|
||||
|
||||
pub(super) fn wblock_spec() -> CommandSpec {
|
||||
CommandSpec::new("wblock", "Write Block", run_wblock)
|
||||
.alias(&["w"])
|
||||
.params("{path, name? (a block, or \"*\" for the whole drawing) | handles?, base?}")
|
||||
CommandSpec::new("wblock", "Write Block", run_wblock).alias(&["w"]).params("{path, name? | handles?, base?}")
|
||||
}
|
||||
|
||||
/// -WBLOCK erases the objects it writes, whatever its mOde option says: AutoCAD 2024 does, and
|
||||
@@ -47,7 +45,6 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
Some("*") => write(s, "wblock", &path, Source::Whole)?,
|
||||
Some(name) => write(s, "wblock", &path, Source::Block(name, base))?,
|
||||
None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?,
|
||||
};
|
||||
|
||||
@@ -39,10 +39,6 @@ fn vertex_value(v: &Value) -> Option<PolyVertex> {
|
||||
Some(PolyVertex { p, bulge: f64_or(v, "bulge", 0.0), start_width: f64_or(v, "startWidth", 0.0), end_width: f64_or(v, "endWidth", 0.0) })
|
||||
}
|
||||
|
||||
fn current_elevation(s: &Session) -> Result<f64> {
|
||||
Ok(s.doc()?.header.f64("ELEVATION", 0.0))
|
||||
}
|
||||
|
||||
pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let raw = p.get("vertices").or_else(|| p.get("points")).and_then(Value::as_array);
|
||||
for v in raw.into_iter().flatten() {
|
||||
@@ -57,7 +53,6 @@ pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut k = lwpoly(vs, bool_or(p, "closed", false));
|
||||
if let EntityKind::LwPolyline(pl) = &mut k {
|
||||
pl.const_width = width;
|
||||
pl.elevation = current_elevation(s)?;
|
||||
}
|
||||
added(s.add_entity(k)?)
|
||||
}
|
||||
@@ -179,7 +174,6 @@ impl Interactive for LineM {
|
||||
#[derive(Default)]
|
||||
pub(super) struct PlineM {
|
||||
verts: Vec<PolyVertex>,
|
||||
elevation: f64,
|
||||
arc_mode: bool,
|
||||
/// Total width at the start and end of the next segment (Width / Halfwidth answers).
|
||||
start_w: f64,
|
||||
@@ -197,7 +191,6 @@ impl PlineM {
|
||||
fn entity(&self, closed: bool) -> EntityKind {
|
||||
let mut k = lwpoly(self.verts.clone(), closed);
|
||||
if let EntityKind::LwPolyline(pl) = &mut k {
|
||||
pl.elevation = self.elevation;
|
||||
// Every segment the same uniform width: store it as the constant width, as before.
|
||||
let segs = if closed { pl.vertices.len() } else { pl.vertices.len().saturating_sub(1) };
|
||||
let w = pl.vertices.first().map_or(0.0, |v| v.start_width);
|
||||
@@ -266,10 +259,6 @@ impl Interactive for PlineM {
|
||||
fn name(&self) -> &'static str {
|
||||
"PLINE"
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
self.elevation = current_elevation(s)?;
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, s: &Session) -> Prompt {
|
||||
if self.asking_width > 0 {
|
||||
let unit = if self.half { "half-width" } else { "width" };
|
||||
|
||||
@@ -232,7 +232,7 @@ impl Interactive for MTextM {
|
||||
None => Prompt::new("Specify first corner", Accept::POINT),
|
||||
Some(a) if !self.boxed() => Prompt::new("Specify opposite corner", Accept::POINT)
|
||||
.kw(&["Height", "Justify", "Line spacing", "Rotation", "Style", "Width", "Columns"])
|
||||
.corner(a),
|
||||
.base(a),
|
||||
_ if self.lines.is_empty() => Prompt::new("Enter text (use \\P for new paragraphs)", Accept::TEXT),
|
||||
_ => Prompt::new("Enter next line of text (empty line to finish)", Accept::TEXT),
|
||||
}
|
||||
|
||||
@@ -593,9 +593,7 @@ fn run_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else if let Some(f) = points_param(p, "fence") {
|
||||
crate::select::select_fence_in(s.doc()?, &space, s.viewport_frozen(), &f)
|
||||
} else if ["handles", "handle"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
// Handles named outright, less the proxies: no selection takes one in.
|
||||
let d = s.doc()?;
|
||||
targets(s, p)?.into_iter().filter(|h| !d.entity(*h).is_some_and(|e| crate::select::kept_as_read(&e.kind))).collect()
|
||||
targets(s, p)?
|
||||
} else {
|
||||
// Nothing to select with: the selection stays, also what the active viewport does not draw.
|
||||
s.stored_selection()
|
||||
|
||||
@@ -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()))
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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 => {}
|
||||
|
||||
@@ -219,18 +219,14 @@ fn type_matches(e: &Entity, ty: Option<&str>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The candidate objects: the whole edit space (without proxies, which no selection takes in), or
|
||||
/// the current selection.
|
||||
/// The candidate objects: the whole edit space, or the current selection.
|
||||
fn candidates(s: &Session, p: &Value) -> Result<Vec<Handle>> {
|
||||
let apply = str_param(p, "applyTo").unwrap_or("drawing").to_ascii_lowercase();
|
||||
if apply.starts_with("sel") || apply == "current" {
|
||||
return Ok(s.selection());
|
||||
}
|
||||
let space = s.space();
|
||||
Ok(s.doc()?
|
||||
.space(&space)
|
||||
.map(|st| st.iter().take(MAX_SCAN).filter(|e| !crate::select::kept_as_read(&e.kind)).map(|e| e.handle).collect())
|
||||
.unwrap_or_default())
|
||||
Ok(s.doc()?.space(&space).map(|st| st.iter().take(MAX_SCAN).map(|e| e.handle).collect()).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn run_qselect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -41,6 +41,7 @@ pub const FILES: &[&str] = &[
|
||||
"options",
|
||||
"pagesetup",
|
||||
"pdfbook",
|
||||
"pdfimport",
|
||||
"plot",
|
||||
"plotstyle",
|
||||
"plottermanager",
|
||||
@@ -237,7 +238,6 @@ pub const NO_FILES: &[&str] = &[
|
||||
"hatchedit",
|
||||
"hatchgenerateboundary",
|
||||
"hatchpick",
|
||||
"wblockpick",
|
||||
"overkill",
|
||||
"block",
|
||||
"-block",
|
||||
|
||||
@@ -52,7 +52,6 @@ pub use cadcraft_doc as doc;
|
||||
pub use cadcraft_fonts as fonts;
|
||||
pub use cadcraft_geom as geom;
|
||||
pub use cadcraft_render as render;
|
||||
pub use cmd::blocks::WblockPicks;
|
||||
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
|
||||
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
|
||||
pub use prompt::{Accept, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
|
||||
@@ -159,8 +158,6 @@ pub struct Session {
|
||||
lisp_last: Option<std::result::Result<lisp::value::Value, String>>,
|
||||
/// What the last HATCHPICK kept (the Hatch and Gradient dialog's picks).
|
||||
pub hatch_picks: Option<cmd::hatch::HatchPicks>,
|
||||
/// What the last WBLOCKPICK kept (the Write Block dialog's picks).
|
||||
pub wblock_picks: Option<cmd::blocks::WblockPicks>,
|
||||
/// The window's menu bar and tool bar as the UI shows them (it reports them every frame).
|
||||
pub bars_shown: cmd::interface::InterfaceBars,
|
||||
/// The bars MENUBAR or TOOLBAR asked to change, for the UI to apply.
|
||||
@@ -224,7 +221,6 @@ impl Session {
|
||||
lisp: lisp::LispState::default(),
|
||||
lisp_last: None,
|
||||
hatch_picks: None,
|
||||
wblock_picks: None,
|
||||
bars_shown: Default::default(),
|
||||
bars_request: Default::default(),
|
||||
pick_hint: None,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
+10
-18
@@ -161,25 +161,19 @@ pub(crate) fn on_frozen_layer(frozen: &[String], e: &Entity) -> bool {
|
||||
/// The last object of `store`, in draw order, that is not on one of the layers in `frozen`, the
|
||||
/// layers frozen in the layout viewport the selection is made through: what the Last option
|
||||
/// takes there. With no such layers it is the last object, whether the drawing shows it or not.
|
||||
/// A proxy is passed over: no selection takes one in ([`kept_as_read`]).
|
||||
pub(crate) fn last_in(store: &cadcraft_doc::EntityStore, frozen: &[String]) -> Option<Handle> {
|
||||
store.iter_rev().find(|e| !kept_as_read(&e.kind) && !on_frozen_layer(frozen, e)).map(|e| e.handle)
|
||||
if frozen.is_empty() {
|
||||
return store.last().map(|e| e.handle);
|
||||
}
|
||||
store.iter().filter(|e| !on_frozen_layer(frozen, e)).last().map(|e| e.handle)
|
||||
}
|
||||
|
||||
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]), it is not
|
||||
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]) and it is not
|
||||
/// on one of the layers in `frozen`, the layers frozen in the layout viewport the selection is
|
||||
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else), and commands can
|
||||
/// edit it. A viewport shows model space, so `frozen` goes with a selection in model space only.
|
||||
/// A proxy (or another record CADCraft keeps as it was read) is drawn and snapped to, but never
|
||||
/// selected: commands can't edit it, and saving writes its record as it was read.
|
||||
/// made through ([`crate::DocState::viewport_frozen`]; empty anywhere else). A viewport shows
|
||||
/// model space, so `frozen` goes with a selection in model space only.
|
||||
pub(crate) fn selectable(d: &Drawing, e: &Entity, frozen: &[String]) -> bool {
|
||||
d.is_visible(e) && !on_frozen_layer(frozen, e) && !kept_as_read(&e.kind)
|
||||
}
|
||||
|
||||
/// Whether `k` is a record CADCraft keeps as it was read and commands can't edit: every
|
||||
/// [`EntityKind::Unknown`] but an OLE2FRAME, which moves and scales with its frame.
|
||||
pub(crate) fn kept_as_read(k: &EntityKind) -> bool {
|
||||
matches!(k, EntityKind::Unknown(u) if !u.is_ole_frame())
|
||||
d.is_visible(e) && !on_frozen_layer(frozen, e)
|
||||
}
|
||||
|
||||
/// Entities to test, in the order to test them, each with its bounds when already known.
|
||||
@@ -605,8 +599,7 @@ mod tests {
|
||||
#[test]
|
||||
fn clicking_an_ole_frame_edge_selects_it() {
|
||||
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
|
||||
let frame =
|
||||
|tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
|
||||
let frame = |tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags });
|
||||
let mut d = Drawing::new_metric();
|
||||
let h = d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "80"), tag(20, "80")])).unwrap();
|
||||
@@ -729,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 {
|
||||
@@ -795,7 +788,6 @@ mod hatch_pattern_pick_tests {
|
||||
let tri = HatchLoop {
|
||||
vertices: [(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(),
|
||||
outer: true,
|
||||
boundary_flags: None,
|
||||
sources: Vec::new(),
|
||||
};
|
||||
let d = solid_hatch(vec![tri], 0);
|
||||
|
||||
@@ -192,7 +192,6 @@ impl Session {
|
||||
}
|
||||
|
||||
fn script_lines(&mut self, text: &str) -> Result<()> {
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
|
||||
for line in text.lines() {
|
||||
// Trailing spaces are inputs (Enter); other trailing whitespace (`\r`) is not.
|
||||
let line = line.trim_end_matches(|c: char| c.is_whitespace() && c != ' ');
|
||||
|
||||
@@ -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();
|
||||
@@ -1561,50 +1552,6 @@ fn setvar_rejects_non_finite_text_for_real_variables() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_is_drawn_but_no_selection_takes_it_in() {
|
||||
// A proxy's graphics are drawn and measured, but saving writes its record unchanged: an edit
|
||||
// could not hold. So a window round a line and a proxy, ALL, SELECTALL and a pick on the
|
||||
// proxy's graphics leave the proxy out, and MOVE moves the line alone.
|
||||
use cadcraft_doc::{Common, Entity, Handle, Line, Space, Unknown, entity_bounds};
|
||||
use cadcraft_geom::Vec3;
|
||||
let mut s = Session::new();
|
||||
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
|
||||
let line = s.doc().unwrap().model.last().unwrap().handle;
|
||||
let drawn = Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(0.0, 5.0, 0.0), b: Vec3::new(10.0, 5.0, 0.0) }));
|
||||
let unknown = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![drawn] };
|
||||
let proxy = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Unknown(unknown)).unwrap();
|
||||
let bounds = |s: &Session| entity_bounds(s.doc().unwrap(), s.doc().unwrap().entity(proxy).unwrap(), 0);
|
||||
let before = bounds(&s);
|
||||
assert!(!before.is_empty(), "the proxy measures as its graphics");
|
||||
|
||||
s.idle_click(Vec2::new(5.0, 5.0), false).unwrap();
|
||||
assert_eq!(s.selection(), Vec::<Handle>::new(), "a pick on the proxy's graphics");
|
||||
s.idle_click(Vec2::new(-1.0, -1.0), false).unwrap();
|
||||
s.idle_click(Vec2::new(11.0, 6.0), false).unwrap();
|
||||
assert_eq!(s.selection(), vec![line], "a window round both");
|
||||
s.execute("selectall", &json!({})).unwrap();
|
||||
assert_eq!(s.selection(), vec![line], "SELECTALL");
|
||||
|
||||
s.execute("move", &json!({"delta": [0, 20]})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(matches!(&d.entity(line).unwrap().kind, EntityKind::Line(l) if l.a.y == 20.0), "the line moved");
|
||||
assert_eq!(bounds(&s), before, "the proxy stayed where its record puts it");
|
||||
|
||||
// Handles named outright leave the proxy out too.
|
||||
s.execute("select", &json!({"handles": [proxy.hex(), line.hex()]})).unwrap();
|
||||
assert_eq!(s.selection(), vec![line], "SELECT by handles");
|
||||
|
||||
// Last passes over the proxy drawn last: it takes the line.
|
||||
s.set_selection(Vec::new());
|
||||
s.start("erase").unwrap();
|
||||
s.input(Input::Text("L".into())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert!(d.entity(line).is_none(), "Last took the line");
|
||||
assert!(d.entity(proxy).is_some(), "the proxy is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_tools_keeps_compatible_command_ids() {
|
||||
assert_eq!(crate::cmd::resolve_alias("-blockreplace"), "blockreplace");
|
||||
|
||||
@@ -144,26 +144,6 @@ fn moving_or_copying_the_hatch_alone_ends_the_link() {
|
||||
assert!(!hatch(&s, &h).associative);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_boundary_flags_survive_refill_and_copy() {
|
||||
let mut session = Session::new();
|
||||
let boundary = handle(&session.execute("rectang", &json!({ "p1": [0, 0], "p2": [4, 2] })).unwrap());
|
||||
let hatch_handle = handle(&session.execute("hatch", &json!({ "handles": [boundary.clone()] })).unwrap());
|
||||
session.doc_mut().unwrap().model.modify(Handle::parse_hex(&hatch_handle).unwrap(), |entity| {
|
||||
if let EntityKind::Hatch(hatch) = &mut entity.kind {
|
||||
hatch.loops[0].boundary_flags = Some(7);
|
||||
}
|
||||
});
|
||||
let expected = hatch(&session, &hatch_handle).loops[0].boundary_flags;
|
||||
session.execute("move", &json!({ "handles": [boundary], "delta": [10, 0] })).unwrap();
|
||||
assert_eq!(hatch(&session, &hatch_handle).loops[0].boundary_flags, expected);
|
||||
let count = session.doc().unwrap().model.len();
|
||||
session.execute("copy", &json!({ "handles": [hatch_handle], "delta": [30, 0] })).unwrap();
|
||||
let copy = session.doc().unwrap().model.iter().skip(count).find(|entity| matches!(entity.kind, EntityKind::Hatch(_))).unwrap();
|
||||
let EntityKind::Hatch(copied) = ©.kind else { panic!("not a hatch") };
|
||||
assert_eq!(copied.loops[0].boundary_flags, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_associative_hatch_keeps_no_sources() {
|
||||
let mut s = Session::new();
|
||||
@@ -186,10 +166,7 @@ fn hostile_sources_never_panic() {
|
||||
let k = EntityKind::Hatch(Hatch {
|
||||
pattern: "ANSI31".into(),
|
||||
solid: false,
|
||||
loops: vec![
|
||||
HatchLoop { vertices: sq, outer: true, boundary_flags: None, sources: sources.clone() },
|
||||
HatchLoop { vertices: nan, outer: false, boundary_flags: None, sources },
|
||||
],
|
||||
loops: vec![HatchLoop { vertices: sq, outer: true, sources: sources.clone() }, HatchLoop { vertices: nan, outer: false, sources }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: true,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -9,11 +9,8 @@ use serde_json::json;
|
||||
fn session() -> (Session, String) {
|
||||
let tag = |code: i32, v: &str| RawTag { code, value: v.into() };
|
||||
let mut d = Drawing::new_imperial();
|
||||
let kind = EntityKind::Unknown(Unknown {
|
||||
dxf_type: "OLE2FRAME".into(),
|
||||
tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")],
|
||||
graphics: Vec::new(),
|
||||
});
|
||||
let kind =
|
||||
EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] });
|
||||
let h = d.add(&Space::Model, Common::default(), kind).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "ole.dxf", None);
|
||||
@@ -78,8 +75,7 @@ fn data_session(chunks: &[usize], hex_override: Option<&str>) -> (Session, Strin
|
||||
tags.push(tag(310, &hex[at..]));
|
||||
}
|
||||
let mut d = Drawing::new_imperial();
|
||||
let h =
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() })).unwrap();
|
||||
let h = d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags })).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "ole.dxf", None);
|
||||
(s, h.hex())
|
||||
@@ -164,11 +160,8 @@ fn a_locked_ole_frame_does_not_block_an_in_place_rotation() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.ensure_layer("L");
|
||||
let common = Common { layer: "L".into(), ..Common::default() };
|
||||
let kind = EntityKind::Unknown(Unknown {
|
||||
dxf_type: "OLE2FRAME".into(),
|
||||
tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")],
|
||||
graphics: Vec::new(),
|
||||
});
|
||||
let kind =
|
||||
EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] });
|
||||
let ole = d.add(&Space::Model, common, kind).unwrap();
|
||||
if let Some(l) = d.layer_mut("L") {
|
||||
l.locked = true;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -8,7 +8,7 @@ use cadcraft_engine::doc::{Block, Common, Drawing, EntityKind, RawTag, Space, Un
|
||||
use serde_json::json;
|
||||
|
||||
fn unknown(kind: &str) -> EntityKind {
|
||||
EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }], graphics: Vec::new() })
|
||||
EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }] })
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -129,7 +129,6 @@ fn proxy_entities_are_reported_only_before_2013() {
|
||||
RawTag { code: 90, value: "498".into() },
|
||||
RawTag { code: 91, value: class.to_string() },
|
||||
],
|
||||
graphics: Vec::new(),
|
||||
})
|
||||
};
|
||||
let mut d = Drawing::new_imperial();
|
||||
@@ -191,7 +190,6 @@ fn saving_sat_text_solids_as_dxf_2013_reports_them() {
|
||||
RawTag { code: 1, value: "400 1 1 0".into() },
|
||||
RawTag { code: 3, value: "End-of-ACIS-data".into() },
|
||||
],
|
||||
graphics: Vec::new(),
|
||||
});
|
||||
d.add(&Space::Model, Common::default(), sat).unwrap();
|
||||
let mut s = Session::empty();
|
||||
@@ -221,7 +219,7 @@ fn a_dxf_2013_loss_is_known_before_saving() {
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
let sat = |d: &mut Drawing| {
|
||||
let tags = vec![RawTag { code: 8, value: "0".into() }, RawTag { code: 1, value: "400 1 1 0".into() }];
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags, graphics: Vec::new() })).unwrap();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags })).unwrap();
|
||||
};
|
||||
let mut modern = Drawing::new_imperial();
|
||||
modern.header.set_str("ACADVER", "AC1032");
|
||||
@@ -257,7 +255,6 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
|
||||
RawTag { code: 1, value: "400 1 1 0".into() },
|
||||
RawTag { code: 3, value: "End-of-ACIS-data".into() },
|
||||
],
|
||||
graphics: Vec::new(),
|
||||
});
|
||||
d.add(&Space::Model, Common::default(), sat).unwrap();
|
||||
d.blocks.insert("Door".into(), std::sync::Arc::new(Block::new("Door")));
|
||||
@@ -279,7 +276,7 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
|
||||
fn a_dwg_keeps_sat_text_solids_only_before_2013() {
|
||||
use cadcraft_engine::cmd::file::{Version, not_saved_as};
|
||||
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
|
||||
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() });
|
||||
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags });
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "700 0 1 0")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap();
|
||||
@@ -355,7 +352,6 @@ fn proxy_entity(strings: &str) -> EntityKind {
|
||||
EntityKind::Unknown(Unknown {
|
||||
dxf_type: "ACAD_PROXY_ENTITY".into(),
|
||||
tags: tags.iter().map(|(code, value)| RawTag { code: *code, value: (*value).into() }).collect(),
|
||||
graphics: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
//! WBLOCKPICK: the Write Block dialog's canvas picks (objects, base point) and their cancel.
|
||||
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
fn session_with_line() -> (Session, cadcraft_engine::doc::Handle) {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap();
|
||||
let h = cadcraft_engine::doc::Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap();
|
||||
s.set_selection(Vec::new());
|
||||
(s, h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_keeps_the_selection() {
|
||||
let (mut s, h) = session_with_line();
|
||||
s.start("wblockpick").unwrap();
|
||||
s.input(Input::Keyword("Objects".into())).unwrap();
|
||||
s.input(Input::Pick(vec![h])).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.running.is_none());
|
||||
let p = s.wblock_picks.take().unwrap();
|
||||
assert_eq!((p.handles, p.base), (vec![h], None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_keeps_the_point() {
|
||||
let (mut s, _) = session_with_line();
|
||||
s.start("wblockpick").unwrap();
|
||||
s.input(Input::Keyword("Base".into())).unwrap();
|
||||
s.input(Input::Point(Vec2::new(3.0, 4.0))).unwrap();
|
||||
assert!(s.running.is_none());
|
||||
let p = s.wblock_picks.take().unwrap();
|
||||
assert_eq!((p.handles.len(), p.base), (0, Some(Vec2::new(3.0, 4.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_keeps_nothing() {
|
||||
let (mut s, h) = session_with_line();
|
||||
s.start("wblockpick").unwrap();
|
||||
s.input(Input::Keyword("Objects".into())).unwrap();
|
||||
s.input(Input::Pick(vec![h])).unwrap();
|
||||
s.input(Input::Cancel).unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert!(s.wblock_picks.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preexisting_selection_still_prompts() {
|
||||
// Even if there is a pickfirst selection, WBLOCKPICK Objects must keep prompting
|
||||
// so the dialog drives picking explicitly — it never bypasses the "Select objects" step.
|
||||
let (mut s, h) = session_with_line();
|
||||
s.set_selection(vec![h]);
|
||||
s.start("wblockpick").unwrap();
|
||||
s.input(Input::Keyword("Objects".into())).unwrap();
|
||||
// Must still be running — "Select objects" prompt expected.
|
||||
assert!(s.running.is_some());
|
||||
assert!(s.wblock_picks.is_none());
|
||||
}
|
||||
+21
-40
@@ -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 ' '..='~' {
|
||||
|
||||
@@ -102,9 +102,6 @@ pub struct MTextLayout {
|
||||
/// Geometry by colour run (strokes plus fillable glyph outlines).
|
||||
pub pieces: Vec<MTextPiece>,
|
||||
pub bounds: Bounds2,
|
||||
/// The box of each column, in the order the text flows through them, measured like `bounds`
|
||||
/// but without the gutters and to each column's own height. One column: `bounds`.
|
||||
pub column_bounds: Vec<Bounds2>,
|
||||
/// Plain text of each laid-out line.
|
||||
pub lines: Vec<String>,
|
||||
/// Whether the geometry stops short: the layout reached its allowance of retained points
|
||||
@@ -734,7 +731,6 @@ pub fn layout_mtext_with(contents: &str, p: &MTextParams) -> MTextLayout {
|
||||
out.bounds = Bounds2::from_points(
|
||||
[Vec2::new(x0, top), Vec2::new(x0 + block_w, top), Vec2::new(x0 + block_w, top - block_h), Vec2::new(x0, top - block_h)].map(xf),
|
||||
);
|
||||
out.column_bounds = vec![out.bounds];
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -700,14 +700,6 @@ pub(super) fn layout(contents: &str, params: &MTextParams, base: &Fmt) -> MTextL
|
||||
[Vec2::new(box_x0, top), Vec2::new(box_x0 + total_w, top), Vec2::new(box_x0 + total_w, top - block_h), Vec2::new(box_x0, top - block_h)]
|
||||
.map(xf),
|
||||
);
|
||||
out.column_bounds = (0..n_cols)
|
||||
.map(|column| {
|
||||
let h = col_bottom.get(column).copied().unwrap_or(0.0).max(col_height(column));
|
||||
let slot = if reversed { n_cols.saturating_sub(1).saturating_sub(column) } else { column };
|
||||
let x0 = box_x0 + slot as f64 * (col_w + gutter);
|
||||
Bounds2::from_points([Vec2::new(x0, top), Vec2::new(x0 + col_w, top), Vec2::new(x0 + col_w, top - h), Vec2::new(x0, top - h)].map(xf))
|
||||
})
|
||||
.collect();
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -109,66 +109,6 @@ fn reversed_columns_run_right_to_left() {
|
||||
assert!(first > 0 && second > 0 && min_x(&l) >= 0.0);
|
||||
}
|
||||
|
||||
/// The geometry points inside `b`.
|
||||
fn points_in(l: &MTextLayout, b: &cadcraft_geom::Bounds2) -> usize {
|
||||
l.strokes.iter().flatten().filter(|p| b.contains(**p)).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_column_has_its_own_box_without_the_gutter() {
|
||||
let two = lay(&"word ".repeat(12), 10.0, Some(MTextColumnSpec { count: 2, gutter: 2.0, height: 6.0, ..Default::default() }));
|
||||
let [a, b] = two.column_bounds.as_slice() else { panic!("{:?}", two.column_bounds) };
|
||||
assert!(two.bounds.contains_box(a) && two.bounds.contains_box(b));
|
||||
assert!(a.max.x < b.min.x, "the gutter lies between the columns: {a:?} {b:?}");
|
||||
assert!(a.width() + b.width() < two.bounds.width());
|
||||
let total = two.strokes.iter().map(Vec::len).sum::<usize>();
|
||||
assert!(points_in(&two, a) > 0 && points_in(&two, b) > 0);
|
||||
assert_eq!(points_in(&two, a) + points_in(&two, b), total, "every point is in its column's box");
|
||||
|
||||
// Three static columns, the text filling two and a half: the half-full column keeps the
|
||||
// column height; text past the last column lengthens only that one.
|
||||
let spec = MTextColumnSpec { count: 3, gutter: 2.0, height: 6.0, ..Default::default() };
|
||||
let three = lay(&"word ".repeat(20), 10.0, Some(spec.clone()));
|
||||
assert_eq!(three.column_bounds.len(), 3);
|
||||
assert!(three.column_bounds.windows(2).all(|w| w[0].max.x < w[1].min.x && (w[0].height() - w[1].height()).abs() < 1e-9));
|
||||
let over = lay(&"word ".repeat(40), 10.0, Some(spec));
|
||||
let [first, .., last] = over.column_bounds.as_slice() else { panic!("{:?}", over.column_bounds) };
|
||||
assert!(last.height() > first.height() && (last.height() - over.bounds.height()).abs() < 1e-9);
|
||||
|
||||
// Manual heights: each column as tall as its own height.
|
||||
let manual = lay("one\\Ntwo", 5.0, Some(MTextColumnSpec { dynamic: true, heights: vec![3.0, 5.0], ..Default::default() }));
|
||||
let [a, b] = manual.column_bounds.as_slice() else { panic!("{:?}", manual.column_bounds) };
|
||||
assert!(a.height() < b.height());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_column_keeps_its_place() {
|
||||
let l = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 3, gutter: 1.0, height: 4.0, ..Default::default() }));
|
||||
let [a, b, c] = l.column_bounds.as_slice() else { panic!("{:?}", l.column_bounds) };
|
||||
assert!(a.max.x < b.min.x && b.max.x < c.min.x);
|
||||
assert!(points_in(&l, a) > 0 && points_in(&l, b) > 0 && points_in(&l, c) == 0);
|
||||
assert!((c.max.x - l.bounds.max.x).abs() < 1e-9 && (c.height() - a.height()).abs() < 1e-9);
|
||||
// Reversed: the column the text starts in is the rightmost.
|
||||
let r = lay("first\\Nsecond", 10.0, Some(MTextColumnSpec { count: 2, height: 1.0, reversed: true, ..Default::default() }));
|
||||
let [a, b] = r.column_bounds.as_slice() else { panic!("{:?}", r.column_bounds) };
|
||||
assert!(a.min.x > b.max.x - 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_column_is_the_whole_box() {
|
||||
let rotated = |p: MTextParams| MTextParams { rotation: 0.4, attach: 5, insert: Vec2::new(3.0, -2.0), ..p };
|
||||
for (s, width, columns) in [
|
||||
("plain text that wraps a few times", 6.0, None),
|
||||
("\\pxl1;paragraph text that wraps\\Pagain", 6.0, None),
|
||||
("no width\\Pat all", 0.0, None),
|
||||
(&*"word ".repeat(30), 10.0, Some(MTextColumnSpec { count: 1, gutter: 5.0, height: 3.0, ..Default::default() })),
|
||||
("one\\Ptwo", 10.0, Some(MTextColumnSpec { dynamic: true, gutter: 5.0, height: 30.0, ..Default::default() })),
|
||||
] {
|
||||
let l = layout_mtext_with(s, &rotated(MTextParams { width, columns, ..MTextParams::new(Vec2::ZERO, 1.0) }));
|
||||
assert_eq!(l.column_bounds, vec![l.bounds], "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_paragraph_codes_do_not_panic() {
|
||||
let huge_tabs = format!("\\pt{};a\tb", (0..100_000).map(|i| i.to_string()).collect::<Vec<_>>().join(","));
|
||||
|
||||
@@ -1,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"
|
||||
|
||||
@@ -62,9 +62,6 @@ struct Rx {
|
||||
block_arrays: HashMap<String, cadcraft_doc::ArrayParams>,
|
||||
/// LAYER record handle (upper case) → layer name (VIEWPORT group 331/341 frozen layers).
|
||||
layers: HashMap<String, String>,
|
||||
/// Layer, linetype and text style names in the order of the file's tables, which proxy
|
||||
/// graphics refer to by index (the drawing's own tables are ordered differently).
|
||||
proxy_tables: cadcraft_doc::ProxyTables,
|
||||
/// UCS record handle (upper case) → UCS name (a layout's named UCS, group 345).
|
||||
ucss: HashMap<String, String>,
|
||||
/// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport
|
||||
@@ -78,26 +75,6 @@ struct Rx {
|
||||
image_defs: HashMap<Handle, String>,
|
||||
}
|
||||
|
||||
/// Order `items` as the file's table lists them (`order`, names in any case), after the `pinned`
|
||||
/// names: records the file doesn't have keep their order after the file's own. A file without
|
||||
/// that table changes nothing.
|
||||
fn keep_file_order<T>(items: &mut [T], name: impl Fn(&T) -> &str, order: &[String], pinned: &[&str]) {
|
||||
if order.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut place: HashMap<String, usize> = HashMap::new();
|
||||
for (i, n) in order.iter().enumerate() {
|
||||
place.entry(n.to_ascii_lowercase()).or_insert(i);
|
||||
}
|
||||
items.sort_by_key(|it| {
|
||||
let n = name(it);
|
||||
match pinned.iter().position(|p| p.eq_ignore_ascii_case(n)) {
|
||||
Some(i) => (0, i),
|
||||
None => place.get(&n.to_ascii_lowercase()).map_or((2, 0), |&i| (1, i)),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Read a DXF file into a drawing.
|
||||
pub fn read(bytes: &[u8]) -> Result<Drawing> {
|
||||
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS)
|
||||
@@ -202,13 +179,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Proxy graphics name layers and linetypes by their place in the file's tables, and saving
|
||||
// writes them unchanged: the tables keep the file's order, with what CADCraft adds after it.
|
||||
keep_file_order(&mut d.layers, |l| &l.name, &rx.proxy_tables.layers, &[]);
|
||||
keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]);
|
||||
// A proxy text takes the first style on its font, so the styles keep the file's order too.
|
||||
let styles: Vec<String> = rx.proxy_tables.styles.iter().map(|(n, _)| n.clone()).collect();
|
||||
keep_file_order(&mut d.text_styles, |s| &s.name, &styles, &[]);
|
||||
// A file CADCraft wrote names its own next handle (#495): its table records and objects
|
||||
// are numbered above it and rebuilt on save, so following $HANDSEED would drift every save.
|
||||
let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim()));
|
||||
@@ -242,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)
|
||||
}
|
||||
|
||||
@@ -275,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.
|
||||
|
||||
@@ -329,7 +329,6 @@ pub(super) fn entity_with_table_budget(
|
||||
other => EntityKind::Unknown(Unknown {
|
||||
dxf_type: other.to_string(),
|
||||
tags: tags.iter().map(|tg| RawTag { code: tg.code, value: tg.str() }).collect(),
|
||||
graphics: Vec::new(),
|
||||
}),
|
||||
};
|
||||
Some((c, k))
|
||||
@@ -489,10 +488,6 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option<String> {
|
||||
/// needs the file's handle maps.
|
||||
pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityKind, rx: &mut Rx) {
|
||||
match (kind, k) {
|
||||
// Its proxy graphics, with the table indices resolved while the file's order is known.
|
||||
("ACAD_PROXY_ENTITY", EntityKind::Unknown(u)) => {
|
||||
u.graphics = cadcraft_doc::proxy_entities(&u.proxy_graphics_bytes(), &rx.proxy_tables, h);
|
||||
}
|
||||
("DIMENSION", EntityKind::Dimension(dm)) => {
|
||||
dm.overrides = crate::dxf_ext::read_dstyle(tags, &rx.styles, &rx.brs, &rx.ltypes);
|
||||
dm.assoc = crate::dxf_ext::read_assoc(tags);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -299,7 +299,6 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
|
||||
let (Some(handle), Some(name)) = (table.s(5), table.s(2)) else { continue };
|
||||
match kind.as_str() {
|
||||
"STYLE" => {
|
||||
rx.proxy_tables.styles.push((name.clone(), table.s(3).unwrap_or_default()));
|
||||
rx.styles.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
"BLOCK_RECORD" => {
|
||||
@@ -311,13 +310,9 @@ fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
|
||||
rx.brs.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
"LTYPE" => {
|
||||
if !name.eq_ignore_ascii_case("ByBlock") && !name.eq_ignore_ascii_case("ByLayer") {
|
||||
rx.proxy_tables.linetypes.push(name.clone());
|
||||
}
|
||||
rx.ltypes.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
"LAYER" => {
|
||||
rx.proxy_tables.layers.push(name.clone());
|
||||
rx.layers.insert(handle.trim().to_ascii_uppercase(), name);
|
||||
}
|
||||
"UCS" => {
|
||||
|
||||
@@ -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 => {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -39,11 +39,7 @@ fn drawing() -> Drawing {
|
||||
d.add(
|
||||
&Space::Model,
|
||||
Common::default(),
|
||||
EntityKind::Unknown(Unknown {
|
||||
dxf_type: "ACME_WIDGET".into(),
|
||||
tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")],
|
||||
graphics: Vec::new(),
|
||||
}),
|
||||
EntityKind::Unknown(Unknown { dxf_type: "ACME_WIDGET".into(), tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")] }),
|
||||
)
|
||||
.unwrap();
|
||||
d.add(&Space::Paper("Layout1".into()), Common::default(), line((1.0, 1.0), (2.0, 2.0))).unwrap();
|
||||
@@ -525,7 +521,7 @@ fn corpus_round_trip_report() {
|
||||
fn types_the_dwg_writer_cannot_write_are_reported_lost() {
|
||||
use corpus::{CorpusReport, FileReport, Format, round_trip};
|
||||
crate::dwg_worker::allow_in_process();
|
||||
let unknown = |t: &str, tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags, graphics: Vec::new() });
|
||||
let unknown = |t: &str, tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags });
|
||||
let mut d = Drawing::new_metric();
|
||||
let widget = vec![tag(100, "AcDbEntity"), tag(100, "AcmeWidget"), tag(10, "1.0"), tag(20, "2.0"), tag(30, "0.0")];
|
||||
d.add(&Space::Model, Common::default(), unknown("ACME_WIDGET", widget.clone())).unwrap();
|
||||
|
||||
+1
-510
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -370,7 +370,7 @@ fn top_line_kept_objects_and_unknown(handle: Handle) -> Drawing {
|
||||
RawTag { code: 100, value: "SyntheticWidget".into() },
|
||||
RawTag { code: 1, value: "widget".into() },
|
||||
];
|
||||
let kind = EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags, graphics: Vec::new() });
|
||||
let kind = EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags });
|
||||
d.model.push(Entity { handle, common: Common::default(), kind });
|
||||
d
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ fn sat_text_is_told_by_its_subclass_and_a_geometry_record() {
|
||||
use cadcraft_doc::foreign::{Foreign, sat_text_acis};
|
||||
use cadcraft_doc::{Handle, RawTag, Unknown};
|
||||
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
|
||||
let solid = |tags: Vec<RawTag>| Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() };
|
||||
let solid = |tags: Vec<RawTag>| Unknown { dxf_type: "3DSOLID".into(), tags };
|
||||
let none = std::collections::BTreeSet::new();
|
||||
let h = Handle(0x2B);
|
||||
// A stray 1 or 3 outside AcDbModelerGeometry is not SAT text.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -69,7 +69,6 @@ mod plot_model_png_scale;
|
||||
mod plot_styles;
|
||||
mod polyface_roundtrip;
|
||||
mod portable_fonts;
|
||||
mod proxy_graphics;
|
||||
mod region_roundtrip;
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
mod render_settings_version;
|
||||
@@ -92,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;
|
||||
|
||||
@@ -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,172 +0,0 @@
|
||||
//! ACAD_PROXY_ENTITY draws its proxy graphics (#2646): read from DXF with the table indices of the
|
||||
//! file, measured in the extents, and written back unchanged.
|
||||
|
||||
use cadcraft_doc::color::Color;
|
||||
use cadcraft_doc::{EntityKind, Space};
|
||||
use cadcraft_io::{read_dxf, write_dxf};
|
||||
|
||||
/// A proxy graphics chunk of type `kind`, its data padded to four bytes.
|
||||
fn chunk(kind: u32, data: &[u8]) -> Vec<u8> {
|
||||
let mut d = data.to_vec();
|
||||
d.resize(d.len().div_ceil(4) * 4, 0);
|
||||
let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec();
|
||||
out.extend(kind.to_le_bytes());
|
||||
out.extend(d);
|
||||
out
|
||||
}
|
||||
|
||||
/// A point in the XY plane as three doubles.
|
||||
fn pt(x: f64, y: f64) -> Vec<u8> {
|
||||
[x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
/// A balloon: layer 1 of the file's LAYER table, colour 1, a circle, a leader and the number.
|
||||
fn balloon() -> Vec<u8> {
|
||||
let mut circle = pt(175.0, 115.0);
|
||||
circle.extend(6.0f64.to_le_bytes());
|
||||
circle.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
let mut leader = 2u32.to_le_bytes().to_vec();
|
||||
leader.extend(pt(170.8, 110.8));
|
||||
leader.extend(pt(150.0, 90.0));
|
||||
let mut text = pt(172.9, 112.0);
|
||||
text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes()));
|
||||
text.extend(pt(1.0, 0.0));
|
||||
text.extend(b"1\0\0\0");
|
||||
text.extend(1i32.to_le_bytes());
|
||||
text.extend(0i32.to_le_bytes());
|
||||
for v in [6.0f64, 1.0, 0.0, 0.0] {
|
||||
text.extend(v.to_le_bytes());
|
||||
}
|
||||
text.extend([0u8; 20]);
|
||||
text.extend(b"isocp.shx\0\0\0\0\0\0\0");
|
||||
let chunks = [chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text)];
|
||||
let body = chunks.concat();
|
||||
let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec();
|
||||
out.extend((chunks.len() as u32).to_le_bytes());
|
||||
out.extend(body);
|
||||
out
|
||||
}
|
||||
|
||||
/// A DXF whose LAYER table holds 0 and BALLOONS only (CADCraft keeps Defpoints at index 1 of
|
||||
/// its own table), a text style on isocp.shx, a line and one proxy balloon.
|
||||
fn file() -> String {
|
||||
let graphics = balloon();
|
||||
let hex: Vec<String> = graphics.chunks(127).map(|c| c.iter().map(|b| format!("{b:02X}")).collect()).collect();
|
||||
let mut tags: Vec<(i32, String)> = vec![(0, "SECTION".into()), (2, "CLASSES".into())];
|
||||
for (c, v) in [(0, "CLASS"), (1, "SYNBALLOON"), (2, "SynBalloon"), (3, "SyntheticProxyApp"), (90, "0"), (280, "0"), (281, "1"), (0, "ENDSEC")] {
|
||||
tags.push((c, v.into()));
|
||||
}
|
||||
for (c, v) in [
|
||||
(0, "SECTION"),
|
||||
(2, "TABLES"),
|
||||
(0, "TABLE"),
|
||||
(2, "LAYER"),
|
||||
(0, "LAYER"),
|
||||
(5, "10"),
|
||||
(2, "0"),
|
||||
(62, "7"),
|
||||
(0, "LAYER"),
|
||||
(5, "11"),
|
||||
(2, "BALLOONS"),
|
||||
(62, "3"),
|
||||
(0, "ENDTAB"),
|
||||
(0, "TABLE"),
|
||||
(2, "STYLE"),
|
||||
(0, "STYLE"),
|
||||
(5, "12"),
|
||||
(2, "ISO"),
|
||||
(3, "isocp.shx"),
|
||||
(0, "ENDTAB"),
|
||||
(0, "ENDSEC"),
|
||||
(0, "SECTION"),
|
||||
(2, "ENTITIES"),
|
||||
(0, "LINE"),
|
||||
(5, "20"),
|
||||
(8, "0"),
|
||||
(10, "50"),
|
||||
(20, "40"),
|
||||
(11, "150"),
|
||||
(21, "90"),
|
||||
(0, "ACAD_PROXY_ENTITY"),
|
||||
(5, "21"),
|
||||
(100, "AcDbEntity"),
|
||||
(8, "0"),
|
||||
(100, "AcDbProxyEntity"),
|
||||
(90, "498"),
|
||||
(91, "500"),
|
||||
(95, "0"),
|
||||
(70, "0"),
|
||||
] {
|
||||
tags.push((c, v.into()));
|
||||
}
|
||||
tags.push((92, graphics.len().to_string()));
|
||||
tags.extend(hex.into_iter().map(|h| (310, h)));
|
||||
for (c, v) in [(93, "0"), (94, "0"), (0, "ENDSEC"), (0, "EOF")] {
|
||||
tags.push((c, v.into()));
|
||||
}
|
||||
tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_draws_its_graphics_with_the_files_table_indices() {
|
||||
let d = read_dxf(file().as_bytes()).expect("read");
|
||||
let proxy = d.model.iter().find(|e| matches!(e.kind, EntityKind::Unknown(_))).expect("proxy");
|
||||
let EntityKind::Unknown(u) = &proxy.kind else { unreachable!() };
|
||||
let kinds: Vec<(&str, &str, Color)> = u.graphics.iter().map(|g| (g.kind.dxf_name(), g.common.layer.as_str(), g.common.color)).collect();
|
||||
// Layer index 1 is BALLOONS, the file's second layer, not CADCraft's Defpoints.
|
||||
assert_eq!(kinds, [("CIRCLE", "BALLOONS", Color::Index(1)), ("LINE", "BALLOONS", Color::Index(1)), ("TEXT", "BALLOONS", Color::Index(1))]);
|
||||
assert!(matches!(&u.graphics[2].kind, EntityKind::Text(t) if t.value == "1" && t.style == "ISO"));
|
||||
// The extents reach the balloon (the line alone ends at 150, 90).
|
||||
let b = d.extents(&Space::Model);
|
||||
assert!(b.max.x >= 181.0 && b.max.y >= 121.0, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_is_written_back_unchanged_and_draws_again() {
|
||||
let d = read_dxf(file().as_bytes()).expect("read");
|
||||
let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen");
|
||||
let graphics = |d: &cadcraft_doc::Drawing| {
|
||||
d.model.iter().find_map(|e| match &e.kind {
|
||||
EntityKind::Unknown(u) => Some((u.proxy_graphics_bytes(), u.graphics.len())),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
assert_eq!(graphics(&again), graphics(&d));
|
||||
assert_eq!(graphics(&d).map(|g| g.1), Some(3));
|
||||
// The saved LAYER table keeps the file's order, so index 1 is still BALLOONS (CADCraft's
|
||||
// Defpoints comes after it) and the reopened graphics stay on that layer.
|
||||
let layers = |d: &cadcraft_doc::Drawing| -> Vec<String> {
|
||||
d.model
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
EntityKind::Unknown(u) => Some(u.graphics.iter().map(|g| g.common.layer.clone()).collect()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
assert_eq!(layers(&again), ["BALLOONS"; 3]);
|
||||
let names: Vec<&str> = again.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["0", "BALLOONS", "Defpoints"]);
|
||||
}
|
||||
|
||||
/// A proxy text takes the first style on its font. With ISO and then Standard both on
|
||||
/// isocp.shx, it is ISO, and stays ISO after a save: CADCraft's own Standard, which the file's
|
||||
/// replaces, would otherwise come first in the saved STYLE table.
|
||||
#[test]
|
||||
fn a_proxy_text_keeps_its_style_after_a_save() {
|
||||
let iso = "0\nSTYLE\n5\n12\n2\nISO\n3\nisocp.shx\n";
|
||||
let src = file().replacen(iso, &format!("{iso}0\nSTYLE\n5\n13\n2\nStandard\n3\nisocp.shx\n"), 1);
|
||||
let style = |d: &cadcraft_doc::Drawing| {
|
||||
d.model.iter().find_map(|e| match &e.kind {
|
||||
EntityKind::Unknown(u) => u.graphics.iter().find_map(|g| match &g.kind {
|
||||
EntityKind::Text(t) => Some(t.style.clone()),
|
||||
_ => None,
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let d = read_dxf(src.as_bytes()).expect("read");
|
||||
assert_eq!(style(&d).as_deref(), Some("ISO"));
|
||||
let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen");
|
||||
assert_eq!(style(&again).as_deref(), Some("ISO"), "after a save");
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -27,7 +27,7 @@ fn drawing() -> Drawing {
|
||||
RawTag { code: 30, value: "3.75".into() },
|
||||
RawTag { code: 330, value: target.hex() },
|
||||
];
|
||||
d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags, graphics: Vec::new() })));
|
||||
d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags })));
|
||||
d.model.push(Entity::new(target, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(5.0, 6.0, 7.0) })));
|
||||
d
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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")) })
|
||||
);
|
||||
}
|
||||
@@ -40,23 +40,6 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A proxy entity draws its proxy graphics as AutoCAD does with PROXYSHOW 1, like block contents:
|
||||
/// layer 0 and ByBlock in the picture stand for the proxy's own layer and properties. Other
|
||||
/// unknown records draw nothing. `own` is the proxy's transparency without its locked-layer fade,
|
||||
/// as for a block reference.
|
||||
pub(crate) fn proxy(b: &mut Builder, ctx: &Ctx, e: &Entity, u: &cadcraft_doc::Unknown, own: u8) {
|
||||
if u.graphics.is_empty() || ctx.depth >= cadcraft_doc::MAX_BLOCK_DEPTH {
|
||||
return;
|
||||
}
|
||||
let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::IDENTITY) };
|
||||
for g in &u.graphics {
|
||||
if !b.expand() {
|
||||
break;
|
||||
}
|
||||
entity(b, &sub, g);
|
||||
}
|
||||
}
|
||||
|
||||
/// `own` is the reference's resolved transparency without its locked-layer fade: what ByBlock
|
||||
/// children inherit (a child fades only for its own layer).
|
||||
pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rgb: Ink, own: u8) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::blocks::{insert, proxy, sub_ctx};
|
||||
use super::blocks::{insert, sub_ctx};
|
||||
use super::dim_draw::{MAX_FILL_SOLIDS, MAX_FILL_TEXTS, block_text_box, dim_text_fill, dimension, dimension_in, solid_covers, starts_text_marks};
|
||||
use super::display::{Kind, NO_LAYER, VIEWPORT_CONTENT};
|
||||
use super::props::{resolve, transparency};
|
||||
@@ -240,7 +240,12 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
|
||||
b.polyline(ctx, rgb, lw, l);
|
||||
}
|
||||
}
|
||||
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => draw_unknown(b, ctx, e, u, rgb, lw, own),
|
||||
// An OLE object's content is not drawn; its frame, from its two corner points, is.
|
||||
EntityKind::Unknown(u) if u.is_ole_frame() => {
|
||||
if let Some(q) = cadcraft_doc::ole_frame(&u.tags) {
|
||||
b.polyline(ctx, rgb, lw, &q);
|
||||
}
|
||||
}
|
||||
kind => {
|
||||
for prim in kind.prims() {
|
||||
match prim {
|
||||
@@ -297,17 +302,6 @@ fn draw_mleader(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &cadcraft_doc::MLeade
|
||||
}
|
||||
}
|
||||
|
||||
/// A record kept as read that draws something: a proxy its proxy graphics, and an OLE object its
|
||||
/// frame, from its two corner points (its content is not drawn). `own`: the proxy's transparency
|
||||
/// without its locked-layer fade, for its graphics.
|
||||
fn draw_unknown(b: &mut Builder, ctx: &Ctx, e: &Entity, u: &cadcraft_doc::Unknown, rgb: Ink, lw: f32, own: u8) {
|
||||
if !u.graphics.is_empty() {
|
||||
proxy(b, ctx, e, u, own);
|
||||
} else if let Some(q) = cadcraft_doc::ole_frame(&u.tags) {
|
||||
b.polyline(ctx, rgb, lw, &q);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_image(b: &mut Builder, ctx: &Ctx, i: &cadcraft_doc::Image, rgb: Ink, lw: f32) {
|
||||
let o = i.insert.xy();
|
||||
let u = i.u.xy() * i.size.x;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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};
|
||||
|
||||
|
||||
@@ -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,
|
||||
@@ -1299,8 +1299,7 @@ fn raster_hatch_pattern_matches_one_by_one() {
|
||||
#[test]
|
||||
fn ole_frame_draws_its_outline() {
|
||||
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
|
||||
let frame =
|
||||
|tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
|
||||
let frame = |tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags });
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "1"), tag(20, "2")])).unwrap();
|
||||
@@ -1334,51 +1333,6 @@ fn without_linetypes_every_line_is_drawn_whole() {
|
||||
assert!(drawn.prims.len() > 2 * continuous.prims.len(), "drawn with its linetype: {} primitives", drawn.prims.len());
|
||||
}
|
||||
|
||||
/// A proxy draws its proxy graphics like block contents: layer 0 and ByBlock in the picture are
|
||||
/// the proxy's own, and the proxy's layer hides all of it.
|
||||
#[test]
|
||||
fn proxy_graphics_draw_like_block_contents() {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layers.push(cadcraft_doc::Layer { name: "Notes".into(), color: Color::Index(3), ..Default::default() });
|
||||
let byblock = Common { color: Color::ByBlock, ..Default::default() };
|
||||
let graphics = vec![
|
||||
block_entity(7, byblock, EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) })),
|
||||
block_entity(
|
||||
7,
|
||||
Common { color: Color::Index(1), ..Default::default() },
|
||||
EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::new(15.0, 0.0, 0.0), radius: 5.0 }),
|
||||
),
|
||||
];
|
||||
let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics });
|
||||
d.add(&Space::Model, Common { layer: "Notes".into(), ..Default::default() }, proxy).unwrap();
|
||||
let l = build(&d, &Space::Model, &Options::default());
|
||||
assert_eq!(l.prims.iter().map(|p| p.color).collect::<Vec<_>>(), [Rgb(0, 255, 0), Rgb(255, 0, 0)]);
|
||||
let b = d.extents(&Space::Model);
|
||||
assert!((b.min.x, b.max.x, b.max.y) == (0.0, 20.0, 5.0), "{b:?}");
|
||||
d.layer_mut("Notes").unwrap().frozen = true;
|
||||
assert!(build(&d, &Space::Model, &Options::default()).prims.is_empty());
|
||||
}
|
||||
|
||||
/// On a locked layer, a proxy's graphics fade like a block's contents: layer 0 in the picture takes
|
||||
/// the proxy's fade, a ByBlock part on an unlocked layer only the proxy's own transparency.
|
||||
#[test]
|
||||
fn proxy_graphics_on_a_locked_layer_fade_like_block_contents() {
|
||||
use cadcraft_doc::Transparency::{ByBlock, ByLayer, Percent};
|
||||
for (own, want) in [(ByLayer, 0), (Percent(20), 20)] {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.layers.push(cadcraft_doc::Layer { name: "Locked".into(), locked: true, ..Default::default() });
|
||||
d.layers.push(cadcraft_doc::Layer { name: "Open".into(), ..Default::default() });
|
||||
let line = |x: f64| EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(x, 0.0, 0.0), b: Vec3::new(x + 1.0, 0.0, 0.0) });
|
||||
let graphics = vec![
|
||||
block_entity(7, Common::default(), line(0.0)),
|
||||
block_entity(7, Common { layer: "Open".into(), transparency: ByBlock, ..Default::default() }, line(2.0)),
|
||||
];
|
||||
let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics });
|
||||
d.add(&Space::Model, Common { layer: "Locked".into(), transparency: own, ..Default::default() }, proxy).unwrap();
|
||||
assert_eq!(faded(&build(&d, &Space::Model, &on_screen(with_transparency()))), vec![50.max(want), want], "{own:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A broken table whose parts, with their repeated labels, together hold more cells than a table may
|
||||
/// lay out is drawn as its outline, though the table's own cells are within the limit.
|
||||
#[test]
|
||||
@@ -1417,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)];
|
||||
@@ -1426,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);
|
||||
|
||||
@@ -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, ¶ms)
|
||||
}
|
||||
|
||||
/// 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, ¶ms);
|
||||
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.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user