mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-24 06:44:29 -06:00
Compare commits
300
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3d23ce225 | ||
|
|
cd96a12ae4 | ||
|
|
ddb9a424ef | ||
|
|
a974b2026f | ||
|
|
9d6f82dc9f | ||
|
|
e811a5183e | ||
|
|
6855f76f5a | ||
|
|
fc82a0d148 | ||
|
|
223314c8eb | ||
|
|
7b8ca63926 | ||
|
|
6601baf63d | ||
|
|
ff0bde679c | ||
|
|
7506ffc83d | ||
|
|
9254277db3 | ||
|
|
3a4cf04b76 | ||
|
|
61b420cfbe | ||
|
|
59f27fb38c | ||
|
|
25bfb60078 | ||
|
|
1ae4c29990 | ||
|
|
6ad7d9dfb7 | ||
|
|
ca92d330a3 | ||
|
|
cfed9aa27a | ||
|
|
0b4337d3ed | ||
|
|
02f8f6df4d | ||
|
|
ba7c7b5845 | ||
|
|
5e5b5133e6 | ||
|
|
73eb57b638 | ||
|
|
bf5538d482 | ||
|
|
051b11a271 | ||
|
|
c5c32e805b | ||
|
|
685bc51442 | ||
|
|
25a7835d04 | ||
|
|
264368b7db | ||
|
|
3673897110 | ||
|
|
d2d754564e | ||
|
|
f5b201f15d | ||
|
|
16929ef8ef | ||
|
|
b1cfeedf81 | ||
|
|
a8c50b0924 | ||
|
|
bebbdca51a | ||
|
|
2e047907f7 | ||
|
|
1cfc7d8f17 | ||
|
|
2733c9d31a | ||
|
|
4680fd28a6 | ||
|
|
e5972c994e | ||
|
|
6c5fdfdd32 | ||
|
|
a4d8cae573 | ||
|
|
8e9dc8a6cb | ||
|
|
371baf176b | ||
|
|
3d9b5f6175 | ||
|
|
924a37abac | ||
|
|
892a7e2a0b | ||
|
|
3d9a59c0a0 | ||
|
|
71929191a9 | ||
|
|
cf6046cc62 | ||
|
|
22c03def7a | ||
|
|
dbef5a6bba | ||
|
|
e8114fdaa3 | ||
|
|
2a0454cacc | ||
|
|
f28011ecec | ||
|
|
a70b9b02e4 | ||
|
|
b206eab39b | ||
|
|
8d3236c5a3 | ||
|
|
f4d4a6e4e1 | ||
|
|
80e9a97164 | ||
|
|
fba67a1c76 | ||
|
|
97dccaf9e7 | ||
|
|
b39170aded | ||
|
|
20d489f059 | ||
|
|
318d8d9de1 | ||
|
|
4076a71dee | ||
|
|
e5a7d38a67 | ||
|
|
46053d43c1 | ||
|
|
6aa64fb5ae | ||
|
|
543285778b | ||
|
|
fed8b0f4e4 | ||
|
|
50baa3cfae | ||
|
|
ef6df4dffa | ||
|
|
97c5670a0a | ||
|
|
ed294b3fb3 | ||
|
|
40ddd7baca | ||
|
|
ea4a59b662 | ||
|
|
9e645ba17a | ||
|
|
8da04230af | ||
|
|
af5c658a4b | ||
|
|
5d76e47342 | ||
|
|
3caad662a4 | ||
|
|
615fee3e12 | ||
|
|
92fe0a655d | ||
|
|
a62dd047a4 | ||
|
|
b4c325a36b | ||
|
|
1ad4fc7c91 | ||
|
|
8178a68f3e | ||
|
|
29a22f7955 | ||
|
|
48f0a590ab | ||
|
|
80f2b6838d | ||
|
|
70e55f21cc | ||
|
|
d3af2d5077 | ||
|
|
afcf5d3461 | ||
|
|
7ecf836de7 | ||
|
|
4b97a1a25e | ||
|
|
4683023d94 | ||
|
|
44e0e431ee | ||
|
|
0b454bb536 | ||
|
|
9f2cd4ca78 | ||
|
|
1d92bb275c | ||
|
|
a5da799a8c | ||
|
|
9537bbbb48 | ||
|
|
d83bf7be22 | ||
|
|
c73b1487ea | ||
|
|
fafe5f128c | ||
|
|
9c53d527f8 | ||
|
|
7ec88f7e27 | ||
|
|
7189295bc3 | ||
|
|
0191a5fa61 | ||
|
|
a7808fdc9d | ||
|
|
2dc136781b | ||
|
|
be0f2f7083 | ||
|
|
5e697dde2b | ||
|
|
2c8b8f438c | ||
|
|
8ea4c908e2 | ||
|
|
410c55aaee | ||
|
|
75cdbd49b4 | ||
|
|
c4c632d1f0 | ||
|
|
120d9dd1a0 | ||
|
|
2c8a6edf9d | ||
|
|
dbe34ad3bc | ||
|
|
1ff6241ecb | ||
|
|
e1f87447cb | ||
|
|
01d6eca913 | ||
|
|
816bd9591c | ||
|
|
aab42ef9df | ||
|
|
a0b29c0a11 | ||
|
|
fae1d05994 | ||
|
|
1c5e4f41f5 | ||
|
|
2cc0100d70 | ||
|
|
db66a8cd95 | ||
|
|
8152c9e71b | ||
|
|
d02dc3e91e | ||
|
|
184571d17b | ||
|
|
3b0f88861b | ||
|
|
5c00b66572 | ||
|
|
0e0344be94 | ||
|
|
3ec1e1b210 | ||
|
|
3165d2735e | ||
|
|
d04d67f8c3 | ||
|
|
67cc9a28c3 | ||
|
|
ceb28303f5 | ||
|
|
8725cc48b2 | ||
|
|
a4364499d4 | ||
|
|
73d1b65f3e | ||
|
|
6fb27ffa9e | ||
|
|
4d2381a5ca | ||
|
|
b84f6a8994 | ||
|
|
a0f3f25760 | ||
|
|
dab89a38ed | ||
|
|
ef12e7a9e2 | ||
|
|
3c956c4ccf | ||
|
|
3ee12a8c62 | ||
|
|
b8f60e1e60 | ||
|
|
984596fead | ||
|
|
e9638efc69 | ||
|
|
d71fb54b39 | ||
|
|
f81c52b979 | ||
|
|
b69dc2a380 | ||
|
|
9b05dbed43 | ||
|
|
59d5d20ab2 | ||
|
|
32d5bd85db | ||
|
|
a684cd506d | ||
|
|
b4ca4fd2b0 | ||
|
|
4d1d85d298 | ||
|
|
f5e98c3cb1 | ||
|
|
014ecbc7dc | ||
|
|
5869cf91f9 | ||
|
|
787929ee50 | ||
|
|
c421d2005b | ||
|
|
6ac52455d9 | ||
|
|
4e482cf617 | ||
|
|
c17cbc9c73 | ||
|
|
8e2aa822f7 | ||
|
|
0e40437d8f | ||
|
|
97903aa83a | ||
|
|
392b0e1678 | ||
|
|
52dfb93b8b | ||
|
|
7b81b92906 | ||
|
|
a34cf69439 | ||
|
|
6ec0f2400a | ||
|
|
203865064a | ||
|
|
e56571eafc | ||
|
|
18effe68b4 | ||
|
|
410bdc733f | ||
|
|
b325046f76 | ||
|
|
48bcb817ed | ||
|
|
467ab20ace | ||
|
|
275f989aa5 | ||
|
|
fd17a05b95 | ||
|
|
2dd428dc2d | ||
|
|
17da6ab38a | ||
|
|
53cebb9020 | ||
|
|
f7b3b68952 | ||
|
|
9eb81b3588 | ||
|
|
b1f477bfc2 | ||
|
|
8c7bfb3efe | ||
|
|
9a4bc98bbf | ||
|
|
ad6d3d12ca | ||
|
|
6412e9c99a | ||
|
|
f7c4c148a3 | ||
|
|
0bd4d54f4a | ||
|
|
158d043d41 | ||
|
|
34b4899eee | ||
|
|
6ed01dea96 | ||
|
|
ce4b33ade2 | ||
|
|
11ee9f1f64 | ||
|
|
e928316c4d | ||
|
|
b6f17bd9be | ||
|
|
a6ee8bc596 | ||
|
|
6294cd1546 | ||
|
|
50a1f833ad | ||
|
|
1a3d2f6015 | ||
|
|
a801739ea7 | ||
|
|
757601780d | ||
|
|
f66434ee8f | ||
|
|
8b6c204fd8 | ||
|
|
41f9e394b9 | ||
|
|
e36d1fde4b | ||
|
|
44a4e05506 | ||
|
|
0829bfa0eb | ||
|
|
2bd916661d | ||
|
|
b3a1e1af40 | ||
|
|
d5720c6403 | ||
|
|
0f94865fa9 | ||
|
|
dc59a8e33c | ||
|
|
b17880ca89 | ||
|
|
0cbe1b7e50 | ||
|
|
577aa81e8b | ||
|
|
72e82c59d0 | ||
|
|
1dcb30426c | ||
|
|
72f8dd8076 | ||
|
|
cc74fe32ed | ||
|
|
722aeb1080 | ||
|
|
44f026833c | ||
|
|
d03af7d7a6 | ||
|
|
60ac0548e1 | ||
|
|
a5c8b1acf6 | ||
|
|
b17523e53c | ||
|
|
53ac71c1fe | ||
|
|
b2ebb3958d | ||
|
|
393475f308 | ||
|
|
a9294b5151 | ||
|
|
9a5f26d5aa | ||
|
|
f646452065 | ||
|
|
5ab29b4090 | ||
|
|
b6cc1c29ee | ||
|
|
015fe2a18d | ||
|
|
bb95044b19 | ||
|
|
bee69e6f24 | ||
|
|
0bf230b14a | ||
|
|
b48c82c1fe | ||
|
|
16290fd8d6 | ||
|
|
a35a9add42 | ||
|
|
aa08cfc0a9 | ||
|
|
e0f8751f08 | ||
|
|
584e5471b1 | ||
|
|
911b4f766e | ||
|
|
0a23281d45 | ||
|
|
3f3ac1ded9 | ||
|
|
dc2acd9b72 | ||
|
|
ef36f222aa | ||
|
|
7f2e4bb817 | ||
|
|
c667151667 | ||
|
|
d2a1090357 | ||
|
|
24e5687c3d | ||
|
|
a35817eaea | ||
|
|
b49137f6dd | ||
|
|
5147aae2c2 | ||
|
|
b551acec8d | ||
|
|
fa4f997eed | ||
|
|
0327f7512b | ||
|
|
61fc55d7b6 | ||
|
|
b121eb1517 | ||
|
|
e0f33d7d93 | ||
|
|
14e3126df8 | ||
|
|
f1aa54b9c2 | ||
|
|
3b8531ff5f | ||
|
|
bbd4eddd45 | ||
|
|
b44cb36865 | ||
|
|
6f5bf85dc0 | ||
|
|
15dcfcfba9 | ||
|
|
e9471f6140 | ||
|
|
17408bdb65 | ||
|
|
7f84dab948 | ||
|
|
5f44be5bdf | ||
|
|
3e4068246d | ||
|
|
032b73347c | ||
|
|
45065cc061 | ||
|
|
7dc9e0ec6f | ||
|
|
54d0e034e4 | ||
|
|
2a9c14e96e | ||
|
|
bfadb1a94e | ||
|
|
fc67a5c28a |
@@ -60,3 +60,4 @@ jobs:
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# 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)
|
||||
+4
-2
@@ -19,7 +19,9 @@ 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 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.
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
@@ -70,7 +72,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 | 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/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/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 |
|
||||
|
||||
Generated
+83
-88
@@ -661,6 +661,7 @@ dependencies = [
|
||||
"craft-window",
|
||||
"eframe",
|
||||
"egui",
|
||||
"fmv-macos-events",
|
||||
"hidapi",
|
||||
"log",
|
||||
"muda",
|
||||
@@ -780,7 +781,7 @@ dependencies = [
|
||||
"cadcraft-render",
|
||||
"craft-dwg",
|
||||
"craft-dxf",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-image-codecs",
|
||||
"craft-pdf",
|
||||
"craft-svg",
|
||||
"image",
|
||||
@@ -817,7 +818,7 @@ dependencies = [
|
||||
"cadcraft-doc",
|
||||
"cadcraft-fonts",
|
||||
"cadcraft-geom",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-image-codecs",
|
||||
"lyon_tessellation",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
@@ -836,7 +837,7 @@ dependencies = [
|
||||
"cadcraft-io",
|
||||
"cadcraft-render",
|
||||
"chrono",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-image-codecs",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"craft-window",
|
||||
@@ -1180,22 +1181,30 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
|
||||
[[package]]
|
||||
name = "craft-dwg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf#7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"log",
|
||||
@@ -1216,22 +1225,26 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c07e38090879ffa994f893df9956c6d5b96c049c#c07e38090879ffa994f893df9956c6d5b96c049c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"kurbo",
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
"unicode-segmentation",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -1254,35 +1267,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"hayro-jpeg2000",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
"craft-metadata",
|
||||
"craft-tiff",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
@@ -1304,15 +1294,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1320,7 +1302,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jsonrpc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1328,7 +1310,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mcp"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b6222158fbc2a628f27d2c1fff9f648cd194404c#b6222158fbc2a628f27d2c1fff9f648cd194404c"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-jsonrpc",
|
||||
"serde_json",
|
||||
@@ -1337,23 +1319,11 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"craft-tiff",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
@@ -1361,17 +1331,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db)",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc)",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"hayro-syntax",
|
||||
"krilla",
|
||||
@@ -1381,14 +1351,13 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-shx"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=2f2d1d84e3a36b3f93e81507aeff3f0da97a7162#2f2d1d84e3a36b3f93e81507aeff3f0da97a7162"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
|
||||
"craft-xml",
|
||||
"flate2",
|
||||
"kurbo",
|
||||
@@ -1402,16 +1371,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1420,7 +1380,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1441,7 +1401,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1468,7 +1428,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -1479,7 +1439,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
@@ -1488,7 +1448,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
@@ -1499,7 +1459,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2097,6 +2057,17 @@ 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"
|
||||
@@ -2446,6 +2417,19 @@ dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "harfrust"
|
||||
version = "0.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "948d0741125ba89cd3e1c23e5642415b6ade7e1d29d67ba25fb925b533e989d6"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"once_cell",
|
||||
"read-fonts 0.43.3",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "harfrust"
|
||||
version = "0.14.0"
|
||||
@@ -2505,7 +2489,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"hayro-ccitt",
|
||||
]
|
||||
@@ -2522,7 +2506,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"hayro-jbig2",
|
||||
"hayro-jpeg2000",
|
||||
@@ -3022,7 +3006,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4284,6 +4268,17 @@ dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.43.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "005c8acf251756c478b0bf402885bfd88a1476020c4c7e6060edc1aa68da38ea"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.44.0"
|
||||
|
||||
+16
-16
@@ -15,10 +15,10 @@ repository = "https://github.com/storytold/cadcraft"
|
||||
cadcraft-geom = { path = "crates/geom" }
|
||||
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
|
||||
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "2f2d1d84e3a36b3f93e81507aeff3f0da97a7162" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0325b2d73676d736e94097dbcef01219cf25c7db" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
cadcraft-color = { path = "crates/color" }
|
||||
cadcraft-doc = { path = "crates/doc" }
|
||||
cadcraft-constraints = { path = "crates/constraints" }
|
||||
@@ -28,17 +28,17 @@ cadcraft-io = { path = "crates/io" }
|
||||
cadcraft-engine = { path = "crates/engine" }
|
||||
cadcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
cadcraft-mcp = { path = "crates/mcp" }
|
||||
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" }
|
||||
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
# SVG/SVGZ import and export geometry (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
# Which paths stored in a drawing (xrefs, data links) may be opened.
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
|
||||
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
|
||||
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false }
|
||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
|
||||
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "c07e38090879ffa994f893df9956c6d5b96c049c", default-features = false }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4.6.11"
|
||||
clap_mangen = { version = "0.3.3", features = ["env"] }
|
||||
@@ -70,8 +70,8 @@ encoding_rs = "0.8.35"
|
||||
quick-xml = "0.42"
|
||||
|
||||
# ui
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
@@ -81,7 +81,7 @@ egui-wgpu = "0.37"
|
||||
# Monotonic time on native and web (performance.now on wasm).
|
||||
web-time = "1.1"
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
@@ -113,9 +113,9 @@ debug = 0
|
||||
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
|
||||
# (Cargo ignores dependency-local patches).
|
||||
[patch.crates-io]
|
||||
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
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" }
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -184,6 +184,34 @@ in the text style or set `FONTFALLBACK` (`CADCRAFT_FONTFALLBACK="Vazirmatn"`). F
|
||||
inside a word (an MTEXT colour change in the middle of a Persian word) break the joining at that
|
||||
point.
|
||||
|
||||
### Portable Windows ZIP
|
||||
|
||||
The Windows portable ZIP includes `portable.txt` beside `cadcraft.exe`. With that
|
||||
marker present, the desktop app's settings, logs, autosaves, workspace data,
|
||||
plotter files, and eframe preferences/window state stay in `CADCraftData` beside
|
||||
the executable. eframe saves its preferences and window state in `CADCraftData/app.ron`.
|
||||
Keep that directory when replacing the binaries. The MSI does not include the
|
||||
marker and continues to use the normal user profile.
|
||||
|
||||
`CADCRAFT_CONFIG_DIR` takes precedence over the marker, including an empty or
|
||||
blank value that disables the settings folder. If `CADCraftData` cannot be
|
||||
created or written, CADCraft warns and uses the normal profile. Existing profile
|
||||
settings are not automatically copied into the portable directory.
|
||||
|
||||
Before switching an existing Windows installation to portable mode, close CADCraft,
|
||||
back up `%APPDATA%\CADCraft`, and copy the settings you want to retain into
|
||||
`CADCraftData`. Include the `autosave` folder if you need to recover unsaved drawings. The
|
||||
preferences and window state are kept apart, in `%APPDATA%\ai.storyteller.cadcraft\data\app.ron`:
|
||||
copy that file to `CADCraftData\app.ron` to keep them.
|
||||
Updating a portable ZIP, including through the updater, can restore `portable.txt`;
|
||||
set `CADCRAFT_CONFIG_DIR` to your existing profile folder to keep using it across updates.
|
||||
|
||||
`cadcraft-cli.exe` does not detect the marker. To share the desktop app's portable
|
||||
settings, pass `--config-dir` with the full path to `CADCraftData`, or set
|
||||
`CADCRAFT_CONFIG_DIR` to that path. The marker is also recognized on other desktop
|
||||
platforms, but is intended for a standalone writable installation, not inside a
|
||||
signed macOS application bundle.
|
||||
|
||||
### Logs
|
||||
|
||||
The desktop app writes its `log` records to standard error and to `logs/cadcraft.log` in the
|
||||
|
||||
+15
-10
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: pre-alpha** · next: alpha, when the six rows of the [alpha gate](docs/roadmap.md#alpha-gate) pass (five fail today; the gate was revised on 2026-11-19 and its hours are not re-estimated yet)
|
||||
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-19 · **Change:** major (alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
> **Last reviewed:** 2026-11-19 · **Last updated:** 2026-11-20 · **Change:** minor (Upcoming updated for what merged on 2026-11-19 and 2026-11-20; previously major: alpha gate revised from user reports: six rows, Windows first; Upcoming re-ranked into three priority tiers; previously minor: re-audit against main 41d9b5e95) · **Target:** Autodesk AutoCAD 2027
|
||||
|
||||
CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and
|
||||
plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a
|
||||
@@ -115,21 +115,23 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
|
||||
- The open findings of the security audit (#1919–#1935): check each against the input limits that
|
||||
landed on 2026-11-11, close what is fixed and fix the rest. A crafted handle that makes new entities
|
||||
overwrite existing ones (#1921) is fixed by #1276.
|
||||
- Hostile-input fixes waiting in pull requests (#2820, #2821, #2765).
|
||||
- A saved file that crashes AutoCAD 2021 (#3303) and dimension text lost on save (#3299).
|
||||
- Crashes and hangs with a reproduction: the web build on a large DXF (#1603), a DWG with 3D content
|
||||
(#2174), startup on older graphics hardware (#1724, #1631, #3222).
|
||||
|
||||
**2. Parity with AutoCAD: the alpha gate rows, then the beta checklist (apart from its items named under tier 3).**
|
||||
- It starts on common hardware (#1596, then an automatic fallback renderer).
|
||||
- It starts on common hardware: an automatic fallback renderer (`CADCRAFT_STENCIL=0` is the manual
|
||||
switch since #3336).
|
||||
- It opens the DWG and DXF files people already have: large files (#3102, #2633, #1088), layouts and
|
||||
paper units (#1672, #2836), and a corpus of real files run in CI.
|
||||
- Saving loses nothing and other CAD programs open the result (#2904, #1687, #3234, #2632).
|
||||
- Input feels like AutoCAD for Windows: clicks while the mouse moves (#1001, #2092), right-click and
|
||||
Space as Enter (#1387), double-click to edit text (#842).
|
||||
- The prompt options that still say "not available yet", and TRIM/EXTEND depth.
|
||||
- Layouts print at scale on a system printer, and the menu bar and panels can always be restored
|
||||
(#3216, #1240).
|
||||
- 714 pull requests are open (2026-11-19). About 230 are mergeable, pass CI and are small; they are
|
||||
- Input feels like AutoCAD for Windows: the fixes for clicks while the mouse moves, right-click and
|
||||
Space as Enter, and double-click text editing landed (#3307, #3345); waiting for the reporters to
|
||||
confirm, and table cells are left (#842).
|
||||
- The prompt options that still say "not available yet" (gaps F1).
|
||||
- Layouts print at scale on a system printer (#3216); the menu bar and panels can be restored since
|
||||
#3308.
|
||||
- 661 pull requests are open (2026-11-20; 714 the day before). About 230 were mergeable, passed CI and were small; they are
|
||||
reviewed and landed in this order, the longest-waiting authors first within a row.
|
||||
|
||||
**3. Lower priority: affects fewer people and nothing breaks without it.**
|
||||
@@ -139,7 +141,9 @@ and the beta checklist are in [docs/roadmap.md](docs/roadmap.md).
|
||||
but a file with 3D content must open safely (tier 1).
|
||||
- Menu breadth against AutoCAD for Mac as a headline number.
|
||||
|
||||
Done since the last ranking: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
|
||||
Done on 2026-11-19 and 2026-11-20: the hostile-input fixes #1276, #2820, #2821 and #2765 (#3304, #3305), clicks while the mouse moves and right-click or Space as Enter (#3307), the interface reset (#3308), paper units (#3309), the UCS command (#3310), -ATTEDIT, -RENAME and -LAYER options (#3311), TRIM/EXTEND depth (#3312), dimension values kept on save (#3335), the stencil switch (#3336), a typed OPEN path (#3343) and double-click text editing (#3345).
|
||||
|
||||
Done before that: precision input (#379, #441, #60, #519), prompt options in TRIM/EXTEND,
|
||||
OFFSET, ROTATE, PLINE, SPLINE, MTEXT and MLEADER (#397, #408, #547), autosave, recovery, AUDIT and
|
||||
RECOVER on the desktop (#406, #416), xrefs (#525), groups (#417), the Block Editor (#824, #833, #885),
|
||||
REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the Dimension Style Manager
|
||||
@@ -166,6 +170,7 @@ REFEDIT (#818), XCLIP (#2354), dynamic block references (#838–#883), and the D
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | minor | Upcoming updated for the merges of 2026-11-19 and 2026-11-20 (security stacks, input, interface reset, paper units, UCS, prompt options, TRIM/EXTEND, text editing in place); pull-request count 714 → 661; percentages and hours not re-scored |
|
||||
| 2026-11-19 | major | Alpha gate revised from user reports (six rows, Windows first; block authoring, xref editing in place and exact curve geometry moved to beta); Upcoming re-ranked into three tiers: urgent (security, leaks, crashes, lost work), parity, lower priority; percentages and hours not re-scored |
|
||||
| 2026-10-24 | minor | Re-audit against main 41d9b5e95: language table, CI gate and open-PR count re-checked against main 41d9b5e95 |
|
||||
| 2026-10-21 | trivial | Progress log: proxy objects keep their class through a save (#1812) |
|
||||
|
||||
@@ -56,6 +56,9 @@ fn install_io() {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
}
|
||||
|
||||
/// `path` as text, for the engine and io calls that take a file name as a string.
|
||||
@@ -76,6 +79,11 @@ pub fn command() -> clap::Command {
|
||||
/// Run the CLI on its arguments (without the program name). Returns the process exit code (0 ok,
|
||||
/// 1 failure, 2 usage). clap reads the arguments as they are: a value that is not valid Unicode
|
||||
/// is a usage error, never a panic as with `std::env::args()`.
|
||||
///
|
||||
/// Reading or writing DWG needs a conversion worker, which this function does not set up: the
|
||||
/// binary calls `cadcraft_io::dwg_worker::use_own_worker()` first. A caller that converts only its
|
||||
/// own, trusted files can call `cadcraft_io::dwg_worker::allow_in_process()` instead. With
|
||||
/// neither, a DWG file gets "no worker is configured" and exit code 1.
|
||||
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
@@ -88,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()) {
|
||||
return match write!(to, "{}", e.render()).and_then(|()| to.flush()) {
|
||||
Err(w) if w.kind() != std::io::ErrorKind::BrokenPipe => {
|
||||
let _ = writeln!(err, "error: can't write the output: {w}");
|
||||
1
|
||||
@@ -158,6 +166,25 @@ 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| eprintln!("[{}/{n}] {rel}", i + 1));
|
||||
let report = corpus::run(&root, &files, &opts, &mut |i, n, rel| io.errln(format_args!("[{}/{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};
|
||||
use super::output::{Streams, export, export_framed, export_window, model_views, undrawn_message};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::Handle;
|
||||
use serde_json::Value;
|
||||
@@ -216,7 +216,15 @@ 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) { export_window(&s, framing, Some(&before))? } else { None };
|
||||
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
|
||||
};
|
||||
export_framed(&s, p, window, io)?;
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -8,6 +8,7 @@ use cadcraft_io::dwg_worker;
|
||||
#[test]
|
||||
fn a_real_worker_reads_and_writes_and_its_death_is_an_error_here() {
|
||||
let drawing = cadcraft_engine::sample::bracket();
|
||||
dwg_worker::allow_in_process();
|
||||
let in_process = cadcraft_io::write(&drawing, "a.dwg").unwrap();
|
||||
|
||||
dwg_worker::use_worker(env!("CARGO_BIN_EXE_cadcraft-cli").into(), vec![dwg_worker::WORKER_ARG.into()]);
|
||||
@@ -34,7 +35,8 @@ fn a_real_worker_reads_and_writes_and_its_death_is_an_error_here() {
|
||||
assert!(e.contains("worker stopped"), "{e}");
|
||||
assert!(cadcraft_io::read(&written, "a.dwg").is_ok(), "the next file gets a new worker");
|
||||
|
||||
// No worker to start: the work happens here, as without one.
|
||||
// A worker that cannot start is an error, even where in-process conversion is allowed.
|
||||
dwg_worker::use_worker("no-such-program-here".into(), Vec::new());
|
||||
assert!(cadcraft_io::read(&written, "a.dwg").is_ok());
|
||||
let e = cadcraft_io::read(&written, "a.dwg").unwrap_err().to_string();
|
||||
assert!(e.contains("could not start"), "{e}");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `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.
|
||||
//! Image exports report how many model-space entities they can't draw, by type. The exit code
|
||||
//! stays 0 (#1208).
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
@@ -70,6 +70,28 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() {
|
||||
assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_image_export_warns_about_undrawn_entities() {
|
||||
let scratch = Scratch::new("run-undrawn");
|
||||
let input = scratch.0.join("proxies.dxf");
|
||||
std::fs::write(&input, PROXIES).unwrap();
|
||||
let image = scratch.0.join("out.svg");
|
||||
let out = cli(&["run", input.to_str().unwrap(), "--export", image.to_str().unwrap()]);
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{:?}: {err}", out.status);
|
||||
assert!(image.is_file());
|
||||
assert!(out.stdout.is_empty(), "the warning belongs on stderr");
|
||||
let warnings: Vec<&str> = err.lines().filter(|l| l.contains("not drawn")).collect();
|
||||
assert_eq!(warnings, [format!("{}: 3 entities not drawn (PDFUNDERLAY: 1, REGION: 2)", image.display())], "{err}");
|
||||
|
||||
let copy = scratch.0.join("copy.dxf");
|
||||
let out = cli(&["run", input.to_str().unwrap(), "--export", copy.to_str().unwrap()]);
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{:?}: {err}", out.status);
|
||||
assert!(copy.is_file());
|
||||
assert!(!err.contains("not drawn"), "{err}");
|
||||
}
|
||||
|
||||
/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it an undrawn entity (#2422); it
|
||||
/// says once that the OLE content inside the frame is not drawn (review on #2587).
|
||||
#[test]
|
||||
|
||||
@@ -824,6 +824,7 @@ fn non_unicode_arguments() {
|
||||
fn non_unicode_output_names() {
|
||||
use std::ffi::OsString;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let s = Scratch::new("nonunicode-out");
|
||||
let latin1 = |ext: &str| {
|
||||
let mut n = b"caf\xe9.".to_vec();
|
||||
@@ -948,3 +949,11 @@ fn json_output_is_pretty_unless_compact() {
|
||||
assert_eq!(r.stdout.lines().count(), 2, "one line per --cmd result: {}", r.stdout);
|
||||
assert_eq!(invoke(&["run", "--sample", "--compact"]).code, 2, "run takes no --compact");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_progress_uses_the_requested_stderr() {
|
||||
run_cases(
|
||||
"roundtrip-progress",
|
||||
&[case("roundtrip progress", &["roundtrip", "{b}", "--same-format", "--no-census"], 0, Starts("b.dxf: opened;"), Line("[1/1] b.dxf"))],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ fn cli(args: &[&str]) -> Output {
|
||||
/// A DWG of 200 lines, and a copy damaged so that the reader skips some of its records (found the
|
||||
/// way the reader's own test finds one: flipping a few bytes at a time across the objects area).
|
||||
fn dwg_and_damaged_copy() -> (Vec<u8>, Vec<u8>) {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let mut dxf = String::from("0\nSECTION\n2\nENTITIES\n");
|
||||
for i in 0..200 {
|
||||
dxf += &format!("0\nLINE\n8\n0\n10\n{i}\n20\n0\n11\n{i}\n21\n10\n");
|
||||
|
||||
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
|
||||
cadcraft-fonts = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -130,6 +130,9 @@ mod web {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
let Some(canvas) = app_canvas() else {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
|
||||
@@ -62,6 +62,11 @@ 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]
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! macOS open-documents and quit Apple events (#158).
|
||||
//!
|
||||
//! A Finder double-click, Open With, a drop on the Dock icon and `open -a CADCraft plan.dxf` don't
|
||||
//! put the path in argv: LaunchServices sends the running (or just-launched) app a
|
||||
//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
|
||||
//! `NSApplicationDelegate`, so AppKit answered "CADCraft cannot open files in the Drawing Exchange
|
||||
//! Format format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which
|
||||
//! this workspace forbids. The pinned `fmv-macos-events` crate wraps exactly that, an
|
||||
//! `NSAppleEventManager` handler registered before Finder's
|
||||
//! launch event that leaves winit's delegate alone, behind a safe main-thread API.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use cadcraft_ui_egui::CadApp;
|
||||
#[cfg(target_os = "macos")]
|
||||
use fmv_macos_events::{Event, Inbox, Registration};
|
||||
|
||||
/// The shape of `fmv_macos_events::Event`, so [`dispatch`] and its tests also build and run where
|
||||
/// that crate is not compiled (PR CI runs on Linux). On macOS the crate's own type is used.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
enum Event {
|
||||
Open(Vec<PathBuf>),
|
||||
Quit,
|
||||
}
|
||||
|
||||
/// Keeps the Apple-event handlers registered; hold it until the event loop returns.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub struct AppleEvents {
|
||||
_registration: Registration,
|
||||
inbox: Inbox,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl AppleEvents {
|
||||
/// Register the handlers. Call on the main thread before the event loop starts, so the event
|
||||
/// that launched the app (a Finder double-click) is caught too.
|
||||
pub fn install() -> Self {
|
||||
let (registration, inbox) = Registration::install();
|
||||
Self { _registration: registration, inbox }
|
||||
}
|
||||
|
||||
/// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
|
||||
pub fn connect(&self, ctx: &egui::Context) -> Inbox {
|
||||
let ctx = ctx.clone();
|
||||
self.inbox.set_wake(move || ctx.request_repaint());
|
||||
self.inbox.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths to hand to OPEN: UTF-8 and non-empty, each once, in the order they arrived. A second
|
||||
/// copy of the same path (Finder sends one per selected item, and a drop can repeat) would open
|
||||
/// the drawing twice.
|
||||
fn openable(paths: impl IntoIterator<Item = PathBuf>) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for p in paths {
|
||||
if let Some(s) = p.to_str().filter(|s| !s.is_empty())
|
||||
&& !out.iter().any(|o| o == s)
|
||||
{
|
||||
out.push(s.to_string());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Dispatch a batch through the regular opening and unsaved-changes paths. Returns whether the
|
||||
/// window may close now; a queued quit must not bypass the Save / Don't Save / Cancel prompt.
|
||||
fn dispatch(events: impl IntoIterator<Item = Event>, app: &mut CadApp) -> bool {
|
||||
let mut quit = false;
|
||||
for e in events {
|
||||
match e {
|
||||
Event::Open(paths) => {
|
||||
for p in openable(paths) {
|
||||
app.open_path(std::path::Path::new(&p));
|
||||
}
|
||||
}
|
||||
Event::Quit => quit = true,
|
||||
}
|
||||
}
|
||||
quit && !app.request_quit()
|
||||
}
|
||||
|
||||
/// Drain the inbox each frame; a quit closes the window like Cmd+Q, prompting for unsaved drawings.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn poll(inbox: &Inbox, app: &mut CadApp, ctx: &egui::Context) {
|
||||
if dispatch(inbox.drain(), app) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Event, dispatch, openable};
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::closing::Choice;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct TestDir(PathBuf);
|
||||
|
||||
impl TestDir {
|
||||
fn new() -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-apple-events-{}-{}", std::process::id(), NEXT_DIR.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn app() -> CadApp {
|
||||
crate::install_io();
|
||||
// The DWG written and read here is the test's own synthetic file; the app starts its DWG
|
||||
// worker in `main`, which a test does not run.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
CadApp::new(Session::new(), Services::default())
|
||||
}
|
||||
|
||||
fn settle(app: &mut CadApp) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while app.opening.busy() && Instant::now() < deadline {
|
||||
app.finish_opening();
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
app.finish_opening();
|
||||
assert!(!app.opening.busy(), "background opening completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_order_and_drops_duplicates_and_empty_paths() {
|
||||
let paths = ["/a/plan.dxf", "", "/b/site.dwg", "/a/plan.dxf"].map(PathBuf::from);
|
||||
assert_eq!(openable(paths), ["/a/plan.dxf", "/b/site.dwg"]);
|
||||
assert!(openable(Vec::new()).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn skips_paths_that_are_not_utf8() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let bad = PathBuf::from(std::ffi::OsString::from_vec(vec![b'/', 0xff, b'.', b'd', b'x', b'f']));
|
||||
assert_eq!(openable([bad, PathBuf::from("/ok.dxf")]), ["/ok.dxf"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_dwg_and_dxf_without_replacing_an_unsaved_drawing() {
|
||||
// Writing and opening the DWG here needs the converter in this process: each test is its own.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let dir = TestDir::new();
|
||||
let dxf = dir.0.join("planta com espaços.dxf");
|
||||
let dwg = dir.0.join("Documentac\u{327}a\u{303}o.dwg");
|
||||
let bytes = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n10\n0\nENDSEC\n0\nEOF\n";
|
||||
let drawing = cadcraft_io::read(bytes, "synthetic.dxf").unwrap();
|
||||
std::fs::write(&dxf, bytes).unwrap();
|
||||
std::fs::write(&dwg, cadcraft_io::write(&drawing, "synthetic.dwg").unwrap()).unwrap();
|
||||
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!dispatch([Event::Open(vec![dxf.clone(), dwg.clone(), dxf.clone(), PathBuf::new()])], &mut app));
|
||||
settle(&mut app);
|
||||
|
||||
assert_eq!(app.session.docs.len(), 3, "each file is opened once alongside the unsaved drawing");
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
for path in [&dxf, &dwg] {
|
||||
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == path.to_str()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_open_reports_the_path_and_keeps_existing_drawings() {
|
||||
let dir = TestDir::new();
|
||||
let missing = dir.0.join("missing drawing.dwg");
|
||||
let mut app = app();
|
||||
let original = app.session.docs[0].uid;
|
||||
assert!(!dispatch([Event::Open(vec![missing.clone()])], &mut app));
|
||||
settle(&mut app);
|
||||
assert_eq!(app.session.docs.len(), 1);
|
||||
assert_eq!(app.session.docs[0].uid, original);
|
||||
assert!(app.session.log.iter().any(|line| line.contains(missing.to_str().unwrap())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_asks_before_closing_unsaved_work_and_can_be_cancelled() {
|
||||
let mut app = app();
|
||||
app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap();
|
||||
assert!(!dispatch([Event::Quit], &mut app), "must not issue a window close before the answer");
|
||||
assert!(app.close_prompt().is_some());
|
||||
assert!(!app.quit_confirmed);
|
||||
assert!(!app.quit_requested);
|
||||
app.answer_close(Choice::Cancel);
|
||||
assert!(app.close_prompt().is_none());
|
||||
assert!(app.session.docs[0].is_dirty());
|
||||
assert!(!app.quit_requested);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quit_event_can_close_a_clean_session() {
|
||||
let mut app = app();
|
||||
assert!(dispatch([Event::Quit], &mut app));
|
||||
assert!(app.close_prompt().is_none());
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,10 @@ pub(crate) const VARS: &[(&str, &str)] = &[
|
||||
/// `CADCRAFT_CONFIG_DIR`.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(crate) struct Env {
|
||||
/// Portable eframe storage file, kept with the other settings instead of the user profile.
|
||||
pub(crate) portable_storage_file: Option<PathBuf>,
|
||||
/// The settings folder (logs, autosave, workspace, plotters): `CADCRAFT_CONFIG_DIR`; else, when
|
||||
/// that is unset, the platform's (`cadcraft_engine::settings_dir::platform`). `None`: no
|
||||
/// that is unset, the portable directory or the platform's (`cadcraft_engine::settings_dir::platform`). `None`: no
|
||||
/// folder, because the variable is empty or blank (the way to run without one) or the
|
||||
/// platform has none.
|
||||
pub(crate) config_dir: Option<PathBuf>,
|
||||
@@ -63,7 +65,26 @@ pub(crate) struct Env {
|
||||
|
||||
impl Env {
|
||||
pub(crate) fn read() -> Env {
|
||||
Env::from_vars(|k| std::env::var_os(k))
|
||||
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(PathBuf::from));
|
||||
Self::from_vars_and_exe(|k| std::env::var_os(k), exe_dir.as_deref())
|
||||
}
|
||||
|
||||
fn from_vars_and_exe(var: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&std::path::Path>) -> Env {
|
||||
let mut vars = Env::from_vars(&var);
|
||||
// An explicit override (including blank, which disables settings) takes precedence.
|
||||
if var(CONFIG_DIR).is_none()
|
||||
&& let Some(exe) = exe_dir
|
||||
{
|
||||
match crate::portable::directory_in(exe) {
|
||||
Ok(Some(data)) => {
|
||||
vars.config_dir = Some(data.clone());
|
||||
vars.portable_storage_file = Some(data.join("app.ron"));
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => log::warn!("portable settings cannot be written ({error}); using the user profile"),
|
||||
}
|
||||
}
|
||||
vars
|
||||
}
|
||||
|
||||
/// [`Env::read`] with `var` looking a variable up.
|
||||
@@ -71,6 +92,7 @@ impl Env {
|
||||
let text = |k: &str| var(k).and_then(|v| v.into_string().ok()).filter(|v| !v.trim().is_empty());
|
||||
let switch = |k: &str| Switch::parse(k, var(k).map(|v| v.to_string_lossy().into_owned()).as_deref());
|
||||
Env {
|
||||
portable_storage_file: None,
|
||||
config_dir: match var(CONFIG_DIR) {
|
||||
Some(dir) if dir.to_str().is_some_and(|d| d.trim().is_empty()) => None,
|
||||
Some(dir) => Some(PathBuf::from(dir)),
|
||||
@@ -102,6 +124,37 @@ mod tests {
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
|
||||
#[test]
|
||||
fn portable_eframe_storage_is_a_file_inside_the_settings_directory() {
|
||||
let exe = std::env::temp_dir().join(format!("cadcraft-env-portable-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join("portable.txt"), "").unwrap();
|
||||
let vars = Env::from_vars_and_exe(env(&[("APPDATA", "/profile")]), Some(&exe));
|
||||
assert_eq!(vars.config_dir, Some(exe.join("CADCraftData")));
|
||||
let storage_file = vars.portable_storage_file.unwrap();
|
||||
assert_eq!(storage_file, exe.join("CADCraftData").join("app.ron"));
|
||||
assert_eq!(storage_file.parent(), vars.config_dir.as_deref());
|
||||
std::fs::write(&storage_file, r#"{"window":"saved window state"}"#).unwrap();
|
||||
let restarted = Env::from_vars_and_exe(env(&[("APPDATA", "/profile")]), Some(&exe));
|
||||
assert_eq!(restarted.portable_storage_file.as_ref(), Some(&storage_file));
|
||||
assert_eq!(std::fs::read_to_string(restarted.portable_storage_file.unwrap()).unwrap(), r#"{"window":"saved window state"}"#);
|
||||
std::fs::remove_dir_all(exe).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_override_skips_portable_probe() {
|
||||
let exe = std::env::temp_dir().join(format!("cadcraft-env-override-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
std::fs::write(exe.join("portable.txt"), "").unwrap();
|
||||
for value in ["/custom", "", " "] {
|
||||
let vars = Env::from_vars_and_exe(env(&[(CONFIG_DIR, value)]), Some(&exe));
|
||||
assert_eq!(vars.config_dir, (!value.trim().is_empty()).then(|| PathBuf::from(value)));
|
||||
assert_eq!(vars.portable_storage_file, None);
|
||||
assert!(!exe.join("CADCraftData").exists());
|
||||
}
|
||||
std::fs::remove_dir_all(exe).unwrap();
|
||||
}
|
||||
|
||||
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
|
||||
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
|
||||
}
|
||||
@@ -146,6 +199,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
read,
|
||||
Env {
|
||||
portable_storage_file: None,
|
||||
config_dir: Some(PathBuf::from("/private/cc")),
|
||||
locale: Some("cs-CZ".into()),
|
||||
vsync: Switch::On,
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
#![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;
|
||||
@@ -23,6 +25,7 @@ mod launch_args;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
mod portable;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod sheet;
|
||||
mod single_instance;
|
||||
@@ -53,6 +56,9 @@ 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 {
|
||||
@@ -101,6 +107,9 @@ 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
|
||||
@@ -173,6 +182,9 @@ pub fn install_io() {
|
||||
});
|
||||
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
|
||||
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
|
||||
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
|
||||
cadcraft_engine::cmd::file::set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
@@ -235,9 +247,12 @@ fn saved_window(app_ron: &str) -> bool {
|
||||
|
||||
/// The window state from the last session is saved and will be restored (#2595). A saved size
|
||||
/// below the minimum (seen on Windows: 64×64 points, which eframe restores un-maximized and
|
||||
/// unusable) is dropped first, so the window opens at its default size.
|
||||
fn restores_window() -> bool {
|
||||
let Some(path) = eframe::storage_dir(APP_ID).map(|dir| dir.join("app.ron")) else { return false };
|
||||
/// unusable) is dropped first, so the window opens at its default size. `portable_file`: the
|
||||
/// portable copy's settings file, read instead of the user profile's.
|
||||
fn restores_window(portable_file: Option<&std::path::Path>) -> bool {
|
||||
let Some(path) = portable_file.map(std::path::PathBuf::from).or_else(|| eframe::storage_dir(APP_ID).map(|dir| dir.join("app.ron"))) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(mut ron) = std::fs::read_to_string(&path) else { return false };
|
||||
// Through a temporary file: a failed write (a full disk) keeps the other saved settings.
|
||||
if let Some(fixed) = without_tiny_window(&ron)
|
||||
@@ -391,7 +406,8 @@ fn main() -> eframe::Result {
|
||||
// The crosshair is drawn by the app: present without a queue on Linux/BSD, where X11
|
||||
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
|
||||
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
|
||||
..window_options(restores_window(), stencil)
|
||||
persistence_path: vars.portable_storage_file.clone(),
|
||||
..window_options(restores_window(vars.portable_storage_file.as_deref()), stencil)
|
||||
};
|
||||
if let Some(icon) = app_icon() {
|
||||
options.viewport = options.viewport.with_icon(icon);
|
||||
@@ -430,6 +446,12 @@ 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,
|
||||
@@ -493,6 +515,14 @@ 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;
|
||||
@@ -520,6 +550,8 @@ 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,6 +144,10 @@ 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);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
//! Windows portable ZIP settings, selected by a marker beside the executable.
|
||||
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// A marker must be a file. Prove the data folder is writable before selecting it.
|
||||
pub(crate) fn directory_in(exe_dir: &Path) -> std::io::Result<Option<PathBuf>> {
|
||||
if !exe_dir.join("portable.txt").is_file() {
|
||||
return Ok(None);
|
||||
}
|
||||
let data = exe_dir.join("CADCraftData");
|
||||
std::fs::create_dir_all(&data)?;
|
||||
let probe = data.join(format!(".portable-write-test-{}", std::process::id()));
|
||||
// A byte, not just an empty file: a full drive can still make the file and refuse its data.
|
||||
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
let written = file.write_all(&[0]).and_then(|()| file.sync_all());
|
||||
drop(file);
|
||||
let removed = std::fs::remove_file(&probe);
|
||||
written?;
|
||||
removed?;
|
||||
Ok(Some(data))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct Temp(PathBuf);
|
||||
|
||||
impl Temp {
|
||||
fn new(name: &str) -> Self {
|
||||
let root = std::env::temp_dir().join(format!("cadcraft-portable-{}-{name}", std::process::id()));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
Self(root)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Temp {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absent_marker_and_directory_named_marker_do_not_enable_portable_mode() {
|
||||
let temp = Temp::new("no-marker");
|
||||
assert_eq!(directory_in(&temp.0).unwrap(), None);
|
||||
std::fs::create_dir(temp.0.join("portable.txt")).unwrap();
|
||||
assert_eq!(directory_in(&temp.0).unwrap(), None);
|
||||
assert!(!temp.0.join("CADCraftData").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marker_selects_adjacent_data_and_preserves_existing_settings() {
|
||||
let temp = Temp::new("settings-é");
|
||||
std::fs::write(temp.0.join("portable.txt"), "").unwrap();
|
||||
let data = directory_in(&temp.0).unwrap().unwrap();
|
||||
assert_eq!(data, temp.0.join("CADCraftData"));
|
||||
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 0);
|
||||
std::fs::write(data.join("workspace.json"), "existing settings").unwrap();
|
||||
assert_eq!(directory_in(&temp.0).unwrap(), Some(data.clone()));
|
||||
assert_eq!(std::fs::read_to_string(data.join("workspace.json")).unwrap(), "existing settings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_data_folder_is_an_error() {
|
||||
let temp = Temp::new("blocked");
|
||||
std::fs::write(temp.0.join("portable.txt"), "").unwrap();
|
||||
std::fs::write(temp.0.join("CADCraftData"), "a file blocks the directory").unwrap();
|
||||
assert!(directory_in(&temp.0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn independent_copies_have_independent_settings() {
|
||||
let a = Temp::new("copy-a");
|
||||
let b = Temp::new("copy-b");
|
||||
for temp in [&a, &b] {
|
||||
std::fs::write(temp.0.join("portable.txt"), "").unwrap();
|
||||
}
|
||||
assert_ne!(directory_in(&a.0).unwrap(), directory_in(&b.0).unwrap());
|
||||
}
|
||||
}
|
||||
@@ -331,16 +331,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for one test, and its socket path.
|
||||
/// A fresh folder for one test, and its socket path. Both names stay short: a Windows socket path
|
||||
/// holds at most 107 bytes, and a long `%TEMP%` already uses most of them.
|
||||
#[cfg(windows)]
|
||||
fn socket_dir(test: &str) -> (Cleanup, PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-single-instance-{}-{test}", std::process::id()));
|
||||
let dir = std::env::temp_dir().join(format!("cc-si-{}-{test}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("instance-test.sock");
|
||||
let path = dir.join("t.sock");
|
||||
(Cleanup(dir), path)
|
||||
}
|
||||
|
||||
/// Whether a socket can be bound at `path` here. It can't when `%TEMP%` is too long or lives
|
||||
/// under a redirected `%LOCALAPPDATA%`; the socket tests then skip instead of failing.
|
||||
#[cfg(windows)]
|
||||
fn can_bind(path: &std::path::Path) -> bool {
|
||||
let bound = uds_windows::UnixListener::bind(path)
|
||||
.map(drop)
|
||||
.map_err(|e| {
|
||||
// Straight to stderr: the test harness hides `eprintln!` from a test that passes.
|
||||
use std::io::Write;
|
||||
let _ = writeln!(std::io::stderr(), "skipping: no AF_UNIX socket at {}: {e}", path.display());
|
||||
})
|
||||
.is_ok();
|
||||
let _ = std::fs::remove_file(path);
|
||||
bound
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_test_socket_path_stays_far_below_the_limit() {
|
||||
// Its own folder, with a name as long as the longest one used here: `socket_dir` empties the
|
||||
// folder, and the launches test may be using "together" at the same moment.
|
||||
let (_dir, path) = socket_dir("lengthck");
|
||||
let added = path.as_os_str().len() - std::env::temp_dir().as_os_str().len();
|
||||
assert!(added <= 40, "{added} bytes on top of %TEMP%");
|
||||
}
|
||||
|
||||
/// The whole exchange over a real socket: a stale socket file is taken over, a later launch
|
||||
/// hands its files to that listener, one that asked for its own window gets it, and a request
|
||||
/// naming a relative path is refused.
|
||||
@@ -348,6 +375,9 @@ mod tests {
|
||||
#[test]
|
||||
fn a_later_launch_hands_its_files_to_the_first() {
|
||||
let (dir, path) = socket_dir("handoff");
|
||||
if !can_bind(&path) {
|
||||
return;
|
||||
}
|
||||
drop(uds_windows::UnixListener::bind(&path).unwrap());
|
||||
assert!(path.exists(), "the stale socket file stays behind");
|
||||
|
||||
@@ -369,6 +399,9 @@ mod tests {
|
||||
fn launches_at_once_open_one_window() {
|
||||
const LAUNCHES: usize = 6;
|
||||
let (dir, path) = socket_dir("together");
|
||||
if !can_bind(&path) {
|
||||
return;
|
||||
}
|
||||
let start = Arc::new(std::sync::Barrier::new(LAUNCHES));
|
||||
let launches: Vec<_> = (0..LAUNCHES)
|
||||
.map(|i| {
|
||||
|
||||
@@ -123,6 +123,11 @@ 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,6 +43,7 @@ mod curves;
|
||||
mod dim;
|
||||
mod fill;
|
||||
mod layout;
|
||||
mod proxy;
|
||||
mod text;
|
||||
mod wipeout;
|
||||
|
||||
@@ -52,12 +53,18 @@ 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 {
|
||||
@@ -264,7 +271,8 @@ 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())],
|
||||
EntityKind::Unknown(_) => Vec::new(),
|
||||
// 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(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,11 @@ 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")]
|
||||
|
||||
@@ -0,0 +1,717 @@
|
||||
//! 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, sources: Vec::new() }] }
|
||||
Region { loops: vec![HatchLoop { vertices, outer: true, boundary_flags: None, 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, sources: Vec::new() }
|
||||
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -371,6 +371,28 @@ 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
|
||||
@@ -516,8 +538,9 @@ 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),
|
||||
// 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),
|
||||
// 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),
|
||||
kind => {
|
||||
let mut b = Bounds2::EMPTY;
|
||||
for p in kind.prims() {
|
||||
@@ -718,12 +741,15 @@ 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 });
|
||||
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
|
||||
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")] })).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()
|
||||
);
|
||||
}
|
||||
|
||||
/// Groups 10/20 inside an application-defined `102 {...}` group belong to the application, not
|
||||
|
||||
@@ -53,6 +53,10 @@ 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.
|
||||
@@ -85,6 +89,9 @@ pub struct Foreign {
|
||||
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
|
||||
/// later save must not take it for this one (#2471).
|
||||
pub version: Option<String>,
|
||||
/// The file's registered applications (APPID names as read, in file order). Saving writes
|
||||
/// them all back, whether or not any xdata still names them.
|
||||
pub appids: Vec<String>,
|
||||
}
|
||||
|
||||
impl Foreign {
|
||||
@@ -103,6 +110,7 @@ impl Foreign {
|
||||
&& self.targets.is_empty()
|
||||
&& self.class_order.is_empty()
|
||||
&& self.data_store.is_empty()
|
||||
&& self.appids.is_empty()
|
||||
}
|
||||
|
||||
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
|
||||
@@ -126,22 +134,89 @@ pub fn sat_text_acis(u: &crate::Unknown, handle: Handle, stored: &std::collectio
|
||||
["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && !stored.contains(&handle) && has_sat_text(&u.tags)
|
||||
}
|
||||
|
||||
/// Whether a solid modeler entity can't be written to a DXF of 2013 and later (`modern`: SAT text
|
||||
/// with no data store record, [`sat_text_acis`]) or of 2010 and earlier (geometry only in the data
|
||||
/// store, which those files don't have, and no SAT text to write instead) (#2334).
|
||||
pub fn acis_left_out(u: &crate::Unknown, handle: Handle, stored: &std::collections::BTreeSet<Handle>, modern: bool) -> bool {
|
||||
if modern {
|
||||
return sat_text_acis(u, handle, stored);
|
||||
}
|
||||
["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && stored.contains(&handle) && !has_sat_text(&u.tags)
|
||||
}
|
||||
|
||||
/// The entities a DXF of 2013 or later leaves out because they hold SAT-text ACIS data
|
||||
/// ([`sat_text_acis`]), counted by DXF type, across model space, layouts and block definitions.
|
||||
pub fn sat_text_dropped(d: &crate::Drawing) -> BTreeMap<String, usize> {
|
||||
acis_dropped(d, true)
|
||||
}
|
||||
|
||||
/// The entities a DXF leaves out by [`acis_left_out`], counted like [`sat_text_dropped`].
|
||||
pub fn acis_dropped(d: &crate::Drawing, modern: bool) -> BTreeMap<String, usize> {
|
||||
let stored = d.foreign.data_store_entities();
|
||||
let mut out = BTreeMap::new();
|
||||
// The writer saves xrefs as references: their blocks (and `xref|` ones) hold nothing in the file.
|
||||
for e in saved_entities(d) {
|
||||
if let crate::EntityKind::Unknown(u) = &e.kind
|
||||
&& acis_left_out(u, e.handle, &stored, modern)
|
||||
{
|
||||
count(&mut out, &u.dxf_type);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The entities a DXF file holds: model space, layouts and block definitions. The writer saves
|
||||
/// xrefs as references: their blocks (and `xref|` ones) hold nothing in the file.
|
||||
fn saved_entities(d: &crate::Drawing) -> impl Iterator<Item = &std::sync::Arc<crate::Entity>> {
|
||||
let own_blocks = d.blocks.values().filter(|b| b.xref_path.is_none() && !xref_dependent(&b.name));
|
||||
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(own_blocks.map(|b| &b.entities));
|
||||
for e in stores.flat_map(|s| s.iter()) {
|
||||
if let crate::EntityKind::Unknown(u) = &e.kind
|
||||
&& sat_text_acis(u, e.handle, &stored)
|
||||
{
|
||||
let n: &mut usize = out.entry(u.dxf_type.to_ascii_uppercase()).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
stores.flat_map(|s| s.iter())
|
||||
}
|
||||
|
||||
/// Add one record of DXF type `kind` to `out`.
|
||||
fn count(out: &mut BTreeMap<String, usize>, kind: &str) {
|
||||
let n: &mut usize = out.entry(kind.to_ascii_uppercase()).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
|
||||
/// Whether a DXF type is a proxy (ACAD_PROXY_OBJECT, ACAD_PROXY_ENTITY).
|
||||
pub fn is_proxy(kind: &str) -> bool {
|
||||
let k = kind.trim();
|
||||
k.eq_ignore_ascii_case("ACAD_PROXY_OBJECT") || k.eq_ignore_ascii_case("ACAD_PROXY_ENTITY")
|
||||
}
|
||||
|
||||
/// Whether a proxy's groups (after its type) give it a separate string stream: a size above 0 in
|
||||
/// group 96 (2007) or 162 (2010 and later) after the `AcDbProxy…` marker. Before 2007 a proxy's
|
||||
/// strings are part of its data, so a file of an earlier version has no form for one that keeps
|
||||
/// them apart (#3229).
|
||||
pub fn proxy_has_string_stream<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)>) -> bool {
|
||||
let mut own = false;
|
||||
for (code, value) in groups {
|
||||
let v = value.as_ref().trim();
|
||||
match code {
|
||||
100 => own = own || v.to_ascii_lowercase().starts_with("acdbproxy"),
|
||||
96 | 162 if own && v.parse::<i64>().is_ok_and(|n| n > 0) => return true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The proxies a DXF earlier than 2007 leaves out because they have a separate string stream
|
||||
/// ([`proxy_has_string_stream`]), counted by DXF type.
|
||||
pub fn proxies_dropped_before_2007(d: &crate::Drawing) -> BTreeMap<String, usize> {
|
||||
let mut out = BTreeMap::new();
|
||||
let has_strings = |tags: &[RawTag]| proxy_has_string_stream(tags.iter().map(|t| (t.code, t.value.as_str())));
|
||||
for e in saved_entities(d) {
|
||||
if let crate::EntityKind::Unknown(u) = &e.kind
|
||||
&& is_proxy(&u.dxf_type)
|
||||
&& has_strings(&u.tags)
|
||||
{
|
||||
count(&mut out, &u.dxf_type);
|
||||
}
|
||||
}
|
||||
for o in d.foreign.objects.iter().filter(|o| is_proxy(&o.kind) && has_strings(&o.tags)) {
|
||||
count(&mut out, &o.kind);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -164,6 +239,23 @@ pub fn data_store_records(tags: &[RawTag]) -> Vec<&[RawTag]> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The ACIS version a modeler entity's SAT text declares (the first number of its first line:
|
||||
/// 400, 700, 21800…), if it has SAT text.
|
||||
pub fn sat_version(tags: &[RawTag]) -> Option<u32> {
|
||||
let marked = tags.iter().take_while(|r| r.code < 1000).any(|r| r.code == 100);
|
||||
let mut in_modeler = !marked;
|
||||
for r in tags.iter().take_while(|r| r.code < 1000) {
|
||||
if r.code == 100 {
|
||||
in_modeler = r.value.trim().eq_ignore_ascii_case("AcDbModelerGeometry");
|
||||
} else if in_modeler && r.code == 1 {
|
||||
let first = r.value.split_whitespace().next()?;
|
||||
// DXF before 2013 encodes SAT text: each character but a space is 159 minus it ("hoo" is 700).
|
||||
return first.parse().ok().or_else(|| first.bytes().map(|b| char::from(159u8.wrapping_sub(b))).collect::<String>().parse().ok());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether an entity's groups hold SAT text: groups 1 and 3 inside its `AcDbModelerGeometry`
|
||||
/// subclass. A file of a version before the subclass markers has no `100` groups: all of its
|
||||
/// groups (before the extended data) are the entity's.
|
||||
|
||||
@@ -57,6 +57,10 @@ 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()
|
||||
}
|
||||
@@ -346,6 +350,7 @@ 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));
|
||||
|
||||
@@ -821,6 +821,18 @@ pub struct PageSetup {
|
||||
/// save keeps where the sheet sits; `None` for a page CADCraft made, written as 0,0 (#2109).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub image_origin: Option<Vec2>,
|
||||
/// The plot layout flags (DXF group 70 of AcDbPlotSettings) as the file had them. Saving keeps
|
||||
/// the bits CADCraft doesn't model (plot paper space last, plot with plot styles, standard
|
||||
/// scale and the rest) as read instead of forcing its defaults (#3227); `None` for page setups
|
||||
/// made in CADCraft.
|
||||
#[serde(skip)]
|
||||
pub file_plot_flags: Option<i64>,
|
||||
/// The standard scale the file chose (DXF group 75, such as 25 for 1:50) and the plot scale it
|
||||
/// was read with. While the scale is unchanged, saving keeps that choice and the standard scale
|
||||
/// flag instead of writing the scale as a custom one; `None` for a custom scale, scaled to
|
||||
/// fit, or a page setup made in CADCraft.
|
||||
#[serde(skip)]
|
||||
pub file_standard_scale: Option<(i64, f64)>,
|
||||
}
|
||||
|
||||
impl Default for PageSetup {
|
||||
@@ -844,6 +856,8 @@ impl Default for PageSetup {
|
||||
paper_mm: None,
|
||||
file_paper: None,
|
||||
image_origin: None,
|
||||
file_plot_flags: None,
|
||||
file_standard_scale: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,9 @@ 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)")
|
||||
@@ -713,6 +716,88 @@ 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;
|
||||
|
||||
@@ -8,7 +8,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::curves::KW;
|
||||
use super::super::file::{drops_unknown, new_folder, not_saved, not_saved_message, report_new_folder, report_not_saved};
|
||||
use super::super::file::{Version, lost_message, lost_writing, new_folder, own_version, report_lost, report_new_folder};
|
||||
use super::super::machines::{SelOutcome, SelectPhase};
|
||||
use super::super::modify::erase_kept;
|
||||
use super::super::{CommandSpec, bad, point_param, str_param, targets};
|
||||
@@ -16,7 +16,9 @@ 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? | handles?, base?}")
|
||||
CommandSpec::new("wblock", "Write Block", run_wblock)
|
||||
.alias(&["w"])
|
||||
.params("{path, name? (a block, or \"*\" for the whole drawing) | handles?, base?}")
|
||||
}
|
||||
|
||||
/// -WBLOCK erases the objects it writes, whatever its mOde option says: AutoCAD 2024 does, and
|
||||
@@ -44,13 +46,14 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost) = match str_param(p, "name") {
|
||||
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)))?,
|
||||
};
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -61,7 +64,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string();
|
||||
let base = point_param(p, "base");
|
||||
let folder = new_folder(&path);
|
||||
let (entities, bytes, lost) = match str_param(p, "name") {
|
||||
let (entities, bytes, lost, version) = match str_param(p, "name") {
|
||||
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
|
||||
None => {
|
||||
let hs = targets(s, p)?;
|
||||
@@ -76,16 +79,17 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let mut r = json!({ "path": path, "entities": entities, "bytes": bytes });
|
||||
report_new_folder(s, &mut r, folder);
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
report_lost(s, &mut r, &path, version, &lost);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Write `what` to `path` through the io hooks; the objects written, the file's size and what a
|
||||
/// DWG file left out, for the caller to report as a save does. The
|
||||
/// Write `what` to `path` through the io hooks; the objects written, the file's size, what the
|
||||
/// file left out (a DWG's unwritten types, a DXF before 2007's proxies with string streams) and
|
||||
/// the version it was written at, for the caller to report as a save does. The
|
||||
/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units
|
||||
/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and
|
||||
/// scaled on insert, and its defaults (text size, current styles, annotation scales).
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>)> {
|
||||
fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap<String, usize>, Version)> {
|
||||
let src = s.doc()?;
|
||||
// The base point becomes the written drawing's origin: by default 0,0 for objects and the
|
||||
// block's base point for a block.
|
||||
@@ -108,13 +112,15 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi
|
||||
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
let lost = if drops_unknown(path) { not_saved(&d) } else { BTreeMap::new() };
|
||||
Ok((d.model.len(), bytes.len(), lost))
|
||||
// The written drawing's own version: the writer is given no other.
|
||||
let version = own_version(&d, path);
|
||||
let lost = lost_writing(&d, path, version);
|
||||
Ok((d.model.len(), bytes.len(), lost, version))
|
||||
}
|
||||
|
||||
/// Say on the command line what the written DWG file left out.
|
||||
fn echo_not_saved(s: &mut Session, lost: &BTreeMap<String, usize>) {
|
||||
if let Some(msg) = not_saved_message(lost) {
|
||||
/// Say on the command line what the file written at `path` and `version` left out.
|
||||
fn echo_not_saved(s: &mut Session, path: &str, version: Version, lost: &BTreeMap<String, usize>) {
|
||||
if let Some(msg) = lost_message(path, version, lost) {
|
||||
s.echo(msg);
|
||||
}
|
||||
}
|
||||
@@ -335,7 +341,7 @@ impl DashWblockM {
|
||||
|
||||
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
|
||||
match write(s, "-wblock", &self.path, what) {
|
||||
Ok((.., lost)) => echo_not_saved(s, &lost),
|
||||
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
}
|
||||
Ok(Step::Done)
|
||||
@@ -346,8 +352,8 @@ impl DashWblockM {
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
|
||||
Ok((.., lost)) => {
|
||||
echo_not_saved(s, &lost);
|
||||
Ok((.., lost, version)) => {
|
||||
echo_not_saved(s, &self.path, version, &lost);
|
||||
erase(s, hs)?;
|
||||
}
|
||||
Err(e) => s.echo(e.to_string()),
|
||||
|
||||
@@ -39,6 +39,10 @@ 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() {
|
||||
@@ -53,6 +57,7 @@ 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)?)
|
||||
}
|
||||
@@ -174,6 +179,7 @@ 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,
|
||||
@@ -191,6 +197,7 @@ 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);
|
||||
@@ -259,6 +266,10 @@ 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"])
|
||||
.base(a),
|
||||
.corner(a),
|
||||
_ if self.lines.is_empty() => Prompt::new("Enter text (use \\P for new paragraphs)", Accept::TEXT),
|
||||
_ => Prompt::new("Enter next line of text (empty line to finish)", Accept::TEXT),
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::{
|
||||
Accept, Chain, Circle, Ellipse, EntityKind, Handle, Input, Interactive, Line, MAX_GEN, PolyVertex, Polyline, Prompt, Result, Session, Step,
|
||||
Value, Vec2, added, bad, bool_or, curves, lwpoly, number, other, point_param, points_param, rect_vertices, shoelace, str_param,
|
||||
};
|
||||
use cadcraft_doc::RawTag;
|
||||
|
||||
// =====================================================================================
|
||||
// REVCLOUD
|
||||
@@ -20,6 +21,11 @@ fn default_arc_len(s: &Session) -> f64 {
|
||||
d.map(|d| d.header.f64("REVCLOUDARCLEN", if metric { 15.0 } else { 0.5 })).unwrap_or(0.5).max(1e-6)
|
||||
}
|
||||
|
||||
/// Maximum arc length remembered between REVCLOUD runs (CADCraft-only state, not an AutoCAD variable); never below `min`.
|
||||
fn default_max_arc_len(s: &Session, min: f64) -> f64 {
|
||||
s.doc().ok().map_or(min, |d| d.header.f64("CADCRAFT_REVCLOUDMAXARCLEN", min)).max(min)
|
||||
}
|
||||
|
||||
/// Bulged closed polyline vertices for a revision cloud around `boundary`.
|
||||
pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, reverse: bool) -> Option<Vec<PolyVertex>> {
|
||||
let mut pts: Vec<Vec2> = Vec::new();
|
||||
@@ -94,6 +100,38 @@ fn cloud_entity(vs: Vec<PolyVertex>, calligraphy: bool, arc_len: f64) -> EntityK
|
||||
lwpoly(vs, true)
|
||||
}
|
||||
|
||||
/// The application name of the xdata that marks a closed polyline as a revision cloud.
|
||||
const REVCLOUD_APP: &str = "RevcloudProps";
|
||||
|
||||
/// Adds a revision cloud with its `RevcloudProps` xdata (how AutoCAD and other readers tell a
|
||||
/// revision cloud from a polyline). Made from object `src`, the cloud takes the object's place
|
||||
/// and properties.
|
||||
fn add_cloud(s: &mut Session, vs: Vec<PolyVertex>, calligraphy: bool, arc_len: f64, src: Option<Handle>) -> Result<Handle> {
|
||||
let h = s.add_entity(cloud_entity(vs, calligraphy, arc_len))?;
|
||||
let mut common = match src {
|
||||
Some(src) => curves::entity(s, src)?.common,
|
||||
None => curves::entity(s, h)?.common,
|
||||
};
|
||||
let mut keep = true;
|
||||
common.xdata.retain(|t| {
|
||||
if t.code == 1001 {
|
||||
keep = !t.value.trim().eq_ignore_ascii_case(REVCLOUD_APP);
|
||||
}
|
||||
keep
|
||||
});
|
||||
common.xdata.extend([
|
||||
RawTag { code: 1001, value: REVCLOUD_APP.into() },
|
||||
RawTag { code: 1070, value: "0".into() },
|
||||
RawTag { code: 1040, value: arc_len.to_string() },
|
||||
]);
|
||||
let d = s.doc_mut()?;
|
||||
d.modify_entity(h, |e| e.common = common)?;
|
||||
if let Some(src) = src {
|
||||
d.remove_entity(src);
|
||||
}
|
||||
Ok(h)
|
||||
}
|
||||
|
||||
pub(super) fn run_revcloud(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let arc_len = p.get("arcLength").and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0).unwrap_or_else(|| default_arc_len(s));
|
||||
let reverse = bool_or(p, "reverse", false);
|
||||
@@ -113,13 +151,7 @@ pub(super) fn run_revcloud(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad("revcloud", "too many points"));
|
||||
}
|
||||
let vs = cloud_vertices(&pts, arc_len, per_edge, reverse).ok_or_else(|| bad("revcloud", "the boundary needs an area"))?;
|
||||
let h = s.add_entity(cloud_entity(vs, calligraphy, arc_len))?;
|
||||
if let Some(src) = src {
|
||||
let common = curves::entity(s, src)?.common;
|
||||
let d = s.doc_mut()?;
|
||||
d.modify_entity(h, |e| e.common = common)?;
|
||||
d.remove_entity(src);
|
||||
}
|
||||
let h = add_cloud(s, vs, calligraphy, arc_len, src)?;
|
||||
added(h)
|
||||
}
|
||||
|
||||
@@ -127,15 +159,31 @@ pub(super) struct RevcloudM {
|
||||
kind: CloudKind,
|
||||
pts: Vec<Vec2>,
|
||||
arc_len: f64,
|
||||
max_arc_len: f64,
|
||||
asking_arc: bool,
|
||||
asking_max: bool,
|
||||
object: bool,
|
||||
/// Outline of the picked object while "Reverse direction" is being asked.
|
||||
picked: Option<(Handle, Vec<Vec2>)>,
|
||||
calligraphy: bool,
|
||||
asking_style: bool,
|
||||
}
|
||||
|
||||
impl RevcloudM {
|
||||
pub(super) fn new(s: &Session, kind: CloudKind) -> Self {
|
||||
RevcloudM { kind, pts: Vec::new(), arc_len: default_arc_len(s), asking_arc: false, object: false, calligraphy: false, asking_style: false }
|
||||
let arc_len = default_arc_len(s);
|
||||
RevcloudM {
|
||||
kind,
|
||||
pts: Vec::new(),
|
||||
arc_len,
|
||||
max_arc_len: default_max_arc_len(s, arc_len),
|
||||
asking_arc: false,
|
||||
asking_max: false,
|
||||
object: false,
|
||||
picked: None,
|
||||
calligraphy: false,
|
||||
asking_style: false,
|
||||
}
|
||||
}
|
||||
fn boundary(&self, extra: Option<Vec2>) -> Vec<Vec2> {
|
||||
let mut pts = self.pts.clone();
|
||||
@@ -151,7 +199,7 @@ impl RevcloudM {
|
||||
let b = self.boundary(None);
|
||||
match cloud_vertices(&b, self.arc_len, self.kind != CloudKind::Free, false) {
|
||||
Some(vs) => {
|
||||
s.add_entity(cloud_entity(vs, self.calligraphy, self.arc_len))?;
|
||||
add_cloud(s, vs, self.calligraphy, self.arc_len, None)?;
|
||||
s.echo("Revision cloud finished.");
|
||||
Ok(Step::Done)
|
||||
}
|
||||
@@ -170,13 +218,19 @@ impl Interactive for RevcloudM {
|
||||
CloudKind::Poly => "Polygonal",
|
||||
CloudKind::Free => "Freehand",
|
||||
};
|
||||
s.echo(format!("Minimum arc length: {0:.4} Maximum arc length: {0:.4} Style: Normal Type: {t}", self.arc_len));
|
||||
s.echo(format!("Minimum arc length: {0:.4} Maximum arc length: {1:.4} Style: Normal Type: {t}", self.arc_len, self.max_arc_len));
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
if self.picked.is_some() {
|
||||
return Prompt::new("Reverse direction", curves::KW).kw(&["Yes", "No"]).default("No");
|
||||
}
|
||||
if self.asking_arc {
|
||||
return Prompt::new("Specify minimum length of arc", Accept::NUMBER).default(format!("{:.4}", self.arc_len));
|
||||
}
|
||||
if self.asking_max {
|
||||
return Prompt::new("Specify maximum length of arc", Accept::NUMBER).default(format!("{:.4}", self.max_arc_len));
|
||||
}
|
||||
if self.asking_style {
|
||||
return Prompt::new("Select arc style", curves::KW).kw(&["Normal", "Calligraphy"]).default("Normal");
|
||||
}
|
||||
@@ -197,13 +251,34 @@ impl Interactive for RevcloudM {
|
||||
}
|
||||
}
|
||||
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
||||
if let Some((h, pts)) = self.picked.take() {
|
||||
let reverse = matches!(&i, Input::Keyword(k) | Input::Text(k) if k.to_ascii_lowercase().starts_with('y'));
|
||||
let vs = cloud_vertices(&pts, self.arc_len, false, reverse).ok_or_else(|| other("The object has no area."))?;
|
||||
add_cloud(s, vs, self.calligraphy, self.arc_len, Some(h))?;
|
||||
s.echo("Revision cloud finished.");
|
||||
return Ok(Step::Done);
|
||||
}
|
||||
if self.asking_arc {
|
||||
if let Input::Text(t) = &i {
|
||||
let v = number(t).filter(|v| *v > 0.0).ok_or_else(|| other("Requires a positive value."))?;
|
||||
self.arc_len = v;
|
||||
s.doc_mut()?.header.set_f64("REVCLOUDARCLEN", v);
|
||||
self.max_arc_len = self.max_arc_len.max(v);
|
||||
let max = self.max_arc_len;
|
||||
let d = s.doc_mut()?;
|
||||
d.header.set_f64("REVCLOUDARCLEN", v);
|
||||
d.header.set_f64("CADCRAFT_REVCLOUDMAXARCLEN", max);
|
||||
}
|
||||
self.asking_arc = false;
|
||||
self.asking_max = true;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.asking_max {
|
||||
if let Input::Text(t) = &i {
|
||||
let v = number(t).filter(|v| *v >= self.arc_len).ok_or_else(|| other("Requires a value not less than the minimum arc length."))?;
|
||||
self.max_arc_len = v;
|
||||
s.doc_mut()?.header.set_f64("CADCRAFT_REVCLOUDMAXARCLEN", v);
|
||||
}
|
||||
self.asking_max = false;
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.asking_style {
|
||||
@@ -214,17 +289,19 @@ impl Interactive for RevcloudM {
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
if self.object {
|
||||
let Input::Point(p) = i else { return if i == Input::Enter { Ok(Step::Cancel) } else { Ok(Step::Continue) } };
|
||||
let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?;
|
||||
let h = match i {
|
||||
Input::Point(p) => curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?,
|
||||
Input::Pick(hs) => hs.first().copied().ok_or_else(|| other("*Invalid selection*"))?,
|
||||
Input::Enter => return Ok(Step::Cancel),
|
||||
_ => return Ok(Step::Continue),
|
||||
};
|
||||
let pts = object_outline(s, h)?;
|
||||
let vs = cloud_vertices(&pts, self.arc_len, false, false).ok_or_else(|| other("The object has no area."))?;
|
||||
let nh = s.add_entity(cloud_entity(vs, self.calligraphy, self.arc_len))?;
|
||||
let common = curves::entity(s, h)?.common;
|
||||
let d = s.doc_mut()?;
|
||||
d.modify_entity(nh, |e| e.common = common)?;
|
||||
d.remove_entity(h);
|
||||
s.echo("Revision cloud finished.");
|
||||
return Ok(Step::Done);
|
||||
if cloud_vertices(&pts, self.arc_len, false, false).is_none() {
|
||||
return Err(other("The object has no area."));
|
||||
}
|
||||
self.object = false;
|
||||
self.picked = Some((h, pts));
|
||||
return Ok(Step::Continue);
|
||||
}
|
||||
match i {
|
||||
Input::Keyword(k) => {
|
||||
|
||||
@@ -755,10 +755,44 @@ fn revcloud_json() {
|
||||
assert!(s.execute("revcloud", &json!({"p1": [0, 0], "p2": [1e300, 1e300], "arcLength": 1e-300})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcloud_saves_revcloudprops_xdata() {
|
||||
let mut s = Session::new();
|
||||
let props = |s: &Session| {
|
||||
let xd = s.doc().unwrap().model.last().unwrap().common.xdata.clone();
|
||||
xd.iter().map(|t| (t.code, t.value.clone())).collect::<Vec<_>>()
|
||||
};
|
||||
let want = vec![(1001, "RevcloudProps".to_string()), (1070, "0".to_string()), (1040, "2".to_string())];
|
||||
s.execute("revcloud", &json!({"p1": [0, 0], "p2": [100, 50], "arcLength": 2})).unwrap();
|
||||
assert_eq!(props(&s), want);
|
||||
let dxf = cadcraft_io::write_dxf(s.doc().unwrap());
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
let groups: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect();
|
||||
assert!(groups.contains(&("1001", "RevcloudProps")), "no RevcloudProps xdata in the DXF");
|
||||
let appid = groups
|
||||
.iter()
|
||||
.enumerate()
|
||||
.any(|(i, g)| *g == ("0", "APPID") && groups[i + 1..].iter().take_while(|g| g.0 != "0").any(|g| *g == ("2", "RevcloudProps")));
|
||||
assert!(appid, "no RevcloudProps APPID record");
|
||||
// Made from an object: the object's properties are kept, the cloud is still a revision cloud.
|
||||
let c = h(&s.execute("circle", &json!({"center": [10, 10], "radius": 1})).unwrap());
|
||||
s.execute("revcloud", &json!({"handle": c, "arcLength": 2})).unwrap();
|
||||
assert_eq!(props(&s), want);
|
||||
// Interactive (the arc length takes a minimum and a maximum, #1714).
|
||||
s.cmdline("revcloud a 2 2").unwrap();
|
||||
s.cmdline("0,0 4,2").unwrap();
|
||||
assert_eq!(props(&s), want);
|
||||
// Interactive Object, after the "Reverse direction" prompt.
|
||||
s.execute("rectang", &json!({"p1": [20, 20], "p2": [24, 22]})).unwrap();
|
||||
s.cmdline("revcloud o 20,21 n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(props(&s), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcloud_command_line() {
|
||||
let mut s = Session::new();
|
||||
s.cmdline("revcloud a 1").unwrap();
|
||||
s.cmdline("revcloud a 1 1").unwrap();
|
||||
s.cmdline("0,0 4,2").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(matches!(last(&s), EntityKind::LwPolyline(p) if p.vertices.len() == 12));
|
||||
@@ -771,11 +805,50 @@ fn revcloud_command_line() {
|
||||
assert_eq!(kinds(&s).len(), 3);
|
||||
// Object option converts a closed polyline.
|
||||
s.execute("rectang", &json!({"p1": [10, 10], "p2": [12, 12]})).unwrap();
|
||||
s.cmdline("revcloud o 10,11").unwrap();
|
||||
s.cmdline("revcloud o 10,11 n").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
assert_eq!(kinds(&s).len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcloud_object_accepts_entity_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("rectang", &json!({"p1": [0, 0], "p2": [4, 4]})).unwrap();
|
||||
let h = s.doc().unwrap().model.last().unwrap().handle;
|
||||
s.cmdline("revcloud o").unwrap();
|
||||
s.input(Input::Pick(vec![h])).unwrap();
|
||||
// Object asks "Reverse direction" next (#1714); Enter keeps it.
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(kinds(&s).len(), 1);
|
||||
assert!(matches!(last(&s), EntityKind::LwPolyline(p) if p.vertices.len() > 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revcloud_arc_length_asks_max_and_object_asks_reverse() {
|
||||
let mut s = Session::new();
|
||||
s.execute("rectang", &json!({"p1": [10, 10], "p2": [12, 12]})).unwrap();
|
||||
s.cmdline("revcloud a 200 800").unwrap();
|
||||
assert!(s.prompt_text().contains("first corner"), "{}", s.prompt_text());
|
||||
s.cmdline("0,0 2000,1000").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
s.cmdline("revcloud").unwrap();
|
||||
assert!(s.log.iter().any(|l| l.contains("Minimum arc length: 200.0000 Maximum arc length: 800.0000")), "{:?}", s.log);
|
||||
s.cmdline("o").unwrap();
|
||||
s.cmdline("10,11").unwrap();
|
||||
assert!(s.running.is_some() && s.prompt_text().contains("Reverse direction"), "{}", s.prompt_text());
|
||||
s.cmdline("n").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
// Yes reverses the arcs (negative bulges).
|
||||
s.execute("rectang", &json!({"p1": [30, 30], "p2": [32, 32]})).unwrap();
|
||||
s.cmdline("revcloud o 30,31 y").unwrap();
|
||||
assert!(s.running.is_none());
|
||||
match last(&s) {
|
||||
EntityKind::LwPolyline(p) => assert!(p.vertices.iter().all(|v| v.bulge < 0.0)),
|
||||
k => panic!("{k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- BREAKLINE ----------------
|
||||
|
||||
fn breakline_points(s: &Session) -> Vec<(f64, f64)> {
|
||||
|
||||
@@ -593,7 +593,9 @@ 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())) {
|
||||
targets(s, p)?
|
||||
// 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()
|
||||
} else {
|
||||
// Nothing to select with: the selection stays, also what the active viewport does not draw.
|
||||
s.stored_selection()
|
||||
|
||||
+145
-43
@@ -83,6 +83,40 @@ pub fn object_records() -> Option<ObjectRecords> {
|
||||
OBJECT_RECORDS.get().copied()
|
||||
}
|
||||
|
||||
/// What a DXF of a version before 2007 leaves out of a drawing because it has no form for a
|
||||
/// proxy's separate string stream, counted by DXF type (installed by the app with the DXF writer,
|
||||
/// a lower layer, which finds it by writing; see `cadcraft_io::proxies_lost`). Without it the
|
||||
/// proxies themselves are counted ([`cadcraft_doc::foreign::proxies_dropped_before_2007`]).
|
||||
pub type ProxiesLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
|
||||
|
||||
static PROXIES_LOST: OnceLock<ProxiesLost> = OnceLock::new();
|
||||
|
||||
pub fn set_proxies_lost(f: ProxiesLost) {
|
||||
let _ = PROXIES_LOST.set(f);
|
||||
}
|
||||
|
||||
/// Version-specific DWG compatibility omissions, counted by the host's actual writer.
|
||||
pub type DwgCompatLost = fn(&Drawing, Version) -> std::collections::BTreeMap<String, usize>;
|
||||
|
||||
static DWG_COMPAT_LOST: OnceLock<DwgCompatLost> = OnceLock::new();
|
||||
|
||||
pub fn set_dwg_compat_lost(f: DwgCompatLost) {
|
||||
let _ = DWG_COMPAT_LOST.set(f);
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of `d` for its proxies' string streams (#3229): empty from
|
||||
/// 2007 on. `d` is written as committed (a reference edit's working copies are not in the file).
|
||||
fn proxies_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
if version >= Version::R2007 {
|
||||
return Default::default();
|
||||
}
|
||||
let d = d.committed();
|
||||
match PROXIES_LOST.get() {
|
||||
Some(f) => f(&d, version),
|
||||
None => cadcraft_doc::foreign::proxies_dropped_before_2007(&d),
|
||||
}
|
||||
}
|
||||
|
||||
/// COMPARE (drawing comparison).
|
||||
pub mod compare;
|
||||
|
||||
@@ -792,15 +826,23 @@ fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The version a drawing is saved in at `path` when none is asked for: its `$ACADVER` (2018 by
|
||||
/// default), and for DWG at least 2004 (the io layer's rule: R2000 DWG has no true colours).
|
||||
fn drawing_version(s: &Session, path: &str) -> Version {
|
||||
let v = s
|
||||
.state()
|
||||
.ok()
|
||||
.and_then(|st| st.drawing().header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver))
|
||||
.unwrap_or_default();
|
||||
pub fn drawing_version(s: &Session, path: &str) -> Version {
|
||||
let v = s.state().ok().and_then(|st| acadver(st.drawing())).unwrap_or_default();
|
||||
if is_dxf(path) { v } else { v.max(Version::R2004) }
|
||||
}
|
||||
|
||||
/// The version `d` is saved in at `path` when none is asked for, as [`drawing_version`] says for
|
||||
/// the active drawing.
|
||||
pub(crate) fn own_version(d: &Drawing, path: &str) -> Version {
|
||||
let v = acadver(d).unwrap_or_default();
|
||||
if is_dxf(path) { v } else { v.max(Version::R2004) }
|
||||
}
|
||||
|
||||
/// The version `d`'s `$ACADVER` names.
|
||||
fn acadver(d: &Drawing) -> Option<Version> {
|
||||
d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver)
|
||||
}
|
||||
|
||||
/// `document.switch index`: require the index, cancel the running command, activate that drawing and bump the epoch even if it was already active (screenshot identity).
|
||||
fn run_switch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("document.switch", "`index` is required"))? as usize;
|
||||
@@ -826,8 +868,9 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
|
||||
if drops_unknown(format!("drawing.{fmt}")) {
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
} else if version >= Version::R2013 && is_dxf_file(format!("drawing.{fmt}")) {
|
||||
report_sat_text_dropped(s, &mut r);
|
||||
} else if is_dxf_file(format!("drawing.{fmt}")) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
@@ -862,10 +905,12 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
|
||||
let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities));
|
||||
for e in stores.flat_map(|s| s.iter()) {
|
||||
if let cadcraft_doc::EntityKind::Unknown(u) = &e.kind {
|
||||
// A DWG before 2013 writes a solid's SAT text as it is; from 2013 the geometry has to be
|
||||
// in the data store, and SAT text alone is lost (#2334).
|
||||
// A DWG before 2013 keeps a solid's SAT text of ACIS 7.0 and later; from 2013 the geometry
|
||||
// has to be in the data store, and SAT text alone is lost. Older SAT (ACIS 4.0, as ZWCAD
|
||||
// writes to DXF 2000) reaches the DWG without usable geometry: ZWCAD 2025 opens such a
|
||||
// solid as a proxy or an empty body (#2334).
|
||||
if MODELER_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t))
|
||||
&& (stored.contains(&e.handle) || (version < Version::R2013 && cadcraft_doc::foreign::has_sat_text(&u.tags)))
|
||||
&& (stored.contains(&e.handle) || (version < Version::R2013 && cadcraft_doc::foreign::sat_version(&u.tags).is_some_and(|v| v >= 700)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -887,6 +932,12 @@ 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
|
||||
}
|
||||
|
||||
@@ -907,9 +958,8 @@ pub fn not_saved_message(lost: &std::collections::BTreeMap<String, usize>) -> Op
|
||||
/// reports the same list afterwards to callers that never get a dialog.
|
||||
pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap<String, usize> {
|
||||
let version = drawing_version(s, path);
|
||||
if is_dxf_file(path) && version >= Version::R2013 {
|
||||
// The drawing a file holds: the host while the Block Editor is open.
|
||||
return s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default();
|
||||
if is_dxf_file(path) {
|
||||
return host_dxf_lost(s, version);
|
||||
}
|
||||
if !drops_unknown(path) {
|
||||
return Default::default();
|
||||
@@ -917,16 +967,85 @@ pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap<Strin
|
||||
s.doc().map(|d| not_saved_as(d, version)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Report what the file `path`, just written at the drawing's own version, left out.
|
||||
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
|
||||
if is_dxf_file(path) {
|
||||
if drawing_version(s, path) >= Version::R2013 {
|
||||
report_sat_text_dropped(s, r);
|
||||
}
|
||||
} else {
|
||||
let lost = loss_on_save(s, path);
|
||||
report_not_saved(s, r, &lost);
|
||||
/// What a DXF of `version` leaves out of the drawing a save writes: the host while the Block
|
||||
/// Editor is open ([`dxf_lost`]).
|
||||
fn host_dxf_lost(s: &Session, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
s.state().map(|st| dxf_lost(st.drawing(), version)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What a DXF of `version` leaves out of `d`: solid modeler entities whose ACIS geometry that
|
||||
/// version has no place for (#2334: SAT text alone from 2013, data store geometry alone before),
|
||||
/// and before 2007 proxies whose strings it can't hold, with the objects that go with them
|
||||
/// (#3229). The two never name the same record: a solid lost before 2013 is lost in 2007 too.
|
||||
fn dxf_lost(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
let mut lost = cadcraft_doc::foreign::acis_dropped(d, version >= Version::R2013);
|
||||
for (kind, n) in proxies_lost(d, version) {
|
||||
let m = lost.entry(kind).or_insert(0);
|
||||
*m = m.saturating_add(n);
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
/// What a file at `path` leaves out of `d`, written at `version`: empty when it keeps everything.
|
||||
pub(crate) fn lost_writing(d: &Drawing, path: &str, version: Version) -> std::collections::BTreeMap<String, usize> {
|
||||
if !is_dxf_file(path) {
|
||||
return if drops_unknown(path) { not_saved_as(d, version) } else { Default::default() };
|
||||
}
|
||||
dxf_lost(d, version)
|
||||
}
|
||||
|
||||
/// Report what the file `path`, just written from the active document (what EXPORT writes: the
|
||||
/// block while the Block Editor is open) at its own version, left out.
|
||||
pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) {
|
||||
let Ok(d) = s.doc() else { return };
|
||||
let version = own_version(d, path);
|
||||
let lost = lost_writing(d, path, version);
|
||||
report_lost(s, r, path, version, &lost);
|
||||
}
|
||||
|
||||
/// Say on the command line what the file `path`, written at `version`, couldn't keep (`lost`),
|
||||
/// in the words for that kind of file, and list it in the result's `notSaved`.
|
||||
pub(crate) fn report_lost(s: &mut Session, r: &mut Value, path: &str, version: Version, lost: &std::collections::BTreeMap<String, usize>) {
|
||||
match lost_message(path, version, lost) {
|
||||
Some(msg) => s.echo(msg),
|
||||
None => return,
|
||||
}
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("notSaved".into(), json!(lost));
|
||||
}
|
||||
}
|
||||
|
||||
/// The command-line warning for what a file at `path` written at `version` left out, or `None`
|
||||
/// when it kept everything.
|
||||
pub(crate) fn lost_message(path: &str, version: Version, lost: &std::collections::BTreeMap<String, usize>) -> Option<String> {
|
||||
if !is_dxf_file(path) {
|
||||
return not_saved_message(lost);
|
||||
}
|
||||
if lost.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Solids (#2334) and, before 2007, proxies and what goes with them (#3229), each with its reason.
|
||||
let list = |solids: bool| -> Vec<String> {
|
||||
lost.iter().filter(|(t, _)| MODELER_TYPES.iter().any(|m| t.eq_ignore_ascii_case(m)) == solids).map(|(t, n)| format!("{n} {t}")).collect()
|
||||
};
|
||||
let mut parts = Vec::new();
|
||||
let solids = list(true);
|
||||
if !solids.is_empty() {
|
||||
let why = if version >= Version::R2013 {
|
||||
"2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them"
|
||||
} else {
|
||||
"2010 and earlier have no data store, where these entities keep their ACIS geometry; save as 2013 or later to keep them"
|
||||
};
|
||||
parts.push(format!("Not saved in the DXF file ({why}): {}", solids.join(", ")));
|
||||
}
|
||||
let others = list(false);
|
||||
if !others.is_empty() {
|
||||
parts.push(format!(
|
||||
"Not saved in the DXF file (proxies that keep their strings apart from their data, which DXF before 2007 can't hold, and the objects that go with them; save as 2007 or later to keep them): {}",
|
||||
others.join(", ")
|
||||
));
|
||||
}
|
||||
Some(parts.join(" "))
|
||||
}
|
||||
|
||||
/// Whether saving to `path` leaves out the entities [`not_saved`] counts: DWG does (the DWG
|
||||
@@ -945,24 +1064,6 @@ fn is_dxf_file(path: impl AsRef<std::path::Path>) -> bool {
|
||||
Format::from_path(path) == Some(Format::Dxf)
|
||||
}
|
||||
|
||||
/// Say on the command line which solid modeler entities a DXF of 2013 or later left out because
|
||||
/// they hold SAT-text ACIS data, which such files keep in a data store instead (#2334).
|
||||
fn report_sat_text_dropped(s: &mut Session, r: &mut Value) {
|
||||
// The drawing a file holds: the host while the Block Editor is open.
|
||||
let lost = s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default();
|
||||
if lost.is_empty() {
|
||||
return;
|
||||
}
|
||||
let list: Vec<String> = lost.iter().map(|(t, n)| format!("{n} {t}")).collect();
|
||||
s.echo(format!(
|
||||
"Not saved in the DXF file (2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them): {}",
|
||||
list.join(", ")
|
||||
));
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("notSaved".into(), json!(lost));
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder a write to `path` has to create, asked before writing so it can be reported after.
|
||||
/// The web has no folders.
|
||||
pub(super) fn new_folder(path: &str) -> Option<String> {
|
||||
@@ -1006,8 +1107,9 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R
|
||||
report_new_folder(s, &mut r, folder);
|
||||
if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) {
|
||||
report_not_saved(s, &mut r, &lost);
|
||||
} else if version >= Version::R2013 && r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
|
||||
report_sat_text_dropped(s, &mut r);
|
||||
} else if r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) {
|
||||
let lost = host_dxf_lost(s, version);
|
||||
report_lost(s, &mut r, "drawing.dxf", version, &lost);
|
||||
}
|
||||
if r.get("path").and_then(Value::as_str).is_some_and(is_drawing_file) {
|
||||
report_fonts(s, &mut r);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
|
||||
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
|
||||
|
||||
mod patfile;
|
||||
pub(super) use edit::{set_pattern, takes_pattern};
|
||||
@@ -36,6 +37,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// Typed with nothing selected it asks for objects, as in AutoCAD, rather than converting none.
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("region", "REGION")))),
|
||||
CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], addPoints?: [[x,y]], addBoundary?: [hex], removeLoops?: [zero-based index] (geometry edits require one hatch), style?, origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))),
|
||||
CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
|
||||
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
|
||||
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
|
||||
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
|
||||
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
|
||||
.enabled(has_doc)
|
||||
@@ -228,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, sources }];
|
||||
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, 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() {
|
||||
@@ -244,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, sources: vec![e.handle] });
|
||||
loops.push(HatchLoop { vertices: vs, outer: false, boundary_flags: None, sources: vec![e.handle] });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -256,7 +260,12 @@ 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, sources });
|
||||
loops.push(HatchLoop {
|
||||
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
|
||||
outer: false,
|
||||
boundary_flags: None,
|
||||
sources,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(loops)
|
||||
@@ -267,7 +276,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(), sources: vec![*h] });
|
||||
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, 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, sources });
|
||||
loops.push(HatchLoop { vertices, outer: l.outer, boundary_flags: l.boundary_flags, sources });
|
||||
}
|
||||
// An erased island: the hatch fills its area.
|
||||
Refill::Erased if !l.outer => {}
|
||||
|
||||
@@ -29,6 +29,59 @@ fn hatches(s: &Session, p: &Value) -> Result<Vec<Handle>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Most polylines one HATCHGENERATEBOUNDARY call creates.
|
||||
const MAX_GENERATED: usize = 10_000;
|
||||
|
||||
/// HATCHGENERATEBOUNDARY: a closed polyline around every boundary loop (outer and islands) of
|
||||
/// the selected hatches, at each hatch's height. The hatches are not changed: an associative
|
||||
/// hatch stays linked to its own boundary objects and is not linked to the new polylines.
|
||||
pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let selected = targets(s, p)?;
|
||||
// The polylines go to the current space, so every hatch must be there too.
|
||||
let space = s.space();
|
||||
let mut loops = Vec::new();
|
||||
let mut found = false;
|
||||
// A hatch named twice gets its boundary once.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
{
|
||||
let d = s.doc()?;
|
||||
for h in selected {
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let EntityKind::Hatch(x) = &e.kind else { continue };
|
||||
if !seen.insert(h) {
|
||||
continue;
|
||||
}
|
||||
found = true;
|
||||
if d.space_of(h).as_ref() != Some(&space) {
|
||||
return Err(bad("hatchgenerateboundary", format!("hatch {} is not in the current space; switch to its layout first", h.hex())));
|
||||
}
|
||||
// Every selected hatch counts: none is left out of a call that succeeds. Compared
|
||||
// against the room left, so a hostile loop count can't overflow the sum.
|
||||
if x.loops.len() > MAX_GENERATED.saturating_sub(loops.len()) {
|
||||
return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches")));
|
||||
}
|
||||
// The elevation runs along the hatch's normal: one facing down Z (mirrored) lies at its
|
||||
// negative, where the polyline, facing up, goes.
|
||||
let z = if e.common.extrusion.z < 0.0 { -x.elevation } else { x.elevation };
|
||||
loops.extend(x.loops.iter().map(|l| (l.vertices.clone(), z)));
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return Err(bad("hatchgenerateboundary", "select one or more hatches"));
|
||||
}
|
||||
// Everything is checked before anything is added, so a refused call leaves nothing behind.
|
||||
let mut created = Vec::new();
|
||||
for (vs, elevation) in loops {
|
||||
let mut kind = lwpoly(vs, true);
|
||||
if let EntityKind::LwPolyline(pl) = &mut kind {
|
||||
pl.elevation = elevation;
|
||||
}
|
||||
created.push(s.add_entity(kind)?.hex());
|
||||
}
|
||||
let n = created.len();
|
||||
Ok(json!({ "handles": created, "message": format!("{n} boundary polyline(s) created.") }))
|
||||
}
|
||||
|
||||
fn outline(l: &HatchLoop) -> Vec<Vec2> {
|
||||
Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(1e-3)
|
||||
}
|
||||
|
||||
@@ -18,6 +18,90 @@ fn text_of(k: &EntityKind) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A box for the in-place editor showing one line of text where `t` sits.
|
||||
pub(crate) fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText {
|
||||
use cadcraft_doc::{HAlign, VAlign};
|
||||
let col = match t.halign {
|
||||
HAlign::Left => 0u8,
|
||||
HAlign::Right => 2,
|
||||
_ => 1,
|
||||
};
|
||||
let row = match t.valign {
|
||||
VAlign::Top => 0u8,
|
||||
VAlign::Middle => 1,
|
||||
_ if t.halign == HAlign::Middle => 1,
|
||||
_ => 2,
|
||||
};
|
||||
// Aligned and fit text is centred between its two points.
|
||||
let at = match t.halign {
|
||||
HAlign::Aligned | HAlign::Fit => t.align_pt.map_or(t.insert, |b| (t.insert + b) * 0.5),
|
||||
_ => t.justify_point().to3(t.insert.z),
|
||||
};
|
||||
cadcraft_doc::MText {
|
||||
insert: at,
|
||||
height: t.height,
|
||||
width: 0.0,
|
||||
attach: row * 3 + col + 1,
|
||||
rotation: t.rotation,
|
||||
style: t.style.clone(),
|
||||
contents: t.value.clone(),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The extents of one line of text as drawn (`value` in `t`'s place, style and justification);
|
||||
/// `None` for empty or unusable extents.
|
||||
fn drawn(d: &cadcraft_doc::Drawing, t: &cadcraft_doc::Text, value: &str) -> Option<cadcraft_geom::Bounds2> {
|
||||
let (_, b) = cadcraft_render::place_text_entity(d, t, value);
|
||||
let ok = [b.min.x, b.min.y, b.max.x, b.max.y].iter().all(|v| v.is_finite()) && b.min.x <= b.max.x && b.min.y <= b.max.y;
|
||||
ok.then_some(b)
|
||||
}
|
||||
|
||||
/// What the in-place editor edits for object `h`: an MTEXT or multileader text as multiline
|
||||
/// text, a TEXT or attribute definition as one line, a dimension's text with `<>` for its value.
|
||||
pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
|
||||
use crate::{EditorKind, TextEditor};
|
||||
let d = s.doc().ok()?;
|
||||
let key = h.hex();
|
||||
let e: &cadcraft_doc::Entity = d.entity(h)?;
|
||||
// Annotative text and dimensions are drawn scaled to the current annotation scale: the box
|
||||
// follows what is drawn. Multiline text keeps its stored height (it is written back from it).
|
||||
let scaled = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
|
||||
Some(cadcraft_doc::anno_scaled(e, f))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match &scaled.as_ref().unwrap_or(e).kind {
|
||||
EntityKind::MText(t) => Some(TextEditor { mtext: t.clone(), kind: EditorKind::MText, key, extents: None }),
|
||||
// A multileader's text opens in the same editor (#1081).
|
||||
EntityKind::MLeader(m) => m.text.clone().map(|mtext| TextEditor { mtext, kind: EditorKind::MText, key, extents: None }),
|
||||
// The box covers the text as drawn: its value, or a definition's tag.
|
||||
EntityKind::Text(t) => Some(TextEditor { mtext: line_box(t), kind: EditorKind::Line, key, extents: drawn(d, t, &t.value) }),
|
||||
EntityKind::AttDef(a) => Some(TextEditor { mtext: line_box(&a.text), kind: EditorKind::Line, key, extents: drawn(d, &a.text, &a.tag) }),
|
||||
EntityKind::Dimension(dm) => {
|
||||
let g = cadcraft_render::dimension_in(d, dm);
|
||||
let measured = cadcraft_render::dimension_in(d, &cadcraft_doc::Dimension { text: String::new(), block: None, ..dm.clone() }).value;
|
||||
let mtext = cadcraft_doc::MText {
|
||||
insert: g.text_pos.to3(0.0),
|
||||
height: if g.text_height > 0.0 && g.text_height.is_finite() { g.text_height } else { 0.18 },
|
||||
width: 0.0,
|
||||
attach: 5,
|
||||
rotation: if g.text_angle.is_finite() { g.text_angle } else { 0.0 },
|
||||
style: d.dim_style(&dm.style).map_or_else(|| "Standard".to_string(), |st| st.text_style.clone()),
|
||||
contents: if dm.text.is_empty() { "<>".into() } else { dm.text.clone() },
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
};
|
||||
Some(TextEditor { mtext, kind: EditorKind::Dimension { measured }, key, extents: None })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> {
|
||||
if curves::is_locked(s, h) {
|
||||
return Err(other("The object is on a locked layer."));
|
||||
@@ -60,8 +144,8 @@ pub(super) struct TextEditM {
|
||||
single: bool,
|
||||
/// Asking for the edit mode.
|
||||
mode: bool,
|
||||
/// The MTEXT being edited, for the in-place editor (#842).
|
||||
mtext: Option<cadcraft_doc::MText>,
|
||||
/// What the in-place editor shows for the picked object (#842).
|
||||
editor: Option<crate::TextEditor>,
|
||||
}
|
||||
|
||||
impl Interactive for TextEditM {
|
||||
@@ -70,7 +154,12 @@ impl Interactive for TextEditM {
|
||||
}
|
||||
/// An MTEXT asking for its new text opens in the in-place editor with its contents.
|
||||
fn editing_mtext(&self) -> Option<cadcraft_doc::MText> {
|
||||
self.h.as_ref().and(self.mtext.clone())
|
||||
self.h.as_ref().and(self.editor.as_ref().filter(|e| e.kind == crate::EditorKind::MText).map(|e| e.mtext.clone()))
|
||||
}
|
||||
/// TEXT, an attribute definition or a dimension asking for its new text opens in the one-line
|
||||
/// in-place editor; MTEXT and multileader text in the MTEXT editor.
|
||||
fn text_editor(&self) -> Option<crate::TextEditor> {
|
||||
if self.mode || self.h.is_none() { None } else { self.editor.clone() }
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
if self.mode {
|
||||
@@ -100,18 +189,13 @@ impl Interactive for TextEditM {
|
||||
if curves::is_locked(s, h) {
|
||||
return Err(other("The object is on a locked layer."));
|
||||
}
|
||||
let kind = curves::entity(s, h)?.kind;
|
||||
let old = text_of(&kind).ok_or_else(|| other("Select a text, mtext, multileader, attribute definition or dimension."))?;
|
||||
self.mtext = match kind {
|
||||
EntityKind::MText(m) => Some(m),
|
||||
// A multileader's text opens in the same editor (#1081).
|
||||
EntityKind::MLeader(m) => m.text,
|
||||
_ => None,
|
||||
};
|
||||
let old = text_of(&curves::entity(s, h)?.kind)
|
||||
.ok_or_else(|| other("Select a text, mtext, multileader, attribute definition or dimension."))?;
|
||||
self.editor = editor_for(s, h);
|
||||
// The editor would drop part of a text this long, and saving would lose it: the
|
||||
// command line asks for it instead.
|
||||
if self.mtext.as_ref().is_some_and(|m| !crate::mtext_edit::Formatted::fits(&m.contents)) {
|
||||
self.mtext = None;
|
||||
if self.editor.as_ref().is_some_and(|e| !crate::mtext_edit::Formatted::fits(&e.mtext.contents)) {
|
||||
self.editor = None;
|
||||
s.echo("This text is too long for the editor; enter the new text at the command line.");
|
||||
}
|
||||
self.h = Some((h, old));
|
||||
@@ -123,12 +207,12 @@ impl Interactive for TextEditM {
|
||||
set_text(s, h, &t)?;
|
||||
self.edits.push((h, before));
|
||||
self.h = None;
|
||||
self.mtext = None;
|
||||
self.editor = None;
|
||||
Ok(if self.single { Step::Done } else { Step::Continue })
|
||||
}
|
||||
(Some(_), Input::Enter) => {
|
||||
self.h = None;
|
||||
self.mtext = None;
|
||||
self.editor = None;
|
||||
Ok(if self.single { Step::Done } else { Step::Continue })
|
||||
}
|
||||
(None, Input::Enter) => Ok(Step::Done),
|
||||
|
||||
@@ -219,14 +219,18 @@ fn type_matches(e: &Entity, ty: Option<&str>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The candidate objects: the whole edit space, or the current selection.
|
||||
/// The candidate objects: the whole edit space (without proxies, which no selection takes in), 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).map(|e| e.handle).collect()).unwrap_or_default())
|
||||
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())
|
||||
}
|
||||
|
||||
fn run_qselect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -67,7 +67,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params("{delta: [dx,dy]} | {from, to} | {center}")
|
||||
.noundo()
|
||||
.transparent()
|
||||
.interactive(|_| Ok(Box::new(PanM::default()))),
|
||||
.interactive(|_| Ok(Box::new(PanM))),
|
||||
CommandSpec::new("-pan", "Pan", run_pan)
|
||||
.params("{delta: [dx,dy]} | {from, to} | {center}")
|
||||
.noundo()
|
||||
.transparent()
|
||||
.interactive(|_| Ok(Box::new(PanPointsM::default()))),
|
||||
CommandSpec::new("pan.left", "Pan Left", |s, _| pan_frac(s, Vec2::new(-0.25, 0.0))).menu(&["View", "Pan", "Left"]).noundo().transparent(),
|
||||
CommandSpec::new("pan.right", "Pan Right", |s, _| pan_frac(s, Vec2::new(0.25, 0.0))).menu(&["View", "Pan", "Right"]).noundo().transparent(),
|
||||
CommandSpec::new("pan.up", "Pan Up", |s, _| pan_frac(s, Vec2::new(0.0, 0.25))).menu(&["View", "Pan", "Up"]).noundo().transparent(),
|
||||
@@ -601,6 +606,26 @@ impl Session {
|
||||
self.touch();
|
||||
Ok(())
|
||||
}
|
||||
/// PAN is in its realtime mode: the UI turns left-button drags into [`Session::realtime_pan`].
|
||||
pub fn realtime_pan_active(&self) -> bool {
|
||||
self.running.as_ref().is_some_and(|r| r.id == "pan") && self.current_prompt().is_some_and(|p| p.message == REALTIME_PAN_PROMPT)
|
||||
}
|
||||
/// One step of a realtime pan drag of `dx`, `dy` screen pixels (y down): the drawing follows
|
||||
/// the cursor. Does nothing outside realtime PAN.
|
||||
pub fn realtime_pan(&mut self, dx: f64, dy: f64) -> Result<()> {
|
||||
if !self.realtime_pan_active() || !dx.is_finite() || !dy.is_finite() {
|
||||
return Ok(());
|
||||
}
|
||||
let px = self.viewport_px.1.max(1.0);
|
||||
let st = self.state_mut()?;
|
||||
let v = st.view();
|
||||
let scale = px / v.height;
|
||||
// A twisted view (DVIEW TWist) turns the screen drag into the drawing's axes.
|
||||
// Only the view moves, as with a middle-button drag: no new revision, so the canvas keeps
|
||||
// its display list and does not rebuild the drawing's geometry on every frame.
|
||||
st.set_view_quiet(View { center: v.center - Vec2::new(dx / scale, -dy / scale).rotate(-v.twist), ..v });
|
||||
Ok(())
|
||||
}
|
||||
/// The zoom of a mouse wheel scroll by `delta` points (up zooms in): ZOOMFACTOR scales it
|
||||
/// (60, the default, zooms about 18% per wheel step).
|
||||
pub fn wheel_zoom_factor(&self, delta: f64) -> f64 {
|
||||
@@ -612,15 +637,47 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct PanM {
|
||||
first: Option<Vec2>,
|
||||
}
|
||||
/// The prompt of realtime PAN; [`Session::realtime_pan_active`] recognises the mode by it.
|
||||
const REALTIME_PAN_PROMPT: &str = "Drag to pan; press Esc or Enter to exit";
|
||||
|
||||
/// PAN: realtime. Dragging with the left button moves the drawing with the cursor until Esc or
|
||||
/// Enter; the whole session is one Zoom Previous entry.
|
||||
struct PanM;
|
||||
|
||||
impl Interactive for PanM {
|
||||
fn name(&self) -> &'static str {
|
||||
"PAN"
|
||||
}
|
||||
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
||||
let st = s.state_mut()?;
|
||||
let v = st.view();
|
||||
st.view_history.push(v);
|
||||
if st.view_history.len() > 50 {
|
||||
st.view_history.remove(0);
|
||||
}
|
||||
Ok(Step::Continue)
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
Prompt::new(REALTIME_PAN_PROMPT, Accept { enter: true, ..Accept::default() })
|
||||
}
|
||||
fn input(&mut self, _s: &mut Session, i: Input) -> Result<Step> {
|
||||
match i {
|
||||
Input::Enter => Ok(Step::Done),
|
||||
_ => Ok(Step::Continue),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// -PAN: a base point and a second point, or a displacement (a point, then Enter).
|
||||
#[derive(Default)]
|
||||
struct PanPointsM {
|
||||
first: Option<Vec2>,
|
||||
}
|
||||
|
||||
impl Interactive for PanPointsM {
|
||||
fn name(&self) -> &'static str {
|
||||
"-PAN"
|
||||
}
|
||||
fn prompt(&self, _s: &Session) -> Prompt {
|
||||
match self.first {
|
||||
None => Prompt::new("Specify base point or displacement (drag with the middle mouse button for realtime pan)", Accept::POINT),
|
||||
@@ -637,7 +694,15 @@ impl Interactive for PanM {
|
||||
run_pan(s, &json!({ "from": [a.x, a.y], "to": [b.x, b.y] }))?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(_, Input::Enter) => Ok(Step::Done),
|
||||
// Enter at the second point: the first point is the displacement, as typed in the
|
||||
// current UCS. The point arrives in world coordinates, so take the UCS origin off
|
||||
// (0,0 in a moved UCS does not pan).
|
||||
(Some(p), Input::Enter) => {
|
||||
let d = p - s.input_ucs().origin.xy();
|
||||
run_pan(s, &json!({ "delta": [d.x, d.y] }))?;
|
||||
Ok(Step::Done)
|
||||
}
|
||||
(None, Input::Enter) => Ok(Step::Done),
|
||||
_ => Ok(Step::Continue),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +123,7 @@ pub const NO_FILES: &[&str] = &[
|
||||
"zoom.extents",
|
||||
"zoom.object",
|
||||
"pan",
|
||||
"-pan",
|
||||
"pan.left",
|
||||
"pan.right",
|
||||
"pan.up",
|
||||
@@ -234,7 +235,9 @@ pub const NO_FILES: &[&str] = &[
|
||||
"boundary",
|
||||
"region",
|
||||
"hatchedit",
|
||||
"hatchgenerateboundary",
|
||||
"hatchpick",
|
||||
"wblockpick",
|
||||
"overkill",
|
||||
"block",
|
||||
"-block",
|
||||
|
||||
@@ -110,6 +110,15 @@ impl Interactive for Guarded {
|
||||
None
|
||||
})
|
||||
}
|
||||
fn text_editor(&self) -> Option<crate::TextEditor> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
}
|
||||
catch_unwind(AssertUnwindSafe(|| self.inner.text_editor())).unwrap_or_else(|_| {
|
||||
self.broken.set(Some("panic in prompt"));
|
||||
None
|
||||
})
|
||||
}
|
||||
fn display_only(&self, s: &Session) -> Option<crate::prompt::DisplayOnly> {
|
||||
if self.broken.get().is_some() {
|
||||
return None;
|
||||
|
||||
@@ -52,9 +52,10 @@ 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, Input, Interactive, Picker, Prompt, Step};
|
||||
pub use prompt::{Accept, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
|
||||
|
||||
mod doc_state;
|
||||
mod error;
|
||||
@@ -158,6 +159,8 @@ 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.
|
||||
@@ -221,6 +224,7 @@ 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,6 +454,19 @@ fn printing_many_lines_is_linear() {
|
||||
assert_eq!(s.log.last().map(String::as_str), Some("a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lisp_pline_keeps_current_elevation() {
|
||||
let mut s = session();
|
||||
ok(&mut s, r#"(setvar "ELEVATION" 800.0)"#);
|
||||
ok(&mut s, r#"(command "_PLINE" '(0 0) '(1000 0) '(1000 100) "")"#);
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "800.0");
|
||||
|
||||
ok(&mut s, r#"(setvar "ELEVATION" -2.5)"#);
|
||||
s.execute("pline", &serde_json::json!({"vertices": [[0, 0], [10, 0]], "width": 2})).unwrap();
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 38 (entget (entlast))))"), "-2.5");
|
||||
assert_eq!(ok(&mut s, "(cdr (assoc 43 (entget (entlast))))"), "2.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_draws_and_one_routine_is_one_undo_step() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -126,23 +126,14 @@ pub fn snap_name(m: u32) -> &'static str {
|
||||
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
|
||||
}
|
||||
|
||||
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
|
||||
/// first, then the closest snap of each other mode in `osmode`, nearest first, without repeats.
|
||||
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
|
||||
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
|
||||
/// first, then deferred snaps, then Nearest), without repeats.
|
||||
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let osnap = |m: u32| crate::snap::osnap(d, space, cursor, aperture, m, base, deferred);
|
||||
let extra = osmode & mode::HATCH;
|
||||
let mut per_mode: Vec<SnapHit> = mode::ALL.iter().filter(|(b, _)| osmode & b != 0).filter_map(|(b, _)| osnap(*b | extra)).collect();
|
||||
per_mode.sort_by(|a, b| a.point.dist(cursor).total_cmp(&b.point.dist(cursor)));
|
||||
let mut out: Vec<SnapHit> = osnap(osmode).into_iter().collect();
|
||||
for h in per_mode {
|
||||
if !out.iter().any(|o| o.mode == h.mode && o.point.near(h.point, aperture * 1e-6)) {
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
out
|
||||
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
|
||||
}
|
||||
|
||||
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
|
||||
|
||||
@@ -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): ortho does not bend the opposite corner, so the rectangle keeps its area.
|
||||
/// cell, MTEXT): 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
|
||||
@@ -338,6 +338,11 @@ pub trait Interactive: Send {
|
||||
fn editing_mtext(&self) -> Option<cadcraft_doc::MText> {
|
||||
None
|
||||
}
|
||||
/// The text the in-place editor edits: where, how, its current contents and what kind of
|
||||
/// object holds it. By default the new multiline text of [`Interactive::editing_mtext`].
|
||||
fn text_editor(&self) -> Option<TextEditor> {
|
||||
self.editing_mtext().map(|mtext| TextEditor { mtext, kind: EditorKind::NewMText, key: String::new(), extents: None })
|
||||
}
|
||||
/// What the drawing area shows in place of the drawing while the command runs (DVIEW draws
|
||||
/// only its preview set); `None` shows the drawing.
|
||||
fn display_only(&self, _s: &Session) -> Option<DisplayOnly> {
|
||||
@@ -356,6 +361,34 @@ pub struct DisplayOnly {
|
||||
pub extra: Vec<cadcraft_doc::Entity>,
|
||||
}
|
||||
|
||||
/// What the in-place text editor edits ([`Interactive::text_editor`]). The editor answers the
|
||||
/// command's text prompt with the new contents (`Input::Text`), or Enter to keep the old text.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TextEditor {
|
||||
/// Where the box sits (insertion point, attachment, rotation), its width (0: grows with the
|
||||
/// text), text height and style; `contents` is the text to start from.
|
||||
pub mtext: cadcraft_doc::MText,
|
||||
pub kind: EditorKind,
|
||||
/// Which object is being edited: a new key means a new text to load.
|
||||
pub key: String,
|
||||
/// The drawn text's extents in drawing units, when known (one line of text): the box covers
|
||||
/// them, whatever the justification.
|
||||
pub extents: Option<cadcraft_geom::Bounds2>,
|
||||
}
|
||||
|
||||
/// The kind of text the in-place editor edits.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EditorKind {
|
||||
/// Multiline text being created (MTEXT).
|
||||
NewMText,
|
||||
/// Existing multiline text: an MTEXT, a multileader's text.
|
||||
MText,
|
||||
/// One line of plain text (TEXT, attribute definition): no formatting, Enter finishes.
|
||||
Line,
|
||||
/// A dimension's text: `<>` stands for the measured value, shown as `measured`.
|
||||
Dimension { measured: String },
|
||||
}
|
||||
|
||||
/// See [`Interactive::drag`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Drag {
|
||||
|
||||
@@ -139,7 +139,7 @@ pub fn bracket() -> Drawing {
|
||||
EntityKind::Hatch(Hatch {
|
||||
pattern: "ANSI31".into(),
|
||||
solid: false,
|
||||
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, sources: Vec::new() }],
|
||||
loops: vec![HatchLoop { vertices: rect_vertices(a, bb), outer: true, boundary_flags: None, sources: Vec::new() }],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: false,
|
||||
|
||||
+18
-10
@@ -161,19 +161,25 @@ 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> {
|
||||
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)
|
||||
store.iter_rev().find(|e| !kept_as_read(&e.kind) && !on_frozen_layer(frozen, e)).map(|e| e.handle)
|
||||
}
|
||||
|
||||
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]) and it is not
|
||||
/// Whether a selection can take `e`: the drawing shows it ([`Drawing::is_visible`]), 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). A viewport shows
|
||||
/// model space, so `frozen` goes with a selection in model space only.
|
||||
/// 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.
|
||||
pub(crate) fn selectable(d: &Drawing, e: &Entity, frozen: &[String]) -> bool {
|
||||
d.is_visible(e) && !on_frozen_layer(frozen, e)
|
||||
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())
|
||||
}
|
||||
|
||||
/// Entities to test, in the order to test them, each with its bounds when already known.
|
||||
@@ -599,7 +605,8 @@ 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 });
|
||||
let frame =
|
||||
|tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
|
||||
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();
|
||||
@@ -722,7 +729,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, sources: Vec::new() }
|
||||
HatchLoop { vertices, outer, boundary_flags: None, sources: Vec::new() }
|
||||
}
|
||||
|
||||
fn ansi31_hatch(loops: Vec<HatchLoop>) -> Drawing {
|
||||
@@ -788,6 +795,7 @@ 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,6 +192,7 @@ impl Session {
|
||||
}
|
||||
|
||||
fn script_lines(&mut self, text: &str) -> Result<()> {
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
|
||||
for line in text.lines() {
|
||||
// Trailing spaces are inputs (Enter); other trailing whitespace (`\r`) is not.
|
||||
let line = line.trim_end_matches(|c: char| c.is_whitespace() && c != ' ');
|
||||
|
||||
@@ -536,6 +536,11 @@ impl Session {
|
||||
self.running.as_ref().and_then(|r| r.machine.editing_mtext())
|
||||
}
|
||||
|
||||
/// The text the running command edits in place ([`Interactive::text_editor`]).
|
||||
pub fn text_editor(&self) -> Option<crate::TextEditor> {
|
||||
self.running.as_ref().and_then(|r| r.machine.text_editor())
|
||||
}
|
||||
|
||||
pub fn current_prompt(&self) -> Option<Prompt> {
|
||||
if let Some(p) = self.lisp_prompt() {
|
||||
return Some(p);
|
||||
|
||||
+143
-59
@@ -72,6 +72,33 @@ impl SnapHit {
|
||||
None => crate::Input::Point(self.point),
|
||||
}
|
||||
}
|
||||
|
||||
fn plain(mode: u32, point: Vec2) -> SnapHit {
|
||||
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
|
||||
}
|
||||
|
||||
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
|
||||
/// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest.
|
||||
fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) {
|
||||
let class = if self.deferred.is_some() {
|
||||
1
|
||||
} else if self.mode == mode::NEA {
|
||||
2
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(class, snap_score(self.mode, self.point, cursor, aperture))
|
||||
}
|
||||
|
||||
/// The same snap as `o`: mode and point, from the same source (paper space, or one
|
||||
/// viewport). Overlapping viewports can show different model points at one paper point;
|
||||
/// each stays a candidate, since DIST measures in the model units of the viewport picked.
|
||||
fn same(&self, o: &SnapHit) -> bool {
|
||||
self.mode == o.mode
|
||||
&& self.deferred.is_some() == o.deferred.is_some()
|
||||
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
|
||||
&& self.point.near(o.point, 1e-9 * (1.0 + self.point.len()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The curve a deferred snap refers to.
|
||||
@@ -211,6 +238,14 @@ pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u3
|
||||
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
|
||||
}
|
||||
|
||||
/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest
|
||||
/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest.
|
||||
/// Snaps seen through layout viewports are included.
|
||||
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
|
||||
let ix = crate::spatial::index(d, space);
|
||||
osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn osnap_with(
|
||||
d: &Drawing,
|
||||
@@ -237,19 +272,39 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
|
||||
let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred);
|
||||
(all.into_iter().next(), prims)
|
||||
}
|
||||
|
||||
/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_all_with_neighborhood(
|
||||
d: &Drawing,
|
||||
space: &Space,
|
||||
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
|
||||
cursor: Vec2,
|
||||
aperture: f64,
|
||||
osmode: u32,
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
) -> (Vec<SnapHit>, Option<Vec<Prim>>) {
|
||||
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
|
||||
return (None, None);
|
||||
return (Vec::new(), None);
|
||||
}
|
||||
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
||||
Some((hit, prims)) => (hit, Some(prims)),
|
||||
None => (None, None),
|
||||
let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
|
||||
Some((hits, prims)) => (hits, Some(prims)),
|
||||
None => (Vec::new(), None),
|
||||
};
|
||||
let views = viewport::near(d, space, cursor, aperture);
|
||||
if views.is_empty() {
|
||||
return (best, near_prims);
|
||||
return (all, near_prims);
|
||||
}
|
||||
let model = Space::Model;
|
||||
let model_ix = crate::spatial::index(d, &model);
|
||||
// What a click picks across spaces stays as it was: each space's best snap, and a viewport's
|
||||
// replaces the best so far only when it scores closer. A paper-space Nearest can therefore
|
||||
// beat an Endpoint seen through a viewport, which `ranked` alone would put first.
|
||||
let mut pick = all.first().copied();
|
||||
for view in views {
|
||||
let model_cursor = view.to_model(cursor);
|
||||
let model_aperture = aperture / view.scale;
|
||||
@@ -257,7 +312,7 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let hit = osnap_in(
|
||||
let hits = osnap_in(
|
||||
d,
|
||||
&model,
|
||||
&model_ix,
|
||||
@@ -268,15 +323,36 @@ pub(crate) fn osnap_with_neighborhood(
|
||||
deferred,
|
||||
&view.viewport.frozen_layers,
|
||||
Some(view.model_clip),
|
||||
)
|
||||
.and_then(|h| view.hit(h));
|
||||
if let Some(hit) = hit
|
||||
&& best.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
|
||||
);
|
||||
if let Some(hit) = hits.first().and_then(|h| view.hit(*h))
|
||||
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
|
||||
{
|
||||
best = Some(hit);
|
||||
pick = Some(hit);
|
||||
}
|
||||
all.extend(hits.into_iter().filter_map(|h| view.hit(h)));
|
||||
}
|
||||
let mut out = ranked(all, cursor, aperture);
|
||||
if let Some(pick) = pick {
|
||||
out.retain(|h| !h.same(&pick));
|
||||
out.insert(0, pick);
|
||||
}
|
||||
(out, near_prims)
|
||||
}
|
||||
|
||||
/// `hits` best first ([`SnapHit::rank`]), without repeats.
|
||||
fn ranked(mut hits: Vec<SnapHit>, cursor: Vec2, aperture: f64) -> Vec<SnapHit> {
|
||||
hits.sort_by(|a, b| {
|
||||
let (ca, sa) = a.rank(cursor, aperture);
|
||||
let (cb, sb) = b.rank(cursor, aperture);
|
||||
ca.cmp(&cb).then(sa.total_cmp(&sb))
|
||||
});
|
||||
let mut out: Vec<SnapHit> = Vec::with_capacity(hits.len());
|
||||
for h in hits {
|
||||
if !out.iter().any(|o| o.same(&h)) {
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
(best, near_prims)
|
||||
out
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -291,10 +367,11 @@ fn osnap_in(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit)
|
||||
) -> Vec<SnapHit> {
|
||||
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn osnap_in_with_prims(
|
||||
d: &Drawing,
|
||||
@@ -307,7 +384,7 @@ fn osnap_in_with_prims(
|
||||
deferred: bool,
|
||||
frozen: &[String],
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<(Option<SnapHit>, Vec<Prim>)> {
|
||||
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
|
||||
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
|
||||
// Intersections between nearby primitives; Apparent Intersection also where their extensions
|
||||
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
|
||||
@@ -345,8 +422,8 @@ fn osnap_in_with_prims(
|
||||
}
|
||||
}
|
||||
}
|
||||
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hit, near_prims))
|
||||
let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
|
||||
Some((hits, near_prims))
|
||||
}
|
||||
|
||||
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
|
||||
@@ -458,7 +535,8 @@ fn gather_in(
|
||||
Some((cands, near_prims))
|
||||
}
|
||||
|
||||
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps.
|
||||
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
|
||||
/// snaps, the deferred snaps and Nearest.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish(
|
||||
mut cands: Vec<(u32, Vec2)>,
|
||||
@@ -469,7 +547,7 @@ fn finish(
|
||||
base: Option<Vec2>,
|
||||
deferred: bool,
|
||||
clip: Option<Bounds2>,
|
||||
) -> Option<SnapHit> {
|
||||
) -> Vec<SnapHit> {
|
||||
// Perpendicular / tangent from the base point.
|
||||
if let Some(bp) = base {
|
||||
for p in near_prims {
|
||||
@@ -507,20 +585,10 @@ fn finish(
|
||||
}
|
||||
}
|
||||
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
|
||||
let best = cands.iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).min_by(|a, b| {
|
||||
// Prefer more specific modes when nearly equidistant.
|
||||
let da = snap_score(a.0, a.1, cursor, aperture);
|
||||
let db = snap_score(b.0, b.1, cursor, aperture);
|
||||
da.total_cmp(&db)
|
||||
});
|
||||
if let Some((m, p)) = best {
|
||||
return Some(SnapHit { point: *p, mode: *m, name: name_of(*m), viewport: None, deferred: None });
|
||||
}
|
||||
if base.is_none()
|
||||
&& deferred
|
||||
&& let Some(h) = deferred_hit(near_prims, cursor, aperture, osmode, clip)
|
||||
{
|
||||
return Some(h);
|
||||
let mut hits: Vec<SnapHit> =
|
||||
cands.into_iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).map(|(m, p)| SnapHit::plain(m, p)).collect();
|
||||
if base.is_none() && deferred {
|
||||
hits.extend(deferred_hits(near_prims, cursor, aperture, osmode, clip));
|
||||
}
|
||||
if osmode & mode::NEA != 0 {
|
||||
// The closest point of all nearby objects, whatever their drawing order.
|
||||
@@ -540,12 +608,13 @@ fn finish(
|
||||
}
|
||||
}
|
||||
if let Some((_, p)) = nb {
|
||||
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
|
||||
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
|
||||
}
|
||||
}
|
||||
None
|
||||
ranked(hits, cursor, aperture)
|
||||
}
|
||||
|
||||
/// Prefer more specific modes when nearly equidistant.
|
||||
fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
|
||||
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
|
||||
}
|
||||
@@ -848,9 +917,11 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
|
||||
}
|
||||
}
|
||||
|
||||
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
|
||||
fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
|
||||
let mut best: Option<(f64, SnapHit)> = None;
|
||||
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
|
||||
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
|
||||
/// perpendicular on the same circle.
|
||||
fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
|
||||
let mut hits = Vec::new();
|
||||
for p in prims {
|
||||
let curve = match p {
|
||||
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
|
||||
@@ -859,32 +930,28 @@ fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip:
|
||||
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
|
||||
_ => continue,
|
||||
};
|
||||
let (m, name, at) = match curve {
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
|
||||
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
|
||||
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
|
||||
}
|
||||
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
|
||||
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
|
||||
// Where the curve was picked: a circle's, an arc's or a segment's own span, an xline/ray
|
||||
// anywhere.
|
||||
let at = match curve {
|
||||
SnapCurve::Circle { center, radius } => Circle::new(center, radius).closest(cursor),
|
||||
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor),
|
||||
SnapCurve::Line { a, b } => {
|
||||
let l = cadcraft_geom::Line::new(a, b);
|
||||
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
|
||||
if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) }
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let dd = at.dist(cursor);
|
||||
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
|
||||
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) }));
|
||||
if !(at.is_finite() && clip.is_none_or(|c| c.contains(at)) && at.dist(cursor) <= aperture) {
|
||||
continue;
|
||||
}
|
||||
let modes: &[(u32, &'static str)] = match curve {
|
||||
SnapCurve::Circle { .. } | SnapCurve::Arc { .. } => &[(mode::TAN, "Deferred Tangent"), (mode::PER, "Deferred Perpendicular")],
|
||||
SnapCurve::Line { .. } => &[(mode::PER, "Deferred Perpendicular")],
|
||||
};
|
||||
for &(m, name) in modes.iter().filter(|(m, _)| osmode & m != 0) {
|
||||
hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) });
|
||||
}
|
||||
}
|
||||
best.map(|(_, h)| h)
|
||||
hits
|
||||
}
|
||||
|
||||
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
|
||||
@@ -1121,6 +1188,23 @@ mod tests {
|
||||
assert_eq!(h.name, "Intersection");
|
||||
}
|
||||
|
||||
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection
|
||||
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap`
|
||||
/// picks.
|
||||
#[test]
|
||||
fn osnap_all_ranks_every_candidate() {
|
||||
let d = drawing();
|
||||
let modes = mode::END | mode::MID | mode::INT | mode::NEA;
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false);
|
||||
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}");
|
||||
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point);
|
||||
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot.
|
||||
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
|
||||
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
|
||||
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
|
||||
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, modes, None, false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn center_quadrant_tangent() {
|
||||
let d = drawing();
|
||||
|
||||
@@ -60,6 +60,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
|
||||
("HPNAME", Kind::Pattern, Def::Str("ANSI31")),
|
||||
("HPSCALE", Kind::Real { min: 0.0, strict: true }, Def::Real(1.0)),
|
||||
("INSNAME", Kind::Name, Def::Str("")),
|
||||
// Percent that objects on locked layers fade on screen; 0 or negative: no fade.
|
||||
("LAYLOCKFADECTL", Kind::Int(-90, 90), Def::Int(50)),
|
||||
("LWDEFAULT", Kind::Choice(&LINEWEIGHTS), Def::Int(25)),
|
||||
// Negative: Through (OFFSET picks a point).
|
||||
("OFFSETDIST", Kind::AnyReal, Def::Real(-1.0)),
|
||||
|
||||
@@ -746,6 +746,15 @@ 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();
|
||||
@@ -1552,6 +1561,50 @@ 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");
|
||||
|
||||
@@ -336,3 +336,24 @@ fn annotative_mtext_columns_follow_the_scale() {
|
||||
assert_eq!((t.height, t.width, c.count, c.gutter, c.height, c.heights), (2.0, 20.0, 2, 2.0, 40.0, vec![6.0, 10.0]));
|
||||
}
|
||||
}
|
||||
|
||||
/// TEXTEDIT's in-place box for annotative text at a non-unit annotation scale has the height and
|
||||
/// extents of the text as drawn (scaled), not as stored (#842 review).
|
||||
#[test]
|
||||
fn the_text_edit_box_of_annotative_text_is_as_drawn() {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
let r = s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap();
|
||||
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
|
||||
let drawn = drawn_height(s.doc().unwrap(), h).unwrap();
|
||||
assert!(drawn > 5.0, "drawn {drawn}");
|
||||
s.cmdline("TEXTEDIT").unwrap();
|
||||
s.input(cadcraft_engine::Input::Point(cadcraft_engine::geom::Vec2::new(0.0, 0.0))).unwrap();
|
||||
let ed = s.text_editor().expect("the editor opens on the text");
|
||||
assert!((ed.mtext.height - 12.5).abs() < 1e-9, "box height {}", ed.mtext.height);
|
||||
let b = ed.extents.unwrap();
|
||||
// The text's layout box (cell height), so a little taller than the strokes, never the
|
||||
// stored 0.25-high text's.
|
||||
assert!(b.height() >= drawn * 0.95 && b.height() <= drawn * 2.0, "box extents {} vs drawn {drawn}", b.height());
|
||||
}
|
||||
|
||||
@@ -65,6 +65,7 @@ fn baseline(d: &Drawing, t: &Text) -> cadcraft_geom::Vec2 {
|
||||
|
||||
#[test]
|
||||
fn all_attribute_value_paths_refresh_small_justified_export_changes() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
for path in ["json", "interactive", "global-json", "global-interactive"] {
|
||||
let (mut s, a, b) = fixture();
|
||||
let before = attributes(s.doc().unwrap(), a);
|
||||
@@ -147,6 +148,7 @@ fn equal_attribute_values_preserve_an_imported_font_baseline() {
|
||||
/// Recomputing a justified baseline must not replace its independent insertion elevation.
|
||||
#[test]
|
||||
fn value_edits_preserve_distinct_insertion_and_alignment_elevations_on_export() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let (mut s, a, _) = fixture();
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
|
||||
@@ -102,6 +102,8 @@ fn new_variables_are_style_overrides_and_read_back() {
|
||||
|
||||
#[test]
|
||||
fn setvar_dimension_variables_are_saved_with_the_drawing() {
|
||||
// The drawing is the test's own, so it is converted in this process.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
// DIMSCALE was kept and DIMTIH, DIMDEC and DIMTAD were not (#3100).
|
||||
let mut s = Session::new();
|
||||
for (name, v) in [("DIMSCALE", json!(2.5)), ("DIMTIH", json!(0)), ("DIMDEC", json!(2)), ("DIMTAD", json!(1))] {
|
||||
@@ -315,6 +317,23 @@ fn tolerance_justification_angular_zeros_and_arc_symbol() {
|
||||
assert_eq!(dim_lines(&g1).len(), dim_lines(&g2).len() + 1, "the symbol drawn over the text");
|
||||
}
|
||||
|
||||
/// DIMPOST frames the angle too, as AutoCAD 2026 does to its own angular dimensions (#1653).
|
||||
#[test]
|
||||
fn dimpost_applies_to_angular_dimensions() {
|
||||
let mut s = Session::new();
|
||||
set(&mut s, "DIMPOST", json!("<> m"));
|
||||
set(&mut s, "DIMADEC", json!(1));
|
||||
// Vertex and two points.
|
||||
s.execute("dimangular", &json!({ "vertex": [0, 0], "p1": [10, 0], "p2": [0, 10], "at": [3, 3] })).unwrap();
|
||||
assert_eq!(last_dim(&s).1.value, "90.0° m");
|
||||
// Two lines picked: the same suffix.
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[0, 0], [5, 8.660254037844387]] })).unwrap();
|
||||
let h: Vec<String> = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).map(|e| e.handle.hex()).collect();
|
||||
s.execute("dimangular", &json!({ "lines": h, "at": [4, 1] })).unwrap();
|
||||
assert_eq!(last_dim(&s).1.value, "60.0° m");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linetypes_and_lineweights_of_dimension_and_extension_lines() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -144,6 +144,26 @@ 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();
|
||||
@@ -166,7 +186,10 @@ fn hostile_sources_never_panic() {
|
||||
let k = EntityKind::Hatch(Hatch {
|
||||
pattern: "ANSI31".into(),
|
||||
solid: false,
|
||||
loops: vec![HatchLoop { vertices: sq, outer: true, sources: sources.clone() }, HatchLoop { vertices: nan, outer: false, sources }],
|
||||
loops: vec![
|
||||
HatchLoop { vertices: sq, outer: true, boundary_flags: None, sources: sources.clone() },
|
||||
HatchLoop { vertices: nan, outer: false, boundary_flags: None, sources },
|
||||
],
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: true,
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
//! HATCHGENERATEBOUNDARY (#2801): closed polylines around existing hatches, which stay as they are.
|
||||
|
||||
use cadcraft_engine::doc::{EntityKind, Handle, Hatch, LwPolyline};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn hatch(s: &Session, h: &str) -> Hatch {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::Hatch(x) => x.clone(),
|
||||
k => panic!("not a hatch: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn poly(s: &Session, h: &str) -> LwPolyline {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::LwPolyline(p) => p.clone(),
|
||||
k => panic!("not a polyline: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(v: &Value) -> String {
|
||||
v["handle"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn handles(v: &Value) -> Vec<String> {
|
||||
v["handles"].as_array().unwrap().iter().map(|h| h.as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String {
|
||||
handle(&s.execute("rectang", &json!({ "p1": a, "p2": b })).unwrap())
|
||||
}
|
||||
|
||||
fn count(s: &Session) -> usize {
|
||||
s.doc().unwrap().model.iter().count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generates_a_closed_polyline_around_a_hatch_without_its_outline() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()] })).unwrap());
|
||||
s.execute("erase", &json!({ "handles": [r] })).unwrap();
|
||||
let before = hatch(&s, &h);
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
|
||||
let new = handles(&v);
|
||||
assert_eq!(new.len(), 1);
|
||||
let p = poly(&s, &new[0]);
|
||||
assert!(p.closed);
|
||||
assert_eq!(p.vertices, before.loops[0].vertices);
|
||||
assert_eq!(hatch(&s, &h), before, "the hatch is not changed");
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
assert_eq!(count(&s), 1, "one undo step removes what was generated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn islands_get_their_own_polylines() {
|
||||
let mut s = Session::new();
|
||||
rect(&mut s, [0.0, 0.0], [20.0, 20.0]);
|
||||
rect(&mut s, [5.0, 5.0], [10.0, 10.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "points": [[2, 2]] })).unwrap());
|
||||
assert_eq!(hatch(&s, &h).loops.len(), 2);
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_selected_hatch_gets_its_boundary() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let b = rect(&mut s, [10.0, 0.0], [14.0, 2.0]);
|
||||
let ha = handle(&s.execute("hatch", &json!({ "handles": [a] })).unwrap());
|
||||
let hb = handle(&s.execute("hatch", &json!({ "handles": [b] })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [ha, hb] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hatch_named_twice_gets_one_boundary() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone(), h] })).unwrap();
|
||||
assert_eq!(handles(&v).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_associative_hatch_stays_linked_to_its_own_boundary() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()], "associative": true })).unwrap());
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
|
||||
let p = handles(&v)[0].clone();
|
||||
// Moving the generated polyline leaves the hatch where it is.
|
||||
s.execute("move", &json!({ "handles": [p], "delta": [0, 10] })).unwrap();
|
||||
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.y, 0.0);
|
||||
// Moving the original rectangle still moves the hatch.
|
||||
s.execute("move", &json!({ "handles": [r], "delta": [10, 0] })).unwrap();
|
||||
assert!(hatch(&s, &h).associative);
|
||||
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.x, 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boundaries_keep_the_hatch_elevation() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
x.elevation = 300.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
assert_eq!(poly(&s, &handles(&v)[0]).elevation, 300.0);
|
||||
}
|
||||
|
||||
/// A mirrored hatch (normal 0,0,-1, as exploding a mirrored block makes) at elevation 300 lies at
|
||||
/// world Z -300; its boundary, facing up, goes there too, not to +300.
|
||||
#[test]
|
||||
fn a_mirrored_hatchs_boundary_keeps_its_world_height() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
e.common.extrusion = cadcraft_engine::geom::Vec3::new(0.0, 0.0, -1.0);
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
x.elevation = 300.0;
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
|
||||
let new = Handle::parse_hex(&handles(&v)[0]).unwrap();
|
||||
let e = s.doc().unwrap().entity(new).unwrap().clone();
|
||||
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
|
||||
assert_eq!(e.common.extrusion.z.signum() * p.elevation, -300.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_hatch_in_another_space_and_adds_nothing() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
|
||||
let before = s.doc().unwrap().entity_count();
|
||||
let e = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap_err();
|
||||
assert!(e.to_string().contains("not in the current space"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().entity_count(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_more_boundaries_than_the_limit_and_adds_nothing() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
// One hatch with more loops than one call may turn into polylines.
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
|
||||
if let EntityKind::Hatch(x) = &mut e.kind {
|
||||
let l = x.loops[0].clone();
|
||||
x.loops = vec![l; 10_001];
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let before = count(&s);
|
||||
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).is_err());
|
||||
assert_eq!(count(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_a_hatch() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [r] })).is_err());
|
||||
assert_eq!(count(&s), 1, "nothing is added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_at_once_on_selected_hatches() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.set_selection(vec![Handle::parse_hex(&h).unwrap()]);
|
||||
s.start("hatchgenerateboundary").unwrap();
|
||||
assert!(s.current_prompt().is_none(), "a pickfirst selection needs no prompt");
|
||||
assert_eq!(count(&s), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asks_for_hatches_without_a_selection() {
|
||||
let mut s = Session::new();
|
||||
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
|
||||
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
|
||||
s.set_selection(Vec::new());
|
||||
s.start("hatchgenerateboundary").unwrap();
|
||||
assert!(s.current_prompt().is_some());
|
||||
s.input(Input::Pick(vec![Handle::parse_hex(&h).unwrap()])).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert_eq!(count(&s), 3);
|
||||
}
|
||||
@@ -68,6 +68,7 @@ mod group_selection;
|
||||
mod groups;
|
||||
mod hatch_assoc;
|
||||
mod hatch_dialog_helpers;
|
||||
mod hatch_generate_boundary;
|
||||
mod hatch_numeric_validation;
|
||||
mod hatch_options;
|
||||
mod helix;
|
||||
@@ -105,6 +106,7 @@ mod mocoro;
|
||||
mod modify_curves;
|
||||
mod mtext_columns;
|
||||
mod mtext_options;
|
||||
mod mtext_ortho;
|
||||
mod multiline_attributes;
|
||||
mod named_viewports;
|
||||
mod named_views;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
|
||||
use cadcraft_engine::geom::{Vec2, Vec3};
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap};
|
||||
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -278,6 +278,46 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
|
||||
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
|
||||
}
|
||||
|
||||
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap
|
||||
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
|
||||
#[test]
|
||||
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
|
||||
let (mut d, paper) = drawing();
|
||||
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
|
||||
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
|
||||
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
|
||||
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
|
||||
assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
|
||||
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
|
||||
let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false);
|
||||
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
|
||||
assert!(
|
||||
all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
|
||||
"Tab reaches the viewport's endpoint: {all:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Overlapping viewports can show different model points at one paper point; Tab offers each,
|
||||
/// since DIST measures in the model units of the viewport picked.
|
||||
#[test]
|
||||
fn overlapping_viewports_each_offer_their_model_point() {
|
||||
let (mut d, paper) = drawing();
|
||||
// This viewport shows the model endpoint (20, 0) at paper (100, 50), a second one over it (0, 0).
|
||||
edit_viewport(&mut d, &paper, |vp| vp.view_center = Vec2::new(20.0, 0.0));
|
||||
let mut vp = match &d.entity(viewport(&d, &paper)).unwrap().kind {
|
||||
EntityKind::Viewport(vp) => vp.clone(),
|
||||
_ => panic!("viewport fixture"),
|
||||
};
|
||||
vp.view_center = Vec2::new(0.0, 0.0);
|
||||
vp.id = 3;
|
||||
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||||
let all = osnap_all(&d, &paper, Vec2::new(100.05, 50.04), 0.5, mode::END, None, false);
|
||||
let mut models: Vec<Vec2> =
|
||||
all.iter().filter(|h| h.point.near(Vec2::new(100.0, 50.0), 1e-9)).filter_map(|h| h.viewport).map(|v| v.point).collect();
|
||||
models.sort_by(|a, b| a.x.total_cmp(&b.x));
|
||||
assert_eq!(models, [Vec2::new(0.0, 0.0), Vec2::new(20.0, 0.0)], "{all:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewport_frozen_layers_do_not_hide_paper_space_geometry() {
|
||||
let (mut d, paper) = drawing();
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
//! MTEXT's opposite corner ignores ortho: the text box keeps its width and proportion (#3388).
|
||||
|
||||
use cadcraft_doc::{EntityKind, MText};
|
||||
use cadcraft_engine::snap::tracking::CursorQuery;
|
||||
use cadcraft_engine::{Input, Session};
|
||||
use cadcraft_geom::{Bounds2, Vec2};
|
||||
use serde_json::json;
|
||||
|
||||
/// Move the cursor to `raw` at the current prompt, as the canvas does.
|
||||
fn hover(s: &mut Session, raw: Vec2) -> Vec2 {
|
||||
let p = s.current_prompt().unwrap();
|
||||
let q = CursorQuery { base: p.base, deferred: p.deferred, corner: p.corner, aperture: 1e-6, tol: 1e-6, now: 0.0, shift: false };
|
||||
let c = s.snap_cursor(raw, &q).point;
|
||||
s.cursor = c;
|
||||
c
|
||||
}
|
||||
|
||||
fn session(ortho: bool) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("setvar", &json!({ "name": "OSMODE", "value": 0 })).unwrap();
|
||||
s.execute("setvar", &json!({ "name": "ORTHOMODE", "value": i32::from(ortho) })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn last_mtext(s: &Session) -> MText {
|
||||
match s.doc().unwrap().model.last().map(|e| e.kind.clone()) {
|
||||
Some(EntityKind::MText(t)) => t,
|
||||
k => panic!("no mtext: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Place an MTEXT from `first` to a cursor click at `second`, returning the preview bounds,
|
||||
/// in-place editor box `(insert, width)` and created entity `(insert, width)`.
|
||||
fn click_mtext(ortho: bool, first: Vec2, second: Vec2) -> ((Vec2, Vec2), (Vec2, f64), (Vec2, f64)) {
|
||||
let mut s = session(ortho);
|
||||
s.cmdline(&format!("mtext {},{}", first.x, first.y)).unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert_eq!(p.message, "Specify opposite corner");
|
||||
assert!(p.corner, "MTEXT opposite corner ignores ortho");
|
||||
let c = hover(&mut s, second);
|
||||
assert!(c.near(second, 1e-9), "opposite corner stays under the cursor: {c:?}");
|
||||
let mut pv = Bounds2::EMPTY;
|
||||
for e in s.preview(c) {
|
||||
pv = pv.union(&cadcraft_doc::entity_bounds(s.doc().unwrap(), &e, 0));
|
||||
}
|
||||
s.input(Input::Point(c)).unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
s.input(Input::Text("Hello".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
assert!(s.current_prompt().is_none(), "MTEXT is done, still at {:?}", s.current_prompt().map(|p| p.message));
|
||||
let t = last_mtext(&s);
|
||||
assert_eq!(t.contents, "Hello");
|
||||
((pv.min, pv.max), (ed.insert.xy(), ed.width), (t.insert.xy(), t.width))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_opposite_corner_ignores_ortho() {
|
||||
let cases = [
|
||||
// Wide box (dx > dy)
|
||||
(Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::ZERO, Vec2::new(10.0, 3.0), Vec2::new(0.0, 3.0), 10.0),
|
||||
// Tall box (dy > dx)
|
||||
(Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::ZERO, Vec2::new(3.0, 10.0), Vec2::new(0.0, 10.0), 3.0),
|
||||
// Opposite quadrant (negative dx and dy)
|
||||
(Vec2::new(10.0, 10.0), Vec2::new(2.0, 4.0), Vec2::new(2.0, 4.0), Vec2::new(10.0, 10.0), Vec2::new(2.0, 10.0), 8.0),
|
||||
];
|
||||
for (first, second, min, max, insert, width) in cases {
|
||||
let on = click_mtext(true, first, second);
|
||||
assert!(on.0.0.near(min, 1e-9) && on.0.1.near(max, 1e-9), "preview bounds with ortho on: {:?}", on.0);
|
||||
assert!(on.1.0.near(insert, 1e-9) && (on.1.1 - width).abs() < 1e-9, "editor box with ortho on: {:?}", on.1);
|
||||
assert!(on.2.0.near(insert, 1e-9) && (on.2.1 - width).abs() < 1e-9, "entity box with ortho on: {:?}", on.2);
|
||||
let off = click_mtext(false, first, second);
|
||||
assert_eq!(off, on, "ortho changes nothing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_coordinate_and_direct_distance_input_with_ortho() {
|
||||
let mut s = session(true);
|
||||
// Absolute coordinate input for the opposite corner.
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
s.cmdline("10,3").unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
assert!(ed.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
|
||||
assert!((ed.width - 10.0).abs() < 1e-9);
|
||||
s.input(Input::Text("Abs".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let t = last_mtext(&s);
|
||||
assert!(t.insert.xy().near(Vec2::new(0.0, 3.0), 1e-9));
|
||||
assert!((t.width - 10.0).abs() < 1e-9);
|
||||
|
||||
// Relative coordinate input for the opposite corner.
|
||||
s.cmdline("mtext 2,3").unwrap();
|
||||
s.cmdline("@4,9").unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
assert!(ed.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
|
||||
assert!((ed.width - 4.0).abs() < 1e-9);
|
||||
s.input(Input::Text("Rel".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let t = last_mtext(&s);
|
||||
assert!(t.insert.xy().near(Vec2::new(2.0, 12.0), 1e-9));
|
||||
assert!((t.width - 4.0).abs() < 1e-9);
|
||||
|
||||
// Direct distance entry goes toward the cursor rather than along an axis.
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
let c = hover(&mut s, Vec2::new(3.0, 4.0));
|
||||
assert!(c.near(Vec2::new(3.0, 4.0), 1e-9));
|
||||
s.cmdline("5").unwrap();
|
||||
let ed = s.editing_mtext().unwrap();
|
||||
assert!(ed.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
|
||||
assert!((ed.width - 3.0).abs() < 1e-9);
|
||||
s.input(Input::Text("Dir".to_string())).unwrap();
|
||||
s.input(Input::Enter).unwrap();
|
||||
let t = last_mtext(&s);
|
||||
assert!(t.insert.xy().near(Vec2::new(0.0, 4.0), 1e-9));
|
||||
assert!((t.width - 3.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtext_escape_cancels_cleanly_with_ortho() {
|
||||
let mut s = session(true);
|
||||
// Cancel at the opposite-corner prompt.
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
let c = hover(&mut s, Vec2::new(10.0, 3.0));
|
||||
assert!(c.near(Vec2::new(10.0, 3.0), 1e-9));
|
||||
s.cancel();
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert!(s.editing_mtext().is_none());
|
||||
assert!(s.doc().unwrap().model.is_empty());
|
||||
|
||||
// Cancel after picking the opposite corner (at the text prompt).
|
||||
s.cmdline("mtext 0,0").unwrap();
|
||||
let c = hover(&mut s, Vec2::new(10.0, 3.0));
|
||||
s.input(Input::Point(c)).unwrap();
|
||||
assert!(s.editing_mtext().is_some());
|
||||
s.cancel();
|
||||
assert!(s.current_prompt().is_none());
|
||||
assert!(s.editing_mtext().is_none());
|
||||
assert!(s.doc().unwrap().model.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_and_pline_still_obey_ortho() {
|
||||
let mut s = session(true);
|
||||
s.cmdline("line 0,0").unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert!(!p.corner, "LINE next point is constrained by ortho");
|
||||
let c = hover(&mut s, Vec2::new(10.0, 3.0));
|
||||
assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps LINE horizontal: {c:?}");
|
||||
s.cancel();
|
||||
|
||||
s.cmdline("pline 0,0").unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert!(!p.corner, "PLINE next point is constrained by ortho");
|
||||
let c = hover(&mut s, Vec2::new(3.0, 10.0));
|
||||
assert!(c.near(Vec2::new(0.0, 10.0), 1e-9), "ortho keeps PLINE vertical: {c:?}");
|
||||
s.cancel();
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Named views (#463): VIEW / -VIEW Save, Window, Restore, Delete, ? and the layer snapshot
|
||||
//! setting; Zoom Realtime and Dynamic; ZOOMFACTOR. (The DXF round trip of views is tested in
|
||||
//! setting; Zoom Realtime and Dynamic; realtime PAN and -PAN; ZOOMFACTOR. (The DXF round trip of views is tested in
|
||||
//! `cadcraft-io`'s `view_tables_roundtrip`.)
|
||||
|
||||
use cadcraft_engine::doc::Space;
|
||||
@@ -155,6 +155,85 @@ fn zoom_realtime_drags_and_enter_ends() {
|
||||
assert_eq!(view(&s), View { center: Vec2::ZERO, height: 25.0, twist: 0.0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pan_realtime_drags_and_enter_ends() {
|
||||
for start in ["pan", "p"] {
|
||||
let mut s = session();
|
||||
set_view(&mut s, 0.0, 0.0, 100.0);
|
||||
s.state_mut().unwrap().view_history.clear();
|
||||
typed(&mut s, &[start]);
|
||||
assert!(s.realtime_pan_active(), "{}", s.prompt_text());
|
||||
// 800 px show 100 units: right 80 px and up 40 px move the drawing with the cursor.
|
||||
s.realtime_pan(80.0, -40.0).unwrap();
|
||||
assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0), "{:?}", view(&s));
|
||||
s.realtime_pan(f64::NAN, 3.0).unwrap();
|
||||
assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0), "{:?}", view(&s));
|
||||
typed(&mut s, &[""]);
|
||||
assert!(s.running.is_none() && !s.realtime_pan_active());
|
||||
// Outside realtime PAN a drag does nothing; Zoom Previous returns to the view before it.
|
||||
s.realtime_pan(80.0, -40.0).unwrap();
|
||||
assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0));
|
||||
s.execute("zoom.previous", &json!({})).unwrap();
|
||||
assert_eq!(view(&s), View { center: Vec2::ZERO, height: 100.0, twist: 0.0 });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pan_realtime_moves_only_the_view() {
|
||||
// A drag frame is not a change of the drawing: the revision stays, so the canvas does not
|
||||
// rebuild the drawing's geometry on every frame (as with a middle-button drag).
|
||||
let mut s = session();
|
||||
set_view(&mut s, 0.0, 0.0, 100.0);
|
||||
typed(&mut s, &["pan"]);
|
||||
let revision = s.state().unwrap().revision;
|
||||
s.realtime_pan(80.0, -40.0).unwrap();
|
||||
assert!(close(view(&s).center.x, -10.0), "{:?}", view(&s));
|
||||
assert_eq!(s.state().unwrap().revision, revision);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pan_realtime_in_a_twisted_view_moves_the_drawing_with_the_cursor() {
|
||||
// A view twisted a quarter turn (DVIEW TWist) shows the drawing's -Y to the right: a drag
|
||||
// 80 px right moves the drawing with it, so the centre moves 10 units up the drawing's Y.
|
||||
let mut s = session();
|
||||
set_view(&mut s, 0.0, 0.0, 100.0);
|
||||
s.state_mut().unwrap().set_view_quiet(View { center: Vec2::ZERO, height: 100.0, twist: std::f64::consts::FRAC_PI_2 });
|
||||
typed(&mut s, &["pan"]);
|
||||
assert!(s.realtime_pan_active(), "{}", s.prompt_text());
|
||||
s.realtime_pan(80.0, 0.0).unwrap();
|
||||
let v = view(&s);
|
||||
assert!(close(v.center.x, 0.0) && close(v.center.y, 10.0), "{v:?}");
|
||||
assert!(close(v.twist, std::f64::consts::FRAC_PI_2), "the pan kept the twist: {v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_pan_takes_two_points_or_a_displacement() {
|
||||
let mut s = session();
|
||||
set_view(&mut s, 0.0, 0.0, 100.0);
|
||||
typed(&mut s, &["-pan", "0,0", "10,5"]);
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(view(&s).center, Vec2::new(-10.0, -5.0));
|
||||
typed(&mut s, &["-pan", "3,4", ""]);
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(view(&s).center, Vec2::new(-13.0, -9.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_pan_displacement_is_measured_in_the_ucs() {
|
||||
// A UCS moved to 100,50: the displacement 0,0 does not pan, and 3,4 pans by 3,4.
|
||||
let mut s = session();
|
||||
set_view(&mut s, 0.0, 0.0, 100.0);
|
||||
s.execute("ucs", &json!({ "origin": [100.0, 50.0] })).unwrap();
|
||||
typed(&mut s, &["-pan", "0,0", ""]);
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(view(&s).center, Vec2::ZERO);
|
||||
typed(&mut s, &["-pan", "3,4", ""]);
|
||||
assert_eq!(view(&s).center, Vec2::new(-3.0, -4.0));
|
||||
// Two points: the difference, which the UCS origin does not change.
|
||||
typed(&mut s, &["-pan", "0,0", "10,5"]);
|
||||
assert_eq!(view(&s).center, Vec2::new(-13.0, -9.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zoom_dynamic_places_and_sizes_the_view_box() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! OFFSET Erase/Layer/Multiple/Undo and the MOVE/COPY Displacement option at the command line.
|
||||
|
||||
use cadcraft_engine::Input;
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use serde_json::json;
|
||||
|
||||
/// Every line as ((ax, ay), (bx, by), layer), sorted by the first y.
|
||||
@@ -62,6 +64,27 @@ fn offset_multiple_and_undo() {
|
||||
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.0), (10.0, 2.0), "0"), l((0.0, 4.0), (10.0, 4.0), "0")]);
|
||||
}
|
||||
|
||||
// Regression test for #618: OFFSET's distance prompt took only a typed number; clicking two points
|
||||
// (the distance between them) was rejected, and the second click had no distance guide.
|
||||
#[test]
|
||||
fn offset_distance_from_two_clicked_points() {
|
||||
let mut s = one_line();
|
||||
s.start("offset").unwrap();
|
||||
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert!(p.message.contains("second point"), "{}", s.prompt_text());
|
||||
assert!(p.base.is_some_and(|b| b.near(Vec2::new(20.0, 20.0), 1e-9)), "the second click is measured from the first");
|
||||
// The guide from the first click to the cursor is the previewed distance.
|
||||
let guide = s.preview(Vec2::new(20.0, 22.5));
|
||||
assert!(matches!(guide.first().map(|e| &e.kind), Some(EntityKind::Line(g)) if g.a.xy().near(Vec2::new(20.0, 20.0), 1e-9)), "{guide:?}");
|
||||
s.input(Input::Point(Vec2::new(20.0, 22.5))).unwrap();
|
||||
assert!(s.current_prompt().unwrap().message.contains("Select object"), "{}", s.prompt_text());
|
||||
assert_eq!(s.doc().unwrap().header.f64("OFFSETDIST", -1.0), 2.5);
|
||||
s.script("5,0 5,1\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.5), (10.0, 2.5), "0")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_json_erase_and_layer() {
|
||||
let mut s = one_line();
|
||||
|
||||
@@ -29,6 +29,7 @@ fn defaults_are_the_ones_the_commands_use() {
|
||||
("DONUTOD", json!(1.0)),
|
||||
("WIPEOUTFRAME", json!(1)),
|
||||
("LWDEFAULT", json!(25)),
|
||||
("LAYLOCKFADECTL", json!(50)),
|
||||
("DIMASSOC", json!(2)),
|
||||
("CPLOTSTYLE", json!("ByLayer")),
|
||||
("TRANSPARENCYDISPLAY", json!(1)),
|
||||
@@ -61,6 +62,9 @@ fn values_reach_the_commands() {
|
||||
assert!(!s.settings.transparency_display);
|
||||
s.cmdline("setvar plottransparencyoverride 2").unwrap();
|
||||
assert_eq!(s.settings.plot_transparency_override, 2);
|
||||
for v in [-90, 0, 90] {
|
||||
assert!(setvar(&mut s, "LAYLOCKFADECTL", json!(v)), "LAYLOCKFADECTL {v}");
|
||||
}
|
||||
assert!(setvar(&mut s, "INSNAME", json!("Valve")));
|
||||
assert!(setvar(&mut s, "INSNAME", json!(".")));
|
||||
assert_eq!(getvar(&mut s, "INSNAME"), json!(""));
|
||||
@@ -74,6 +78,8 @@ fn bad_values_and_unknown_names_are_refused() {
|
||||
("POLYSIDES", json!(5000)),
|
||||
("TRIMMODE", json!(3)),
|
||||
("LWDEFAULT", json!(26)),
|
||||
("LAYLOCKFADECTL", json!(91)),
|
||||
("LAYLOCKFADECTL", json!(-91)),
|
||||
("HPSCALE", json!(0)),
|
||||
("HPNAME", json!("NO-SUCH-PATTERN")),
|
||||
("DONUTOD", json!(0)),
|
||||
|
||||
@@ -30,7 +30,7 @@ fn transparent_zoom_resumes_the_running_command() {
|
||||
s.cmdline("").unwrap();
|
||||
s.cancel();
|
||||
// Scripts nest the same way.
|
||||
s.script("LINE 0,0 'PAN 0,0 1,1 5,0\n\n").unwrap();
|
||||
s.script("LINE 0,0 '-PAN 0,0 1,1 5,0\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), 2);
|
||||
// Enter ends the nested command; Esc and a new command cancel both levels.
|
||||
|
||||
@@ -72,6 +72,7 @@ fn edit(drawing: Drawing, handle: Handle, points: &[Vec2], explicit: bool, index
|
||||
}
|
||||
|
||||
fn check(format: &str, interactive: bool) {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
for explicit in [false, true] {
|
||||
for reversed in [false, true] {
|
||||
let (drawing, handle, points) = fixture(explicit, reversed);
|
||||
@@ -166,6 +167,7 @@ fn polyline_closedness_is_not_inferred_from_coincident_endpoints() {
|
||||
|
||||
#[test]
|
||||
fn coincident_endpoints_remain_separately_editable_after_save() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let original = [Vec2::ZERO, Vec2::new(8.0, 0.0), Vec2::new(8.0, 6.0), Vec2::new(0.0, 6.0)];
|
||||
for explicit in [false, true] {
|
||||
for interactive in [false, true] {
|
||||
|
||||
@@ -9,8 +9,11 @@ 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")] });
|
||||
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 h = d.add(&Space::Model, Common::default(), kind).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "ole.dxf", None);
|
||||
@@ -75,7 +78,8 @@ 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 })).unwrap();
|
||||
let h =
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() })).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "ole.dxf", None);
|
||||
(s, h.hex())
|
||||
@@ -160,8 +164,11 @@ 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")] });
|
||||
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 ole = d.add(&Space::Model, common, kind).unwrap();
|
||||
if let Some(l) = d.layer_mut("L") {
|
||||
l.locked = true;
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
//! What a DXF before 2007 leaves out for its proxies' string streams, counted by the real DXF
|
||||
//! writer (#3229): only what 2007 would keep, from the drawing the command writes. In its own
|
||||
//! test binary because it installs the real io hooks for the whole process.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, SaveAs, set_io, set_proxies_lost, set_write_as};
|
||||
use cadcraft_engine::doc::Drawing;
|
||||
use serde_json::{Value, json};
|
||||
#[path = "support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
|
||||
/// The real reader and writer, and the real proxy-loss count.
|
||||
fn install() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
set_write_as(|d, name, o: &SaveAs| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
set_proxies_lost(cadcraft_io::proxies_lost);
|
||||
cadcraft_engine::cmd::file::set_dwg_compat_lost(cadcraft_io::dwg_compat_lost);
|
||||
}
|
||||
|
||||
/// A proxy entity of class 500 (WIDGETX) in `owner`, with a string stream of `strings` bytes.
|
||||
fn proxy(handle: &str, owner: &str, strings: &str, class: &str) -> Vec<(String, String)> {
|
||||
let p = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
vec![
|
||||
p("0", "ACAD_PROXY_ENTITY"),
|
||||
p("5", handle),
|
||||
p("330", owner),
|
||||
p("100", "AcDbEntity"),
|
||||
p("8", "0"),
|
||||
p("100", "AcDbProxyEntity"),
|
||||
p("90", "498"),
|
||||
p("91", class),
|
||||
p("95", "393245"),
|
||||
p("70", "0"),
|
||||
p("162", strings),
|
||||
p("161", "16"),
|
||||
p("310", "AABB"),
|
||||
]
|
||||
}
|
||||
|
||||
fn pairs(text: &str) -> Vec<(String, String)> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
lines.chunks(2).map(|c| (c[0].trim().to_string(), c.get(1).map_or(String::new(), |v| v.trim().to_string()))).collect()
|
||||
}
|
||||
|
||||
/// A drawing with `$ACADVER` `acadver` read from a DXF holding the class WIDGETX and, in model
|
||||
/// space, the proxies `entities` gives (each from the model space block record's handle).
|
||||
fn drawing(acadver: &str, entities: impl Fn(&str) -> Vec<Vec<(String, String)>>) -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", "AC1024");
|
||||
let text = String::from_utf8(cadcraft_io::write(&d, "p.dxf").unwrap()).unwrap();
|
||||
let mut p = pairs(&text);
|
||||
let g = |c: &str, v: &str| (c.to_string(), v.to_string());
|
||||
let classes = p.iter().position(|q| q.0 == "2" && q.1 == "CLASSES").unwrap() + 1;
|
||||
let class =
|
||||
[g("0", "CLASS"), g("1", "WIDGETX"), g("2", "AcDbWidgetX"), g("3", "ObjectDBX Classes"), g("90", "4095"), g("280", "0"), g("281", "1")];
|
||||
p.splice(classes..classes, class);
|
||||
// The model space block record: the owner of model space entities.
|
||||
let record_end = |i: usize| i + 1 + p[i + 1..].iter().position(|q| q.0 == "0").unwrap_or(p.len() - i - 1);
|
||||
let ms = (0..p.len())
|
||||
.filter(|&i| p[i].0 == "0" && p[i].1 == "BLOCK_RECORD")
|
||||
.find(|&i| p[i..record_end(i)].iter().any(|q| q.0 == "2" && q.1.eq_ignore_ascii_case("*Model_Space")))
|
||||
.unwrap();
|
||||
let owner = p[ms..].iter().find(|q| q.0 == "5").unwrap().1.clone();
|
||||
let ents = p.iter().position(|q| q.0 == "2" && q.1 == "ENTITIES").unwrap();
|
||||
let end = ents + p[ents..].iter().position(|q| q.0 == "0" && q.1 == "ENDSEC").unwrap();
|
||||
p.splice(end..end, entities(&owner).into_iter().flatten());
|
||||
let bytes: String = p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect();
|
||||
let mut d = cadcraft_io::read(bytes.as_bytes(), "p.dxf").unwrap();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d
|
||||
}
|
||||
|
||||
/// Two proxies with string streams, one whose class number names no class (no version writes
|
||||
/// it), and one without: before 2007 only the first one is lost to the string stream.
|
||||
fn three_proxies(owner: &str) -> Vec<Vec<(String, String)>> {
|
||||
vec![proxy("AAA1", owner, "8", "500"), proxy("AAA2", owner, "8", "777"), proxy("AAA3", owner, "0", "500")]
|
||||
}
|
||||
|
||||
fn not_saved(r: &Value) -> Value {
|
||||
r.get("notSaved").cloned().unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
fn legacy_visualstyles_warn_only_for_2007_dwg() {
|
||||
install();
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let source = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1021\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n30\n0\n11\n10\n21\n5\n31\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_VISUALSTYLE\n350\n20\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nSynthetic\n350\n21\n\
|
||||
0\nVISUALSTYLE\n5\n21\n330\n20\n100\nAcDbVisualStyle\n2\nSynthetic\n70\n0\n71\n1\n72\n1\n73\n1\n90\n0\n40\n1.0\n41\n0.5\n63\n7\n\
|
||||
74\n2\n91\n0\n64\n7\n65\n7\n75\n1\n175\n1\n42\n30.0\n92\n0\n66\n7\n43\n1.0\n76\n1\n77\n0\n78\n0\n67\n7\n79\n1\n\
|
||||
170\n0\n171\n0\n290\n0\n174\n0\n93\n0\n44\n0.0\n173\n0\n291\n0\n0\nENDSEC\n0\nEOF\n";
|
||||
let drawing = cadcraft_io::read_dxf(source.as_bytes()).unwrap();
|
||||
let mut session = Session::empty();
|
||||
session.open_drawing(drawing, "styles.dxf", None);
|
||||
assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&session, "styles.dwg").get("VISUALSTYLE"), Some(&1));
|
||||
for (format, version) in [("dwg", 2007), ("dwg", 2013), ("dxf", 2007)] {
|
||||
let start = session.log.len();
|
||||
let result = session.execute("document.bytes", &json!({"format": format, "version": version})).unwrap();
|
||||
if format == "dwg" && version == 2007 {
|
||||
assert_eq!(not_saved(&result), json!({"VISUALSTYLE": 1}));
|
||||
assert!(session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
|
||||
} else {
|
||||
assert_eq!(not_saved(&result), Value::Null);
|
||||
assert!(!session.log[start..].iter().any(|message| message.contains("VISUALSTYLE")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_no_version_writes_is_not_reported() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let path = dir.path_str("out.dxf");
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "{:?}", s.log);
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2007 })).unwrap();
|
||||
assert_eq!(not_saved(&r), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_reports_the_drawing_it_writes() {
|
||||
// In the Block Editor EXPORT writes the block, which holds no proxy: nothing is lost.
|
||||
install();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }));
|
||||
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
|
||||
let line = s.execute("entities", &json!({ "type": "LINE" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string();
|
||||
s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [line], "keep": "convert" })).unwrap();
|
||||
s.execute("bedit", &json!({ "name": "B" })).unwrap();
|
||||
let n = s.log.len();
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(not_saved(&r), Value::Null, "{:?}", &s.log[n..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reference_edit_working_copy_is_not_counted_twice() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", |o| vec![proxy("AAA1", o, "8", "500")]), "proxy.dxf", None);
|
||||
s.execute("block", &json!({ "name": "W", "base": [0, 0], "handles": ["AAA1"], "keep": "convert" })).unwrap();
|
||||
let ins = s.execute("entities", &json!({ "type": "INSERT" })).unwrap()["entities"][0]["handle"].as_str().unwrap().to_string();
|
||||
let path = dir.path_str("before.dxf");
|
||||
let r = s.execute("saveas", &json!({ "path": path, "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "in the block");
|
||||
s.execute("refedit", &json!({ "handle": ins })).unwrap();
|
||||
// Saves wait for REFCLOSE; the QSAVE question and `document.bytes` count the committed drawing.
|
||||
let r = s.execute("document.bytes", &json!({ "format": "dxf", "version": 2000 })).unwrap();
|
||||
assert_eq!(not_saved(&r), json!({ "ACAD_PROXY_ENTITY": 1 }), "the working copy isn't written");
|
||||
assert_eq!(cadcraft_engine::cmd::file::loss_on_save(&s, "during.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_wblock_of_the_whole_drawing_reports_a_pre_2007_dxf() {
|
||||
install();
|
||||
let dir = TempDir::new("proxy-loss");
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015", three_proxies), "proxy.dxf", None);
|
||||
let path = dir.path_str("whole.dxf").replace('\\', "/");
|
||||
s.cmdline(&format!("(command \"_.-WBLOCK\" \"{path}\" \"\" \"*\")")).unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert!(std::path::Path::new(&path).exists());
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.ends_with("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Kept render settings are in the form of the file they were read from, whatever the drawing's
|
||||
//! `$ACADVER` says after a SAVEAS to another version: saving a 2018 drawing down to 2000 and back
|
||||
//! up to 2018 writes the class version the 2018 file had, not one higher (which BricsCAD refuses,
|
||||
//! #907).
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::cmd::file::{IoHooks, set_io, set_write_as};
|
||||
use serde_json::json;
|
||||
|
||||
/// A 2018 DXF with one mental ray render settings object, stored as `90 2` (class version 1 in the
|
||||
/// 2013+ form).
|
||||
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
|
||||
0\nSECTION\n2\nOBJECTS\n\
|
||||
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\
|
||||
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\
|
||||
0\nMENTALRAYRENDERSETTINGS\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n\
|
||||
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nENDSEC\n0\nEOF\n";
|
||||
|
||||
/// The `AcDbRenderSettings` class version in a written DXF.
|
||||
fn class_version(path: &std::path::Path) -> Option<i64> {
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
let l: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let at = l.windows(2).position(|w| w == ["0", "MENTALRAYRENDERSETTINGS"])?;
|
||||
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
|
||||
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saveas_down_and_back_up_keeps_the_render_settings_class_version() {
|
||||
set_io(IoHooks {
|
||||
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
|
||||
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
set_write_as(|d, name, o| {
|
||||
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
|
||||
});
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-render-settings-saveas-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "render.dxf", None);
|
||||
let save = |s: &mut Session, name: &str, version: &str| {
|
||||
let path = dir.join(name);
|
||||
s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": version })).unwrap();
|
||||
class_version(&path)
|
||||
};
|
||||
|
||||
assert_eq!(save(&mut s, "2018.dxf", "2018"), Some(2), "same version: as read");
|
||||
assert_eq!(save(&mut s, "2000.dxf", "2000"), Some(1), "the 2000 form is one lower");
|
||||
s.execute("qsave", &json!({})).unwrap();
|
||||
assert_eq!(class_version(&dir.join("2000.dxf")), Some(1), "QSAVE keeps the 2000 form");
|
||||
assert_eq!(save(&mut s, "back.dxf", "2018"), Some(2), "back to 2018: the 2018 file's value, not one higher");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -212,6 +212,7 @@ fn whole_drawings_are_told_from_cut_off_ones() {
|
||||
/// in a 2018 and a 2000 file, it doesn't replace the good backup; whole, it does.
|
||||
#[test]
|
||||
fn a_dwg_cut_off_anywhere_keeps_the_good_backup() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let _saving = saving();
|
||||
hooks();
|
||||
for version in [2018, 2000] {
|
||||
|
||||
@@ -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() }] })
|
||||
EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }], graphics: Vec::new() })
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -129,6 +129,7 @@ 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();
|
||||
@@ -190,6 +191,7 @@ 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();
|
||||
@@ -219,7 +221,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 })).unwrap();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags, graphics: Vec::new() })).unwrap();
|
||||
};
|
||||
let mut modern = Drawing::new_imperial();
|
||||
modern.header.set_str("ACADVER", "AC1032");
|
||||
@@ -255,6 +257,7 @@ 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")));
|
||||
@@ -268,19 +271,27 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() {
|
||||
assert_eq!(r["notSaved"], json!({ "REGION": 1 }));
|
||||
}
|
||||
|
||||
/// A DWG before 2013 writes a solid's SAT text as it is, so a save there doesn't list a solid that
|
||||
/// holds it; from 2013 the geometry must be in the data store and SAT text alone is lost, so the
|
||||
/// save lists it. A solid with neither is always listed (#2334).
|
||||
/// A DWG before 2013 writes a solid's SAT text of ACIS 7.0 and later, so a save there doesn't list
|
||||
/// a solid that holds it; from 2013 the geometry must be in the data store and SAT text alone is
|
||||
/// lost, so the save lists it. Older SAT (ACIS 4.0) and a solid with neither are always listed
|
||||
/// (#2334).
|
||||
#[test]
|
||||
fn a_dwg_keeps_sat_text_solids_only_before_2013() {
|
||||
use cadcraft_engine::cmd::file::{Version, not_saved_as};
|
||||
let tag = |code: i32, value: &str| RawTag { code, value: value.into() };
|
||||
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags });
|
||||
let solid = |tags: Vec<RawTag>| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() });
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 1 1 0")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "700 0 1 0")])).unwrap();
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 1)].into_iter().collect(), "2010 keeps the SAT-text solid");
|
||||
assert_eq!(not_saved_as(&d, Version::R2018), [("3DSOLID".to_string(), 2)].into_iter().collect(), "2018 loses it");
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 85 1 0")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2)].into_iter().collect(), "ACIS 4.0 SAT is listed");
|
||||
// The same versions encoded, as a DXF before 2013 holds them: 700 is kept, 400 is listed.
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "hoo o n o")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2)].into_iter().collect(), "encoded ACIS 7.0 SAT is kept");
|
||||
d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "koo gj n o")])).unwrap();
|
||||
assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 3)].into_iter().collect(), "encoded ACIS 4.0 SAT is listed");
|
||||
}
|
||||
|
||||
/// The DWG bridge writes OLE objects (`ole2frame_roundtrip` in the io tests), so saving one as
|
||||
@@ -302,3 +313,110 @@ fn ole_objects_are_not_reported() {
|
||||
assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1), ("ole2frame".to_string(), 1)].into_iter().collect(), "{v:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A solid whose geometry only the data store keeps (read from a 2013+ file) has nothing to write
|
||||
/// to a DXF of 2010 or earlier, which has no data store: the save leaves it out and says so, and
|
||||
/// the interactive save knows it beforehand; 2013 and later keep it (#2334).
|
||||
#[test]
|
||||
fn saving_data_store_solids_as_dxf_2010_reports_them() {
|
||||
use cadcraft_engine::cmd::file::loss_on_save;
|
||||
use cadcraft_engine::doc::foreign::Foreign;
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec()));
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", "AC1032");
|
||||
let h = d.add(&Space::Model, Common::default(), unknown("3DSOLID")).unwrap();
|
||||
let record = vec![
|
||||
RawTag { code: 0, value: "ACDSRECORD".into() },
|
||||
RawTag { code: 320, value: h.hex() },
|
||||
RawTag { code: 2, value: "ASM_Data".into() },
|
||||
RawTag { code: 310, value: "00".into() },
|
||||
];
|
||||
d.foreign = std::sync::Arc::new(Foreign { data_store: record, ..Foreign::default() });
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "solid.dxf", None);
|
||||
assert!(loss_on_save(&s, "solid.dxf").is_empty(), "2018 keeps it");
|
||||
|
||||
let path = std::env::temp_dir().join(format!("cadcraft-ds-note-{}.dxf", std::process::id()));
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2010 })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "3DSOLID": 1 }));
|
||||
assert!(s.log.iter().any(|l| l.contains("2010 and earlier have no data store") && l.contains("1 3DSOLID")), "{:?}", s.log);
|
||||
assert_eq!(loss_on_save(&s, "solid.dxf"), [("3DSOLID".to_string(), 1)].into_iter().collect(), "now a 2010 drawing");
|
||||
|
||||
let n = s.log.len();
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2018 })).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(r.get("notSaved").is_none() && s.log.len() == n);
|
||||
}
|
||||
|
||||
/// A proxy entity (as a 2010 file has it) whose string stream is `strings` long (group 162).
|
||||
fn proxy_entity(strings: &str) -> EntityKind {
|
||||
let tags = [(8, "0"), (100, "AcDbProxyEntity"), (90, "498"), (91, "500"), (162, strings), (161, "16"), (310, "AABB")];
|
||||
EntityKind::Unknown(Unknown {
|
||||
dxf_type: "ACAD_PROXY_ENTITY".into(),
|
||||
tags: tags.iter().map(|(code, value)| RawTag { code: *code, value: (*value).into() }).collect(),
|
||||
graphics: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A DXF before 2007 has no form for a proxy's separate string stream: the writer leaves such a
|
||||
/// proxy out, and the save says so instead of dropping it silently (#3229).
|
||||
#[test]
|
||||
fn a_dxf_before_2007_reports_the_proxies_it_leaves_out() {
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
// SAVEAS at a chosen version goes through this hook (each test may run in its own process).
|
||||
set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec()));
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap();
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(d, "proxy.dxf", None);
|
||||
let path = std::env::temp_dir().join(format!("cadcraft-proxy-r2000-{}.dxf", std::process::id()));
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2000 })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings");
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2007 })).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(r.get("notSaved").is_none(), "2007 keeps it");
|
||||
}
|
||||
|
||||
/// The interactive QSAVE asks before a pre-2007 DXF replaces a file and leaves such proxies out,
|
||||
/// with the same list (#3229).
|
||||
#[test]
|
||||
fn a_pre_2007_dxf_proxy_loss_is_known_before_saving() {
|
||||
use cadcraft_engine::cmd::file::loss_on_save;
|
||||
let drawing = |acadver: &str| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d
|
||||
};
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015"), "proxy.dxf", None);
|
||||
assert_eq!(loss_on_save(&s, "proxy.dxf"), [("ACAD_PROXY_ENTITY".to_string(), 1)].into_iter().collect());
|
||||
s.open_drawing(drawing("AC1021"), "proxy.dxf", None);
|
||||
assert!(loss_on_save(&s, "proxy.dxf").is_empty(), "2007 keeps it");
|
||||
}
|
||||
|
||||
/// EXPORT writes a DXF at the drawing's own version: before 2007 it leaves the same proxies out
|
||||
/// and says so, like a save (#3229).
|
||||
#[test]
|
||||
fn exporting_a_dxf_before_2007_reports_the_proxies_it_leaves_out() {
|
||||
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None });
|
||||
let drawing = |acadver: &str| {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.header.set_str("ACADVER", acadver);
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("8")).unwrap();
|
||||
d.add(&Space::Model, Common::default(), proxy_entity("0")).unwrap();
|
||||
d
|
||||
};
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1015"), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert_eq!(r["notSaved"], json!({ "ACAD_PROXY_ENTITY": 1 }), "only the one with strings");
|
||||
assert!(s.log.iter().any(|l| l.contains("DXF before 2007") && l.contains("1 ACAD_PROXY_ENTITY")), "{:?}", s.log);
|
||||
let mut s = Session::empty();
|
||||
s.open_drawing(drawing("AC1021"), "proxy.dxf", None);
|
||||
let r = s.execute("export", &json!({ "format": "dxf" })).unwrap();
|
||||
assert!(r.get("notSaved").is_none(), "2007 keeps it");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//! 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());
|
||||
}
|
||||
@@ -31,6 +31,7 @@ fn folder(tag: &str) -> TempDir {
|
||||
}
|
||||
|
||||
fn save(d: &Drawing, path: &Path) {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
std::fs::write(path, cadcraft_io::write(d, path).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -477,6 +477,18 @@ mod tests {
|
||||
ttf::fallback_for('\u{0E01}').filter(|f| ['\u{0E14}', '\u{0E34}', '\u{0E4C}', '\u{0E33}', '\u{0E10}'].iter().all(|c| f.has_glyph(*c)))
|
||||
}
|
||||
|
||||
/// A Thai face's letters are measured in ems: ก has neither ascender nor descender, ไ rises
|
||||
/// above it, and a space or an unmapped character has no height.
|
||||
#[test]
|
||||
fn thai_glyph_heights_are_measured_in_ems() {
|
||||
let Some(face) = thai_face() else { return };
|
||||
let ko = face.glyph_height('ก').unwrap_or_default();
|
||||
assert!((0.2..1.0).contains(&ko), "ก is {ko} em");
|
||||
assert!(face.glyph_height('ไ').is_some_and(|h| h > ko), "ไ is taller than ก");
|
||||
assert_eq!(face.glyph_height(' '), None);
|
||||
assert_eq!(face.glyph_height('\u{10fffd}'), None);
|
||||
}
|
||||
|
||||
/// Lowest point of the glyph that shows `c`.
|
||||
fn bottom_of(sh: &Shaped, c: char) -> Option<f64> {
|
||||
let t = sh.text.iter().find(|t| t.ch == c)?;
|
||||
|
||||
+42
-22
@@ -649,31 +649,41 @@ 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 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 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 insert = p.insert;
|
||||
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 mut sh = shape_line_dir(font, s, height, p.width_factor, 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.
|
||||
@@ -740,6 +750,15 @@ 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 ' '..='~' {
|
||||
@@ -839,13 +858,14 @@ mod ttf_tests {
|
||||
#[test]
|
||||
fn fallback_ranking_prefers_wide_coverage_regular_fonts() {
|
||||
let stems: Vec<String> =
|
||||
["zapfino", "dejavusans", "notosanscjk-bold", "notosanscjk-regular", "wqy-zenhei", "notosansarabic-regular", "arial"]
|
||||
["zapfino", "dejavusans", "notosanscjk-bold", "notosanscjk-regular", "wqy-zenhei", "notosansarabic-regular", "arial", "unifont"]
|
||||
.map(String::from)
|
||||
.to_vec();
|
||||
let r = crate::ttf::rank_fallback(&stems);
|
||||
assert_eq!(r.first().map(String::as_str), Some("notosanscjk-regular"));
|
||||
assert_eq!(r.get(1).map(String::as_str), Some("notosanscjk-bold"));
|
||||
assert_eq!(r.get(2).map(String::as_str), Some("wqy-zenhei"));
|
||||
assert_eq!(r.get(r.len().wrapping_sub(2)).map(String::as_str), Some("unifont"), "a last resort, but ahead of unknown fonts");
|
||||
assert_eq!(r.last().map(String::as_str), Some("zapfino"));
|
||||
assert_eq!(r.len(), stems.len());
|
||||
}
|
||||
|
||||
@@ -102,6 +102,9 @@ 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
|
||||
@@ -731,6 +734,7 @@ 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,6 +700,14 @@ 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
|
||||
}
|
||||
|
||||
|
||||
+156
-8
@@ -35,6 +35,9 @@ use skrifa::{FontRef, GlyphId, MetadataProvider};
|
||||
|
||||
use crate::{Run, Shaped};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod dirs;
|
||||
|
||||
/// One face of a font file (a TrueType collection holds several).
|
||||
#[derive(Clone)]
|
||||
pub struct Face {
|
||||
@@ -92,6 +95,17 @@ impl Face {
|
||||
Some(s.chars().filter(|c| !c.is_control()).take(80).collect::<String>()).filter(|s| !s.trim().is_empty())
|
||||
})
|
||||
}
|
||||
/// How tall the glyph of `c` is, from its lowest to its highest point, in ems: `None` when the
|
||||
/// face doesn't map `c` or its glyph has no outline (a space, or one too big to keep).
|
||||
pub fn glyph_height(&self, c: char) -> Option<f64> {
|
||||
let g = glyph(self, c);
|
||||
if !g.mapped {
|
||||
return None;
|
||||
}
|
||||
let (low, high) = g.contours.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), p| (low.min(p.y), high.max(p.y)));
|
||||
let height = (high - low) / f64::from(UPEM);
|
||||
(height.is_finite() && height > 0.0).then_some(height)
|
||||
}
|
||||
|
||||
/// The glyph ids the face's character map gives `chars` (`None` for an unmapped one).
|
||||
pub(crate) fn glyph_ids(&self, chars: &[char]) -> Vec<Option<u32>> {
|
||||
@@ -144,7 +158,11 @@ const MAX_CACHED_CHARS: usize = 50_000;
|
||||
pub(crate) const MAX_SHAPED_POINTS: usize = 8_000_000;
|
||||
|
||||
/// Fonts known to cover many scripts (CJK first), tried first for missing glyphs. Matched as
|
||||
/// substrings of the normalised file stem.
|
||||
/// substrings of the normalised file stem. The last two are the wide nets: GNU FreeSerif (most
|
||||
/// non-CJK scripts, with real OpenType shaping; in the default font set of NixOS and many
|
||||
/// distributions), then Unifont (every BMP character, as bitmap-like outlines; the only
|
||||
/// CJK-capable font of NixOS's default set) for what FreeSerif lacks. Both come before the
|
||||
/// alphabetical rest, which the bounded search never gets through.
|
||||
const PREFERRED_FALLBACK: &[&str] = &[
|
||||
"notosanscjk",
|
||||
"sourcehansans",
|
||||
@@ -168,6 +186,8 @@ const PREFERRED_FALLBACK: &[&str] = &[
|
||||
"dejavusans",
|
||||
"segoeui",
|
||||
"arial",
|
||||
"freeserif",
|
||||
"unifont",
|
||||
];
|
||||
/// Fonts known to cover a right-to-left script, tried before the general search for its
|
||||
/// characters (the general search loads a bounded number of files, and wide-coverage CJK fonts
|
||||
@@ -342,11 +362,11 @@ fn system_font_dirs() -> Vec<PathBuf> {
|
||||
dirs.push(PathBuf::from(l).join("Microsoft\\Windows\\Fonts"));
|
||||
}
|
||||
} else {
|
||||
dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(Into::into));
|
||||
if let Some(h) = std::env::var_os("HOME") {
|
||||
dirs.push(PathBuf::from(&h).join(".fonts"));
|
||||
dirs.push(PathBuf::from(h).join(".local/share/fonts"));
|
||||
}
|
||||
// Where fontconfig looks: NixOS, Guix and Flatpak keep fonts outside /usr/share/fonts
|
||||
// (#674). Later directories take precedence (the stack pops them first), so the
|
||||
// resolver's priority order is reversed; [`scan_dirs`] reads each resolved
|
||||
// directory once and skips missing ones.
|
||||
dirs.extend(dirs::font_dirs(|k| std::env::var_os(k), dirs::read_config).into_iter().rev());
|
||||
}
|
||||
dirs
|
||||
}
|
||||
@@ -866,6 +886,16 @@ pub fn find(name: &str) -> Option<Face> {
|
||||
r
|
||||
}
|
||||
|
||||
/// The installed font file with this stem (`DejaVuSans`, `NotoSansCJK-Regular`; case and an
|
||||
/// extension don't matter), wherever the system keeps its fonts. A font compiled in from
|
||||
/// craft-fonts is no file and gives `None`.
|
||||
pub fn installed_font_path(stem: &str) -> Option<PathBuf> {
|
||||
match lock().paths.get(&key(stem))? {
|
||||
Source::File(p) => Some(p.clone()),
|
||||
Source::Static(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
struct Prefs {
|
||||
alt: String,
|
||||
fallback: Vec<String>,
|
||||
@@ -1073,9 +1103,38 @@ pub fn descent_ratio(face: &Face) -> Option<f64> {
|
||||
(r.is_finite() && r > 0.0 && r < 2.0).then_some(r)
|
||||
}
|
||||
|
||||
/// Cap height of a font in font units at 1000 units per em: the OS/2 value, else the height
|
||||
/// of its "H", else an estimate from the ascent.
|
||||
/// Cap heights the installation pins for metric-compatible substitutes, from `CADCRAFT_CAP_HEIGHT`
|
||||
/// (`LiberationSans=715.8;LiberationSans-Bold=715.8`): a substitute keeps the advance widths of
|
||||
/// the font it stands in for but not its cap height, so scaling by the substitute's own OS/2
|
||||
/// value draws text the size of the substitute, not of the requested font. Each entry names a
|
||||
/// substitute's PostScript name and the cap height to give it, in font units at 1000 per em: the
|
||||
/// cap height of the font it replaces, not its own.
|
||||
fn cap_height_overrides() -> &'static HashMap<String, f64> {
|
||||
static OVERRIDES: OnceLock<HashMap<String, f64>> = OnceLock::new();
|
||||
OVERRIDES.get_or_init(|| parse_cap_height_overrides(&std::env::var("CADCRAFT_CAP_HEIGHT").unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Parse a `Name=height;…` list; entries without a name or with a height below 1 unit or not
|
||||
/// finite are dropped (a font's own cap height is never taken below 1 either: a tiny one would
|
||||
/// scale its glyphs past any drawing's extent). Names are matched normalised, like family names.
|
||||
fn parse_cap_height_overrides(spec: &str) -> HashMap<String, f64> {
|
||||
spec.split(';')
|
||||
.filter_map(|entry| {
|
||||
let (name, height) = entry.split_once('=')?;
|
||||
let height: f64 = height.trim().parse().ok()?;
|
||||
(height.is_finite() && height >= 1.0 && !name.trim().is_empty()).then(|| (norm(name.trim()), height))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Cap height of a font in font units at 1000 units per em: the value `CADCRAFT_CAP_HEIGHT`
|
||||
/// pins for this font's PostScript name, else the OS/2 value, else the height of its "H",
|
||||
/// else an estimate from the ascent.
|
||||
fn cap_height(f: &FontRef) -> f64 {
|
||||
let named = f.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).next().map(|s| norm(&s.to_string()));
|
||||
if let Some(height) = named.as_deref().and_then(|n| cap_height_overrides().get(n)) {
|
||||
return *height;
|
||||
}
|
||||
let metrics = f.metrics(Size::new(UPEM), LocationRef::default());
|
||||
let measured = || {
|
||||
let gid = f.charmap().map('H')?;
|
||||
@@ -1408,6 +1467,74 @@ mod family_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cap_height_override_tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[test]
|
||||
fn cap_height_env_parses_name_height_entries() {
|
||||
let m = parse_cap_height_overrides("LiberationSans=715.8;LiberationSans-Bold=715.8");
|
||||
let mut want = HashMap::new();
|
||||
want.insert("liberationsans".to_string(), 715.8);
|
||||
want.insert("liberationsansbold".to_string(), 715.8);
|
||||
assert_eq!(m, want);
|
||||
assert_eq!(
|
||||
parse_cap_height_overrides("LiberationSans = 715.8 ; NotoSansCJK=1466"),
|
||||
parse_cap_height_overrides("LiberationSans=715.8;NotoSansCJK=1466").into_iter().collect::<HashMap<_, _>>(),
|
||||
"spaces around names and heights are tolerated"
|
||||
);
|
||||
assert!(
|
||||
parse_cap_height_overrides("noheight;=5;Arial=0;Arial=-1;Arial=abc").is_empty(),
|
||||
"entries without a name or a positive finite height are dropped"
|
||||
);
|
||||
assert!(parse_cap_height_overrides("").is_empty());
|
||||
assert!(
|
||||
parse_cap_height_overrides("Arial=0.0001;Arial=1e-300").is_empty(),
|
||||
"a height below 1 unit is dropped, as `cap_height` never goes below 1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cap_height_override_applies_only_to_the_named_font() {
|
||||
let m = parse_cap_height_overrides("LiberationSans=715.8");
|
||||
assert_eq!(m.get(&norm("LiberationSans")), Some(&715.8));
|
||||
assert_eq!(m.get(&norm("Liberation Sans")), Some(&715.8), "names match normalised");
|
||||
assert_eq!(m.get(&norm("DejaVuSans")), None);
|
||||
assert_eq!(m.get(&norm("LiberationSans-Bold")), None);
|
||||
}
|
||||
|
||||
/// With no override for the face, `cap_height` walks its chain: the OS/2 value when the face
|
||||
/// has one, else the height of its "H", else an estimate from the ascent. Uses the first of
|
||||
/// these common fonts that is installed (Windows, macOS and Linux each have one); skips
|
||||
/// without any. No override is in play: `CADCRAFT_CAP_HEIGHT` names other faces, and the
|
||||
/// test binary's env is read once — a face this test does not name stays unoverridden.
|
||||
#[test]
|
||||
fn cap_height_without_an_override_follows_the_fallback_chain() {
|
||||
let found = ["Arial", "Helvetica", "DejaVuSans", "Verdana", "LiberationSans-Regular"].into_iter().find_map(find);
|
||||
let Some(face) = found else { return };
|
||||
let f = face.font().expect("the face parses");
|
||||
let named = f.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).next().map(|s| norm(&s.to_string())).unwrap_or_default();
|
||||
let m = f.metrics(Size::new(UPEM), LocationRef::default());
|
||||
let h_height = || {
|
||||
let gid = f.charmap().map('H')?;
|
||||
let b = f.glyph_metrics(Size::new(UPEM), LocationRef::default()).bounds(gid)?;
|
||||
Some(b.y_max).filter(|y| y.is_finite() && *y > 0.0)
|
||||
};
|
||||
let got = cap_height(&f);
|
||||
let want = if cap_height_overrides().contains_key(&named) {
|
||||
return; // this installation pins the face: the override leg is covered by the parser tests
|
||||
} else if let Some(cap) = m.cap_height.filter(|c| c.is_finite() && *c > 0.0) {
|
||||
f64::from(cap)
|
||||
} else if let Some(h) = h_height() {
|
||||
f64::from(h)
|
||||
} else {
|
||||
f64::from(m.ascent) * 0.72
|
||||
};
|
||||
assert!((got - want.max(1.0)).abs() < 1.0, "cap height {got} tracks the chain's value {want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod geometry_budget_tests {
|
||||
use super::*;
|
||||
@@ -1495,4 +1622,25 @@ mod scan_tests {
|
||||
#[cfg(all(unix, not(any(target_os = "macos", target_os = "android", target_env = "ohos"))))]
|
||||
assert!(dirs.iter().any(|d| d == std::path::Path::new("/usr/share/fonts")), "{dirs:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_symlink_back_up_the_tree_does_not_hide_the_other_font_directories() {
|
||||
let root = std::env::temp_dir().join(format!("cadcraft-font-walk-{}", std::process::id()));
|
||||
let (looped, other) = (root.join("looped"), root.join("other"));
|
||||
std::fs::create_dir_all(&looped).unwrap();
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
std::fs::write(looped.join("a.ttf"), b"").unwrap();
|
||||
// The kernel gives up on a symlink chain after about 40 hops; with this many entries,
|
||||
// reading the directory at every hop would still run past the 20 000 entry budget.
|
||||
for i in 0..600 {
|
||||
std::fs::write(looped.join(format!("readme{i}.txt")), b"").unwrap();
|
||||
}
|
||||
std::fs::write(other.join("b.ttf"), b"").unwrap();
|
||||
std::os::unix::fs::symlink(&looped, looped.join("again")).unwrap();
|
||||
// The looped directory is walked first.
|
||||
let found = scan_dirs(&[other.clone(), looped.clone()], false);
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
assert!(found.contains_key("a") && found.contains_key("b"), "{found:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,502 @@
|
||||
//! Where installed fonts live on Linux and the BSDs, the way fontconfig finds them: the XDG base
|
||||
//! directories, the `<dir>` entries of fontconfig's configuration (NixOS and Guix keep each font
|
||||
//! package in its own store path, nowhere near `/usr/share/fonts`) and the host fonts a Flatpak
|
||||
//! sandbox mounts. Directories only: fontconfig's aliases and matching rules are not read.
|
||||
//!
|
||||
//! The resolver is a pure function of the environment and a configuration reader, so its tests
|
||||
//! run the same on every machine.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Bounds on a configuration a package or a user may have made hostile: files read, `<include>`
|
||||
/// nesting, bytes per file, elements per file, entries per path list, directories returned.
|
||||
const MAX_CONFIG_FILES: usize = 256;
|
||||
const MAX_INCLUDE_DEPTH: usize = 4;
|
||||
const MAX_CONFIG_BYTES: u64 = 1 << 20;
|
||||
const MAX_ELEMENTS: usize = 4096;
|
||||
const MAX_PATH_LIST: usize = 64;
|
||||
const MAX_DIRS: usize = 1024;
|
||||
|
||||
/// Where Flatpak mounts the host's system, local and user font directories in a sandbox (it also
|
||||
/// lists them in `/run/host/font-dirs.xml`, which the runtime's `fonts.conf` includes).
|
||||
const FLATPAK_FONT_DIRS: &[&str] = &["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"];
|
||||
|
||||
/// What an `<include>` names: a configuration file's text, or the `[0-9]*.conf` files of a
|
||||
/// directory, sorted, as fontconfig reads them.
|
||||
pub(super) enum Include {
|
||||
File(String),
|
||||
Dir(Vec<PathBuf>),
|
||||
}
|
||||
|
||||
/// Font directories in priority order, without duplicates: the user's XDG font directories,
|
||||
/// `$XDG_DATA_DIRS/fonts` (`/usr/local/share/fonts` and `/usr/share/fonts` whether listed or
|
||||
/// not), Flatpak's host font mounts, then the `<dir>` entries of fontconfig's configuration
|
||||
/// (`$FONTCONFIG_FILE`, else `fonts.conf` in the configuration path, following its `<include>`s;
|
||||
/// as in fontconfig, the path is `$FONTCONFIG_PATH`'s directories then `/etc/fonts`). `env` reads an
|
||||
/// environment variable, `read` a configuration file or directory (`None` when missing).
|
||||
pub(super) fn font_dirs(env: impl Fn(&str) -> Option<OsString>, read: impl Fn(&Path) -> Option<Include>) -> Vec<PathBuf> {
|
||||
let var = |k: &str| env(k).filter(|v| !v.is_empty());
|
||||
let home = var("HOME").map(PathBuf::from);
|
||||
let data_home = var("XDG_DATA_HOME").map(PathBuf::from).or_else(|| home.as_ref().map(|h| h.join(".local/share")));
|
||||
let config_home = var("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| home.as_ref().map(|h| h.join(".config")));
|
||||
let list = |k: &str, default: &str| -> Vec<PathBuf> {
|
||||
std::env::split_paths(&var(k).unwrap_or_else(|| default.into())).filter(|p| p.is_absolute()).take(MAX_PATH_LIST).collect()
|
||||
};
|
||||
let mut user: Vec<PathBuf> = data_home.iter().map(|d| d.join("fonts")).chain(home.iter().map(|h| h.join(".fonts"))).collect();
|
||||
user.extend(list("XDG_DATA_DIRS", "/usr/local/share:/usr/share").into_iter().map(|d| d.join("fonts")));
|
||||
user.extend(["/usr/local/share/fonts", "/usr/share/fonts"].iter().chain(FLATPAK_FONT_DIRS).map(PathBuf::from));
|
||||
let mut config_path = list("FONTCONFIG_PATH", "/etc/fonts");
|
||||
if !config_path.iter().any(|p| p == Path::new("/etc/fonts")) {
|
||||
config_path.push(PathBuf::from("/etc/fonts"));
|
||||
}
|
||||
let mut r = Resolver { home, data_home, config_home, config_path, read: &read, out: Vec::new(), visited: HashSet::new() };
|
||||
for d in user {
|
||||
r.add(d);
|
||||
}
|
||||
r.include(&var("FONTCONFIG_FILE").map(|f| f.to_string_lossy().into_owned()).unwrap_or_else(|| "fonts.conf".into()), None, 0);
|
||||
r.out
|
||||
}
|
||||
|
||||
struct Resolver<'a> {
|
||||
home: Option<PathBuf>,
|
||||
data_home: Option<PathBuf>,
|
||||
config_home: Option<PathBuf>,
|
||||
/// Where a relative top-level name is looked up: `$FONTCONFIG_PATH`'s directories, then
|
||||
/// `/etc/fonts`.
|
||||
config_path: Vec<PathBuf>,
|
||||
read: &'a dyn Fn(&Path) -> Option<Include>,
|
||||
out: Vec<PathBuf>,
|
||||
/// Configuration files and directories read: cycles and the file bound.
|
||||
visited: HashSet<PathBuf>,
|
||||
}
|
||||
|
||||
impl Resolver<'_> {
|
||||
fn add(&mut self, p: PathBuf) {
|
||||
if p.is_absolute() && self.out.len() < MAX_DIRS && !self.out.contains(&p) {
|
||||
self.out.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
/// A path with a leading `~` meaning `$HOME`.
|
||||
fn expand_home(&self, s: &str) -> Option<PathBuf> {
|
||||
match s.strip_prefix('~') {
|
||||
Some(rest) => self.home.as_ref().map(|h| h.join(rest.trim_start_matches('/'))),
|
||||
None => Some(PathBuf::from(s)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Follow an `<include>` (or the top-level file): an absolute name, or a relative one looked
|
||||
/// up in the configuration path. `here` is the including file's directory.
|
||||
fn include(&mut self, name: &str, here: Option<&Path>, depth: usize) {
|
||||
match self.expand_home(name) {
|
||||
Some(p) if p.is_absolute() => {
|
||||
self.config(&p, depth);
|
||||
}
|
||||
Some(p) => {
|
||||
let bases: Vec<PathBuf> = if here.is_some() { here.map(Path::to_path_buf).into_iter().collect() } else { self.config_path.clone() };
|
||||
for base in bases {
|
||||
if self.config(&base.join(&p), depth) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a configuration file (or every file of a directory) and its includes, nested at most
|
||||
/// `MAX_INCLUDE_DEPTH` deep. True when something was read.
|
||||
fn config(&mut self, file: &Path, depth: usize) -> bool {
|
||||
if depth > MAX_INCLUDE_DEPTH || self.visited.len() >= MAX_CONFIG_FILES || !self.visited.insert(file.to_path_buf()) {
|
||||
return false;
|
||||
}
|
||||
let xml = match (self.read)(file) {
|
||||
Some(Include::File(xml)) => xml,
|
||||
Some(Include::Dir(files)) => {
|
||||
for f in files.iter().take(MAX_CONFIG_FILES) {
|
||||
self.config(f, depth);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
None => return false,
|
||||
};
|
||||
let here = file.parent().map(Path::to_path_buf);
|
||||
for e in elements(&xml) {
|
||||
match (e.name, e.prefix) {
|
||||
("dir", Some("xdg")) => {
|
||||
if let Some(d) = self.data_home.as_ref().map(|d| d.join(&e.text)) {
|
||||
self.add(d);
|
||||
}
|
||||
}
|
||||
("dir", Some("relative")) => {
|
||||
if let Some(d) = here.as_ref().map(|h| h.join(&e.text)) {
|
||||
self.add(d);
|
||||
}
|
||||
}
|
||||
// "default", "cwd" or none: as written; a relative directory is skipped.
|
||||
("dir", _) => {
|
||||
if let Some(d) = self.expand_home(&e.text) {
|
||||
self.add(d);
|
||||
}
|
||||
}
|
||||
("include", Some("xdg")) => {
|
||||
if let Some(f) = self.config_home.as_ref().map(|c| c.join(&e.text)) {
|
||||
self.config(&f, depth + 1);
|
||||
}
|
||||
}
|
||||
("include", Some("relative")) => self.include(&e.text, here.as_deref(), depth + 1),
|
||||
("include", _) => self.include(&e.text, None, depth + 1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
struct Element<'a> {
|
||||
name: &'a str,
|
||||
prefix: Option<&'a str>,
|
||||
text: String,
|
||||
}
|
||||
|
||||
/// The `<dir>` and `<include>` elements of a configuration file with text, in order, with their
|
||||
/// `prefix` attribute; comments are skipped. A bounded scan over the text: fontconfig files are
|
||||
/// small and regular.
|
||||
fn elements(xml: &str) -> Vec<Element<'_>> {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = xml;
|
||||
while let Some(i) = rest.find('<') {
|
||||
let Some(tag) = rest.get(i + 1..) else { break };
|
||||
if let Some(c) = tag.strip_prefix("!--") {
|
||||
rest = c.find("-->").and_then(|j| c.get(j + 3..)).unwrap_or("");
|
||||
continue;
|
||||
}
|
||||
let Some(end) = tag.find('>') else { break };
|
||||
let (head, after) = (tag.get(..end).unwrap_or(""), tag.get(end + 1..).unwrap_or(""));
|
||||
rest = after;
|
||||
let (name, attrs) = head.split_once(char::is_whitespace).unwrap_or((head, ""));
|
||||
if !matches!(name, "dir" | "include") {
|
||||
continue;
|
||||
}
|
||||
let prefix = attribute(attrs, "prefix");
|
||||
let text = unescape(after.split('<').next().unwrap_or("").trim());
|
||||
if !text.is_empty() {
|
||||
out.push(Element { name, prefix, text });
|
||||
}
|
||||
if out.len() >= MAX_ELEMENTS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The value of the attribute `name` in a start tag's attribute list: name, optional whitespace,
|
||||
/// `=`, optional whitespace, a single- or double-quoted value, in any order. `None` when absent
|
||||
/// or not well-formed up to it.
|
||||
fn attribute<'a>(attrs: &'a str, name: &str) -> Option<&'a str> {
|
||||
let mut rest = attrs;
|
||||
loop {
|
||||
rest = rest.trim_start();
|
||||
let key_end = rest.find(|c: char| c == '=' || c.is_whitespace())?;
|
||||
let key = rest.get(..key_end)?;
|
||||
rest = rest.get(key_end..)?.trim_start().strip_prefix('=')?.trim_start();
|
||||
let quote = rest.chars().next().filter(|c| matches!(c, '"' | '\''))?;
|
||||
rest = rest.get(1..)?;
|
||||
let value_end = rest.find(quote)?;
|
||||
let value = rest.get(..value_end)?;
|
||||
if key == name {
|
||||
return Some(value);
|
||||
}
|
||||
rest = rest.get(value_end + 1..)?;
|
||||
}
|
||||
}
|
||||
|
||||
fn unescape(s: &str) -> String {
|
||||
if !s.contains('&') {
|
||||
return s.to_string();
|
||||
}
|
||||
s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&")
|
||||
}
|
||||
|
||||
/// Read a configuration file (skipped beyond `MAX_CONFIG_BYTES`) or list a directory's
|
||||
/// `[0-9]*.conf` files, sorted.
|
||||
pub(super) fn read_config(path: &Path) -> Option<Include> {
|
||||
use std::io::Read as _;
|
||||
if path.is_dir() {
|
||||
let conf =
|
||||
|p: &Path| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.ends_with(".conf"));
|
||||
let mut files: Vec<PathBuf> = std::fs::read_dir(path).ok()?.flatten().map(|e| e.path()).filter(|p| conf(p)).take(MAX_CONFIG_FILES).collect();
|
||||
files.sort();
|
||||
return Some(Include::Dir(files));
|
||||
}
|
||||
let mut xml = String::new();
|
||||
std::fs::File::open(path).ok()?.take(MAX_CONFIG_BYTES.saturating_add(1)).read_to_string(&mut xml).ok()?;
|
||||
(xml.len() as u64 <= MAX_CONFIG_BYTES).then_some(Include::File(xml))
|
||||
}
|
||||
|
||||
/// The tests build configurations from POSIX paths such as `/usr/share/fonts`, which only a Unix
|
||||
/// `Path` takes as absolute, so they run on Unix only; the resolver itself builds everywhere.
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn env_of<'a>(vars: &'a [(&str, &str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
|
||||
move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
|
||||
}
|
||||
|
||||
fn reader<'a>(files: &'a [(&str, &str)], dirs: &'a [(&str, &[&str])]) -> impl Fn(&Path) -> Option<Include> + 'a {
|
||||
move |p| {
|
||||
if let Some((_, xml)) = files.iter().find(|(n, _)| Path::new(n) == p) {
|
||||
return Some(Include::File((*xml).to_string()));
|
||||
}
|
||||
dirs.iter().find(|(n, _)| Path::new(n) == p).map(|(_, fs)| Include::Dir(fs.iter().map(PathBuf::from).collect()))
|
||||
}
|
||||
}
|
||||
|
||||
fn paths(v: &[&str]) -> Vec<PathBuf> {
|
||||
v.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
const XDG: &[&str] = &["/usr/local/share/fonts", "/usr/share/fonts", "/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"];
|
||||
|
||||
#[test]
|
||||
fn xdg_defaults_without_variables() {
|
||||
let d = font_dirs(env_of(&[("HOME", "/home/u")]), |_| None);
|
||||
assert_eq!(d, paths(&[&["/home/u/.local/share/fonts", "/home/u/.fonts"], XDG].concat()));
|
||||
assert_eq!(font_dirs(|_| None, |_| None), paths(XDG), "no HOME: system directories only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xdg_variables_name_the_font_dirs() {
|
||||
let env = env_of(&[
|
||||
("HOME", "/home/u"),
|
||||
("XDG_DATA_HOME", "/data"),
|
||||
("XDG_DATA_DIRS", "/nix/profile/share:/run/current-system/sw/share:relative:/usr/share/:"),
|
||||
]);
|
||||
let d = font_dirs(env, |_| None);
|
||||
assert_eq!(
|
||||
d.get(..6),
|
||||
Some(
|
||||
paths(&[
|
||||
"/data/fonts",
|
||||
"/home/u/.fonts",
|
||||
"/nix/profile/share/fonts",
|
||||
"/run/current-system/sw/share/fonts",
|
||||
"/usr/share/fonts",
|
||||
"/usr/local/share/fonts"
|
||||
])
|
||||
.as_slice()
|
||||
)
|
||||
);
|
||||
assert_eq!(d.len(), 9, "{d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fontconfig_dirs_nixos_style() {
|
||||
let files = [
|
||||
(
|
||||
"/etc/fonts/fonts.conf",
|
||||
"<?xml version=\"1.0\"?>\n<!DOCTYPE fontconfig SYSTEM \"urn:fontconfig:fonts.dtd\">\n<fontconfig>\n\
|
||||
<!-- Font directory list -->\n<cachedir prefix=\"xdg\">fontconfig</cachedir>\n\
|
||||
<include ignore_missing=\"yes\">/etc/fonts/conf.d</include>\n<dir prefix=\"xdg\">fonts</dir>\n\
|
||||
<dir>/nix/store/aaa-dejavu-fonts-minimal-2.37</dir>\n</fontconfig>\n",
|
||||
),
|
||||
(
|
||||
"/etc/fonts/conf.d/00-nixos-cache.conf",
|
||||
"<fontconfig>\n <!-- Font directories -->\n <dir>/nix/store/bbb-dejavu-fonts-2.37</dir>\n<dir salt=\"x\">/nix/store/ccc-unifont-16.0.03</dir>\n\
|
||||
<!-- <dir>/commented/out</dir> -->\n <cachedir>/nix/store/ddd-fc-cache</cachedir>\n</fontconfig>\n",
|
||||
),
|
||||
(
|
||||
"/etc/fonts/conf.d/50-user.conf",
|
||||
"<fontconfig>\n<include ignore_missing=\"yes\" prefix=\"xdg\">fontconfig/conf.d</include>\n</fontconfig>\n",
|
||||
),
|
||||
(
|
||||
"/home/u/.config/fontconfig/conf.d/10-hm-fonts.conf",
|
||||
"<fontconfig>\n<include ignore_missing=\"yes\">/nix/store/eee-home-manager-path/etc/fonts/conf.d</include>\n\
|
||||
<dir>/nix/store/eee-home-manager-path/share/fonts</dir>\n<dir>/etc/profiles/per-user/u/share/fonts</dir>\n</fontconfig>\n",
|
||||
),
|
||||
];
|
||||
let dirs: [(&str, &[&str]); 2] = [
|
||||
("/etc/fonts/conf.d", &["/etc/fonts/conf.d/00-nixos-cache.conf", "/etc/fonts/conf.d/50-user.conf"]),
|
||||
("/home/u/.config/fontconfig/conf.d", &["/home/u/.config/fontconfig/conf.d/10-hm-fonts.conf"]),
|
||||
];
|
||||
let d = font_dirs(env_of(&[("HOME", "/home/u"), ("XDG_DATA_DIRS", "/etc/profiles/per-user/u/share")]), reader(&files, &dirs));
|
||||
let expect = [
|
||||
"/home/u/.local/share/fonts",
|
||||
"/home/u/.fonts",
|
||||
"/etc/profiles/per-user/u/share/fonts",
|
||||
"/usr/local/share/fonts",
|
||||
"/usr/share/fonts",
|
||||
"/run/host/fonts",
|
||||
"/run/host/local-fonts",
|
||||
"/run/host/user-fonts",
|
||||
"/nix/store/bbb-dejavu-fonts-2.37",
|
||||
"/nix/store/ccc-unifont-16.0.03",
|
||||
"/nix/store/eee-home-manager-path/share/fonts",
|
||||
"/nix/store/aaa-dejavu-fonts-minimal-2.37",
|
||||
];
|
||||
assert_eq!(d, paths(&expect));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fontconfig_dirs_debian_style() {
|
||||
let files = [
|
||||
(
|
||||
"/etc/fonts/fonts.conf",
|
||||
"<fontconfig>\n<dir>/usr/share/fonts</dir>\n<dir>/usr/local/share/fonts</dir>\n<dir prefix=\"xdg\">fonts</dir>\n\
|
||||
<dir>~/.fonts</dir>\n<dir>/opt/fonts & more</dir>\n<dir>relative/skipped</dir>\n<dir prefix=\"cwd\">also/skipped</dir>\n\
|
||||
<include ignore_missing=\"yes\">conf.d</include>\n</fontconfig>\n",
|
||||
),
|
||||
("/etc/fonts/conf.d/51-local.conf", "<fontconfig><include ignore_missing=\"yes\">local.conf</include></fontconfig>"),
|
||||
("/etc/fonts/conf.d/52-site.conf", "<fontconfig><include prefix=\"relative\">../site/fonts.conf</include></fontconfig>"),
|
||||
("/etc/fonts/local.conf", "<fontconfig><dir>/srv/fonts</dir><dir prefix=\"relative\">more</dir></fontconfig>"),
|
||||
("/etc/fonts/conf.d/../site/fonts.conf", "<fontconfig><dir>/site/fonts</dir></fontconfig>"),
|
||||
];
|
||||
let dirs: [(&str, &[&str]); 1] = [("/etc/fonts/conf.d", &["/etc/fonts/conf.d/51-local.conf", "/etc/fonts/conf.d/52-site.conf"])];
|
||||
let d = font_dirs(env_of(&[("HOME", "/home/u")]), reader(&files, &dirs));
|
||||
let tail: Vec<PathBuf> = d.iter().skip(7).cloned().collect();
|
||||
assert_eq!(tail, paths(&["/opt/fonts & more", "/srv/fonts", "/etc/fonts/more", "/site/fonts"]));
|
||||
assert_eq!(d.len(), 11, "the directories already listed are not repeated: {d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fontconfig_file_and_path_variables() {
|
||||
let files = [("/cfg/custom.conf", "<fontconfig><dir>/custom/fonts</dir></fontconfig>")];
|
||||
let env = env_of(&[("FONTCONFIG_FILE", "custom.conf"), ("FONTCONFIG_PATH", "/nowhere:/cfg")]);
|
||||
let d = font_dirs(env, reader(&files, &[]));
|
||||
assert_eq!(d.last(), Some(&PathBuf::from("/custom/fonts")));
|
||||
let d = font_dirs(env_of(&[("FONTCONFIG_FILE", "/cfg/custom.conf")]), reader(&files, &[]));
|
||||
assert_eq!(d.last(), Some(&PathBuf::from("/custom/fonts")));
|
||||
assert_eq!(font_dirs(env_of(&[("FONTCONFIG_FILE", "/cfg/missing.conf")]), reader(&files, &[])), paths(XDG));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fontconfig_path_names_the_default_configuration() {
|
||||
// FONTCONFIG_PATH alone: its fonts.conf is the configuration, and /etc/fonts still
|
||||
// follows it in the path, as in fontconfig.
|
||||
let files = [
|
||||
("/cfg/fonts.conf", "<fontconfig><dir>/cfg/fonts</dir></fontconfig>"),
|
||||
("/etc/fonts/fonts.conf", "<fontconfig><dir>/etc/listed</dir></fontconfig>"),
|
||||
];
|
||||
let d = font_dirs(env_of(&[("FONTCONFIG_PATH", "/nowhere:/cfg")]), reader(&files, &[]));
|
||||
assert_eq!(d.last(), Some(&PathBuf::from("/cfg/fonts")), "{d:?}");
|
||||
let d = font_dirs(env_of(&[("FONTCONFIG_PATH", "/nowhere")]), reader(&files, &[]));
|
||||
assert_eq!(d.last(), Some(&PathBuf::from("/etc/listed")), "{d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefix_attributes_with_whitespace_around_equals() {
|
||||
// Legal XML: whitespace, newlines included, on either side of '=', attributes in any
|
||||
// order. /cfg is not on the configuration path, so a relative include or directory is
|
||||
// found only through its prefix.
|
||||
let files = [
|
||||
(
|
||||
"/cfg/fonts.conf",
|
||||
"<fontconfig>\n<dir prefix = \"relative\">extra-fonts</dir>\n<dir\n prefix\n =\n 'xdg'\n>more-fonts</dir>\n\
|
||||
<include ignore_missing = \"yes\" prefix = \"xdg\">fontconfig/fonts.conf</include>\n\
|
||||
<include\n\tignore_missing=\"yes\"\n\tprefix\n\t=\n\t\"relative\"\n>site.conf</include>\n</fontconfig>\n",
|
||||
),
|
||||
("/home/u/.config/fontconfig/fonts.conf", "<fontconfig><dir>/xdg-included</dir></fontconfig>"),
|
||||
("/cfg/site.conf", "<fontconfig><dir>/site-included</dir></fontconfig>"),
|
||||
];
|
||||
let env = env_of(&[("HOME", "/home/u"), ("XDG_DATA_HOME", "/data"), ("FONTCONFIG_FILE", "/cfg/fonts.conf")]);
|
||||
let d = font_dirs(env, reader(&files, &[]));
|
||||
let tail: Vec<PathBuf> = d.iter().skip(XDG.len() + 2).cloned().collect();
|
||||
assert_eq!(tail, paths(&["/cfg/extra-fonts", "/data/more-fonts", "/xdg-included", "/site-included"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn include_cycles_and_depth_are_bounded() {
|
||||
let files = [
|
||||
("/etc/fonts/fonts.conf", "<fontconfig><dir>/d0</dir><include>/etc/fonts/b.conf</include></fontconfig>"),
|
||||
(
|
||||
"/etc/fonts/b.conf",
|
||||
"<fontconfig><dir>/d1</dir><include>/etc/fonts/fonts.conf</include><include>/etc/fonts/b.conf</include></fontconfig>",
|
||||
),
|
||||
];
|
||||
let d = font_dirs(|_| None, reader(&files, &[]));
|
||||
assert_eq!(d.iter().skip(XDG.len()).cloned().collect::<Vec<_>>(), paths(&["/d0", "/d1"]));
|
||||
|
||||
let chain: Vec<(String, String)> = (0..10)
|
||||
.map(|i| {
|
||||
(format!("/etc/fonts/{i}.conf"), format!("<fontconfig><dir>/depth{i}</dir><include>/etc/fonts/{}.conf</include></fontconfig>", i + 1))
|
||||
})
|
||||
.collect();
|
||||
let read = |p: &Path| chain.iter().find(|(n, _)| Path::new(n) == p).map(|(_, xml)| Include::File(xml.clone()));
|
||||
let d = font_dirs(env_of(&[("FONTCONFIG_FILE", "/etc/fonts/0.conf")]), read);
|
||||
let depths: Vec<&PathBuf> = d.iter().skip(XDG.len()).collect();
|
||||
assert_eq!(depths.len(), MAX_INCLUDE_DEPTH + 1, "{depths:?}");
|
||||
assert_eq!(depths.last().map(|p| p.as_path()), Some(Path::new("/depth4")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_files_are_bounded() {
|
||||
let names: Vec<String> = (0..1000).map(|i| format!("/etc/fonts/conf.d/{i:04}.conf")).collect();
|
||||
let read = |p: &Path| {
|
||||
if p == Path::new("/etc/fonts/fonts.conf") {
|
||||
return Some(Include::File("<fontconfig><include>/etc/fonts/conf.d</include></fontconfig>".into()));
|
||||
}
|
||||
if p == Path::new("/etc/fonts/conf.d") {
|
||||
return Some(Include::Dir(names.iter().map(PathBuf::from).collect()));
|
||||
}
|
||||
p.starts_with("/etc/fonts/conf.d").then(|| Include::File(format!("<fontconfig><dir>{}</dir></fontconfig>", p.display())))
|
||||
};
|
||||
let d = font_dirs(|_| None, read);
|
||||
assert!(d.len() <= XDG.len() + MAX_CONFIG_FILES, "{}", d.len());
|
||||
assert!(d.len() > XDG.len() + 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elements_survive_odd_markup() {
|
||||
let xml = "<dir><dir>/unterminated<include>/x</include><dir prefix='relative'>r</dir><dir></dir><!-- never closed <dir>/no</dir>";
|
||||
let e = elements(xml);
|
||||
let got: Vec<(&str, Option<&str>, &str)> = e.iter().map(|e| (e.name, e.prefix, e.text.as_str())).collect();
|
||||
assert_eq!(got, [("dir", None, "/unterminated"), ("include", None, "/x"), ("dir", Some("relative"), "r")]);
|
||||
assert!(elements("").is_empty());
|
||||
assert!(elements("<").is_empty());
|
||||
assert!(elements("<dir").is_empty());
|
||||
let huge: String = "<dir>/a</dir>".repeat(MAX_ELEMENTS * 2);
|
||||
assert_eq!(elements(&huge).len(), MAX_ELEMENTS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_in_any_order_and_spacing() {
|
||||
let prefix = |xml: &str| elements(xml).first().and_then(|e| e.prefix).map(str::to_string);
|
||||
assert_eq!(prefix("<dir salt=\"x\" prefix='xdg'>f</dir>"), Some("xdg".into()));
|
||||
assert_eq!(prefix("<dir prefix=\"relative\" salt=\"x\">f</dir>"), Some("relative".into()));
|
||||
assert_eq!(prefix("<dir salt = 'prefix=\"xdg\"' prefix = \"cwd\">f</dir>"), Some("cwd".into()), "a value is not an attribute");
|
||||
assert_eq!(prefix("<include\nignore_missing = \"yes\"\nprefix\n=\n\"xdg\"\n>f</include>"), Some("xdg".into()));
|
||||
assert_eq!(prefix("<dir prefix=xdg>f</dir>"), None, "an unquoted value is not well-formed");
|
||||
assert_eq!(prefix("<dir prefix>f</dir>"), None);
|
||||
assert_eq!(prefix("<dir prefix=\"unterminated>f</dir>"), None);
|
||||
assert_eq!(prefix("<dir salt=\"x\">f</dir>"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_config_skips_oversize_files_and_lists_conf_files() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"cadcraft-fontdirs-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::UNIX_EPOCH.elapsed().map(|d| d.as_nanos()).unwrap_or(0)
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("10-small.conf"), "<fontconfig><dir>/small</dir></fontconfig>").unwrap();
|
||||
std::fs::write(dir.join("05-first.conf"), "<fontconfig/>").unwrap();
|
||||
std::fs::write(dir.join("README"), "not a config").unwrap();
|
||||
std::fs::write(dir.join("local.conf"), "<fontconfig/>").unwrap();
|
||||
std::fs::write(dir.join("99-big.conf"), vec![b' '; (MAX_CONFIG_BYTES + 1) as usize]).unwrap();
|
||||
match read_config(&dir) {
|
||||
Some(Include::Dir(files)) => assert_eq!(files, [dir.join("05-first.conf"), dir.join("10-small.conf"), dir.join("99-big.conf")]),
|
||||
_ => panic!("a directory lists its [0-9]*.conf files"),
|
||||
}
|
||||
assert!(matches!(read_config(&dir.join("10-small.conf")), Some(Include::File(x)) if x.contains("/small")));
|
||||
assert!(read_config(&dir.join("99-big.conf")).is_none(), "oversize file skipped");
|
||||
assert!(read_config(&dir.join("missing.conf")).is_none());
|
||||
let small = dir.join("10-small.conf").to_string_lossy().into_owned();
|
||||
let d = font_dirs(env_of(&[("FONTCONFIG_FILE", &small)]), read_config);
|
||||
assert_eq!(d.last(), Some(&PathBuf::from("/small")));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -109,6 +109,66 @@ 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(","));
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
//! A synthetic TrueType (sfnt) font file, built in code for tests that need a real font without a
|
||||
//! font file in the repository or one installed on the machine: `head`, `hhea`, `maxp`, `hmtx`,
|
||||
//! `glyf`, `loca`, a format-4 `cmap` and `OS/2`, laid out in a sorted table directory.
|
||||
//!
|
||||
//! Test-only, and shared: `crates/render/src/tests.rs` (the level-of-detail fixture) and
|
||||
//! `crates/io/tests/pdf_text.rs` (the PDF writer's embedding fixtures) build their fonts with it,
|
||||
//! each including this file with `#[path]`, so neither needs a published API, a dependency or a
|
||||
//! copy of the other's tables. `crates/fonts` is the layer that reads those tables
|
||||
//! (`crates/fonts/src/ttf.rs`), which is why the skeleton lives beside its tests; the glyph shapes,
|
||||
//! the character map ranges and the metrics a font records stay at the caller that needs them.
|
||||
|
||||
fn be16(v: &mut Vec<u8>, x: u16) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
|
||||
fn be32(v: &mut Vec<u8>, x: u32) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
|
||||
/// A simple glyph, with the point and contour counts `maxp` records for the font.
|
||||
pub struct Glyph {
|
||||
bytes: Vec<u8>,
|
||||
points: usize,
|
||||
contours: usize,
|
||||
}
|
||||
|
||||
/// `.notdef`: no contours, no bytes.
|
||||
pub fn notdef() -> Glyph {
|
||||
Glyph { bytes: Vec::new(), points: 0, contours: 0 }
|
||||
}
|
||||
|
||||
/// One simple glyph: closed contours of on-curve points, with the box the file records for it.
|
||||
pub fn glyph(contours: &[Vec<(i16, i16)>]) -> Glyph {
|
||||
let points: Vec<(i16, i16)> = contours.iter().flatten().copied().collect();
|
||||
let mut g = Vec::new();
|
||||
be16(&mut g, contours.len() as u16);
|
||||
let box_ = points.iter().fold((i16::MAX, i16::MAX, i16::MIN, i16::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));
|
||||
for v in [box_.0, box_.1, box_.2, box_.3] {
|
||||
be16(&mut g, v as u16);
|
||||
}
|
||||
let mut end = 0u16;
|
||||
for c in contours {
|
||||
end = end.saturating_add(c.len() as u16);
|
||||
be16(&mut g, end.saturating_sub(1));
|
||||
}
|
||||
be16(&mut g, 0);
|
||||
g.extend(std::iter::repeat_n(1u8, points.len()));
|
||||
let (mut px, mut py) = (0i16, 0i16);
|
||||
for (x, _) in &points {
|
||||
be16(&mut g, x.wrapping_sub(px) as u16);
|
||||
px = *x;
|
||||
}
|
||||
for (_, y) in &points {
|
||||
be16(&mut g, y.wrapping_sub(py) as u16);
|
||||
py = *y;
|
||||
}
|
||||
while g.len() % 4 != 0 {
|
||||
g.push(0);
|
||||
}
|
||||
Glyph { bytes: g, points: points.len(), contours: contours.len() }
|
||||
}
|
||||
|
||||
/// What the callers differ in; every other table field is the same in each font this builds.
|
||||
pub struct Sfnt<'a> {
|
||||
/// `glyf` entries, `.notdef` first.
|
||||
pub glyphs: &'a [Glyph],
|
||||
/// `cmap` format-4 segments: first character code, last character code, and glyph id minus
|
||||
/// code. The `0xFFFF` segment that ends the map is added here.
|
||||
pub cmap: &'a [(u16, u16, i16)],
|
||||
/// The advance width every glyph shares, in em units.
|
||||
pub advance: u16,
|
||||
/// The left side bearing every glyph shares.
|
||||
pub lsb: i16,
|
||||
/// `hmtx` entries written. Fewer than the glyphs `hhea` declares is a deliberately short
|
||||
/// table: that font is malformed on purpose, and a reader must cope with it, not repair it.
|
||||
pub metrics: usize,
|
||||
/// `OS/2` `fsType`: the embedding permissions, `0` for any use.
|
||||
pub fs_type: u16,
|
||||
/// `head`'s ink box: xMin, yMin, xMax, yMax.
|
||||
pub ink_box: [i16; 4],
|
||||
}
|
||||
|
||||
/// Em units per em: with a 700-unit cap height, one em is 1000 units, so a text height of one unit
|
||||
/// is a cap height of one unit.
|
||||
const UNITS_PER_EM: u16 = 1000;
|
||||
|
||||
/// The font file `f` describes, as a TrueType file.
|
||||
pub fn bytes(f: &Sfnt<'_>) -> Vec<u8> {
|
||||
let mut glyf = Vec::new();
|
||||
let mut loca = Vec::new();
|
||||
for g in f.glyphs {
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
glyf.extend_from_slice(&g.bytes);
|
||||
}
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
let mut head = Vec::new();
|
||||
be32(&mut head, 0x0001_0000); // version
|
||||
be32(&mut head, 0x0001_0000); // fontRevision
|
||||
be32(&mut head, 0); // checkSumAdjustment
|
||||
be32(&mut head, 0x5F0F_3CF5); // magic
|
||||
be16(&mut head, 0); // flags
|
||||
be16(&mut head, UNITS_PER_EM);
|
||||
head.extend_from_slice(&[0; 16]); // created, modified
|
||||
for v in f.ink_box {
|
||||
be16(&mut head, v as u16);
|
||||
}
|
||||
// macStyle, lowestRecPPEM, fontDirectionHint, indexToLocFormat 1 = long offsets (`loca` holds
|
||||
// `u32`), glyphDataFormat.
|
||||
for v in [0u16, 8, 2, 1, 0] {
|
||||
be16(&mut head, v);
|
||||
}
|
||||
let mut hhea = Vec::new();
|
||||
be32(&mut hhea, 0x0001_0000);
|
||||
// ascender, descender, lineGap, advanceWidthMax, minLeftSideBearing, minRightSideBearing,
|
||||
// xMaxExtent, caretSlopeRise, caretSlopeRun, caretOffset, four reserved, metricDataFormat.
|
||||
for v in [800i16, -200, 0, f.advance as i16, 0, 0, f.advance as i16, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut hhea, v as u16);
|
||||
}
|
||||
be16(&mut hhea, f.glyphs.len() as u16); // numberOfHMetrics
|
||||
let max_points = f.glyphs.iter().map(|g| g.points).max().unwrap_or(0);
|
||||
let max_contours = f.glyphs.iter().map(|g| g.contours).max().unwrap_or(0);
|
||||
let mut maxp = Vec::new();
|
||||
be32(&mut maxp, 0x0001_0000);
|
||||
// numGlyphs, maxPoints, maxContours, maxCompositePoints, maxCompositeContours, maxZones, and
|
||||
// the composite and instruction maxima after them.
|
||||
for v in [f.glyphs.len() as u16, max_points as u16, max_contours as u16, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut maxp, v);
|
||||
}
|
||||
let mut hmtx = Vec::new();
|
||||
for _ in 0..f.metrics {
|
||||
be16(&mut hmtx, f.advance);
|
||||
be16(&mut hmtx, f.lsb as u16);
|
||||
}
|
||||
// cmap: version 0 with one encoding record (Windows, Unicode BMP), a format-4 subtable over
|
||||
// the caller's segments and the `0xFFFF` one that ends it.
|
||||
let segs: Vec<(u16, u16, i16)> = f.cmap.iter().copied().chain([(0xFFFF, 0xFFFF, 1)]).collect();
|
||||
let seg_count = segs.len() as u32;
|
||||
let seg_selector = seg_count.ilog2();
|
||||
let seg_search_range = 2 * (1 << seg_selector);
|
||||
let mut sub = Vec::new();
|
||||
be16(&mut sub, 4); // format
|
||||
be16(&mut sub, (16 + segs.len() * 8) as u16); // length
|
||||
be16(&mut sub, 0); // language
|
||||
be16(&mut sub, (segs.len() * 2) as u16); // segCountX2
|
||||
for v in [seg_search_range as u16, seg_selector as u16, (2 * seg_count - seg_search_range) as u16] {
|
||||
be16(&mut sub, v);
|
||||
}
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.1);
|
||||
}
|
||||
be16(&mut sub, 0); // reservedPad
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.0);
|
||||
}
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.2 as u16);
|
||||
}
|
||||
for _ in &segs {
|
||||
be16(&mut sub, 0); // idRangeOffset
|
||||
}
|
||||
let mut cmap = Vec::new();
|
||||
for v in [0u16, 1, 3, 1] {
|
||||
be16(&mut cmap, v);
|
||||
}
|
||||
be32(&mut cmap, 12); // the subtable, straight after the records
|
||||
cmap.extend_from_slice(&sub);
|
||||
let mut os2 = vec![0u8; 78];
|
||||
os2[8..10].copy_from_slice(&f.fs_type.to_be_bytes());
|
||||
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
|
||||
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
|
||||
tables.sort_by_key(|t| *t.0);
|
||||
let mut out = Vec::new();
|
||||
be32(&mut out, 0x0001_0000); // sfnt version 1.0
|
||||
let num_tables = tables.len() as u32;
|
||||
let table_selector = num_tables.ilog2();
|
||||
let dir_search_range = 16 * (1 << table_selector);
|
||||
// numTables, searchRange, entrySelector, rangeShift: 16-byte records, largest power of two first.
|
||||
for v in [num_tables as u16, dir_search_range as u16, table_selector as u16, (16 * num_tables - dir_search_range) as u16] {
|
||||
be16(&mut out, v);
|
||||
}
|
||||
let mut off = 12 + 16 * tables.len();
|
||||
for (t, d) in &tables {
|
||||
out.extend_from_slice(*t);
|
||||
be32(&mut out, 0); // checkSum: the readers here do not verify it
|
||||
be32(&mut out, off as u32);
|
||||
be32(&mut out, d.len() as u32);
|
||||
off += d.len().div_ceil(4) * 4;
|
||||
}
|
||||
for (_, d) in &tables {
|
||||
out.extend_from_slice(d);
|
||||
while out.len() % 4 != 0 {
|
||||
out.push(0);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! The angles of a hatch's elliptic boundary edges in the DXF a DWG is read through.
|
||||
//!
|
||||
//! A DWG holds an elliptic edge's start and end angles in radians, and so does the DXF the DWG
|
||||
//! decoder writes (groups 50 and 51 of an edge of type 3). DXF itself keeps them in degrees, which
|
||||
//! is how [`crate::dxf_read`] reads them: a circle stored as an elliptic edge with the end angle
|
||||
//! 6.2832 became an arc of 6.28 degrees, and the hatch covered the hole it should have left open.
|
||||
//! Only the DWG path needs this; a DXF file is read as written.
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
/// `dxf` with the start and end angles (groups 50 and 51) of every elliptic hatch edge (edge type
|
||||
/// 3, group 72) turned from radians to degrees. The text is handled as bytes: a drawing from
|
||||
/// before 2007 is written in its code page, which is not UTF-8, and every other byte is kept as it
|
||||
/// was. Binary DXF, and text with no such edge, come back as they were.
|
||||
pub(crate) fn elliptic_edge_degrees(dxf: Vec<u8>) -> Vec<u8> {
|
||||
if dxf.starts_with(b"AutoCAD Binary DXF") || !dxf.windows(5).any(|w| w == b"HATCH") {
|
||||
return dxf;
|
||||
}
|
||||
let mut out = Vec::with_capacity(dxf.len());
|
||||
let mut lines = dxf.split_inclusive(|b| *b == b'\n');
|
||||
let mut in_hatch = false;
|
||||
// After an elliptic edge's type, until the next edge or loop: the angles still to convert.
|
||||
let mut ellipse = false;
|
||||
let mut changed = false;
|
||||
while let Some(code_line) = lines.next() {
|
||||
let Some(value_line) = lines.next() else {
|
||||
out.extend_from_slice(code_line);
|
||||
break;
|
||||
};
|
||||
let code = code_line.trim_ascii();
|
||||
let value = value_line.trim_ascii();
|
||||
match code {
|
||||
b"0" => {
|
||||
in_hatch = value == b"HATCH";
|
||||
ellipse = false;
|
||||
}
|
||||
b"72" if in_hatch => ellipse = value == b"3",
|
||||
b"92" | b"97" if in_hatch => ellipse = false,
|
||||
b"50" | b"51" if in_hatch && ellipse => {
|
||||
if let Some(radians) = std::str::from_utf8(value).ok().and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) {
|
||||
let ending = &value_line[value_line.trim_ascii_end().len()..];
|
||||
out.extend_from_slice(code_line);
|
||||
out.extend_from_slice(format!("{}", radians * 180.0 / PI).as_bytes());
|
||||
out.extend_from_slice(ending);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out.extend_from_slice(code_line);
|
||||
out.extend_from_slice(value_line);
|
||||
}
|
||||
if changed { out } else { dxf }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pairs(text: &str) -> Vec<(String, String)> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
|
||||
}
|
||||
|
||||
const HATCH: &str = "0\r\nHATCH\r\n91\r\n1\r\n92\r\n1\r\n93\r\n2\r\n72\r\n3\r\n10\r\n5.0\r\n20\r\n6.0\r\n11\r\n-55.5\r\n21\r\n0.0\r\n40\r\n1.0\r\n50\r\n0.0\r\n51\r\n6.283185307179586\r\n73\r\n1\r\n72\r\n1\r\n10\r\n1.0\r\n20\r\n2.0\r\n11\r\n3.0\r\n21\r\n4.0\r\n50\r\n7.0\r\n0\r\nLINE\r\n50\r\n9.0\r\n";
|
||||
|
||||
#[test]
|
||||
fn an_elliptic_edge_gets_its_angles_in_degrees_and_nothing_else_changes() {
|
||||
let out = String::from_utf8(elliptic_edge_degrees(HATCH.as_bytes().to_vec())).unwrap();
|
||||
let p = pairs(&out.replace("\r\n", "\n"));
|
||||
let value = |code: &str, n: usize| p.iter().filter(|(c, _)| c == code).nth(n).map(|(_, v)| v.parse::<f64>().unwrap());
|
||||
assert!((value("51", 0).unwrap() - 360.0).abs() < 1e-9);
|
||||
assert_eq!(value("50", 0), Some(0.0));
|
||||
// A line edge's 50 and another entity's are left alone, as is the line ending.
|
||||
assert_eq!(value("50", 1), Some(7.0));
|
||||
assert_eq!(value("50", 2), Some(9.0));
|
||||
assert!(out.contains("\r\n") && !out.replace("\r\n", "").contains('\r'));
|
||||
}
|
||||
|
||||
/// A drawing from before 2007 is written in its code page: an accented letter is one byte that
|
||||
/// is not valid UTF-8, and it must not stop the angles being converted or change.
|
||||
#[test]
|
||||
fn a_code_page_drawing_still_has_its_angles_converted() {
|
||||
let mut dxf = b"0\r\nTEXT\r\n1\r\ncaf".to_vec();
|
||||
dxf.push(0xE9);
|
||||
dxf.extend_from_slice(b"\r\n");
|
||||
dxf.extend_from_slice(HATCH.as_bytes());
|
||||
let out = elliptic_edge_degrees(dxf.clone());
|
||||
assert!(std::str::from_utf8(&dxf).is_err(), "the input is not UTF-8");
|
||||
assert!(out.windows(4).any(|w| w == b"caf\xE9"), "the accented byte is kept");
|
||||
let text: String = out.iter().map(|b| char::from(*b)).collect();
|
||||
assert!(text.contains("51\r\n360"), "the end angle is 360 degrees: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_without_a_hatch_ellipse_comes_back_untouched() {
|
||||
let dxf = b"0\nLINE\n50\n1.5\n".to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(dxf.clone()), dxf);
|
||||
let binary = b"AutoCAD Binary DXF\r\n\x1a\x00HATCH".to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(binary.clone()), binary);
|
||||
// A hatch with no elliptic edge is left as it is.
|
||||
let plain = "0\nHATCH\n72\n1\n50\n2.0\n".as_bytes().to_vec();
|
||||
assert_eq!(elliptic_edge_degrees(plain.clone()), plain);
|
||||
}
|
||||
}
|
||||
@@ -79,24 +79,12 @@ fn has_images(store: &EntityStore) -> bool {
|
||||
}
|
||||
|
||||
/// Fill in each image's definition (path, name, pixel size) from the IMAGEDEF it points to.
|
||||
pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
/// `refs`: each IMAGE entity's handle in the drawing → its IMAGEDEF handle (upper case), noted
|
||||
/// as the entity was read, so an image whose repeated handle was reassigned keeps its own.
|
||||
pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing, refs: &HashMap<Handle, String>) {
|
||||
if !has_images(&d.model) && !d.layouts.iter().any(|l| has_images(&l.entities)) && !d.blocks.values().any(|b| has_images(&b.entities)) {
|
||||
return;
|
||||
}
|
||||
// IMAGE handle → IMAGEDEF handle.
|
||||
let mut refs: HashMap<Handle, String> = HashMap::new();
|
||||
for s in secs.iter().filter(|s| s.name == "ENTITIES" || s.name == "BLOCKS") {
|
||||
each_record(s.tags, |kind, tags| {
|
||||
if kind != "IMAGE" {
|
||||
return;
|
||||
}
|
||||
let h = tags.iter().find(|t| t.code == 5).and_then(|t| Handle::parse_hex(&t.str()));
|
||||
let def = tags.iter().find(|t| t.code == 340).map(|t| key(&t.str()));
|
||||
if let (Some(h), Some(def)) = (h, def) {
|
||||
refs.insert(h, def);
|
||||
}
|
||||
});
|
||||
}
|
||||
// IMAGEDEF objects, and the names dictionaries give them.
|
||||
let mut defs: HashMap<String, Def> = HashMap::new();
|
||||
let mut names: HashMap<String, String> = HashMap::new();
|
||||
|
||||
+179
-13
@@ -16,9 +16,9 @@ use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number};
|
||||
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
|
||||
use craft_dxf::{SectionRef, Tag};
|
||||
use craft_dxf::{SectionRef, Tag, Version};
|
||||
|
||||
/// Named object dictionary entries CADCraft writes itself from its model (plus every key that
|
||||
/// starts with `CADCRAFT`): they are read into the model, not kept raw. A change that starts
|
||||
@@ -457,6 +457,10 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
if !f.is_empty() {
|
||||
f.version = file_version(secs);
|
||||
}
|
||||
// Added after the version: registered applications alone are no kept objects whose groups
|
||||
// the DWG writer must read as the file's version, and nearly every file has some (ACAD).
|
||||
let appids = tables.iter().filter(|(k, _, _)| k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string());
|
||||
f.appids = appids.take(MAX_OBJECTS).collect();
|
||||
// The file's handles of the objects CADCraft writes itself (AutoLISP's `handent`).
|
||||
f.handles = ids.iter().filter(|(h, _)| !ents.contains_key(*h)).filter_map(|(h, k)| Some((handle(h)?, k.clone()))).take(MAX_OBJECTS).collect();
|
||||
if !f.is_empty() || !f.handles.is_empty() {
|
||||
@@ -686,6 +690,102 @@ pub(crate) fn data_store(tags: &mut Vec<Tag>, d: &Drawing, modern: bool) {
|
||||
tags.splice(at..at, out);
|
||||
}
|
||||
|
||||
/// Most constraint nodes, and connections per node, looked at in one constraint group.
|
||||
const MAX_CONSTRAINT_NODES: usize = 100_000;
|
||||
|
||||
/// Put the status of every node of the kept 2D constraint groups (`ACDBASSOC2DCONSTRAINTGROUP`)
|
||||
/// where a reader of the version the text is read as expects it: AutoCAD 2013 and later
|
||||
/// (`modern`) write it after the node's connections, earlier versions right after its id. The
|
||||
/// groups are kept as read, so a 2013+ drawing written in an older version's form had them in the
|
||||
/// wrong order, and its reader took every node's status from somewhere else: AutoCAD refused the
|
||||
/// DWG the bridge made from it ("Error Decrypting Data"). A group whose nodes can't all be found
|
||||
/// is left as it is.
|
||||
pub(crate) fn constraint_node_order(tags: &mut [Tag], modern: bool) {
|
||||
let mut i = 0;
|
||||
while i < tags.len() {
|
||||
let end = tags.iter().skip(i + 1).position(|t| t.code == 0).map_or(tags.len(), |k| i + 1 + k);
|
||||
if tags.get(i).is_some_and(|t| t.code == 0 && t.str().trim().eq_ignore_ascii_case("ACDBASSOC2DCONSTRAINTGROUP"))
|
||||
&& let Some(rec) = tags.get_mut(i + 1..end)
|
||||
{
|
||||
constraint_group_order(rec, modern);
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
}
|
||||
|
||||
/// [`constraint_node_order`] for one group's groups after its type.
|
||||
fn constraint_group_order(rec: &mut [Tag], modern: bool) {
|
||||
let Some(start) = rec.iter().position(|t| t.code == 100 && t.str().trim().eq_ignore_ascii_case("AcDbAssoc2dConstraintGroup")) else {
|
||||
return;
|
||||
};
|
||||
let end = rec.iter().skip(start + 1).position(|t| t.code == 100 || t.code >= 1000).map_or(rec.len(), |k| start + 1 + k);
|
||||
let Some(sec) = rec.get_mut(start + 1..end) else { return };
|
||||
let Some(nodes) = constraint_nodes(sec) else { return };
|
||||
for (at, len, old) in nodes {
|
||||
// Old order: id, status, count, connections; modern: id, count, connections, status.
|
||||
if let Some(head) = sec.get_mut(at + 1..at + len) {
|
||||
match (old, modern) {
|
||||
(true, true) => head.rotate_left(1),
|
||||
(false, false) => head.rotate_right(1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where each non-root node of a constraint group section starts: (index of its id, length of its
|
||||
/// id, status and connections, whether its status comes right after the id). `None` unless every
|
||||
/// node the group lists is found.
|
||||
fn constraint_nodes(sec: &[Tag]) -> Option<Vec<(usize, usize, bool)>> {
|
||||
let int = |p: usize, code: i32| sec.get(p).filter(|t| t.code == code).and_then(|t| t.str().trim().parse::<i64>().ok());
|
||||
let count = |p: usize| int(p, 90).and_then(|n| usize::try_from(n).ok()).filter(|n| *n <= MAX_CONSTRAINT_NODES);
|
||||
// Version, flag and work plane, then the dependency and the actions.
|
||||
let mut p = sec.iter().position(|t| t.code == 360)? + 1;
|
||||
p += count(p)? + 1;
|
||||
// The next node id, then the root node: id, connections, status (290).
|
||||
int(p, 90)?;
|
||||
int(p + 1, 90)?;
|
||||
p += count(p + 2)? + 3;
|
||||
int(p, 290)?;
|
||||
p += 1;
|
||||
// The registry: class name and id of each node.
|
||||
let n = count(p)?;
|
||||
p += 1;
|
||||
let mut ids = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
sec.get(p).filter(|t| t.code == 1)?;
|
||||
ids.push(int(p + 1, 90)?);
|
||||
p += 2;
|
||||
}
|
||||
let known: HashSet<i64> = ids.iter().copied().collect();
|
||||
// Groups looked at while searching for headers, capped so a hostile group can't take long.
|
||||
let budget = std::cell::Cell::new(MAX_CONSTRAINT_NODES.saturating_mul(100));
|
||||
// A node header at `q`: its length and whether it is in the old order. Connections are ids of
|
||||
// nodes (or of the root, 0), which keeps a node's data from passing for the next header.
|
||||
let header = |q: usize, id: i64| -> Option<(usize, bool)> {
|
||||
int(q, 90).filter(|v| *v == id)?;
|
||||
let old = sec.get(q + 1)?.code == 70;
|
||||
let c = q + 1 + usize::from(old);
|
||||
let n = count(c).filter(|n| *n <= known.len())?;
|
||||
budget.set(budget.get().checked_sub(n + 1)?);
|
||||
for k in 0..n {
|
||||
int(c + 1 + k, 90).filter(|v| *v == 0 || known.contains(v))?;
|
||||
}
|
||||
if !old {
|
||||
int(c + 1 + n, 70)?;
|
||||
}
|
||||
Some((n + 3, old))
|
||||
};
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
let at = (p..sec.len()).find(|q| header(*q, id).is_some())?;
|
||||
let (len, old) = header(at, id)?;
|
||||
out.push((at, len, old));
|
||||
p = at + len;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Drop a dictionary's modelled entries (key and handle) from its groups.
|
||||
fn strip_entries(tags: &mut Vec<RawTag>) {
|
||||
let mut out = Vec::with_capacity(tags.len());
|
||||
@@ -941,13 +1041,61 @@ fn unknown_handles(d: &Drawing) -> HashSet<String> {
|
||||
all_entities(d).filter(|e| matches!(e.kind, EntityKind::Unknown(_))).map(|e| e.handle.hex()).collect()
|
||||
}
|
||||
|
||||
/// Render settings (`RENDERSETTINGS`, `MENTALRAYRENDERSETTINGS`, `RAPIDRTRENDERSETTINGS`) store
|
||||
/// their `AcDbRenderSettings` class version (the first group 90 after that marker) in the form of
|
||||
/// the file's version: a 2013+ file stores it one higher, and a 2013 file stores a rapid RT one
|
||||
/// one lower, as acadrust reads and writes them (`write_render_settings_dxf` in acadrust 0.6.6's
|
||||
/// `io/dxf/writer/section_writer.rs`, and its DWG class-object reader and writer; the test
|
||||
/// `render_settings_class_version_matches_what_acadrust_writes` fails if the two drift apart). A
|
||||
/// kept object carries the form of the file it was read from ([`Foreign::version`], not the
|
||||
/// drawing's `$ACADVER`, which SAVEAS changes); written into a file read as another version, it
|
||||
/// takes that version's form. The DWG bridge's R2000 text is read as the version the kept objects
|
||||
/// came from (craft-dwg's `encode_kept_noted`), so there they stay as read (#907, #2471).
|
||||
///
|
||||
/// Only that first group 90 is converted, on purpose: the group 90 that starts a kind's own
|
||||
/// subclass (`AcDbMentalRayRenderSettings`, `AcDbRapidRTRenderSettings`) is that kind's version,
|
||||
/// stored the same in every file version, and is left as read.
|
||||
pub(crate) fn render_settings_versions(tags: &mut [Tag], source: Option<Version>, declared: Version) {
|
||||
let Some(source) = source.filter(|s| *s != declared) else { return };
|
||||
let shift = |rapid: bool, v: Version| if rapid { -i64::from(v == Version::R2013) } else { i64::from(v >= Version::R2013) };
|
||||
let (mut kind, mut in_base) = (String::new(), false);
|
||||
for t in tags.iter_mut() {
|
||||
match t.code {
|
||||
0 => {
|
||||
kind = up(&t.str());
|
||||
in_base = false;
|
||||
}
|
||||
100 if matches!(kind.as_str(), "RENDERSETTINGS" | "MENTALRAYRENDERSETTINGS" | "RAPIDRTRENDERSETTINGS") => {
|
||||
in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings");
|
||||
}
|
||||
90 if in_base => {
|
||||
let rapid = kind == "RAPIDRTRENDERSETTINGS";
|
||||
let logical = t.i64().saturating_sub(shift(rapid, source));
|
||||
*t = Tag::i(90, logical.saturating_add(shift(rapid, declared)));
|
||||
in_base = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the drawing's foreign data back into a written file's tags (see the module comment).
|
||||
pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle, Vec<String>>, modern: bool) {
|
||||
/// `strings`: whether the file has a form for a proxy's separate string stream (a DXF of 2007 or
|
||||
/// later, or the DWG bridge); without one such a proxy is left out (#3229). Returns the foreign
|
||||
/// objects written, by their handles in the drawing (the file gives them new ones).
|
||||
pub(crate) fn finish(
|
||||
tags: &mut Vec<Tag>,
|
||||
d: &Drawing,
|
||||
reactors: &HashMap<Handle, Vec<String>>,
|
||||
modern: bool,
|
||||
target_modern: bool,
|
||||
strings: bool,
|
||||
) -> HashSet<Handle> {
|
||||
let f = d.foreign.as_ref();
|
||||
let unknown = unknown_handles(d);
|
||||
let xd: XdataOf = all_entities(d).filter(|e| !e.common.xdata.is_empty()).map(|e| (e.handle, e.common.xdata.as_slice())).collect();
|
||||
if f.is_empty() && unknown.is_empty() && xd.is_empty() {
|
||||
return;
|
||||
return HashSet::new();
|
||||
}
|
||||
let recs = written_records(tags);
|
||||
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
|
||||
@@ -970,14 +1118,21 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
numbers.entry(n).or_insert(500_i64.saturating_add(i64::try_from(i).unwrap_or(i64::MAX)));
|
||||
}
|
||||
let renumber = |old| proxy_class_number(f, &numbers, old);
|
||||
// A proxy is dropped when its class isn't written, or when its strings have no place here.
|
||||
let no_room = |t: &[(i32, &str)]| !strings && proxy_has_string_stream(t.iter().copied());
|
||||
// Entities of types CADCraft doesn't model, placed among the written ones.
|
||||
let mut planned = plan_unknown(d, &recs, tags, &roles, modern);
|
||||
let mut planned = plan_unknown(d, &recs, tags, &roles, modern, target_modern);
|
||||
for list in planned.values_mut() {
|
||||
list.retain_mut(|(_, t)| {
|
||||
if !t.first().is_some_and(|z| is_proxy(&z.str())) {
|
||||
return true;
|
||||
}
|
||||
let Some(n) = renumber(class_number(t.iter().map(|x| (x.code, x.str())))) else { return false };
|
||||
let groups: Vec<(i32, String)> = t.iter().map(|x| (x.code, x.str())).collect();
|
||||
let groups: Vec<(i32, &str)> = groups.iter().map(|(c, v)| (*c, v.as_str())).collect();
|
||||
if no_room(&groups) {
|
||||
return false;
|
||||
}
|
||||
let Some(n) = renumber(class_number(groups.iter().copied())) else { return false };
|
||||
set_class_number(t, n);
|
||||
true
|
||||
});
|
||||
@@ -1015,8 +1170,11 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
// Keep established live paths available to descendants during this pass as well.
|
||||
let mut alive_memo: HashMap<String, bool> = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect();
|
||||
let kept = |h: &str| kept.get(h) == Some(&true);
|
||||
for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none())
|
||||
{
|
||||
let dropped = |o: &ForeignObject| {
|
||||
let groups: Vec<(i32, &str)> = o.tags.iter().map(|r| (r.code, r.value.as_str())).collect();
|
||||
no_room(&groups) || renumber(class_number(groups.iter().copied())).is_none()
|
||||
};
|
||||
for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && dropped(o)) {
|
||||
alive_memo.insert(o.handle.hex(), false);
|
||||
}
|
||||
for o in &f.objects {
|
||||
@@ -1113,7 +1271,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
join_entries(&map, b, kept, &mut out);
|
||||
}
|
||||
}
|
||||
add_appids(&mut out);
|
||||
add_appids(&mut out, &f.appids);
|
||||
let top = max_handle(&out).saturating_add(1);
|
||||
if let Some(t) = seed_index(&out).and_then(|i| out.get_mut(i))
|
||||
&& Handle::parse_hex(&t.str()).is_none_or(|h| h.0 < top)
|
||||
@@ -1121,6 +1279,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
|
||||
*t = Tag::s(5, format!("{top:X}"));
|
||||
}
|
||||
*tags = out;
|
||||
map.alive.keys().filter_map(|h| handle(h)).collect()
|
||||
}
|
||||
|
||||
/// Kept extension dictionaries of written records: those that go on a record without its own,
|
||||
@@ -1202,6 +1361,7 @@ fn plan_unknown(
|
||||
tags: &[Tag],
|
||||
roles: &HashMap<ForeignKey, String>,
|
||||
modern: bool,
|
||||
target_modern: bool,
|
||||
) -> HashMap<usize, Vec<(String, Vec<Tag>)>> {
|
||||
let stored = d.foreign.data_store_entities();
|
||||
let mut out: HashMap<usize, Vec<(String, Vec<Tag>)>> = HashMap::new();
|
||||
@@ -1241,7 +1401,9 @@ fn plan_unknown(
|
||||
for e in store.iter() {
|
||||
match &e.kind {
|
||||
EntityKind::Unknown(u) => {
|
||||
if modern && cadcraft_doc::foreign::sat_text_acis(u, e.handle, &stored) {
|
||||
if (modern && cadcraft_doc::foreign::sat_text_acis(u, e.handle, &stored))
|
||||
|| (!target_modern && cadcraft_doc::foreign::acis_left_out(u, e.handle, &stored, false))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let t = unknown_entity(u, e, &owner, paper);
|
||||
@@ -1435,9 +1597,13 @@ fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>)
|
||||
}
|
||||
}
|
||||
|
||||
/// APPID records for every application with xdata in the file, added to the APPID table.
|
||||
fn add_appids(out: &mut Vec<Tag>) {
|
||||
let used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
|
||||
/// APPID records for every application with xdata in the file and every one the file read had
|
||||
/// (`kept`), added to the APPID table.
|
||||
fn add_appids(out: &mut Vec<Tag>, kept: &[String]) {
|
||||
let mut used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
|
||||
for name in kept.iter().filter(|n| !n.is_empty()) {
|
||||
used.entry(up(name)).or_insert_with(|| name.clone());
|
||||
}
|
||||
let recs = written_records(out);
|
||||
let Some(table) = recs.iter().position(|r| {
|
||||
r.sec == "TABLES" && r.kind == "TABLE" && val(out.get(r.start + 1..r.end).unwrap_or(&[]), 2).is_some_and(|n| up(&n) == "APPID")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! DXF → Drawing.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use cadcraft_color::{Color, Rgb};
|
||||
use cadcraft_doc::{
|
||||
@@ -24,8 +24,8 @@ mod tables;
|
||||
mod text;
|
||||
|
||||
use document::{
|
||||
apply_sortents, count_skipped, dropped_paper_views, outside_sections, parse_entities, place_blocks, place_entities, read_blocks, read_objects,
|
||||
setup_layouts,
|
||||
HandlePolicy, apply_sortents, count_skipped, dropped_paper_views, outside_sections, parse_entities, place_blocks, place_entities, read_blocks,
|
||||
read_objects, setup_layouts,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use entities::acad_table;
|
||||
@@ -62,6 +62,9 @@ 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
|
||||
@@ -71,6 +74,28 @@ struct Rx {
|
||||
block: Option<String>,
|
||||
/// The points HATCH boundary curves may still be sampled into.
|
||||
curves: hatch::CurvePoints,
|
||||
/// IMAGE entity handle, as read (a repeated one reassigned) → its IMAGEDEF handle (upper case).
|
||||
image_defs: HashMap<Handle, String>,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -102,6 +127,18 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
||||
let mut blocks: Vec<BlockDef> = Vec::new();
|
||||
let mut layout_objs: Vec<LayoutDef> = Vec::new();
|
||||
let mut entities = Vec::new();
|
||||
// One set for every list: a generated handle must be unique across blocks and ENTITIES
|
||||
// (a *MODEL_SPACE block and an ENTITIES record both land in the model space).
|
||||
let mut seen_handles = HashSet::new();
|
||||
// Model/paper-space handles retain priority if an in-memory drawing or damaged DXF also
|
||||
// assigns one to a block entity. This preserves top-level references while letting block
|
||||
// handles be repaired before their deferred fixups are recorded.
|
||||
let reserved_entity_handles: HashSet<Handle> = secs
|
||||
.iter()
|
||||
.filter(|s| s.name == "ENTITIES")
|
||||
.flat_map(|s| record_slices(s.tags))
|
||||
.filter_map(|(_, tags)| common::T(tags).s(5).and_then(|h| Handle::parse_hex(&h)))
|
||||
.collect();
|
||||
let mut objs = Objects::default();
|
||||
// Every handle another program's file already uses is taken before anything gets a new one:
|
||||
// its $HANDSEED can be lower than its handles, and entities made while reading (the faces of
|
||||
@@ -145,17 +182,33 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
||||
match s.name {
|
||||
"HEADER" => header(s.tags, &mut d),
|
||||
"TABLES" => tables(s.tags, &mut d, &mut rx),
|
||||
"BLOCKS" => blocks.extend(read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped)),
|
||||
"BLOCKS" => {
|
||||
blocks.extend(read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped, &mut seen_handles, &reserved_entity_handles))
|
||||
}
|
||||
// A damaged file may split its entities over several ENTITIES sections (#865).
|
||||
"ENTITIES" => {
|
||||
let mut n = 0;
|
||||
entities.extend(parse_entities(&record_slices(s.tags), &mut d, &mut rx, &mut n, &mut table_cells_left));
|
||||
entities.extend(parse_entities(
|
||||
&record_slices(s.tags),
|
||||
&mut d,
|
||||
&mut rx,
|
||||
&mut n,
|
||||
&mut table_cells_left,
|
||||
&mut HandlePolicy { seen: &mut seen_handles, reserved: &reserved_entity_handles, source_wins: true },
|
||||
));
|
||||
count_skipped(&mut skipped, "ENTITIES", n);
|
||||
}
|
||||
"OBJECTS" => read_objects(s.tags, &mut objs, &mut layout_objs),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// 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()));
|
||||
@@ -165,7 +218,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
|
||||
number_unknown_viewport_ids(&mut d, &dropped_paper_views(&rx, &paper_block_for, &first_layout));
|
||||
apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout);
|
||||
objs.apply(&mut d, &rx);
|
||||
crate::dxf_image::resolve(&secs, &mut d);
|
||||
crate::dxf_image::resolve(&secs, &mut d, &rx.image_defs);
|
||||
crate::dxf_mline::resolve(&secs, &mut d);
|
||||
// Keep handles unique against the header's seed.
|
||||
let seed = d.header.str("HANDSEED", "");
|
||||
@@ -189,6 +242,7 @@ 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)
|
||||
}
|
||||
|
||||
@@ -221,6 +275,23 @@ fn number_unknown_viewport_ids(d: &mut Drawing, sheet_dropped: &std::collections
|
||||
}
|
||||
}
|
||||
|
||||
/// Capture after all tables and entity fixups, including files whose tables follow entities.
|
||||
fn remember_text_fits(d: &mut Drawing) {
|
||||
let mut fits = std::collections::BTreeMap::new();
|
||||
for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())) {
|
||||
let texts: Vec<&Text> = match &e.kind {
|
||||
EntityKind::Text(t) => vec![t],
|
||||
EntityKind::AttDef(a) => vec![&a.text],
|
||||
EntityKind::Insert(i) => i.attribs.iter().map(|a| &a.text).collect(),
|
||||
_ => continue,
|
||||
};
|
||||
if texts.iter().any(|t| matches!(t.halign, HAlign::Aligned | HAlign::Fit)) {
|
||||
fits.insert(e.handle, texts.into_iter().map(|t| (t.clone(), d.text_style(&t.style).cloned().unwrap_or_default())).collect());
|
||||
}
|
||||
}
|
||||
std::sync::Arc::make_mut(&mut d.foreign).text_fits = fits;
|
||||
}
|
||||
|
||||
/// An entity from the groups of a DXF record of type `kind` (without its `0` group), as the
|
||||
/// reader makes it, with plain strings as [`crate::entity_groups`] gives them (not the file's
|
||||
/// `^ ` escapes). AutoLISP's `entmake` and `entmod` are built on it.
|
||||
|
||||
@@ -1,14 +1,57 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::common::T;
|
||||
use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity};
|
||||
use super::objects::{MAX_OBJECTS, Objects, page_setup};
|
||||
use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, Vec2, record_slices};
|
||||
|
||||
/// Allocate an entity handle that is unique within the DXF, including against handles assigned
|
||||
/// to earlier malformed or generated entities.
|
||||
fn fresh_entity_handle(d: &mut Drawing, seen: &mut HashSet<Handle>, reserved: &HashSet<Handle>) -> Handle {
|
||||
// The seed saturates at `u64::MAX`: once a file uses that handle, `new_handle` keeps
|
||||
// returning it and a plain retry loop would never terminate. Stop as soon as it stops
|
||||
// advancing.
|
||||
let mut previous = None;
|
||||
loop {
|
||||
let h = d.new_handle();
|
||||
if !reserved.contains(&h) && seen.insert(h) {
|
||||
return h;
|
||||
}
|
||||
if previous == Some(h) {
|
||||
break;
|
||||
}
|
||||
previous = Some(h);
|
||||
}
|
||||
// Every value the seed can still reach is taken, so scan from the bottom: the occupied set
|
||||
// is finite, which guarantees a free handle within its size plus one candidates.
|
||||
let limit = seen.len().saturating_add(reserved.len()).saturating_add(1);
|
||||
let mut candidate = 1u64;
|
||||
for _ in 0..limit {
|
||||
let h = Handle(candidate);
|
||||
if !reserved.contains(&h) && seen.insert(h) {
|
||||
return h;
|
||||
}
|
||||
candidate = candidate.saturating_add(1);
|
||||
}
|
||||
// Unreachable in practice (pigeonhole over the finite occupied set); never lose the entity.
|
||||
d.new_handle()
|
||||
}
|
||||
|
||||
/// How an ENTITIES list assigns handles: the handles already seen anywhere in the file, the
|
||||
/// ones the block records reserved, and whether a record's own handle beats the reservation.
|
||||
pub(super) struct HandlePolicy<'a> {
|
||||
pub seen: &'a mut HashSet<Handle>,
|
||||
pub reserved: &'a HashSet<Handle>,
|
||||
pub source_wins: bool,
|
||||
}
|
||||
|
||||
pub(super) fn parse_entities(
|
||||
recs: &[(String, &[Tag])],
|
||||
d: &mut Drawing,
|
||||
rx: &mut Rx,
|
||||
skipped: &mut usize,
|
||||
table_cells_left: &mut usize,
|
||||
hp: &mut HandlePolicy<'_>,
|
||||
) -> Vec<(Option<String>, bool, Entity)> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
@@ -58,13 +101,18 @@ pub(super) fn parse_entities(
|
||||
// A file's handles keep their identity, however high they are (#913, #939).
|
||||
Some(h) => {
|
||||
d.bump_handseed(h);
|
||||
h
|
||||
// A file's own handle wins when it is the first copy on a source list that
|
||||
// keeps them (ENTITIES); block copies yield to the reserved top-level ones.
|
||||
let kept = if hp.source_wins { hp.seen.insert(h) } else { !hp.reserved.contains(&h) && hp.seen.insert(h) };
|
||||
if kept { h } else { fresh_entity_handle(d, hp.seen, hp.reserved) }
|
||||
}
|
||||
None => d.new_handle(),
|
||||
None => fresh_entity_handle(d, hp.seen, hp.reserved),
|
||||
};
|
||||
entity_extras(kind, tags, h, &mut k, rx);
|
||||
let more: Vec<_> =
|
||||
extra.into_iter().map(|f| (owner.clone(), paper, Entity { handle: d.new_handle(), common: c.clone(), kind: f })).collect();
|
||||
let more: Vec<_> = extra
|
||||
.into_iter()
|
||||
.map(|f| (owner.clone(), paper, Entity { handle: fresh_entity_handle(d, hp.seen, hp.reserved), common: c.clone(), kind: f }))
|
||||
.collect();
|
||||
out.push((owner, paper, Entity { handle: h, common: c, kind: k }));
|
||||
out.extend(more);
|
||||
} else if kind == "HATCH" {
|
||||
@@ -73,14 +121,6 @@ pub(super) fn parse_entities(
|
||||
*skipped = skipped.saturating_add(1);
|
||||
}
|
||||
}
|
||||
// Assign fresh handles to duplicates (hostile files).
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for (_, _, e) in &mut out {
|
||||
if !seen.insert(e.handle) {
|
||||
e.handle = d.new_handle();
|
||||
seen.insert(e.handle);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -91,6 +131,8 @@ pub(super) fn read_blocks(
|
||||
rx: &mut Rx,
|
||||
table_cells_left: &mut usize,
|
||||
skipped: &mut std::collections::BTreeMap<String, usize>,
|
||||
seen_handles: &mut HashSet<Handle>,
|
||||
reserved_handles: &HashSet<Handle>,
|
||||
) -> Vec<BlockDef> {
|
||||
let recs = record_slices(tags);
|
||||
for (k, tg) in &recs {
|
||||
@@ -116,7 +158,14 @@ pub(super) fn read_blocks(
|
||||
}
|
||||
let body = recs.get(i + 1..j).unwrap_or(&[]);
|
||||
rx.block = Some(name.to_ascii_uppercase());
|
||||
let ents = parse_entities(body, d, rx, &mut n, table_cells_left);
|
||||
let ents = parse_entities(
|
||||
body,
|
||||
d,
|
||||
rx,
|
||||
&mut n,
|
||||
table_cells_left,
|
||||
&mut HandlePolicy { seen: seen_handles, reserved: reserved_handles, source_wins: false },
|
||||
);
|
||||
rx.block = None;
|
||||
blocks.push((name, base, description, ents, xref));
|
||||
i = j + 1;
|
||||
|
||||
@@ -88,6 +88,7 @@ fn lwpolyline(tags: &[Tag], c: &mut Common, t: &T) -> Option<EntityKind> {
|
||||
// In a tilted plane: drawn as seen from above, at the vertices' mean height, its
|
||||
// vertices now plan coordinates.
|
||||
(verts, elevation) = plan_of_tilted(c.extrusion, elevation, &verts, flags & 1 != 0);
|
||||
thickness_along_z(c);
|
||||
c.extrusion = Vec3::Z;
|
||||
} else if c.extrusion.z < 0.0 {
|
||||
for v in &mut verts {
|
||||
@@ -328,6 +329,7 @@ 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))
|
||||
@@ -487,6 +489,10 @@ 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);
|
||||
@@ -515,6 +521,13 @@ pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityK
|
||||
rx.table_style_fix.push((h, t.s(342).map(|sh| sh.trim().to_ascii_uppercase()).unwrap_or_default()));
|
||||
}
|
||||
}
|
||||
// Keyed by the handle the entity was given, so an IMAGE whose repeated handle was
|
||||
// reassigned still finds its own IMAGEDEF.
|
||||
("IMAGE", EntityKind::Image(_)) => {
|
||||
if let Some(def) = tags.iter().find(|t| t.code == 340) {
|
||||
rx.image_defs.insert(h, def.str().trim().to_ascii_uppercase());
|
||||
}
|
||||
}
|
||||
("INSERT", EntityKind::Insert(ins)) => {
|
||||
rx.inserted.insert(ins.block.to_ascii_uppercase());
|
||||
}
|
||||
@@ -570,7 +583,7 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
|
||||
break;
|
||||
}
|
||||
}
|
||||
let c = common(t);
|
||||
let mut c = common(t);
|
||||
let mut extra: Vec<EntityKind> = Vec::new();
|
||||
let k = if flags & 64 != 0 {
|
||||
// Face records that name a missing vertex (or fewer than three) are dropped: they draw
|
||||
@@ -592,13 +605,26 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
|
||||
} else if flags & 8 != 0 {
|
||||
EntityKind::Polyline3d(Polyline3d { points: pts.iter().map(|p| p.0).collect(), closed: flags & 1 != 0 })
|
||||
} else {
|
||||
// A 2D polyline's vertices are in its OCS: mirrored like LWPOLYLINE.
|
||||
let m = if c.extrusion.z < 0.0 { -1.0 } else { 1.0 };
|
||||
// A 2D polyline's vertices are in its OCS, at the elevation of the POLYLINE's own point:
|
||||
// in a tilted plane drawn as seen from above like LWPOLYLINE, else mirrored like it.
|
||||
let closed = flags & 1 != 0;
|
||||
let mut vertices: Vec<PolyVertex> = pts.iter().map(|p| PolyVertex { p: p.0.xy(), bulge: p.1, start_width: p.2, end_width: p.3 }).collect();
|
||||
let mut elevation = t.p(10).z;
|
||||
if tilted(c.extrusion, run_points(&vertices, elevation, closed)) {
|
||||
(vertices, elevation) = plan_of_tilted(c.extrusion, elevation, &vertices, closed);
|
||||
thickness_along_z(&mut c);
|
||||
c.extrusion = Vec3::Z;
|
||||
} else if c.extrusion.z < 0.0 {
|
||||
for v in &mut vertices {
|
||||
v.p.x = -v.p.x;
|
||||
v.bulge = -v.bulge;
|
||||
}
|
||||
}
|
||||
EntityKind::LwPolyline(LwPolyline {
|
||||
vertices: pts.iter().map(|p| PolyVertex { p: Vec2::new(m * p.0.x, p.0.y), bulge: m * p.1, start_width: p.2, end_width: p.3 }).collect(),
|
||||
closed: flags & 1 != 0,
|
||||
vertices,
|
||||
closed,
|
||||
const_width: t.fd(40, 0.0).min(t.fd(41, 0.0)).max(0.0),
|
||||
elevation: t.p(10).z,
|
||||
elevation,
|
||||
plinegen: flags & 128 != 0,
|
||||
})
|
||||
};
|
||||
@@ -707,3 +733,11 @@ fn helix(tags: &[Tag]) -> Helix {
|
||||
}
|
||||
.sanitized()
|
||||
}
|
||||
|
||||
/// A polyline drawn as seen from above gets the normal +Z: its thickness keeps the side of Z it
|
||||
/// extruded toward, which the normal it is losing said.
|
||||
fn thickness_along_z(c: &mut Common) {
|
||||
if c.extrusion.z < 0.0 {
|
||||
c.thickness = -c.thickness;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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, sources });
|
||||
loops.push(HatchLoop { vertices: verts, outer, boundary_flags: Some(flags), sources });
|
||||
}
|
||||
curves.left = curves.left.saturating_sub(start_left.saturating_sub(budget.left));
|
||||
if budget.cut {
|
||||
|
||||
@@ -421,6 +421,8 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
|
||||
// Plot layout flags: 2 display plot styles, 4 centred, 16 standard scale (75 = 0: scaled
|
||||
// to fit), 128 lineweights.
|
||||
if let Some(flags) = t.i(70) {
|
||||
// Kept to be written back (a 16-bit group: only those bits).
|
||||
p.file_plot_flags = Some(flags & 0xFFFF);
|
||||
p.show_plot_styles = flags & 2 != 0;
|
||||
p.center = flags & 4 != 0;
|
||||
p.lineweights = flags & 128 != 0;
|
||||
@@ -432,6 +434,13 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
|
||||
if let Some(s) = pos(ratio).or_else(|| pos(t.f(147))) {
|
||||
p.scale = s;
|
||||
}
|
||||
// A standard scale (flag 16, group 75 above 0: 0 is scaled to fit, the DXF Reference lists
|
||||
// 1 to 32), kept with the scale it stands for so a save can tell it was not changed.
|
||||
if t.i(70).is_some_and(|f| f & 16 != 0)
|
||||
&& let Some(code) = t.i(75).filter(|c| (1..=32).contains(c))
|
||||
{
|
||||
p.file_standard_scale = Some((code, p.scale));
|
||||
}
|
||||
p.plot_area = match t.i(74) {
|
||||
Some(0) => "display",
|
||||
Some(1) => "extents",
|
||||
|
||||
@@ -299,6 +299,7 @@ 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" => {
|
||||
@@ -310,9 +311,13 @@ 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,7 +70,8 @@ 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, sources: Vec::new() }];
|
||||
let mut loops =
|
||||
vec![HatchLoop { vertices: pl.vertices.into_iter().filter(fin).collect(), outer: first_outer, boundary_flags: None, sources: Vec::new() }];
|
||||
let mut total = 0usize;
|
||||
let mut cur: Option<HatchLoop> = None;
|
||||
let mut expect_flag = false;
|
||||
@@ -81,7 +82,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, sources: Vec::new() });
|
||||
cur = Some(HatchLoop { vertices: Vec::new(), outer: false, boundary_flags: None, sources: Vec::new() });
|
||||
expect_flag = true;
|
||||
}
|
||||
1070 if expect_flag => {
|
||||
|
||||
@@ -24,6 +24,8 @@ mod entity;
|
||||
mod header;
|
||||
mod layout;
|
||||
mod objects;
|
||||
mod proxy;
|
||||
pub use proxy::proxies_lost;
|
||||
mod sections;
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -149,15 +151,70 @@ pub fn write(d: &Drawing) -> String {
|
||||
|
||||
/// The drawing's DXF tags, declaring `version` in `$ACADVER`.
|
||||
pub fn tags(d: &Drawing, version: Version) -> Vec<Tag> {
|
||||
tags_for(d, version, version, version < Version::R2004)
|
||||
tags_kept(d, version).0
|
||||
}
|
||||
|
||||
/// [`tags`], with the foreign objects the file keeps, by their handles in the drawing.
|
||||
fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::HashSet<cadcraft_doc::Handle>) {
|
||||
let (mut tags, kept) = sections::tags_kept_for(d, version, version, version < Version::R2004, false);
|
||||
// Kept proxies in this version's layout (#3229). Not for the DWG bridge, whose writer reads
|
||||
// them in the layout of the DWG they came from.
|
||||
proxy::proxy_layout(&mut tags, version);
|
||||
(tags, kept)
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
let mut tags = tags_for(d, Version::R2000, dwg, false);
|
||||
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);
|
||||
}
|
||||
}
|
||||
bridge_markers(&mut tags);
|
||||
craft_dxf::write_ascii(&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
|
||||
}
|
||||
|
||||
/// Proxy type names and lookup-parameter subclass names must match the bridge reader's spelling.
|
||||
|
||||
@@ -2,13 +2,15 @@ use super::{
|
||||
Block, Color, Common, Dimension, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext,
|
||||
};
|
||||
|
||||
/// What happens to the anonymous `*D` blocks read from a file (#495): a dimension that still
|
||||
/// names its block regenerates its geometry under that name, keeping the block's entity
|
||||
/// handles, and `*D` blocks nothing else references are not written again.
|
||||
/// What happens to the dimension blocks read from a file (#495): a dimension that still names
|
||||
/// its block is written with that block, under its name, and `*D` blocks nothing else
|
||||
/// references are not written again. The block a dimension names may have any name: other
|
||||
/// programs don't always use `*D` (#3299).
|
||||
pub(super) struct DimBlockPlan {
|
||||
/// Dimension (model or paper space) → the read block whose name and handles it reuses.
|
||||
pub(super) reuse: HashMap<Handle, std::sync::Arc<Block>>,
|
||||
/// Upper-case names of `*D` blocks not written as ordinary blocks.
|
||||
/// Upper-case names of blocks not written as ordinary blocks: `*D` blocks and the blocks
|
||||
/// dimensions name, when nothing else uses them.
|
||||
pub(super) skip: std::collections::HashSet<String>,
|
||||
}
|
||||
|
||||
@@ -16,6 +18,12 @@ fn is_dim_block(name: &str) -> bool {
|
||||
name.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("*D"))
|
||||
}
|
||||
|
||||
/// The read block, not named `*D`, that a dimension block definition named `name` is written
|
||||
/// from (#3299): its record and block properties are written as read.
|
||||
pub(super) fn kept_named_dim_block<'a>(d: &'a Drawing, name: &str) -> Option<&'a Block> {
|
||||
d.block(name).filter(|_| !is_dim_block(name)).map(|b| b.as_ref())
|
||||
}
|
||||
|
||||
pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan {
|
||||
let spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect();
|
||||
// Block names other objects use: inserts and multileader contents anywhere, and dimensions
|
||||
@@ -35,12 +43,19 @@ pub(super) fn dim_block_plan(d: &Drawing) -> DimBlockPlan {
|
||||
for e in d.blocks.values().flat_map(|b| b.entities.iter()) {
|
||||
note(e, true, &mut used);
|
||||
}
|
||||
let skip = d.blocks.keys().filter(|n| is_dim_block(n)).map(|n| n.to_ascii_uppercase()).filter(|n| !used.contains(n)).collect();
|
||||
// Blocks the dimensions of model and paper space still name, whatever their names.
|
||||
let named: std::collections::HashSet<String> = spaces
|
||||
.iter()
|
||||
.flat_map(|s| s.iter())
|
||||
.filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { dm.block.as_ref().map(|n| n.to_ascii_uppercase()) } else { None })
|
||||
.collect();
|
||||
let skip =
|
||||
d.blocks.keys().map(|n| n.to_ascii_uppercase()).filter(|n| is_dim_block(n) || named.contains(n)).filter(|n| !used.contains(n)).collect();
|
||||
let mut plan = DimBlockPlan { reuse: HashMap::new(), skip };
|
||||
let mut claimed = std::collections::HashSet::new();
|
||||
for e in spaces.iter().flat_map(|s| s.iter()) {
|
||||
let EntityKind::Dimension(dm) = &e.kind else { continue };
|
||||
let Some(b) = dm.block.as_deref().filter(|n| is_dim_block(n)).and_then(|n| d.block(n)) else { continue };
|
||||
let Some(b) = dm.block.as_deref().and_then(|n| d.block(n)) else { continue };
|
||||
let key = b.name.to_ascii_uppercase();
|
||||
if plan.skip.contains(&key) && claimed.insert(key) {
|
||||
plan.reuse.insert(e.handle, b.clone());
|
||||
|
||||
@@ -254,8 +254,69 @@ 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>) {
|
||||
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
|
||||
};
|
||||
let attdef = attdef_prompt.is_some();
|
||||
// An attribute definition with no default value is drawn as its tag, whatever its prompt: the
|
||||
// baseline start AutoCAD stored is judged against the tag's width too. A stored point that is
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user