diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 000000000..de64ad3ee --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c2cf475e8..a0ae76e01 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,6 +18,12 @@ concurrency: cancel-in-progress: false jobs: + # Regenerates contributors/contributors.json for the release commit; every build bundles it. + credits: + permissions: + contents: read + pull-requests: read + uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main git-sources: name: Git dependencies come from storytold runs-on: ubuntu-latest @@ -58,7 +64,7 @@ jobs: PY release: - needs: git-sources + needs: [git-sources, credits] permissions: # The reusable release workflow tags and uploads the draft release. contents: write @@ -70,6 +76,7 @@ jobs: app-title: CADCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 version: ${{ inputs.version }} + contributors-artifact: ${{ needs.credits.outputs.artifact-name }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} diff --git a/AGENTS.md b/AGENTS.md index 309f3f0ce..8d040f598 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,13 +1,62 @@ + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + # CADCraft — instructions for agents CADCraft is a clean-room, open-source, pure-Rust computer-aided design and drafting application targeting Autodesk AutoCAD parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows, Linux and FreeBSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop-class), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../pdfcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign). ## Start every session here -1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/autocad/*` (`01-observed-ui.md` holds measured observations of the running reference app; `04-menu-tree.txt` the menu tree by name). -2. Library decisions: `plan/adr/0001-geometry-libraries.md` (what we may depend on, what is rejected for licence reasons). -3. Follow the autonomous operation protocol (`plan/execution-plan.md` §6). Don't stop to ask unless it lists the decision as the owner's. - -`plan/` is gitignored (local only). +Read [`ROADMAP.md`](ROADMAP.md) and [`docs/gaps.md`](docs/gaps.md). `plan/` is an optional gitignored notebook (status, execution notes, `plan/autocad/*`). Do not ask for it and do not stop when it is absent. Licence choices stay inside the house-rules allowlist. ## Never crash People trust CADCraft with their drawings; a crash loses their work. **This outranks feature work.** @@ -28,9 +77,8 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr - **Programmatic calls never open dialogs.** `engine.execute` runs the JSON form with defaults; only menu/toolbar invocation starts the interactive prompt sequence. - **Layering** is enforced by `cargo xtask layers`: L0 `geom`, `dxf` → L1 `color`, `doc` → L2 `fonts`, `render`, `constraints` → L3 `io` → L4 `engine` → L5 `ui-egui`, `mcp` → apps. Nothing below L5 depends on egui/eframe/winit/wgpu/rfd. **The UI crate is swappable.** - **The UI is thin**: panels read engine state and act through `app.run(id, params)` / `app.start(id)` / `app.cmdline(text)`. Colours come from `theme::Tokens`. -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). Commit after every feature arc that builds, and push to `main`. +- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). Commit after every feature arc that builds. ## Running and looking at the app - `cargo run --release -p cadcraft -- --sample --control PORT` (sample drawing + control channel). Pick a free port; other crafting apps use control ports too. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f9772bca5..4140c55cc 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -78,3 +78,4 @@ Generated-in-code assets are original and have no file to list: | `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker | | `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending | | `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending | +| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) | diff --git a/CLAUDE.md b/CLAUDE.md index 659cc8c2b..43c994c2d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,52 +1 @@ -# CADCraft — instructions for agents - -CADCraft is a clean-room, open-source, pure-Rust computer-aided design and drafting application targeting Autodesk AutoCAD parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows, Linux and FreeBSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop-class), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../pdfcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign). - -## Start every session here -1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/autocad/*` (`01-observed-ui.md` holds measured observations of the running reference app; `04-menu-tree.txt` the menu tree by name). -2. Library decisions: `plan/adr/0001-geometry-libraries.md` (what we may depend on, what is rejected for licence reasons). -3. Follow the autonomous operation protocol (`plan/execution-plan.md` §6). Don't stop to ask unless it lists the decision as the owner's. - -`plan/` is gitignored (local only). - -## Never crash -People trust CADCraft with their drawings; a crash loses their work. **This outranks feature work.** -- **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). -- **Errors are `Result`** through the crate's error type and `?`. An unfinished feature returns an error or reports "not available yet"; it never panics. -- **Input-derived numbers are hostile** (DXF/DWG files, command-line text, MCP/control params): `get()` not `[i]`, checked arithmetic, no NaN casts, cap input-sized allocations and loop counts. -- **Bound recursion** (nested/cyclic block references: `MAX_BLOCK_DEPTH`). -- **Last-resort guard:** `Session::execute` and every step of an interactive command (its factory, `begin`, input, `prompt`, `preview` and the passes after it; `crates/engine/src/guard.rs`) run under `catch_unwind`; an escaped panic restores the drawing and reports an error. It does nothing on wasm, where a panic aborts. -- **Prove it:** every crash fix lands with a regression test (see `crates/engine/tests/panic_hunt.rs` and `hostile_dxf_does_not_panic` in `crates/io/src/tests.rs`). -- Every workspace crate manifest carries `[lints] workspace = true` to inherit `[workspace.lints]`; every production crate root carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`. - -## Non-negotiables -- **Clean-room.** AutoCAD is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic drawings, take screenshots (by window id) stored only under `plan/autocad/screenshots/` (never committed). **Never** read, disassemble or copy anything inside the AutoCAD bundle (names/listings only); never copy Autodesk fonts (SHX), hatch patterns (`.pat`), linetypes (`.lin`), templates, CUI/PGP files, icons, artwork or help text; never commit files produced by AutoCAD. File formats come from public specifications (Autodesk's published DXF Reference, the Open Design Alliance's public DWG specification) and our own synthetic tests. Never copy or link GPL/LGPL/AGPL code (LibreDWG, LibreCAD, QCAD, FreeCAD's planegcs, SolveSpace, OpenCASCADE) — don't even read their sources. -- **Assets — absolutely essential.** CADCraft contains **no Autodesk, Adobe or Avid iconography, images, fonts, patterns or artwork — ever.** Every icon is drawn in code (`crates/ui-egui/src/icons.rs`), every hatch pattern and linetype is our own definition (`crates/doc/src/library.rs`), the drafting font is our own (`crates/fonts/src/stroke.rs`). Any file asset must be original, public domain/CC0, OSI-licensed, or redistributable Creative Commons (or licensed open source by a contributor who made it), and **must have a row in `ATTRIBUTION.md`** with author, source and licence (`cargo xtask assets` enforces it). The only exception is the ArtCraft brand in `docs/brand/` (trademarks, `docs/brand/LICENSE-brand.txt`). Screenshots of Autodesk software are never committed. Breaking this rule is the most serious mistake you can make in this repo. -- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`, embedded by `crates/fonts/build.rs`), never a `Cargo.toml` dependency. Code and tests must work without it. -- **Shared test corpora** live in separate repos (`storytold/-corpus`); never commit large binary fixtures here. -- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (`CommandSpec`: id = AutoCAD's command name in lower case, label, menu path, shortcut, aliases, params doc, `enabled`, JSON `run`, optional `interactive` prompt machine) + tests. UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The command line, menus, toolbar, Tool Sets, scripts, CLI, control channel and MCP all reach the same commands. -- **Programmatic calls never open dialogs.** `engine.execute` runs the JSON form with defaults; only menu/toolbar invocation starts the interactive prompt sequence. -- **Layering** is enforced by `cargo xtask layers`: L0 `geom`, `dxf` → L1 `color`, `doc` → L2 `fonts`, `render`, `constraints` → L3 `io` → L4 `engine` → L5 `ui-egui`, `mcp` → apps. Nothing below L5 depends on egui/eframe/winit/wgpu/rfd. **The UI crate is swappable.** -- **The UI is thin**: panels read engine state and act through `app.run(id, params)` / `app.start(id)` / `app.cmdline(text)`. Colours come from `theme::Tokens`. -- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). Commit after every feature arc that builds, and push to `main`. - -## Running and looking at the app -- `cargo run --release -p cadcraft -- --sample --control PORT` (sample drawing + control channel). Pick a free port; other crafting apps use control ports too. -- Drive it with JSON lines on `127.0.0.1:PORT`: - - `{"id":1,"method":"cmdline.input","params":{"text":"circle 0,0 5"}}` — type at the command line exactly like a user (prompts, keywords, `@dx,dy`, `@d **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-21 · **Change:** trivial (progress log: proxy objects keep their class through a save, #1812; previously minor: HATCHEDIT boundary add/remove progress) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-24 · **Change:** minor (re-audit against main 41d9b5e95: language table, CI gate, open-PR count; previously: progress log: proxy objects keep their class through a save, #1812; previously minor: HATCHEDIT boundary add/remove progress) · **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 scriptable CLI, a web build, Linux and FreeBSD builds, and a free licence. **Why pre-alpha:** four of AutoCAD's five core workflows fail the [alpha gate](docs/roadmap.md#alpha-gate). -Precise drafting lacks object snap tracking and has stubbed TRIM/EXTEND/OFFSET options; blocks -can't be edited in a block editor (REFEDIT edits them in place, xrefs not yet); plots ignore plot styles; and a DWG saved by -CADCraft drops everything it doesn't model and has never been checked in +Precise drafting still has approximate ellipse and spline intersections and a few stubbed prompt options +(object snap tracking, TRIM/EXTEND/OFFSET options and typed snap overrides have landed); dynamic blocks can't be +authored and xrefs can't be edited in place (the Block Editor, REFEDIT, dynamic block editing and XCLIP have landed); +plots go only to PDF, PNG and SVG files (plot styles and the Plot dialog have landed); and a DWG saved by +CADCraft drops what acadrust doesn't model and has never been checked in AutoCAD. Dimensioning passes. Ready for real work (≈ 38%) is also under the ~40% alpha bar. Beta is ≈ 600–930 h away. @@ -19,7 +21,7 @@ is ≈ 600–930 h away. | Number | Value | Kind | |---|---|---| -| Feature breadth (AutoCAD for Mac menu items with a live command) | **50%** (245 / 491; 2D menus only ≈ 65%) | measured ([parity-checklist.md](docs/parity-checklist.md) + UI-only commands) | +| Feature breadth (AutoCAD for Mac menu items with a live command) | **50%** (245 / 491 at the 2026-10-10 re-measure, including UI-only commands; not re-measured since; the generated checklist counts engine commands only and now reads 298 / 491; 2D menus only ≈ 65%) | measured ([parity-checklist.md](docs/parity-checklist.md) + UI-only commands) | | Ready for real work | **≈ 38%** | estimated ([target-app-parity.md](docs/target-app-parity.md)) | | Mainstream practitioner (2D drafter) | **≈ 28%** (lower than the full number: file exchange, stability and interaction discounts multiply) | estimated ([target-app-parity.md](docs/target-app-parity.md#mainstream-practitioner)) | | Essentials user | **≈ 46%** | estimated ([target-app-parity.md](docs/target-app-parity.md#essentials-user)) | @@ -80,40 +82,40 @@ Hours are Opus 5.5 agent wall-clock hours, calibrated on this repo's own build: ## Languages -AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus partial -Ukrainian and German. Detail: [localization-parity.md](docs/localization-parity.md). +AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus eighteen catalogs +(Ukrainian, Brazilian Portuguese, German, Spanish, Czech, Russian, French, Simplified Chinese, Italian, Korean, Swedish, Arabic, Greek, Hungarian, Turkish, Bosnian, Georgian and Vietnamese). Detail: [localization-parity.md](docs/localization-parity.md). | Language | Status | UI translated | |---|---|---:| | English | full | 100% | -| Simplified Chinese | none | 0% | -| Spanish | none | 0% | +| Simplified Chinese | partial | 1,337 catalog rows | +| Spanish | partial | 1,243 catalog rows | | Hindi | none | 0% | -| Arabic | none | 0% | -| French | none | 0% | -| Portuguese | none | 0% | +| Arabic | partial | 1,229 catalog rows | +| French | partial | 1,004 catalog rows | +| Portuguese (Brazilian) | partial | 1,243 catalog rows | | Indonesian | none | 0% | | Japanese | none | 0% | -| Greek | complete current catalog | 1,330 current source keys; independent proofreading pending | -| German | partial | ≈ 100% of the catalog (989 rows) | -| Korean | none | 0% | -| Vietnamese | none | 0% | +| Greek | partial | 1,330 catalog rows; independent proofreading pending | +| German | partial | 1,031 catalog rows | +| Korean | partial | 1,235 catalog rows | +| Vietnamese | partial | 1,460 catalog rows (2026-11-07); native review pending | -Other languages shipped: Ukrainian and German (989 catalog rows each; Ukrainian landed with #36), Brazilian Portuguese, Spanish, Czech, Russian, French, Simplified Chinese and Italian (1,227 rows, 2026-10-12); engine messages stay English. +Other languages shipped: Ukrainian (1,357 rows, the reference catalog, #36), Czech (1,215), Russian (1,005), Italian (1,352), Swedish (1,382), Hungarian (1,326) and Turkish (1,330), counted 2026-10-24; engine messages stay English. Every catalog but Ukrainian's has strings added since it landed that still fall back to English: 6 (Italian, Swedish) to 296 (French) per `cargo xtask i18n` ([localization-parity.md](docs/localization-parity.md)). ## Upcoming Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md). -1. Gate and land: fix fmt on main, run `cargo xtask ci` on every PR, land the 47 open PRs (15–25 h). -2. Stop losing data on save; native MULTILEADER; save DWG/DXF at a chosen version (30–45 h). +1. Gate and land: CI runs `cargo xtask ci` on every PR since #1987 (fmt on main is fixed); land the 450 open PRs (2026-10-24) (15–25 h). +2. Stop losing data on save (DXF done, #528; native MULTILEADER, #459, and the save version, #421, done; through DWG, acadrust still drops some content) (30–45 h). 3. Real-file DWG/DXF corpus and a black-box check in AutoCAD (10–15 h + owner). -4. Precision input: object snap tracking, extension/parallel snaps, FROM/M2P/TK, snap overrides, - editable dynamic input (25–35 h). -5. Unstub prompt options in TRIM/EXTEND, OFFSET, ROTATE, PLINE, SPLINE, MTEXT, MLEADER (15–25 h). -6. Autosave, recovery, AUDIT, RECOVER (10–15 h). +4. ~~Precision input: object snap tracking, extension/parallel snaps, FROM/M2P/TK, snap overrides, + editable dynamic input.~~ Done (#379, #441, #60, #519; `snap/tracking.rs`, `pointmod.rs`, `dyninput.rs`). +5. ~~Unstub prompt options in TRIM/EXTEND, OFFSET, ROTATE, PLINE, SPLINE, MTEXT, MLEADER.~~ Done (#397, #408, #547); the stubs left are in gaps F1. +6. ~~Autosave, recovery, AUDIT, RECOVER.~~ Done on the desktop (#406, #416); the web build has no autosave (gaps F4). 7. Exact ellipse/spline geometry and correct polyline offsets (30–50 h). -8. Xrefs, block editor, groups, then dynamic blocks (80–120 h). +8. Xrefs, block editor, groups, then dynamic blocks (80–120 h): xrefs (#525), groups (#417), the Block Editor (#824, #833, #885), REFEDIT (#818), XCLIP and XCLIPFRAME (#2354) and dynamic block references (#838–#883) landed; left: dynamic-block authoring, editing an xref in place. ## Progress log @@ -136,6 +138,7 @@ Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md) | Date | Change | Summary | |---|---|---| +| 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) | | 2026-10-14 | minor | Progress log: HATCHEDIT boundary add/remove | | 2026-10-12 | trivial | Progress log: closed-polyline TRIM (#726) | diff --git a/apps/cadcraft-cli/src/output.rs b/apps/cadcraft-cli/src/output.rs index 83fa17dfd..46283753e 100644 --- a/apps/cadcraft-cli/src/output.rs +++ b/apps/cadcraft-cli/src/output.rs @@ -162,19 +162,31 @@ pub(crate) fn export_framed(s: &Session, out: &Path, window: Option, io /// as unknown objects, `Proxy` in `info`), or `None` when there are none. pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option { let mut types: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); + let mut ole = 0usize; for e in d.model.iter() { + // An OLE2FRAME's frame outline is drawn, so it isn't an undrawn entity; its content is + // not, which gets a note of its own. if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind { + if u.is_ole_frame() && cadcraft_engine::doc::ole_frame(&u.tags).is_some() { + ole = ole.saturating_add(1); + continue; + } let n = types.entry(u.dxf_type.as_str()).or_insert(0); *n = n.saturating_add(1); } } let n = types.values().fold(0usize, |a, n| a.saturating_add(*n)); - if n == 0 { - return None; + let mut lines = Vec::new(); + if n > 0 { + let list: Vec = types.iter().map(|(t, n)| format!("{t}: {n}")).collect(); + let entities = if n == 1 { "entity" } else { "entities" }; + lines.push(format!("{path}: {n} {entities} not drawn ({})", list.join(", "))); } - let list: Vec = types.iter().map(|(t, n)| format!("{t}: {n}")).collect(); - let entities = if n == 1 { "entity" } else { "entities" }; - Some(format!("{path}: {n} {entities} not drawn ({})", list.join(", "))) + if ole > 0 { + let objects = if ole == 1 { "object" } else { "objects" }; + lines.push(format!("{path}: {ole} OLE {objects} shown as the frame only (the OLE content is not drawn)")); + } + if lines.is_empty() { None } else { Some(lines.join("\n")) } } /// The reader's notes on what it left out of `path` (a damaged DWG's unreadable object records, diff --git a/apps/cadcraft-cli/tests/dwg_worker.rs b/apps/cadcraft-cli/tests/dwg_worker.rs index 8656b84ff..264cee435 100644 --- a/apps/cadcraft-cli/tests/dwg_worker.rs +++ b/apps/cadcraft-cli/tests/dwg_worker.rs @@ -16,6 +16,13 @@ fn a_real_worker_reads_and_writes_and_its_death_is_an_error_here() { let read = cadcraft_io::read(&written, "a.dwg").unwrap(); assert_eq!(read.model.len(), drawing.model.len()); + // A drawing whose kept objects came from a 2018 file: the worker gets that version with the + // request and reads the bridge DXF as it, as this process does. + let mut kept = drawing.clone(); + kept.foreign = std::sync::Arc::new(cadcraft_engine::doc::foreign::Foreign { version: Some("AC1032".into()), ..Default::default() }); + let written = cadcraft_io::write(&kept, "a.dwg").unwrap(); + assert_eq!(cadcraft_io::read(&written, "a.dwg").unwrap().model.len(), drawing.model.len()); + // A decode error comes back as that error, not as the worker stopping. let mut bad = in_process.clone(); bad.truncate(64); diff --git a/apps/cadcraft-cli/tests/it/undrawn_entities.rs b/apps/cadcraft-cli/tests/it/undrawn_entities.rs index 7e7189379..59762d283 100644 --- a/apps/cadcraft-cli/tests/it/undrawn_entities.rs +++ b/apps/cadcraft-cli/tests/it/undrawn_entities.rs @@ -7,6 +7,25 @@ fn cli(args: &[&str]) -> Output { Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap() } +/// A fresh scratch directory that is removed on drop, also when an assertion fails. +struct Scratch(std::path::PathBuf); + +impl Scratch { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id())); + // A directory left behind by an earlier run with the same process id must not leak in. + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).expect("create scratch dir"); + Scratch(dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + /// A line, two foreign REGIONs and a PDF underlay: the last three are kept as unknown entities. const PROXIES: &str = "0\nSECTION\n2\nENTITIES\n\ 0\nLINE\n8\n0\n10\n0\n20\n0\n11\n5\n21\n5\n\ @@ -17,8 +36,8 @@ const PROXIES: &str = "0\nSECTION\n2\nENTITIES\n\ #[test] fn convert_to_an_image_warns_about_entities_it_cannot_draw() { - let dir = std::env::temp_dir().join(format!("cc-cli-undrawn-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let scratch = Scratch::new("undrawn"); + let dir = scratch.0.clone(); let input = dir.join("proxies.dxf"); std::fs::write(&input, PROXIES).unwrap(); let input = input.to_str().unwrap(); @@ -49,5 +68,37 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() { let out = cli(&["convert", sample.to_str().unwrap(), dir.join("sample.svg").to_str().unwrap()]); assert!(out.status.success()); assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr)); - let _ = std::fs::remove_dir_all(&dir); +} + +/// 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] +fn an_ole_frame_is_noted_as_frame_only() { + let scratch = Scratch::new("ole"); + let dir = scratch.0.clone(); + let input = dir.join("ole.dxf"); + let ole = "0\nSECTION\n2\nENTITIES\n0\nOLE2FRAME\n8\n0\n100\nAcDbOle2Frame\n10\n0\n20\n0\n30\n0\n11\n5\n21\n-3\n31\n0\n0\nENDSEC\n0\nEOF\n"; + std::fs::write(&input, ole).unwrap(); + let out = cli(&["convert", input.to_str().unwrap(), dir.join("out.png").to_str().unwrap()]); + assert!(out.status.success()); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!err.contains("entity not drawn") && !err.contains("entities not drawn"), "{err}"); + let notes: Vec<&str> = err.lines().filter(|l| l.contains("OLE")).collect(); + assert_eq!(notes, [format!("{}: 1 OLE object shown as the frame only (the OLE content is not drawn)", input.display())], "{err}"); +} + +/// An OLE2FRAME without usable corners (here group 11/21 missing) has no outline to draw, so it is +/// an undrawn entity, not "shown as the frame only" (review on #2587). +#[test] +fn an_ole_frame_without_corners_is_counted_as_not_drawn() { + let scratch = Scratch::new("ole-nocorner"); + let dir = scratch.0.clone(); + let input = dir.join("ole.dxf"); + let ole = "0\nSECTION\n2\nENTITIES\n0\nOLE2FRAME\n8\n0\n100\nAcDbOle2Frame\n10\n0\n20\n0\n30\n0\n0\nENDSEC\n0\nEOF\n"; + std::fs::write(&input, ole).unwrap(); + let out = cli(&["convert", input.to_str().unwrap(), dir.join("out.png").to_str().unwrap()]); + assert!(out.status.success()); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains(&format!("{}: 1 entity not drawn (OLE2FRAME: 1)", input.display())), "{err}"); + assert!(!err.contains("frame only"), "{err}"); } diff --git a/apps/cadcraft-web/Cargo.toml b/apps/cadcraft-web/Cargo.toml index b1225faf7..b73444064 100644 --- a/apps/cadcraft-web/Cargo.toml +++ b/apps/cadcraft-web/Cargo.toml @@ -20,7 +20,9 @@ cadcraft-ui-egui = { workspace = true } cadcraft-io = { workspace = true } cadcraft-fonts = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" } +# 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" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } @@ -33,4 +35,5 @@ web-sys = { version = "0.3", features = ["HtmlInputElement", "FileList", "File"] eframe = { workspace = true, features = ["persistence", "wgpu", "accesskit"] } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" +js-sys = "0.3" web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url", "MessageEvent", "UrlSearchParams", "MediaQueryList", "Event", "EventTarget", "CustomEvent", "CustomEventInit"] } diff --git a/apps/cadcraft-web/src/api.rs b/apps/cadcraft-web/src/api.rs new file mode 100644 index 000000000..574130f7e --- /dev/null +++ b/apps/cadcraft-web/src/api.rs @@ -0,0 +1,61 @@ +//! `window.cadcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the app's +//! own control channel, the one the desktop control server drives (`docs/control-protocol.md`). +//! +//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`, +//! `screenshot`, as promises with a timeout). This module is CADCraft's part: a [`Request`] that +//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the +//! reply. A call the page gave up on drops its [`PendingReply`], which cancels a request the app has +//! not started, so the app skips it instead of running it late. + +use std::rc::Rc; +use std::sync::mpsc::{Receiver, channel}; + +use cadcraft_ui_egui::{ControlRequest, PendingReply}; +use craft_web_api::methods::Methods; +use craft_web_api::page::{PageApi, Request}; +use serde_json::{Value, json}; +use wasm_bindgen_futures::JsFuture; + +/// The app id in `window.`. +const APP: &str = "cadcraft"; + +/// How often a waiting call looks for the app's reply, in milliseconds (about a frame). +const POLL_MS: i32 = 16; + +/// Put `window.cadcraft` on the page and return the queue the app drains each frame (hand it to +/// `CadApp::with_control`). An existing `window.cadcraft` keeps the functions it already has. +pub fn install(ctx: egui::Context) -> Receiver { + let (queue, requests) = channel::(); + let request: Request = Rc::new(move |method, params| { + let (control, reply) = ControlRequest::new(method, params); + if queue.send(control).is_err() { + return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) }); + } + ctx.request_repaint(); + Box::pin(wait(reply)) + }); + if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() { + log::warn!("couldn't install window.{APP}: {e:?}"); + } + requests +} + +/// The app's reply, polled about once a frame. Dropping this future (the page's timeout) drops +/// `reply`, which cancels the request if the app has not started it. +async fn wait(reply: PendingReply) -> Value { + loop { + if let Some(reply) = reply.try_reply() { + return reply; + } + sleep(POLL_MS).await; + } +} + +async fn sleep(ms: i32) { + let promise = js_sys::Promise::new(&mut |resolve, _| { + if let Some(window) = web_sys::window() { + let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); + } + }); + let _ = JsFuture::from(promise).await; +} diff --git a/apps/cadcraft-web/src/main.rs b/apps/cadcraft-web/src/main.rs index 7a867b78a..3d1c00d4c 100644 --- a/apps/cadcraft-web/src/main.rs +++ b/apps/cadcraft-web/src/main.rs @@ -10,6 +10,8 @@ //! `data-host="page"` on the canvas, talking over DOM `CustomEvent`s on it (`host.rs`). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(target_arch = "wasm32")] +mod api; #[cfg(target_arch = "wasm32")] pub mod download; #[cfg(target_arch = "wasm32")] @@ -160,7 +162,8 @@ mod web { Box::new(move |cc| { // Embedded, the host sends the drawing: start on the Start tab, not Drawing1. let session = if app_bridge.is_some() { Session::empty() } else { Session::new() }; - let mut app = CadApp::new(session, services()); + let control = crate::api::install(cc.egui_ctx.clone()); + let mut app = CadApp::new(session, services()).with_control(control); app.system_languages = web_sys::window().map(|w| w.navigator().languages().iter().filter_map(|v| v.as_string()).collect()).unwrap_or_default(); if let Some(profile) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::options::PROFILE_KEY)) { diff --git a/apps/cadcraft/Cargo.toml b/apps/cadcraft/Cargo.toml index ee1b8b9c8..cf9809c97 100644 --- a/apps/cadcraft/Cargo.toml +++ b/apps/cadcraft/Cargo.toml @@ -55,7 +55,11 @@ muda = { version = "0.21", default-features = false } objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] } # The same winit eframe uses (the storytold fork, patched in the workspace): its opt-in that turns # AppKit's terminate (Cmd+Q, Dock Quit) into a close request, so unsaved changes are asked about. -winit = { version = "0.30", default-features = false } +# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs). +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" # Rust HID backends: no proprietary SDK or C HID library. [target.'cfg(target_os = "windows")'.dependencies] diff --git a/apps/cadcraft/src/control_server.rs b/apps/cadcraft/src/control_server.rs index d502e1408..88007b889 100644 --- a/apps/cadcraft/src/control_server.rs +++ b/apps/cadcraft/src/control_server.rs @@ -250,17 +250,18 @@ fn parse_line(bytes: &[u8]) -> Line { Ok(v) => v, Err(e) => return Line::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")), }; - let Some(obj) = msg.as_object() else { + let Value::Object(mut obj) = msg else { return Line::Reject("not a control request (expected a JSON object); closing the connection".into()); }; - let Some(method) = obj.get("method").and_then(Value::as_str) else { + let Some(Value::String(method)) = obj.remove("method") else { return Line::Reject("not a control request (missing string `method`); closing the connection".into()); }; + // Moved out of the parsed object, not cloned: `params` can be most of the line. Line::Request { - id: obj.get("id").cloned().unwrap_or(Value::Null), - method: method.to_string(), - params: obj.get("params").cloned().unwrap_or(json!({})), - token: obj.get("token").and_then(Value::as_str).map(str::to_string), + id: obj.remove("id").unwrap_or(Value::Null), + method, + params: obj.remove("params").unwrap_or(json!({})), + token: obj.remove("token").and_then(|t| if let Value::String(t) = t { Some(t) } else { None }), } } diff --git a/apps/cadcraft/src/logging.rs b/apps/cadcraft/src/logging.rs index 724d09c1a..e4e86c982 100644 --- a/apps/cadcraft/src/logging.rs +++ b/apps/cadcraft/src/logging.rs @@ -148,7 +148,20 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> { /// One formatted log line: ` [] : \n`. pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String { let message = message.strip_suffix('\n').unwrap_or(message); - format!("{ts} {level:<5} [{thread}] {target}: {message}\n") + // A message can carry text from a file (a code page name, a path), so it must not be able to + // start what looks like another record: control characters other than tab and line feed are + // shown escaped, and every continuation line is indented, so only this function's own + // timestamp is ever at the start of a line. + let mut safe = String::with_capacity(message.len()); + for c in message.chars() { + match c { + '\n' => safe.push_str("\n "), + '\t' => safe.push('\t'), + c if c.is_control() => safe.extend(c.escape_default()), + c => safe.push(c), + } + } + format!("{ts} {level:<5} [{thread}] {target}: {safe}\n") } /// Where formatted lines go besides standard error: kept in memory until a file is attached, @@ -441,8 +454,14 @@ mod tests { format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "cadcraft", "app icon: invalid PNG signature"), "2026-10-08T07:59:17.728Z WARN [main] cadcraft: app icon: invalid PNG signature\n" ); - // A multi-line message keeps its lines; the record still ends in exactly one newline. - assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n")); + // A multi-line message keeps its lines, indented so they can't pass for records; the + // record still ends in exactly one newline. + assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n b\n")); + // Control characters in a message (from a file) can't forge a record. + let forged = format_line("t", log::Level::Warn, "w", "x", "page\r\n2026-01-01T00:00:00Z ERROR [main] x: fake\u{1b}[0m"); + assert_eq!(forged.lines().count(), 2); + assert!(forged.lines().skip(1).all(|l| l.starts_with(" "))); + assert!(!forged.contains('\r') && !forged.contains('\u{1b}')); } #[test] diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index f5eef8932..7d33cec19 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -23,13 +23,15 @@ mod launch_args; mod logging; #[cfg(target_os = "macos")] mod native_menu; +#[cfg(target_os = "macos")] +mod sheet; mod spacemouse; mod system_animations; mod workspace; use cadcraft_engine::Session; use cadcraft_ui_egui::switch::Switch; -use cadcraft_ui_egui::{CadApp, Services, i18n}; +use cadcraft_ui_egui::{CadApp, Pick, Services, i18n}; struct App { cad: CadApp, @@ -159,28 +161,41 @@ pub fn install_io() { fn services() -> Services { Services { - pick_open: Some(Box::new(|| { - rfd::FileDialog::new() - .add_filter(i18n::t("Drawings (DWG, DXF)"), &["dwg", "dxf", "dwt"]) - .add_filter(i18n::t("SVG drawings (SVG, SVGZ)"), &["svg", "svgz"]) - .add_filter(i18n::t("All files"), &["*"]) - .pick_file() - .map(|p| p.to_string_lossy().to_string()) - })), - pick_save: Some(Box::new(|name: &str| { - filters_for_save(name) - .iter() - .fold(rfd::FileDialog::new().set_file_name(name), |d, (label, ext)| d.add_filter(i18n::t(label), &[*ext])) - .save_file() - .map(|p| p.to_string_lossy().to_string()) - })), + pick_open: Some(Box::new(|| file_dialog(&Pick::Open).pick_file().map(|p| p.to_string_lossy().to_string()))), + pick_save: Some(Box::new(|name: &str| file_dialog(&Pick::Save(name.into())).save_file().map(|p| p.to_string_lossy().to_string()))), + // macOS shows the dialogs as sheets (`sheet::start_pick`), set once the window exists. + start_pick: None, // APPLOAD: AutoLISP routines only, starting where the last one was loaded from. - pick_lisp: Some(Box::new(|dir: &str| { - let dialog = rfd::FileDialog::new().add_filter(i18n::t("AutoLISP (LSP)"), &["lsp"]).add_filter(i18n::t("All files"), &["*"]); - let dialog = if dir.is_empty() { dialog } else { dialog.set_directory(dir) }; - dialog.pick_file().map(|p| p.to_string_lossy().to_string()) - })), + pick_lisp: Some(Box::new(|dir: &str| file_dialog(&Pick::Lisp(dir.into())).pick_file().map(|p| p.to_string_lossy().to_string()))), no_file_system: false, + pick_pgp: Some(Box::new(|dir: Option<&str>| { + file_dialog(&Pick::Pgp(dir.unwrap_or_default().into())).pick_file().map(|p| p.to_string_lossy().to_string()) + })), + } +} + +/// The file types `pick` offers: (label, extensions). Shared by the blocking dialogs and the +/// macOS sheets. +fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> { + match pick { + Pick::Open => vec![ + (i18n::t("Drawings (DWG, DXF)"), vec!["dwg", "dxf", "dwt"]), + (i18n::t("SVG drawings (SVG, SVGZ)"), vec!["svg", "svgz"]), + (i18n::t("All files"), vec!["*"]), + ], + Pick::Save(name) => filters_for_save(name).iter().map(|(label, ext)| (i18n::t(label), vec![*ext])).collect(), + Pick::Lisp(_) => vec![(i18n::t("AutoLISP (LSP)"), vec!["lsp"]), (i18n::t("All files"), vec!["*"])], + Pick::Pgp(_) => vec![(i18n::t("Alias files (PGP)"), vec!["pgp"])], + } +} + +/// The blocking dialog for `pick` (Windows, Linux, FreeBSD). +fn file_dialog(pick: &Pick) -> rfd::FileDialog { + let dialog = filters(pick).iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts)); + match pick { + Pick::Save(name) => dialog.set_file_name(name), + Pick::Lisp(dir) | Pick::Pgp(dir) if !dir.is_empty() => dialog.set_directory(dir), + _ => dialog, } } @@ -353,6 +368,12 @@ fn main() -> eframe::Result { options, Box::new(move |cc| { let mut app = CadApp::new(Session::empty(), services()); + // File dialogs are sheets on macOS: a modal loop inside the event handler crashes the + // app when the dialog is resized (#1527). + #[cfg(target_os = "macos")] + if let Some(window) = cc.winit_window().cloned() { + app.services.start_pick = Some(sheet::start_pick(window, cc.egui_ctx.clone())); + } let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref()); if let Some(ui) = restored { app.ui = ui; diff --git a/apps/cadcraft/src/sheet.rs b/apps/cadcraft/src/sheet.rs new file mode 100644 index 000000000..f18da9d45 --- /dev/null +++ b/apps/cadcraft/src/sheet.rs @@ -0,0 +1,51 @@ +//! macOS file dialogs as sheets. Shown in line, or from a helper thread that rfd hands to the main +//! thread's modal loop, a panel runs AppKit's modal event loop; resizing it sends window events +//! back into winit's event handler and winit aborts the app (#1527). A sheet returns at once and +//! the window keeps running; a thread of its own waits for the answer. + +use std::sync::Arc; + +use cadcraft_ui_egui::{Pick, StartPick}; + +type Answer = std::pin::Pin> + Send>>; + +/// `Services::start_pick`: shows `pick` as a sheet on `window`; `ui` is woken when it answers. +pub fn start_pick(window: Arc, ui: egui::Context) -> StartPick { + Box::new(move |pick, done| { + let (sheet_tx, sheet_rx) = std::sync::mpsc::channel::(); + let ui = ui.clone(); + // The thread first, so the answer of a sheet once shown always has somewhere to go. If it + // cannot start, `done` is dropped unanswered and the app says the dialog could not be + // shown. + let spawned = std::thread::Builder::new().name("file-dialog".into()).spawn(move || { + if let Ok(answer) = sheet_rx.recv() { + done(pollster::block_on(answer)); + ui.request_repaint(); + } + }); + if let Err(e) = spawned { + log::warn!("file dialog: {e}"); + return; + } + // rfd builds the panel and begins the sheet here, on the main thread (as it must). + let dialog = + crate::filters(&pick).iter().fold(rfd::AsyncFileDialog::new().set_parent(&*window), |d, (label, exts)| d.add_filter(*label, exts)); + let path = |f: rfd::FileHandle| f.path().to_string_lossy().to_string(); + let answer: Answer = match pick { + Pick::Save(name) => { + let picked = dialog.set_file_name(name).save_file(); + Box::pin(async move { picked.await.map(path) }) + } + Pick::Lisp(dir) | Pick::Pgp(dir) => { + let dialog = if dir.is_empty() { dialog } else { dialog.set_directory(dir) }; + let picked = dialog.pick_file(); + Box::pin(async move { picked.await.map(path) }) + } + Pick::Open => { + let picked = dialog.pick_file(); + Box::pin(async move { picked.await.map(path) }) + } + }; + let _ = sheet_tx.send(answer); + }) +} diff --git a/contributors/people.toml b/contributors/people.toml index 8b23d2c24..cde01f932 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -37,7 +37,9 @@ display_name = "Tasos Sangiotis" sync_github_name = false [people.vangel76] -sync_github_name = true +real_name = "Valentin Klein" +display_name = "vangel76" +sync_github_name = false [people.WladmirJunior] real_name = "Wladmir Júnior" @@ -88,6 +90,10 @@ sync_github_name = false real_name = "Robert Lee" sync_github_name = true +[people.assamaral] +real_name = "assamaral" +sync_github_name = false + [people.2ez4gcx] real_name = "Doan Huynh Huu Khuong" display_name = "Doan Huynh Huu Khuong" diff --git a/crates/constraints/src/auto.rs b/crates/constraints/src/auto.rs index 211be6b93..b24d3e736 100644 --- a/crates/constraints/src/auto.rs +++ b/crates/constraints/src/auto.rs @@ -232,6 +232,10 @@ pub fn infer_placed(d: &Drawing, placed: &[Handle], others: &[Handle], o: &Infer let mut extra = Vec::new(); let mut on = Vec::new(); for (rp, p) in g.points.iter().filter(|(r, _)| placed.contains(&r.handle)) { + // Nothing is added once the candidates are full, so the points left need no search. + if extra.len() + on.len() + out.len() >= MAX_CANDIDATES { + break; + } if out.iter().any(|c| c.kind == ConstraintKind::Coincident && c.refs.contains(rp)) { continue; } @@ -267,20 +271,22 @@ pub fn infer_placed(d: &Drawing, placed: &[Handle], others: &[Handle], o: &Infer // Perpendicular lines meeting in a T (a perpendicular snap onto the middle of a line). let atol = if o.angle_tolerance.is_finite() { o.angle_tolerance.clamp(0.0, 45.0).to_radians() } else { 0.0 }; let allow_per = o.types.is_empty() || o.types.iter().any(|t| t.eq_ignore_ascii_case(ConstraintKind::Perpendicular.name())); - for (r1, a1, b1) in g.lines.iter().filter(|(r, _, _)| placed.contains(&r.handle)) { + 'per: for (r1, a1, b1) in g.lines.iter().filter(|(r, _, _)| allow_per && placed.contains(&r.handle)) { for (r2, a2, b2) in g.lines.iter().filter(|(r, _, _)| r.handle != r1.handle) { + // Full: nothing more can be added, so the pairs left need no geometry or duplicate search. + if out.len() + extra.len() + on.len() >= MAX_CANDIDATES { + break 'per; + } let (l1, l2) = (Line::new(*a1, *b1), Line::new(*a2, *b2)); let touches = |l: &Line, p: Vec2| l.dist(p) <= tol && (0.0..=1.0).contains(&l.param_of(p)); let tee = [*a1, *b1].iter().any(|p| touches(&l2, *p)) || [*a2, *b2].iter().any(|p| touches(&l1, *p)); let ang = ang_between(*b1 - *a1, *b2 - *a2); - let dup = out.iter().any(|c| c.kind == ConstraintKind::Perpendicular && c.refs.contains(r1) && c.refs.contains(r2)); - if allow_per - && tee - && !dup + // The duplicate search scans every candidate, so it comes after the cheap tests. + if tee && (std::f64::consts::FRAC_PI_2 - ang).abs() <= atol && l1.len() > tol && l2.len() > tol - && out.len() < MAX_CANDIDATES + && !out.iter().any(|c| c.kind == ConstraintKind::Perpendicular && c.refs.contains(r1) && c.refs.contains(r2)) { out.push(Constraint { id: 0, kind: ConstraintKind::Perpendicular, refs: vec![*r1, *r2], name: String::new(), expr: String::new() }); } diff --git a/crates/constraints/src/dof.rs b/crates/constraints/src/dof.rs index e6128665c..7ac58e112 100644 --- a/crates/constraints/src/dof.rs +++ b/crates/constraints/src/dof.rs @@ -138,7 +138,9 @@ pub fn dof(d: &Drawing, handles: &[Handle]) -> Result { let cons: Vec<&Constraint> = d.constraints.iter().take(MAX_CONSTRAINTS).collect(); let mut prep = Prep::new(crate::model::MAX_RIGID_WORK); let (comps, _) = build_with(d, &cons, &SolveOptions::default(), &mut prep)?; - let want = |h: Handle| handles.is_empty() || handles.contains(&h); + // The selection as a set, built once: a scan of the list per slot multiplied the two sizes. + let selected: HashSet = handles.iter().copied().collect(); + let want = |h: Handle| handles.is_empty() || selected.contains(&h); let mut objects = Vec::new(); let mut seen = HashSet::new(); let mut total = Some(0usize); diff --git a/crates/doc/src/array.rs b/crates/doc/src/array.rs index 1514bc055..e71b28739 100644 --- a/crates/doc/src/array.rs +++ b/crates/doc/src/array.rs @@ -204,6 +204,23 @@ impl ArrayParams { self.replaced.iter().rev().find(|r| (r.i, r.j, r.level) == (i, j, level)).map_or(self.source.as_str(), |r| r.block.as_str()) } + /// [`block_for`](Self::block_for) for many items: the replacements are indexed once (the last + /// entry for a place wins, as there), so each lookup is O(1) instead of a scan of `replaced`. + pub fn block_lookup<'a>(&'a self) -> impl Fn(u32, u32, u32) -> &'a str + 'a { + // Only places `items()` generates are indexed, so stray out-of-range records cost nothing. + let (cols, rows) = match &self.kind { + ArrayKind::Rect(r) => (r.cols, r.rows), + ArrayKind::Polar(p) => (p.items, p.rows), + }; + let index: std::collections::HashMap<(u32, u32, u32), &str> = self + .replaced + .iter() + .filter(|r| r.i < cols && r.j < rows && r.level < self.levels) + .map(|r| ((r.i, r.j, r.level), r.block.as_str())) + .collect(); + move |i, j, level| index.get(&(i, j, level)).copied().unwrap_or(self.source.as_str()) + } + /// The block references that make up the array block: one per item, on layer 0 with ByBlock /// properties so they take the array's. Handles are allocated from `d`. `None` when the /// parameters are not [valid](Self::is_valid). @@ -217,9 +234,10 @@ impl ArrayParams { ..Common::default() }; let mut out = Vec::with_capacity(items.len()); + let block_for = self.block_lookup(); for it in items { let ins = Insert { - block: self.block_for(it.i, it.j, it.level).to_string(), + block: block_for(it.i, it.j, it.level).to_string(), insert: it.insert, scale: Vec3::new(1.0, 1.0, 1.0), rotation: it.rotation, @@ -301,6 +319,18 @@ mod tests { } } + #[test] + fn block_lookup_agrees_with_block_for_and_the_last_replacement_wins() { + let mut p = rect(3, 2); + let r = |i, j, level, b: &str| ReplacedItem { i, j, level, block: b.into() }; + p.replaced = vec![r(1, 0, 0, "A"), r(1, 0, 0, "B"), r(2, 1, 1, "C")]; + let look = p.block_lookup(); + for (i, j, level) in [(0, 0, 0), (1, 0, 0), (2, 1, 1), (2, 1, 0)] { + assert_eq!(look(i, j, level), p.block_for(i, j, level)); + } + assert_eq!((look(1, 0, 0), look(0, 0, 0)), ("B", "*U1")); + } + #[test] fn rect_items_go_column_row_level() { let items = rect(3, 2).items().unwrap_or_default(); diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index c22a6df86..ded8271c5 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -674,6 +674,10 @@ fn apply( /// Associative hatches of block `b` whose loop is one closed polyline of the block take its /// outline again (it may have been stretched). fn refill_hatches(b: &mut Block) { + // Each loop gets its own copy of the outline, so many small loops on one big outline multiply it; + // past this many vertices in all, the remaining loops keep the outline they have. + const MAX_REFILLED_VERTICES: usize = 4_000_000; + let mut budget = MAX_REFILLED_VERTICES; let outlines: HashMap> = b .entities .iter() @@ -689,7 +693,9 @@ fn refill_hatches(b: &mut Block) { for l in &mut hh.loops { if let [s] = l.sources.as_slice() && let Some(vs) = outlines.get(s) + && let Some(left) = budget.checked_sub(vs.len()) { + budget = left; l.vertices.clone_from(vs); } } diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index 535506806..832e0925f 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -60,6 +60,13 @@ pub struct Unknown { pub tags: Vec, } +impl Unknown { + /// Whether this is an OLE2FRAME (the type name is matched without regard to case). + pub fn is_ole_frame(&self) -> bool { + self.dxf_type.eq_ignore_ascii_case("OLE2FRAME") + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] pub enum EntityKind { @@ -469,6 +476,7 @@ impl EntityKind { let a = if mirror { t.rotation() } else { t.rotation() + rot }; t.dir = Vec2::from_angle(cadcraft_geom::norm_angle(a)).to3(0.0); } + EntityKind::Unknown(u) if u.is_ole_frame() => crate::ole_frame_transform(&mut u.tags, m), EntityKind::Unknown(_) => {} } } diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index e2a748606..9f29c07b6 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -9,6 +9,239 @@ use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim}; /// Nested block references deeper than this are ignored (cyclic or hostile files). pub const MAX_BLOCK_DEPTH: usize = 16; +/// Positions in `tags` of the groups outside application-defined `102 {` .. `102 }` groups, whose +/// codes are the application's own and not the entity's. +fn outside_app(tags: &[crate::RawTag]) -> impl Iterator + '_ { + let mut in_app = false; + tags.iter().enumerate().filter_map(move |(i, t)| { + if t.code == 102 { + in_app = t.value.starts_with('{'); + None + } else { + (!in_app).then_some(i) + } + }) +} + +/// The positions of the frame's corner groups 10, 20, 11, 21 (in that order) and their values: +/// the first of each outside application groups, found in one pass that stops at the last. +fn ole_corner_groups(tags: &[crate::RawTag]) -> Option<[(usize, f64); 4]> { + let mut found: [Option<(usize, f64)>; 4] = [None; 4]; + for i in outside_app(tags) { + let Some(t) = tags.get(i) else { continue }; + let slot = match t.code { + 10 => 0, + 20 => 1, + 11 => 2, + 21 => 3, + _ => continue, + }; + if let Some(f) = found.get_mut(slot).filter(|f| f.is_none()) { + *f = Some((i, t.value.trim().parse::().ok().filter(|v| v.is_finite())?)); + if found.iter().all(Option::is_some) { + break; + } + } + } + let [Some(a), Some(b), Some(c), Some(d)] = found else { return None }; + Some([a, b, c, d]) +} + +/// The closed outline of an OLE2FRAME from its upper-left (groups 10, 20) and lower-right +/// (groups 11, 21) corners (DXF Reference, OLE2FRAME); `None` when either is missing or not finite. +pub fn ole_frame(tags: &[crate::RawTag]) -> Option<[Vec2; 5]> { + let [(_, x1), (_, y1), (_, x2), (_, y2)] = ole_corner_groups(tags)?; + let (a, b) = (Vec2::new(x1, y1), Vec2::new(x2, y2)); + Some([a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y), a]) +} + +/// The bytes of the OLE data before its corners: a 2-byte marker. +const OLE_HEADER: usize = 2; +/// The corners in the OLE data: four of x, y, z as little-endian doubles (upper left, upper right, +/// lower right, lower left). +const OLE_CORNERS: usize = 12; + +/// Replace the four corners at the start of the OLE data (the 310 groups' hex, in order) by `new` +/// (upper left, upper right, lower right, lower left), keeping z and every group's length and +/// letter case. Only the groups that cover the header are decoded and rewritten; the rest of the +/// payload is not touched. Data that is not valid hex, too short, or whose corners are not the old +/// `frame`'s is left alone. +fn ole_data_transform(tags: &mut [crate::RawTag], new: [Vec2; 4], frame: [f64; 4]) { + const END: usize = OLE_HEADER + OLE_CORNERS * 8; + let mut bytes: Vec = Vec::with_capacity(END); + // The groups read, and how many leading bytes of each belong to the header. + let mut spans: Vec<(usize, usize)> = Vec::new(); + for i in outside_app(tags).filter(|&i| tags.get(i).is_some_and(|t| t.code == 310)) { + if bytes.len() >= END { + break; + } + let Some(t) = tags.get(i) else { return }; + let s = t.value.trim(); + if s.len() % 2 != 0 || !s.is_ascii() { + return; + } + let take = (s.len() / 2).min(END - bytes.len()); + for k in 0..take { + // `from_str_radix` also takes a sign, so each digit is checked first. + let Some(h) = s.get(2 * k..2 * k + 2).filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit())) else { return }; + let Ok(b) = u8::from_str_radix(h, 16) else { return }; + bytes.push(b); + } + spans.push((i, take)); + } + if bytes.len() < END { + return; + } + // Only data whose corners are this frame's corners (UL, UR, LR, LL) has the layout above; any + // other header is not ours to rewrite. + let [x1, y1, x2, y2] = frame; + let want = [(x1, y1), (x2, y1), (x2, y2), (x1, y2)]; + // Two corners match within a fixed tolerance for ordinary coordinates (CORNER_EPS at most), or + // within a few ulps of the coordinate where that is larger, which is from about 1.1e9 up. + let near = |a: f64, b: f64| { + let m = a.abs().max(b.abs()); + (a - b).abs() <= (1e-9 * m.max(1.0)).min(CORNER_EPS).max(4.0 * f64::EPSILON * m) + }; + for (c, (wx, wy)) in want.iter().enumerate() { + let at = OLE_HEADER + c * 24; + let rd = |o: usize| bytes.get(o..o + 8).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes); + let (Some(x), Some(y)) = (rd(at), rd(at + 8)) else { return }; + if !(near(x, *wx) && near(y, *wy)) { + return; + } + } + for (c, p) in new.iter().enumerate() { + let at = OLE_HEADER + c * 24; + if let Some(s) = bytes.get_mut(at..at + 8) { + s.copy_from_slice(&p.x.to_le_bytes()); + } + if let Some(s) = bytes.get_mut(at + 8..at + 16) { + s.copy_from_slice(&p.y.to_le_bytes()); + } + } + let mut pos = 0; + for (i, n) in spans { + let (Some(t), Some(chunk)) = (tags.get_mut(i), bytes.get(pos..pos + n)) else { return }; + // Leave any padding around the digits, and the digits after the header, as they were. + let start = t.value.len() - t.value.trim_start().len(); + // Only the rewritten digits and a few after them, for the case of the nearest letter: a + // hostile 310 line can be as long as the file (the value is checked to be ASCII above). + let end = start.saturating_add(2 * n + 64).min(t.value.len()); + let hex = recase(chunk, t.value.get(start..end).unwrap_or_default()); + t.value.replace_range(start..start + 2 * n, &hex); + pos += n; + } +} + +/// The hex of `chunk`, each digit in the case of the digit at the same place in `old`. A digit that +/// was a number and becomes a letter takes the case of the nearest letter in `old`, upper when there +/// is none, so bytes that did not change keep their exact text. +fn recase(chunk: &[u8], old: &str) -> String { + let old = old.as_bytes(); + // For each place, whether the letter nearest to it (the one at it, else the closest before or + // after; the one before on a tie) is lower case: one pass for the next letter at or after each + // place, one for the previous, then the nearer of the two. + let mut next: Vec> = vec![None; old.len()]; + let mut seen: Option<(usize, bool)> = None; + for (i, c) in old.iter().enumerate().rev() { + if c.is_ascii_alphabetic() { + seen = Some((i, c.is_ascii_lowercase())); + } + if let Some(slot) = next.get_mut(i) { + *slot = seen; + } + } + let mut lower_at = vec![false; old.len()]; + let mut prev: Option<(usize, bool)> = None; + for (i, c) in old.iter().enumerate() { + if c.is_ascii_alphabetic() { + prev = Some((i, c.is_ascii_lowercase())); + } + let after = next.get(i).copied().flatten(); + let lower = match (prev, after) { + (Some((p, lp)), Some((q, lq))) => { + if i - p <= q - i { + lp + } else { + lq + } + } + (Some((_, l)), None) | (None, Some((_, l))) => l, + (None, None) => false, + }; + if let Some(slot) = lower_at.get_mut(i) { + *slot = lower; + } + } + let mut out = String::with_capacity(chunk.len() * 2); + for (k, b) in chunk.iter().enumerate() { + for (j, d) in [b >> 4, b & 15].into_iter().enumerate() { + let digit = char::from_digit(d.into(), 16).unwrap_or('0'); + out.push(if lower_at.get(2 * k + j).copied().unwrap_or(false) { digit } else { digit.to_ascii_uppercase() }); + } + } + out +} + +/// The fixed part of the tolerance when matching the corners in the OLE data to the frame's. The +/// header holds the same f64 the frame groups print, so they agree to a few ulps. Up to about 1.1e9 +/// a fixed tolerance of at most this decides, so that distinct geometry does not match; above that, +/// four ulps of the coordinate (`4 * EPSILON * |x|`) exceed it and decide instead. +const CORNER_EPS: f64 = 1e-6; + +/// Transform an OLE2FRAME by `m`: its two corners are mapped through `m` (a DWG save writes the +/// frame's position from these groups), and so are the corners at the start of its OLE data (310 +/// groups), which a reader of the saved file may trust instead. The frame stays axis aligned with +/// its upper-left corner first. A matrix that keeps the axes or swaps them (a move, scale, mirror or +/// quarter turn) gives the box of the two mapped corners. Any other turn would collapse that box +/// (a square turned 45° maps its two corners level), so the frame's centre is mapped and its size +/// kept, scaled by `m`'s, its sides swapped when the turn is nearer a quarter turn. Commands refuse +/// a rotation or mirror (see [`ole_frame_accepts`]), but internal callers such as EXPLODE, REFEDIT +/// and paste still apply them, and must leave a consistent frame. A frame with no usable corners is +/// left alone. +pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) { + let Some([(ix1, x1), (iy1, y1), (ix2, x2), (iy2, y2)]) = ole_corner_groups(tags) else { return }; + let frame = [x1, y1, x2, y2]; + let t = 1e-12 * (m.a.abs() + m.b.abs() + m.c.abs() + m.d.abs()); + let axes_kept = (m.b.abs() <= t && m.c.abs() <= t) || (m.a.abs() <= t && m.d.abs() <= t); + let (a, b) = if axes_kept { + (m.apply(Vec2::new(x1, y1)), m.apply(Vec2::new(x2, y2))) + } else { + let center = m.apply(Vec2::new((x1 + x2) / 2.0, (y1 + y2) / 2.0)); + // A plain turn keeps the size exactly; cos² + sin² can miss 1 by an ulp or two. + let s = (m.a * m.d - m.b * m.c).abs().sqrt(); + let scale = if (s - 1.0).abs() < 1e-12 { 1.0 } else { s }; + let (mut w, mut h) = ((x2 - x1).abs() * scale, (y2 - y1).abs() * scale); + // Where the frame's x axis goes: nearer to y than to x is nearer a quarter turn. + if m.b.abs() > m.a.abs() { + std::mem::swap(&mut w, &mut h); + } + (center - Vec2::new(w, h) / 2.0, center + Vec2::new(w, h) / 2.0) + }; + if !(a.x.is_finite() && a.y.is_finite() && b.x.is_finite() && b.y.is_finite()) { + return; + } + let (lo, hi) = (Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y))); + let (ul, lr) = (Vec2::new(lo.x, hi.y), Vec2::new(hi.x, lo.y)); + for (i, v) in [(ix1, ul.x), (iy1, ul.y), (ix2, lr.x), (iy2, lr.y)] { + if let Some(t) = tags.get_mut(i) { + t.value = v.to_string(); + } + } + ole_data_transform(tags, [ul, Vec2::new(lr.x, ul.y), lr, Vec2::new(ul.x, lr.y)], frame); +} + +/// Whether `m` can move an OLE2FRAME: a translation (move, copy, stretch of the whole frame) or a +/// uniform scale with a positive factor, which keep the frame axis aligned and its upper-left corner +/// upper-left. +pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool { + const T: f64 = 1e-12; + // The tolerance grows with the scale: a matrix built from two angles (ALIGN) leaves rounding noise + // in b and c of about `scale * 1e-16`. + let t = T * m.a.abs(); + m.b.abs() < t && m.c.abs() < t && m.a > 0.0 && (m.a - m.d).abs() <= t +} + /// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` characters, following its justification /// the same way the renderer places it (the stroke font is about 0.88 of the height per character). fn text_box(t: &crate::Text, len: usize) -> Bounds2 { @@ -283,6 +516,8 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< Bounds2::from_points([o, o + u, o + v, o + u + v]) } EntityKind::LwPolyline(p) => lwpolyline_bounds(p), + // An OLE object's content is not drawn, but its frame is, so the frame counts (#2422). + EntityKind::Unknown(u) if u.is_ole_frame() => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points), kind => { let mut b = Bounds2::EMPTY; for p in kind.prims() { @@ -478,6 +713,41 @@ mod tests { assert!(bounds(EntityKind::MLeader(empty)).max.x < 26.0); } + /// An OLE2FRAME counts in the extents through its corner tags (#2422); a missing or + /// non-finite corner counts as nothing. + #[test] + fn ole_frame_counts_in_extents() { + let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() }; + let frame = |tags: Vec| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags }); + let b = bounds(frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])); + assert_eq!((b.min, b.max), (Vec2::new(30.0, -22.0), Vec2::new(35.0, -19.0))); + assert!(bounds(frame(vec![tag(10, "1"), tag(20, "2")])).is_empty(), "one corner is not a frame"); + assert!(bounds(frame(vec![tag(10, "NaN"), tag(20, "0"), tag(11, "1"), tag(21, "inf")])).is_empty()); + assert!(bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")] })).is_empty()); + } + + /// Groups 10/20 inside an application-defined `102 {...}` group belong to the application, not + /// to the frame: the real corners come after it (review on #2587). + #[test] + fn ole_frame_skips_application_groups() { + let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() }; + let tags = vec![ + tag(102, "{ACAD_REACTORS"), + tag(10, "900"), + tag(20, "900"), + tag(11, "901"), + tag(21, "901"), + tag(102, "}"), + tag(10, "30"), + tag(20, "-19"), + tag(11, "35"), + tag(21, "-22"), + ]; + let q = ole_frame(&tags).expect("frame"); + assert_eq!((q[0], q[2]), (Vec2::new(30.0, -19.0), Vec2::new(35.0, -22.0))); + assert!(ole_frame(&tags[..6]).is_none(), "corners only inside the group are not a frame"); + } + #[test] fn a_shared_block_cache_measures_as_a_fresh_one_for_each_entity() { let line = |a: (f64, f64), b: (f64, f64), layer: &str| { @@ -558,4 +828,291 @@ mod tests { let b = entity_bounds(&d, &array(u32::MAX, 1, 0.0), 0); assert!((b.max.x - (10.0 * 9_999.0 + 1.0)).abs() < 1e-6, "{b:?}"); } + + /// An OLE2FRAME at large coordinates, with its OLE data header holding the frame's corners + /// shifted by `dx` in x. + fn big_frame(dx: f64) -> Vec { + let (x1, y1, x2, y2) = (1e9, 1e9, 1e9 + 10.0, 1e9 + 5.0); + let mut blob = vec![1u8, 0]; + for (x, y) in [(x1, y1), (x2, y1), (x2, y2), (x1, y2)] { + for v in [x + dx, y, 7.0] { + blob.extend_from_slice(&v.to_le_bytes()); + } + } + let tag = |code: i32, value: String| crate::RawTag { code, value }; + vec![ + tag(10, x1.to_string()), + tag(20, y1.to_string()), + tag(11, x2.to_string()), + tag(21, y2.to_string()), + tag(310, blob.iter().map(|b| format!("{b:02X}")).collect()), + ] + } + + /// The x of the first corner in the OLE data of a [`big_frame`]. + fn data_x(tags: &[crate::RawTag]) -> f64 { + let hex = tags.last().map(|t| t.value.as_str()).unwrap_or_default(); + let bytes: Vec = (0..hex.len() / 2).filter_map(|i| u8::from_str_radix(hex.get(2 * i..2 * i + 2)?, 16).ok()).collect(); + bytes.get(2..10).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes).unwrap_or(f64::NAN) + } + + /// The match between the frame and the corners in its OLE data does not loosen with the + /// coordinate: half a unit off at 1e9 is not the frame, so the bytes stay as they are (review + /// on #2587). + #[test] + fn a_half_unit_offset_at_large_coordinates_is_not_the_frame() { + let mut tags = big_frame(0.5); + let before = tags.last().cloned(); + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(1.0, 1.0))); + assert_eq!(tags.first().map(|t| t.value.as_str()), Some("1000000001"), "the frame tags move"); + assert_eq!(tags.last().map(|t| &t.value), before.as_ref().map(|t| &t.value), "the 310 bytes stay identical"); + } + + #[test] + fn exact_corners_at_large_coordinates_still_move() { + let mut tags = big_frame(0.0); + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(1.0, 1.0))); + assert_eq!(data_x(&tags), 1e9 + 1.0); + } + + /// A translation, and a uniform positive scale about any point, keep a frame axis aligned and + /// upper-left; a rotation, a mirror, a non-uniform or non-positive scale do not. + #[test] + fn ole_frame_accepts_translations_and_uniform_positive_scales_only() { + use cadcraft_geom::Mat3; + let p = Vec2::new(3.0, -4.0); + assert!(ole_frame_accepts(&Mat3::translate(p))); + assert!(ole_frame_accepts(&Mat3::scale_about(p, 2.5))); + assert!(ole_frame_accepts(&Mat3::scale_about(p, 1e-3))); + assert!(!ole_frame_accepts(&Mat3::scale(2.0, 3.0))); + assert!(!ole_frame_accepts(&Mat3::scale_about(p, -1.0))); + assert!(!ole_frame_accepts(&Mat3::scale_about(p, 0.0))); + assert!(!ole_frame_accepts(&Mat3::rotate_about(p, 0.5))); + assert!(!ole_frame_accepts(&Mat3::mirror(Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0)))); + } + /// ALIGN with a scale builds its matrix from two angles that agree only to rounding, so a large + /// scale leaves a rotation part of about `scale * 1e-16`. That is a scale, not a turn: the + /// tolerance for it grows with the scale, while a real turn is still refused (review on #2587). + #[test] + fn ole_frame_accepts_a_large_scale_with_rounding_noise_in_its_rotation() { + use cadcraft_geom::Mat3; + let p = Vec2::new(3.0, -4.0); + let noisy = Mat3::scale_about(p, 1e6).then_before(Mat3::rotate_about(p, 2e-16)); + assert!(noisy.b.abs() > 1e-12, "the setup must exceed an absolute tolerance: {}", noisy.b); + assert!(ole_frame_accepts(&noisy)); + let turned = Mat3::scale_about(p, 1e6).then_before(Mat3::rotate_about(p, 1e-6)); + assert!(!ole_frame_accepts(&turned)); + } + + /// The corners (x, y) in the OLE data header of a frame built by [`big_frame`]-style tags. + fn header_corners(tags: &[crate::RawTag]) -> Vec<(f64, f64)> { + let hex: String = tags.iter().filter(|t| t.code == 310).map(|t| t.value.as_str()).collect(); + let bytes: Vec = (0..hex.len() / 2).filter_map(|i| u8::from_str_radix(hex.get(2 * i..2 * i + 2)?, 16).ok()).collect(); + let f = |o: usize| bytes.get(o..o + 8).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes).unwrap_or(f64::NAN); + (0..4).map(|c| (f(2 + c * 24), f(10 + c * 24))).collect() + } + + fn small_frame() -> Vec { + let mut blob = vec![1u8, 0]; + for (x, y) in [(30.0f64, -19.0f64), (35.0, -19.0), (35.0, -22.0), (30.0, -22.0)] { + for v in [x, y, 7.0] { + blob.extend_from_slice(&v.to_le_bytes()); + } + } + let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() }; + vec![ + tag(10, "30"), + tag(20, "-19"), + tag(11, "35"), + tag(21, "-22"), + crate::RawTag { code: 310, value: blob.iter().map(|b| format!("{b:02X}")).collect() }, + ] + } + + /// Internal callers (EXPLODE, REFEDIT, paste, array placement) transform a frame by any matrix. + /// It stays axis aligned: groups 10/20 are the upper-left of its box, 11/21 the lower-right, + /// and the OLE data holds the same box (review on #2587). A mirror keeps the axes, so the box + /// is that of the mapped corners; a 30° turn keeps the frame's own 5 x 3 about its turned + /// centre, where the corners' box would flatten it. + #[test] + fn a_rotated_frame_stays_axis_aligned_and_consistent() { + use cadcraft_geom::Mat3; + let rotate = Mat3::rotate_about(Vec2::new(1.0, 2.0), 30f64.to_radians()); + let mirror = Mat3::mirror(Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0)); + for (m, turned) in [(rotate, true), (mirror, false)] { + let mut tags = small_frame(); + let mapped = if turned { + let c = m.apply(Vec2::new(32.5, -20.5)); + [c - Vec2::new(2.5, 1.5), c + Vec2::new(2.5, 1.5)] + } else { + [m.apply(Vec2::new(30.0, -19.0)), m.apply(Vec2::new(35.0, -22.0))] + }; + let (minx, maxx) = (mapped[0].x.min(mapped[1].x), mapped[0].x.max(mapped[1].x)); + let (miny, maxy) = (mapped[0].y.min(mapped[1].y), mapped[0].y.max(mapped[1].y)); + ole_frame_transform(&mut tags, &m); + let g = |code: i32| tags.iter().find(|t| t.code == code).and_then(|t| t.value.parse::().ok()).unwrap_or(f64::NAN); + assert_eq!((g(10), g(20), g(11), g(21)), (minx, maxy, maxx, miny)); + assert_eq!(header_corners(&tags), vec![(minx, maxy), (maxx, maxy), (maxx, miny), (minx, miny)]); + } + } + /// `from_str_radix` accepts a leading sign, so "+A" must not count as a hex byte (review on + /// #2587): data with one is not valid and MOVE leaves its bytes alone. + #[test] + fn a_plus_sign_in_ole_data_is_not_hex() { + let mut tags = small_frame(); + let hex = tags.last().map(|t| t.value.clone()).unwrap_or_default(); + // The marker's first byte is 01: "+1" would decode to the same byte. + let signed = format!("+1{}", hex.get(2..).unwrap_or_default()); + if let Some(t) = tags.last_mut() { + t.value = signed.clone(); + } + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(10.0, 5.0))); + assert_eq!(tags.first().map(|t| t.value.as_str()), Some("40"), "the frame tags still move"); + assert_eq!(tags.last().map(|t| t.value.as_str()), Some(signed.as_str())); + } + + /// A payload of 1,000 groups of 127 bytes: only the group(s) holding the 98-byte header are + /// rewritten. Later groups stay as they were, even ones that are not valid hex or have padding + /// (the old code re-encoded the whole payload and gave up on any bad group). + #[test] + fn a_large_ole_payload_only_rewrites_its_leading_groups() { + let mut tags = small_frame(); + let first = tags.pop().map(|t| t.value).unwrap_or_default(); + let mut head = first.clone(); + // Fill the first group up to 127 bytes. + head.push_str(&"ab".repeat(127 - first.len() / 2)); + tags.push(crate::RawTag { code: 310, value: head }); + for g in 1..1000 { + let value = match g { + 2 => format!(" {} ", "Ab".repeat(127)), + 500 => "ZZ".repeat(127), + _ => "ab".repeat(127), + }; + tags.push(crate::RawTag { code: 310, value }); + } + let rest: Vec = tags.iter().skip(5).map(|t| t.value.clone()).collect(); + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(10.0, 5.0))); + assert_eq!(header_corners(&tags[..5]), vec![(40.0, -14.0), (45.0, -14.0), (45.0, -17.0), (40.0, -17.0)]); + let after: Vec = tags.iter().skip(5).map(|t| t.value.clone()).collect(); + assert_eq!(after, rest, "every group after the first is string-identical"); + assert_eq!(tags.get(4).map(|t| t.value.len()), Some(254), "the first group keeps its length"); + } + + /// Above about 8.6e9 one ulp of an f64 is more than the fixed ceiling on the corner match, so a + /// text corner one ulp from the header double must still count as the same corner (review on + /// #2587). + #[test] + fn ole_frame_moves_at_2e10_with_a_one_ulp_text_corner() { + let mut tags = big_frame(0.0); + // Rebuild the frame at 2e10: the header keeps the exact corners, the text is one ulp off. + let (x1, y1, x2, y2) = (2e10f64, 2e10f64, 2e10 + 10.0, 2e10 + 5.0); + let mut blob = vec![1u8, 0]; + for (x, y) in [(x1, y1), (x2, y1), (x2, y2), (x1, y2)] { + for v in [x, y, 7.0] { + blob.extend_from_slice(&v.to_le_bytes()); + } + } + let text_x1 = f64::from_bits(x1.to_bits() + 1); + tags[0].value = text_x1.to_string(); + tags[1].value = y1.to_string(); + tags[2].value = x2.to_string(); + tags[3].value = y2.to_string(); + if let Some(t) = tags.last_mut() { + t.value = blob.iter().map(|b| format!("{b:02X}")).collect(); + } + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(1e4, 1e4))); + assert_eq!(header_corners(&tags)[0].0, text_x1 + 1e4, "the header moved with the frame"); + } + + /// Below scale 1 the rotation bound is still relative to the scale: a small real turn at a tiny + /// scale is refused, and so is a non-uniform scale whose two factors differ by more than a + /// relative 1e-12 (review on #2587). + #[test] + fn ole_frame_refuses_a_small_turn_at_a_tiny_scale() { + use cadcraft_geom::Mat3; + let p = Vec2::new(3.0, -4.0); + let turned = Mat3::scale_about(p, 1e-9).then_before(Mat3::rotate_about(p, 0.05f64.to_radians())); + assert!(!ole_frame_accepts(&turned)); + assert!(ole_frame_accepts(&Mat3::scale_about(p, 1e-9))); + assert!(!ole_frame_accepts(&Mat3::scale(1e-6, 1e-6 + 5e-13))); + } + + /// Hex digits keep the case they had: bytes the transform does not change come back as the + /// identical text, also in a group that mixes upper and lower case (review on #2587). + #[test] + fn moving_an_ole_frame_keeps_each_hex_digits_case() { + let mut tags = small_frame(); + let old = tags.last().map(|t| t.value.clone()).unwrap_or_default(); + let mixed: String = old.chars().enumerate().map(|(i, c)| if i < 24 { c.to_ascii_lowercase() } else { c }).collect(); + assert_ne!(mixed, old); + if let Some(t) = tags.last_mut() { + t.value = mixed.clone(); + } + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(10.0, 5.0))); + let new = tags.last().map(|t| t.value.clone()).unwrap_or_default(); + assert_eq!(new.len(), mixed.len()); + let byte = |s: &str, i: usize| s.get(2 * i..2 * i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); + let mut same = 0; + for i in 0..mixed.len() / 2 { + if byte(&mixed, i) == byte(&new, i) { + same += 1; + assert_eq!(mixed.get(2 * i..2 * i + 2), new.get(2 * i..2 * i + 2), "byte {i}"); + } + } + assert!(same > 40, "most of the header is unchanged: {same}"); + assert_eq!(header_corners(&tags)[0], (40.0, -14.0)); + } + + /// A frame from `(x1, y1)` (upper left) to `(x2, y2)` (lower right), its OLE header holding the + /// same corners. + fn frame_at(x1: f64, y1: f64, x2: f64, y2: f64) -> Vec { + let mut blob = vec![1u8, 0]; + for (x, y) in [(x1, y1), (x2, y1), (x2, y2), (x1, y2)] { + for v in [x, y, 0.0] { + blob.extend_from_slice(&v.to_le_bytes()); + } + } + let tag = |code: i32, value: String| crate::RawTag { code, value }; + vec![ + tag(10, x1.to_string()), + tag(20, y1.to_string()), + tag(11, x2.to_string()), + tag(21, y2.to_string()), + tag(310, blob.iter().map(|b| format!("{b:02X}")).collect()), + ] + } + + fn size(tags: &[crate::RawTag]) -> (f64, f64, Vec2) { + let o = ole_frame(tags).unwrap(); + let b = Bounds2::from_points(o); + (b.width(), b.height(), b.center()) + } + + /// A frame turned by an angle that isn't a quarter turn keeps its size about its turned + /// centre instead of collapsing to the box of its two corners (a 10 x 10 square turned 45° + /// became 14.14 x 0), and the OLE header follows (#2587 review). + #[test] + fn a_frame_turned_off_the_axes_keeps_its_size() { + use cadcraft_geom::Mat3; + let close = |a: f64, b: f64| (a - b).abs() < 1e-9; + let mut tags = frame_at(0.0, 10.0, 10.0, 0.0); + ole_frame_transform(&mut tags, &Mat3::rotate(std::f64::consts::FRAC_PI_4)); + let (w, h, c) = size(&tags); + assert!(close(w, 10.0) && close(h, 10.0), "{w} x {h}"); + assert!(close(c.x, 0.0) && close(c.y, 50f64.sqrt()), "{c:?}"); + let (ul, lr) = (header_corners(&tags)[0], header_corners(&tags)[2]); + assert!(close(ul.0, -5.0) && close(lr.1, 50f64.sqrt() - 5.0), "the header follows: {ul:?} {lr:?}"); + // Nearer a quarter turn, the sides swap: a 10 wide, 4 tall frame turned 100° is 4 x 10. + let mut tags = frame_at(0.0, 4.0, 10.0, 0.0); + ole_frame_transform(&mut tags, &Mat3::rotate(100f64.to_radians())); + let (w, h, _) = size(&tags); + assert!(close(w, 4.0) && close(h, 10.0), "{w} x {h}"); + // A turn and its inverse bring the frame back. + let mut tags = frame_at(2.0, 9.0, 7.0, 3.0); + let m = Mat3::rotate(0.3); + ole_frame_transform(&mut tags, &m); + ole_frame_transform(&mut tags, &m.inverse().unwrap()); + let (w, h, c) = size(&tags); + assert!(close(w, 5.0) && close(h, 6.0) && close(c.x, 4.5) && close(c.y, 6.0), "{w} x {h} at {c:?}"); + } } diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 406f4e12b..8116cd412 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -55,6 +55,8 @@ impl ForeignExtra { pub struct Foreign { /// CLASS records (groups after `0 CLASS`) of the kept objects' and entities' types. pub classes: Vec>, + /// Classes retain every source position, including duplicate names. + pub complete_class_table: bool, /// Kept objects, in file order. pub objects: Vec, /// Entries of the named object dictionary that CADCraft doesn't write itself: (key, object). @@ -75,9 +77,19 @@ pub struct Foreign { /// surfaces, which from 2013 on those entities don't carry themselves: each `ACDSRECORD` /// names its entity with a 320 handle (see [`Foreign::data_store_entities`]). pub data_store: Vec, + /// The `$ACADVER` of the file all this was read from: its groups are in that version's form. + /// 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, } impl Foreign { + /// The class of the file's CLASSES a proxy's group 91 names (see [`class_number`]), if any. + /// Saving as DWG keeps a proxy with that class and leaves out one whose class it can't name. + pub fn proxy_class(&self, tags: &[RawTag]) -> Option<&str> { + class_index(class_number(tags.iter().map(|r| (r.code, r.value.as_str())))).and_then(|i| self.class_order.get(i)).map(String::as_str) + } + pub fn is_empty(&self) -> bool { self.objects.is_empty() && self.dictionary.is_empty() @@ -256,3 +268,29 @@ impl Foreign { } } } + +/// Where a proxy's class number is: its first group 91 outside the `102 {NAME` … `102 }` groups +/// (an application's can hold a 91 of its own) and before any xdata. +pub fn class_group>(groups: impl IntoIterator) -> Option { + let mut in_group = false; + for (i, (code, value)) in groups.into_iter().enumerate() { + match code { + 1000.. => return None, + 102 => in_group = value.as_ref().trim().starts_with('{'), + 91 if !in_group => return Some(i), + _ => {} + } + } + None +} + +/// A proxy's class number (see [`class_group`]). +pub fn class_number>(groups: impl IntoIterator + Clone) -> Option { + let i = class_group(groups.clone())?; + groups.into_iter().nth(i).and_then(|(_, v)| v.as_ref().trim().parse().ok()) +} + +/// The place in CLASSES a class number names (500 is the first class). +pub fn class_index(number: Option) -> Option { + usize::try_from(number?.checked_sub(500)?).ok() +} diff --git a/crates/doc/src/header.rs b/crates/doc/src/header.rs index c6f17fd7e..52b9d34b1 100644 --- a/crates/doc/src/header.rs +++ b/crates/doc/src/header.rs @@ -90,6 +90,23 @@ impl Header { .filter(|p| p.is_finite() && if allow_zero { p.x >= 0.0 && p.y >= 0.0 } else { p.x > 0.0 && p.y > 0.0 }) .unwrap_or(Vec2::new(0.5, 0.5)) } + /// The model view the drawing was saved at: `$VIEWCTR` (centre) and `$VIEWSIZE` (height, in + /// drawing units), when both are present and usable. A DXF file keeps the pair in HEADER and + /// repeats it in the `*ACTIVE` VPORT record (12/22 and 40); a reader opens the drawing on it + /// rather than on the extents, so a drawing saved on one detail of a large sheet opens there. + pub fn saved_view(&self) -> Option<(Vec2, f64)> { + let center = self.point("VIEWCTR")?.xy(); + let height = self.get("VIEWSIZE").and_then(HVal::as_f64)?; + (center.is_finite() && height.is_finite() && height > 1e-9).then_some((center, height)) + } + /// Record the view the drawing is saved at (see [`Header::saved_view`]). A view that cannot + /// be shown is not recorded, so a usable stored view is never replaced by an unusable one. + pub fn set_saved_view(&mut self, center: Vec2, height: f64) { + if center.is_finite() && height.is_finite() && height > 1e-9 { + self.set("VIEWCTR", HVal::Point(center.to3(0.0))); + self.set_f64("VIEWSIZE", height); + } + } pub fn set_f64(&mut self, name: &str, v: f64) { self.set(name, HVal::Real(v)); } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2b11a5bd3..873e83b83 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -29,7 +29,10 @@ pub use cadcraft_color as color; pub use cadcraft_geom as geom; pub use constraint::*; pub use entity::*; -pub use extents::{BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached}; +pub use extents::{ + BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, ole_frame_accepts, + ole_frame_transform, +}; pub use format::Format; pub use gdt::*; pub use header::{HVal, Header}; diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index 9ad951f6e..5707e0c90 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -486,16 +486,24 @@ impl DimStyle { /// Set fields from a JSON object of field or DIM* variable names (numbers, booleans as /// 0/1, colours as ACI numbers or names). Returns the names that were not recognised or - /// had unusable values. + /// had unusable values. When several spellings name one field, the last one wins and the + /// superseded ones are not validated. pub fn apply_fields(&mut self, src: &serde_json::Map) -> Vec { use serde_json::Value; let mut rejected = Vec::new(); let Ok(mut cur) = serde_json::to_value(&*self) else { return src.keys().cloned().collect() }; + // Spellings of one field (`DIMPOST`, `dimpost`, `textPrefix`…): only the last is applied, so + // the style is checked once per field, not once per spelling (each check copies its strings). + let last_spelling: std::collections::HashMap<&str, &String> = + src.keys().filter_map(|k| DimStyle::field_name(k).filter(|f| *f != "name").map(|f| (f, k))).collect(); for (k, v) in src { let Some(field) = DimStyle::field_name(k).filter(|f| *f != "name") else { rejected.push(k.clone()); continue; }; + if last_spelling.get(field) != Some(&k) { + continue; + } let Some(obj) = cur.as_object_mut() else { break }; let Some(old) = obj.get(field).cloned() else { rejected.push(k.clone()); @@ -799,6 +807,13 @@ pub struct PageSetup { /// The layout's paper units are millimetres (plot paper units 1 in DXF) whatever the /// drawing's MEASUREMENT says; otherwise paper units follow MEASUREMENT (#1058). pub paper_mm: bool, + /// Paper size (DXF groups 44, 45) and plot rotation (group 73) as the file stored them. + /// Saving writes them back while they still describe `width_mm`, `height_mm` and + /// `landscape`, so each program's convention for media defined wider than tall survives a + /// round trip: AutoCAD stores a portrait size and a quarter turn, ZWCAD the media's own size + /// and no turn (#1463). `None` for page setups made in CADCraft. + #[serde(skip)] + pub file_paper: Option<(f64, f64, i64)>, /// The paper image origin (DXF groups 148/149, in plot paper units) as the file had it, so a /// save keeps where the sheet sits; `None` for a page CADCraft made, written as 0,0 (#2109). #[serde(skip_serializing_if = "Option::is_none")] @@ -824,6 +839,7 @@ impl Default for PageSetup { show_plot_styles: false, plot_transparency: false, paper_mm: false, + file_paper: None, image_origin: None, } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index ec3f38ebb..1f11ba494 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -714,3 +714,14 @@ fn space_names_its_tab() { assert_eq!(p.layout(), Some("Sheet A")); assert_eq!(p.tab_name(), "Sheet A"); } + +/// Several spellings of one DIM field apply once, the last in the map's order, and none is rejected. +#[test] +fn dim_style_spellings_of_one_field_apply_once() { + let mut st = DimStyle::default(); + let m = serde_json::json!({ "textHeight": 2.5, "TEXTHEIGHT": 3.5, "DIMTXT": 4.5 }); + let m = m.as_object().unwrap(); + let want = m.values().next_back().and_then(serde_json::Value::as_f64).unwrap(); + assert!(st.apply_fields(m).is_empty()); + assert_eq!(st.text_height, want); +} diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index f143b7be8..4d1eee279 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -65,7 +65,9 @@ fn mb(n: u64) -> String { #[cfg(not(no_dwg_bridge))] pub mod worker; #[cfg(not(no_dwg_bridge))] -pub use worker::{WORKER_ARG, crash_worker_for_test, decode, encode_as, encode_noted, serve_if_asked, use_own_worker, use_worker}; +pub use worker::{WORKER_ARG, crash_worker_for_test, decode, encode_as, encode_kept_noted, encode_noted, serve_if_asked, use_own_worker, use_worker}; +#[cfg(not(no_dwg_bridge))] +mod proxy_transport; #[cfg(not(no_dwg_bridge))] mod native { @@ -107,6 +109,13 @@ mod native { } let mut notes = read_notes(&outcome.stats); let mut doc = outcome.document; + notes.extend( + guarded(AssertUnwindSafe(|| application_objects(&mut doc))).map_err(|_| "the DWG application object conversion failed".to_string())?, + ); + // After application_objects, so the proxy objects it makes are numbered as the DXF's. + notes.extend( + guarded(AssertUnwindSafe(|| super::proxy_transport::prepare(&mut doc))).map_err(|_| "the DWG proxy conversion failed".to_string())?, + ); let orphans = guarded(AssertUnwindSafe(|| post_process(&mut doc))).map_err(|_| "the DWG post-processing failed on this file".to_string())?; if orphans > 0 { let (s, were) = if orphans == 1 { ("", "was") } else { ("s", "were") }; @@ -390,6 +399,214 @@ mod native { std::panic::catch_unwind(f).map_err(|_| ()) } + /// The version a proxy record of a DWG of `version` names its format by (Open Design + /// Specification for .dwg, proxy objects): 19 for R13, 21 for R14, 23 for 2000, 25 for 2004, + /// 27 for 2007, 29 for 2010, 31 for 2013 and 33 for 2018; `None` for any other version. + pub(super) fn proxy_dwg_version(version: acadrust::DxfVersion) -> Option { + Some(match version.version_code() { + 1012 => 19, + 1014 => 21, + 1015 => 23, + 1018 => 25, + 1021 => 27, + 1024 => 29, + 1027 => 31, + 1032 => 33, + _ => return None, + }) + } + + /// Objects of another application's class that acadrust keeps only as their DWG record + /// (`ObjectType::Unknown`, which has no DXF form): its DXF writer left them out, and the + /// references to them went with them (a dimension's extension dictionary entry naming its + /// application data, say), with no note. Each is carried as a proxy object of its class instead + /// (DXF Reference, ACAD_PROXY_OBJECT), so the DXF keeps it and a DWG written from that DXF has it + /// again: its common object data (owner, reactors, extension dictionary) and the streams after + /// it (data bits, R2007+ strings, object references), as the Open Design Specification for .dwg + /// splits an object record. Objects of the drawing database's own classes are not turned into + /// another application's proxies. What is still without a DXF form is named in the notes, so a + /// save over the original is not mistaken for a complete one. + fn application_objects(doc: &mut acadrust::CadDocument) -> Vec { + use acadrust::objects::{ObjectType, ProxyObject}; + let classes: Vec = doc.classes.iter().cloned().collect(); + let source = doc.dwg_source_version.unwrap_or(doc.version); + if let Some(dwg_version) = proxy_dwg_version(source) { + let maintenance = i32::from(doc.maintenance_version); + for object in doc.objects.values_mut() { + let ObjectType::Unknown { handle, raw_dwg_data: Some(data), raw_dwg_handle_bits, raw_dwg_version: Some(version), type_name, .. } = + &*object + else { + continue; + }; + if !application_class(&classes, type_name) { + continue; + } + let raw = acadrust::entities::RawRecord { data: data.clone(), handle_bits: *raw_dwg_handle_bits, version: *version }; + let handle = *handle; + // A record that doesn't split stays as it was, and is named below. + let Ok(Ok(record)) = std::panic::catch_unwind(AssertUnwindSafe(|| object_record(&raw, handle.value()))) else { continue }; + let Some(class) = classes.iter().find(|c| c.class_number == record.kind && !c.is_an_entity) else { continue }; + *object = ObjectType::ProxyObject(ProxyObject { + handle, + owner: record.owner, + reactors: record.reactors, + xdictionary_handle: record.xdictionary, + proxy_id: 499, + class_id: i32::from(class.class_number), + dwg_version, + maintenance_version: maintenance, + version: (maintenance << 16) | dwg_version, + payload: record.payload, + text_payload: record.text_payload, + object_ids: record.object_ids, + ..Default::default() + }); + } + } + let mut left: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); + for object in doc.objects.values() { + if let ObjectType::Unknown { type_name, raw_dxf_codes: None, .. } = object { + let n = left.entry(type_name.as_str()).or_insert(0); + *n = n.saturating_add(1); + } + } + if left.is_empty() { + return Vec::new(); + } + let total = left.values().fold(0usize, |a, n| a.saturating_add(*n)); + let mut list: Vec = left.iter().take(NOTE_TYPES).map(|(t, n)| format!("{t:.60} × {n}")).collect(); + if left.len() > NOTE_TYPES { + list.push(format!("{} more types", left.len() - NOTE_TYPES)); + } + vec![format!( + "DWG: {total} objects of types CADCraft doesn't keep were left out ({}); saving over the original file would lose them", + list.join(", ") + )] + } + + /// Whether `name` is an object class of another application, which only that application + /// rebuilds: not one of the drawing database's own classes (`AcDb…`/`ACDB…`/`ACAD_…`), whose + /// leftovers the database regenerates itself. + fn application_class(classes: &[acadrust::classes::DxfClass], name: &str) -> bool { + classes.iter().any(|c| { + !c.is_an_entity + && c.dxf_name.eq_ignore_ascii_case(name) + && !c.cpp_class_name.starts_with("AcDb") + && !["ACDB", "ACAD_", "ACAD"].iter().any(|p| c.dxf_name.to_ascii_uppercase().starts_with(p)) + }) + } + + /// An application object acadrust kept only as its record: the parts a proxy object carries. + struct ObjectRecord { + kind: i16, + owner: acadrust::types::Handle, + reactors: Vec, + xdictionary: Option, + payload: acadrust::objects::ProxyPayload, + text_payload: acadrust::objects::ProxyPayload, + object_ids: Vec, + } + + /// Split an object record into its common object data and the uninterpreted streams after it + /// (data bits, R2007+ strings and object references), as an application object's proxy holds + /// them (Open Design Specification for .dwg, common object data and proxy objects). The record + /// is hostile: sizes are checked against it, and acadrust's checked stream reader does the rest. + fn object_record(raw: &acadrust::entities::RawRecord, handle: u64) -> Result { + use acadrust::io::dwg::{ + DwgVersion, dwg_reference_type::DwgReferenceType, dwg_stream_readers::object_reader::DwgObjectReader, + dwg_stream_writers::bit_writer::DwgBitWriter, + }; + use acadrust::objects::{ProxyObjectReference, ProxyPayload, ProxyReferenceKind}; + use acadrust::types::{DxfVersion, Handle}; + if raw.data.len() > 32 << 20 { + return Err("object record exceeds the transport limit".into()); + } + let handle_bits = usize::try_from(raw.handle_bits).map_err(|_| "object has a negative handle stream size")?; + let total_bits = raw.data.len().checked_mul(8).ok_or("object record is too large")?; + if handle_bits > total_bits { + return Err("object handle stream exceeds its record".into()); + } + let version = DwgVersion::from_dxf_version(raw.version).map_err(|e| e.to_string())?; + let mut frame = DwgBitWriter::new(version, raw.version); + frame.write_modular_short(raw.data.len()); + if raw.version >= DxfVersion::AC1024 { + frame.write_modular_char(handle_bits); + } + frame.write_bytes(&raw.data); + let reader = DwgObjectReader::new(frame.into_bytes(), raw.version, std::collections::HashMap::new()).map_err(|e| e.to_string())?; + let (kind, mut streams) = reader.read_record_at(0).map_err(|e| e.to_string())?; + if kind < 500 { + return Err("object has no application class".into()); + } + let common = reader.read_common_non_entity_data(&mut streams, kind); + streams.check_error().map_err(|e| e.to_string())?; + if common.common.handle != handle { + return Err("object record names another handle".into()); + } + let read_bits = |count: usize, bit: &mut dyn FnMut() -> bool| -> Result { + if count > total_bits { + return Err("object stream exceeds its record".into()); + } + let n = u32::try_from(count).map_err(|_| "object stream is too large")?; + let mut bytes = vec![0u8; count.div_ceil(8)]; + for index in 0..count { + if bit() + && let Some(b) = bytes.get_mut(index / 8) + { + *b |= 0x80 >> (index % 8); + } + } + Ok(ProxyPayload::from_bits(&bytes, n)) + }; + let main = usize::try_from(streams.main_remaining_bits()).map_err(|_| "object body has an invalid size")?; + let payload = read_bits(main, &mut || streams.read_bit())?; + let text_payload = if raw.version >= DxfVersion::AC1021 { + let bits = usize::try_from(streams.text_remaining_bits()).map_err(|_| "object has a negative string stream size")?; + read_bits(bits, &mut || streams.read_text_bit())? + } else { + ProxyPayload::default() + }; + // Every reference to the end of the handle stream, null ones too: an object keeps a null pointer in its + // field's place, and the references after it are the next fields' (as acadrust reads a proxy's own). R2010+ + // records give the stream's exact length; the bits of its last byte past it are padding. + let mut object_ids = Vec::new(); + let mut left = if raw.version >= DxfVersion::AC1024 { + streams.get_handle_bits().max(0).min(streams.handle_remaining_bits()) + } else { + streams.handle_remaining_bits() + }; + while left >= 8 { + if object_ids.len() >= 100_000 { + return Err("object has too many references".into()); + } + let before = streams.handle_remaining_bits(); + let (target, reference) = streams.read_handle_reference(handle); + let used = before.saturating_sub(streams.handle_remaining_bits()); + if used <= 0 || used > left { + break; + } + left -= used; + let kind = match reference { + DwgReferenceType::SoftOwnership => ProxyReferenceKind::SoftOwnership, + DwgReferenceType::HardOwnership => ProxyReferenceKind::HardOwnership, + DwgReferenceType::SoftPointer => ProxyReferenceKind::SoftPointer, + DwgReferenceType::HardPointer => ProxyReferenceKind::HardPointer, + DwgReferenceType::Undefined => ProxyReferenceKind::Undefined, + }; + object_ids.push(ProxyObjectReference { handle: Handle::from(target), kind }); + } + streams.check_error().map_err(|e| e.to_string())?; + Ok(ObjectRecord { + kind, + owner: Handle::from(common.owner_handle), + reactors: common.reactors.into_iter().map(Handle::from).collect(), + xdictionary: common.xdictionary_handle.map(Handle::from), + payload, + text_payload, + object_ids, + }) + } + /// [`table_merges`] visiting at most `budget` cells in all; a range that would pass it is /// left unmerged. Returns the cells visited. fn table_merges_within(doc: &mut acadrust::CadDocument, budget: usize) -> usize { @@ -652,7 +869,7 @@ mod native { /// Convert DXF bytes into a DWG file of the DXF's version, and at least AutoCAD 2004 /// (AC1018). pub fn dxf_to_dwg(dxf: &[u8]) -> Result, String> { - convert(dxf, None).map(|(dwg, _)| dwg) + convert(dxf, None, None).map(|(dwg, _)| dwg) } /// Convert DXF bytes into a DWG file of `version`, a code from [`super::VERSIONS`] ("AC1032"), @@ -665,7 +882,32 @@ mod native { /// DXF type it can't write (other programs' custom entities and objects that the DWG reader /// didn't read from a DWG of this version), empty when the DWG keeps everything. pub fn dxf_to_dwg_noted(dxf: &[u8], version: &str) -> Result<(Vec, super::Unwritten), String> { - let v = match version.trim().to_ascii_uppercase().as_str() { + convert(dxf, Some(writable(version)?), None) + } + + /// Like [`dxf_to_dwg_as`], for a DXF that declares an older version than the groups it carries + /// over from another file. CADCraft's R2000 DWG bridge holds the objects it keeps without + /// modelling them (render settings, fields, associative and dynamic block data) as they were + /// read from a file of version `kept` ("AC1032"), and acadrust reads several of those + /// differently by version: read as R2000, an AC1032 file's mental ray render settings came out + /// a class version too high, for which the ODA rejects the whole DWG, and a field lost its + /// cached value. So the DXF is read as `kept` declares. A `kept` version that is unknown, or + /// not newer than the DXF's own, changes nothing. + pub fn dxf_to_dwg_kept_as(dxf: &[u8], version: &str, kept: &str) -> Result, String> { + dxf_to_dwg_kept_noted(dxf, version, kept).map(|(dwg, _)| dwg) + } + + /// [`dxf_to_dwg_kept_as`], also returning what the DWG writer left out, as + /// [`dxf_to_dwg_noted`] does. + pub fn dxf_to_dwg_kept_noted(dxf: &[u8], version: &str, kept: &str) -> Result<(Vec, super::Unwritten), String> { + let kept = acadrust::DxfVersion::from_version_string(kept.trim().to_ascii_uppercase().as_str()); + let kept = (kept != acadrust::DxfVersion::Unknown).then_some(kept); + convert(dxf, Some(writable(version)?), kept) + } + + /// The DWG version for a code from [`super::VERSIONS`]. + fn writable(version: &str) -> Result { + Ok(match version.trim().to_ascii_uppercase().as_str() { "AC1015" => acadrust::DxfVersion::AC1015, "AC1018" => acadrust::DxfVersion::AC1018, "AC1021" => acadrust::DxfVersion::AC1021, @@ -673,8 +915,72 @@ mod native { "AC1027" => acadrust::DxfVersion::AC1027, "AC1032" => acadrust::DxfVersion::AC1032, _ => return Err(super::unsupported(version)), + }) + } + + /// The ASCII DXF with its `$ACADVER` set to `kept` when that is newer than the version it + /// declares, or `None` to read it as it is (binary, no `$ACADVER`, or non-ASCII text without a + /// `$DWGCODEPAGE` to decode it by). From AutoCAD 2007 (AC1021) a DXF is UTF-8, so other bytes + /// are first decoded with the code page the DXF declares; `\U+XXXX` escapes read the same in + /// every version, and CADCraft's R2000 DXF is ASCII with such escapes. + pub(super) fn declare_version(dxf: &[u8], kept: acadrust::DxfVersion) -> Option> { + if dxf.starts_with(b"AutoCAD Binary DXF") { + return None; + } + let (_, declared) = header_value(dxf, b"$ACADVER")?; + let declared = acadrust::DxfVersion::from_version_string(std::str::from_utf8(declared).ok()?); + if declared >= kept { + return None; + } + let text: std::borrow::Cow<'_, [u8]> = if dxf.is_ascii() || kept < acadrust::DxfVersion::AC1021 { + std::borrow::Cow::Borrowed(dxf) + } else { + // As acadrust decodes an older DXF: by its code page, Windows-1252 for one it doesn't + // know; a code page that names UTF-8 needs no decoding. + let (_, code_page) = header_value(dxf, b"$DWGCODEPAGE")?; + match acadrust::io::dxf::code_page::encoding_from_code_page(std::str::from_utf8(code_page).ok()?) { + Some(encoding) => { + let (text, errors) = encoding.decode_without_bom_handling(dxf); + if errors { + return None; + } + std::borrow::Cow::Owned(text.into_owned().into_bytes()) + } + None => std::borrow::Cow::Borrowed(std::str::from_utf8(dxf).ok()?.as_bytes()), + } }; - convert(dxf, Some(v)) + let (at, value) = header_value(&text, b"$ACADVER")?; + let code = kept.to_string(); + let mut out = Vec::with_capacity(text.len().saturating_add(code.len())); + out.extend_from_slice(text.get(..at)?); + out.extend_from_slice(code.as_bytes()); + out.extend_from_slice(text.get(at.checked_add(value.len())?..)?); + Some(out) + } + + /// The byte offset and the trimmed value of header variable `name` in an ASCII DXF: the value + /// of the group that follows the `9` group naming it. The file is read as (group code, + /// value) line pairs, in one pass with no buffering, up to the first `0`/`ENDSEC`, the end + /// of the HEADER section: a large input without one costs time, not memory (a line index of + /// a 32 MiB file used 0.8 GB). Lines may end in `\r\n`. + pub(super) fn header_value<'a>(dxf: &'a [u8], name: &[u8]) -> Option<(usize, &'a [u8])> { + let mut offset = 0usize; + let mut lines = dxf.split(|b| *b == b'\n').map(|line| { + let at = offset.saturating_add(line.len() - line.trim_ascii_start().len()); + offset = offset.saturating_add(line.len()).saturating_add(1); + (at, line.trim_ascii()) + }); + while let (Some((_, code)), Some((_, value))) = (lines.next(), lines.next()) { + if code == b"0" && value == b"ENDSEC" { + return None; + } + if code == b"9" && value == name { + let (_, code) = lines.next()?; + let (at, value) = lines.next()?; + return (code != b"0" && code != b"9").then_some((at, value)); + } + } + None } /// The current dimension and text styles' names from their handles: a DWG stores the @@ -711,6 +1017,150 @@ mod native { } } + /// The DXF names of an ASCII DXF's CLASS records, in CLASSES order: a proxy's class number + /// (group 91) is 500 plus its class's place here (DXF Reference, ACAD_PROXY_OBJECT). Empty for + /// one without a CLASSES section. `None` for a binary DXF, whose classes this doesn't read: + /// CADCraft's own bridge DXF is always ASCII, and only a binary DXF given to the public + /// conversion functions comes here. + pub(super) fn dxf_class_names(dxf: &[u8]) -> Option> { + let pairs = super::proxy_transport::text_pairs(dxf)?; + let mut names = Vec::new(); + let (mut section, mut in_classes, mut in_class) = (false, false, false); + for pair in pairs { + let (code, value) = pair?; + match (code, value.as_str()) { + (0, "ENDSEC") if in_classes => break, + (0, "SECTION") => section = true, + (2, name) if section => { + in_classes = name == "CLASSES"; + section = false; + } + (0, kind) if in_classes => { + in_class = kind == "CLASS"; + // Even an unnamed record keeps its place in the source class table. + if in_class { + names.push(String::new()); + } + } + (1, value) if in_class => { + if let Some(last) = names.last_mut() { + *last = value.to_string(); + } + in_class = false; + } + _ => section = false, + } + } + Some(names) + } + + /// Proxy objects' and entities' class numbers as the DWG numbers its classes. A DXF proxy + /// names its class by its place in the DXF's CLASSES (`classes`, from 500), but acadrust's + /// reader puts its own default classes first and numbers the DXF's after them, so the DXF + /// number named another class in the DWG: a 2018 drawing's piping proxies became + /// LARGE_RADIAL_DIMENSION and SECTIONOBJECT, and the ODA File Converter refused the file. A + /// proxy whose number names no class of the DXF is left out: kept as it is, its number would + /// name some other class of the DWG, for the same reason. + /// + /// Before 2013 (AC1027) acadrust writes only the classes it knows a pre-2013 DWG needs, and a + /// proxy's class is not one of them: the proxy would name a missing class (the ODA refuses + /// the file: "No ClassId") or, by its old number, some other class. Such a DWG leaves the + /// proxies out instead, as it does other programs' data it can't write (`not_saved` reports + /// the entities). So does a DXF whose classes are unknown (`classes` is `None`, a binary + /// DXF): its proxies' numbers can't be mapped, and kept as they are they would name the + /// wrong classes and the ODA would refuse the file. Returns the proxies left out, by DXF type, for + /// what the DWG writer left out ([`super::Unwritten`]). + fn proxy_classes(doc: &mut acadrust::CadDocument, classes: Option<&[String]>) -> super::Unwritten { + let classes = match classes { + Some(c) if doc.version >= acadrust::DxfVersion::AC1027 => c, + _ => { + let entities: Vec = doc + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Extended(x) if matches!(x.data, acadrust::entities::ExtendedEntityData::Proxy(_)) => { + Some(x.common.handle) + } + _ => None, + }) + .collect(); + let objects: Vec = + doc.objects.iter().filter_map(|(h, o)| matches!(o, acadrust::objects::ObjectType::ProxyObject(_)).then_some(*h)).collect(); + for h in &entities { + doc.remove_entity(*h); + } + for h in &objects { + doc.objects.remove(h); + } + return left_out(objects.len(), entities.len()); + } + }; + // Name matching cannot choose between different source classes with the same name. + // Count those proxies as unwritten rather than silently changing their class identity. + let mut unique = std::collections::HashMap::new(); + for name in classes { + unique.entry(name.to_uppercase()).and_modify(|value| *value = false).or_insert(true); + } + let number = |id: i32| -> Option { + let name = classes.get(usize::try_from(id.checked_sub(500)?).ok()?)?; + if unique.get(&name.to_uppercase()) != Some(&true) { + return None; + } + doc.classes.get_by_name(name).map(|c| i32::from(c.class_number)) + }; + let objects: Vec<(acadrust::Handle, Option)> = doc + .objects + .iter() + .filter_map(|(h, o)| match o { + acadrust::objects::ObjectType::ProxyObject(p) => Some((*h, number(p.class_id))), + _ => None, + }) + .collect(); + let entities: Vec<(acadrust::Handle, Option)> = doc + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Extended(x) => match &x.data { + acadrust::entities::ExtendedEntityData::Proxy(p) => Some((x.common.handle, number(p.class_id))), + _ => None, + }, + _ => None, + }) + .collect(); + let unmapped = |list: &[(acadrust::Handle, Option)]| list.iter().filter(|(_, n)| n.is_none()).map(|(h, _)| *h).collect::>(); + let (gone_objects, gone_entities) = (unmapped(&objects), unmapped(&entities)); + for h in &gone_objects { + doc.objects.remove(h); + } + for h in &gone_entities { + doc.remove_entity(*h); + } + let objects = objects.into_iter().filter_map(|(h, n)| Some((h, n?))); + let entities = entities.into_iter().filter_map(|(h, n)| Some((h, n?))); + for (h, n) in objects { + if let Some(acadrust::objects::ObjectType::ProxyObject(p)) = doc.objects.get_mut(&h) { + p.class_id = n; + } + } + let entities: std::collections::HashMap = entities.into_iter().collect(); + for e in doc.entities_mut() { + if let acadrust::entities::EntityType::Extended(x) = e { + let Some(n) = entities.get(&x.common.handle).copied() else { continue }; + if let acadrust::entities::ExtendedEntityData::Proxy(p) = &mut x.data { + p.class_id = n; + } + } + } + left_out(gone_objects.len(), gone_entities.len()) + } + + /// Proxy objects and entities left out of the DWG, by their DXF types. + fn left_out(objects: usize, entities: usize) -> super::Unwritten { + [("ACAD_PROXY_OBJECT", objects), ("ACAD_PROXY_ENTITY", entities)] + .into_iter() + .filter(|(_, n)| *n > 0) + .map(|(t, n)| (t.to_string(), n)) + .collect() + } + /// The current layer (`$CLAYER`) by its name, the same way as [`current_dimstyle`]: a DWG /// stores the handle of the layer, and the one read with the DXF needn't be the layer's in /// the document, so the drawing reopened with layer "0" current (#2252). @@ -722,7 +1172,8 @@ mod native { } } - fn convert(dxf: &[u8], version: Option) -> Result<(Vec, super::Unwritten), String> { + /// `kept`: the version the DXF's carried-over groups were read from ([`dxf_to_dwg_kept_as`]). + fn convert(dxf: &[u8], version: Option, kept: Option) -> Result<(Vec, super::Unwritten), String> { // Reject a pathologically large DXF before handing it to the third-party decoder, which // allocates tables and section buffers from the input's declared sizes and cannot be // interrupted once it starts (CWE-789). This bounds the large-input variant; the decoder @@ -734,7 +1185,20 @@ mod native { mb(Limits::DEFAULT.max_dxf_bytes as u64) )); } - let data = dxf.to_vec(); + // Decoding a code page to UTF-8 can grow the text, so the limit applies again. + let data = match kept.and_then(|k| declare_version(dxf, k)) { + Some(d) if d.len() > Limits::DEFAULT.max_dxf_bytes => { + return Err(format!( + "DXF: the input is {} as UTF-8, larger than the {} CADCraft converts to DWG", + mb(d.len() as u64), + mb(Limits::DEFAULT.max_dxf_bytes as u64) + )); + } + Some(d) => d, + None => dxf.to_vec(), + }; + let (classes, source) = guarded(AssertUnwindSafe(|| (dxf_class_names(&data), super::proxy_transport::source_classes(&data)))) + .map_err(|_| "the DXF proxy class conversion failed".to_string())?; let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) .map_err(|_| "the DXF→DWG conversion failed".to_string())? .map_err(|e| format!("DXF: {e}"))?; @@ -749,10 +1213,25 @@ mod native { // The fix-ups run on the third-party reader's document, so a panic in one is an error, not a crash. let unwritten = guarded(AssertUnwindSafe(|| { super::fail_in_test("convert"); + // From 2013 the DWG takes the source classes as they are, duplicates and metadata + // included; otherwise (before 2013, a binary DXF, classes that can't be written back) + // proxies are matched to classes by name or left out. + let restored = match source { + Some(source) if doc.version >= acadrust::DxfVersion::AC1027 => super::proxy_transport::restore_classes(&mut doc, source), + _ => None, + }; + let proxies = match restored { + Some((objects, entities)) => left_out(objects, entities), + None => proxy_classes(&mut doc, classes.as_deref()), + }; other_layout_owners(&mut doc); table_style_rows(&mut doc, true); dimension_flags(&mut doc); - let unwritten = drop_unwritable(&mut doc); + let mut unwritten = drop_unwritable(&mut doc); + for (kind, n) in proxies { + let total = unwritten.entry(kind).or_insert(0); + *total = total.saturating_add(n); + } current_dimstyle(&mut doc); add_variable_dictionary(&mut doc); current_text_style(&mut doc); @@ -917,10 +1396,132 @@ mod native { assert_eq!(guarded(|| 3), Ok(3)); } } + + #[cfg(test)] + mod application_object_tests { + use super::*; + use acadrust::CadDocument; + use acadrust::classes::DxfClass; + use acadrust::objects::{ObjectType, ProxyObjectReference, ProxyPayload, ProxyReferenceKind, RegisteredClassObject}; + use acadrust::types::{DxfVersion, Handle}; + + /// An object of another application's class that acadrust keeps only as its record (a + /// vertical product's dimension data, say) is carried as that class's proxy object, with its + /// data bits, references, owner and extension dictionary, through DXF and back to DWG, twice. + #[test] + fn undecoded_application_object_is_kept_as_its_proxy() { + for version in [DxfVersion::AC1027, DxfVersion::AC1032] { + let mut source = CadDocument::new(); + source.version = version; + source.classes.add_or_update(DxfClass::new("TESTCONTAINER", "xyzDbTestContainer")); + let handle = Handle::from(0x2Bu64); + let target = Handle::from(0x2Cu64); + let payload = ProxyPayload::from_bits(&[0x5A, 0x3C, 0xC0], 18); + // A null pointer between two references: it keeps its place, the one after it is not lost. + let references = vec![ + ProxyObjectReference { handle: target, kind: ProxyReferenceKind::HardPointer }, + ProxyObjectReference { handle: Handle::from(0u64), kind: ProxyReferenceKind::SoftPointer }, + ProxyObjectReference { handle: Handle::from(0x0Cu64), kind: ProxyReferenceKind::HardPointer }, + ]; + source.objects.insert( + handle, + ObjectType::RegisteredClass(RegisteredClassObject { + handle, + owner: Handle::from(0x0Cu64), + dxf_name: "TESTCONTAINER".into(), + cpp_class_name: "xyzDbTestContainer".into(), + payload: payload.clone(), + object_ids: references.clone(), + ..Default::default() + }), + ); + let mut dwg = acadrust::DwgWriter::write_to_vec(&source).unwrap(); + // acadrust has no model of it: read back, it is only its record. + let decoded = acadrust::DwgReader::from_stream(Cursor::new(dwg.clone())).read().unwrap(); + assert!(matches!(decoded.objects.get(&handle), Some(ObjectType::Unknown { .. })), "{:?}", decoded.objects.get(&handle)); + for generation in 0..2 { + let (dxf, notes) = dwg_to_dxf_noted(&dwg, Limits::DEFAULT).unwrap(); + assert!(notes.is_empty(), "{version:?} {generation}: {notes:?}"); + // The DXF has the object, by its handle, as a proxy record. + let text = String::from_utf8_lossy(&dxf); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let record = lines.windows(4).any(|w| w == ["0", "ACAD_PROXY_OBJECT", "5", "2B"]); + assert!(record, "{version:?} {generation}: no proxy record for the object"); + dwg = dxf_to_dwg_as(&dxf, "AC1032").unwrap(); + let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.clone())).read().unwrap(); + let Some(ObjectType::ProxyObject(proxy)) = doc.objects.get(&handle) else { panic!("{version:?} {generation}: proxy object") }; + assert_eq!(proxy.payload.bit_count, payload.bit_count); + assert_eq!(proxy.payload.data(), payload.data()); + assert_eq!(proxy.object_ids, references); + let class = doc.classes.iter().find(|c| i32::from(c.class_number) == proxy.class_id).unwrap(); + assert_eq!(class.dxf_name, "TESTCONTAINER"); + assert!(!class.is_an_entity); + } + } + } + + /// The database's own classes are not turned into another application's proxies; what is + /// left without a DXF form is said, not dropped silently. + #[test] + fn database_objects_without_a_form_are_reported() { + let mut doc = CadDocument::new(); + doc.classes.add_or_update(DxfClass::new("BLOCKPROPERTIESTABLE", "AcDbBlockPropertiesTable")); + let handle = Handle::from(0x40u64); + doc.objects.insert( + handle, + ObjectType::Unknown { + type_name: "BLOCKPROPERTIESTABLE".into(), + handle, + owner: Handle::from(0x0Cu64), + raw_dxf_codes: None, + raw_dwg_data: Some(vec![0; 8]), + raw_dwg_handle_bits: 0, + raw_dwg_version: Some(DxfVersion::AC1032), + }, + ); + let notes = application_objects(&mut doc); + assert!(matches!(doc.objects.get(&handle), Some(ObjectType::Unknown { .. }))); + assert_eq!( + notes, + [ + "DWG: 1 objects of types CADCraft doesn't keep were left out (BLOCKPROPERTIESTABLE × 1); saving over the original file would lose them" + ] + ); + } + + /// A record that doesn't split stays as it was and is named, never guessed at. + #[test] + fn invalid_object_records_are_rejected() { + for handle_bits in [-1, 1000] { + let raw = acadrust::entities::RawRecord { data: vec![0; 8], handle_bits, version: DxfVersion::AC1032 }; + assert!(object_record(&raw, 42).is_err()); + } + let mut doc = CadDocument::new(); + doc.classes.add_or_update(DxfClass::new("TESTCONTAINER", "xyzDbTestContainer")); + let handle = Handle::from(0x41u64); + doc.objects.insert( + handle, + ObjectType::Unknown { + type_name: "TESTCONTAINER".into(), + handle, + owner: Handle::from(0x0Cu64), + raw_dxf_codes: None, + raw_dwg_data: Some(vec![0xFF; 4]), + raw_dwg_handle_bits: 1000, + raw_dwg_version: Some(DxfVersion::AC1032), + }, + ); + let notes = application_objects(&mut doc); + assert!(matches!(doc.objects.get(&handle), Some(ObjectType::Unknown { .. }))); + assert!(notes.iter().any(|n| n.contains("(TESTCONTAINER × 1)")), "{notes:?}"); + } + } } #[cfg(not(no_dwg_bridge))] -pub use native::{dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as, dxf_to_dwg_noted}; +pub use native::{ + dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as, dxf_to_dwg_kept_as, dxf_to_dwg_kept_noted, dxf_to_dwg_noted, +}; /// What saving as DWG left out: how many records of each DXF type (upper case) the DWG writer /// can't write. @@ -975,6 +1576,13 @@ pub fn encode_as(dxf: &[u8], version: &str) -> Result, String> { pub fn encode_noted(dxf: &[u8], version: &str) -> Result<(Vec, Unwritten), String> { dxf_to_dwg_noted(dxf, version) } +#[cfg(no_dwg_bridge)] +pub fn encode_kept_noted(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec, Unwritten), String> { + match kept { + Some(kept) => dxf_to_dwg_kept_noted(dxf, version, kept), + None => dxf_to_dwg_noted(dxf, version), + } +} #[cfg(no_dwg_bridge)] pub fn dwg_to_dxf(_bytes: &[u8]) -> Result, String> { @@ -1000,6 +1608,14 @@ pub fn dxf_to_dwg_as(_dxf: &[u8], _version: &str) -> Result, String> { pub fn dxf_to_dwg_noted(_dxf: &[u8], _version: &str) -> Result<(Vec, Unwritten), String> { Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } +#[cfg(no_dwg_bridge)] +pub fn dxf_to_dwg_kept_as(_dxf: &[u8], _version: &str, _kept: &str) -> Result, String> { + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} +#[cfg(no_dwg_bridge)] +pub fn dxf_to_dwg_kept_noted(_dxf: &[u8], _version: &str, _kept: &str) -> Result<(Vec, Unwritten), String> { + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) +} #[cfg(test)] mod tests { @@ -1285,13 +1901,109 @@ mod tests { assert_eq!(notes, ["DWG: 3 DGN line style components that no line style definition uses were left out"]); } + /// An R2000 DXF header (`\r\n` lines, as CADCraft writes them) with `extra` after `$ACADVER`. + #[cfg(not(no_dwg_bridge))] + fn r2000(extra: &[u8]) -> Vec { + let mut dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n 9\r\n$DWGCODEPAGE\r\n 3\r\nANSI_1252\r\n".to_vec(); + dxf.extend_from_slice(b" 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\n"); + dxf.extend_from_slice(extra); + dxf.extend_from_slice(b"\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"); + dxf + } + + /// The kept version replaces only the `$ACADVER` value; everything else stays byte for byte. + #[cfg(not(no_dwg_bridge))] + #[test] + fn declare_version_changes_only_acadver() { + let dxf = r2000(b"A\\U+00E7\\U+00E3o"); + let out = native::declare_version(&dxf, acadrust::DxfVersion::AC1032).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), String::from_utf8(dxf).unwrap().replacen("AC1015", "AC1032", 1)); + } + + /// A kept version not newer than the declared one, a binary DXF and a DXF without `$ACADVER` + /// are read as they are. + #[cfg(not(no_dwg_bridge))] + #[test] + fn declare_version_leaves_what_it_need_not_change() { + let dxf = r2000(b"x"); + assert_eq!(native::declare_version(&dxf, acadrust::DxfVersion::AC1015), None); + assert_eq!(native::declare_version(&dxf, acadrust::DxfVersion::AC1009), None); + assert_eq!(native::declare_version(b"AutoCAD Binary DXF\r\n\x1a\0", acadrust::DxfVersion::AC1032), None); + let no_version = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + assert_eq!(native::declare_version(no_version, acadrust::DxfVersion::AC1032), None); + // A `$ACADVER` outside the HEADER section is not the file's version. + let late = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n"; + assert_eq!(native::declare_version(late, acadrust::DxfVersion::AC1032), None); + } + + /// The header is read as group code and value pairs up to the first `0`/`ENDSEC`: a `$ACADVER` + /// name whose value would come after it, or a file that never ends its HEADER, is no version + /// to replace, and `\r\n` lines keep the value's offset right. + #[cfg(not(no_dwg_bridge))] + #[test] + fn declare_version_reads_the_header_in_pairs_up_to_endsec() { + let cut = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 0\r\nENDSEC\r\n 1\r\nAC1015\r\n"; + assert_eq!(native::declare_version(cut, acadrust::DxfVersion::AC1032), None); + let endless = vec![b'\n'; 1 << 20]; + assert_eq!(native::declare_version(&endless, acadrust::DxfVersion::AC1032), None); + let crlf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1015\r\n 0\r\nENDSEC\r\n"; + let out = native::declare_version(crlf, acadrust::DxfVersion::AC1032).unwrap(); + assert_eq!(out, b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1032\r\n 0\r\nENDSEC\r\n"); + } + + /// Declared as 2007 or later, a DXF is UTF-8: code page text is decoded first. Declared as an + /// older version, the code page bytes stay as they are. + #[cfg(not(no_dwg_bridge))] + #[test] + fn declare_version_decodes_a_code_page_for_utf8_versions() { + let dxf = r2000(b"A\xe7\xe3o"); + let utf8 = native::declare_version(&dxf, acadrust::DxfVersion::AC1032).unwrap(); + let text = String::from_utf8(utf8).unwrap(); + assert!(text.contains("\r\nAção\r\n") && text.contains("$ACADVER\r\n 1\r\nAC1032\r\n"), "{text}"); + let legacy = native::declare_version(&dxf, acadrust::DxfVersion::AC1018).unwrap(); + assert!(legacy.windows(4).any(|w| w == b"A\xe7\xe3o"), "the code page bytes stay"); + assert!(legacy.windows(6).any(|w| w == b"AC1018")); + // A code page it doesn't know is read as Windows-1252, as acadrust reads an older DXF. + let at = dxf.windows(9).position(|w| w == b"ANSI_1252").unwrap(); + let unknown = [&dxf[..at], b"NO_SUCH_CP".as_slice(), &dxf[at + 9..]].concat(); + let text = String::from_utf8(native::declare_version(&unknown, acadrust::DxfVersion::AC1032).unwrap()).unwrap(); + assert!(text.contains("\r\nAção\r\n"), "{text}"); + // Without a `$DWGCODEPAGE` there is nothing to decode it by: it is read as it is. + let none = [&dxf[..at - 21], &dxf[at + 11..]].concat(); + assert!(!none.windows(12).any(|w| w == b"$DWGCODEPAGE"), "{}", String::from_utf8_lossy(&none)); + assert_eq!(native::declare_version(&none, acadrust::DxfVersion::AC1032), None); + } + + /// An unknown kept version converts as [`dxf_to_dwg_as`] does. + #[cfg(not(no_dwg_bridge))] + #[test] + fn unknown_kept_version_converts_as_before() { + let dxf = r2000(b"x"); + assert_eq!(dxf_to_dwg_kept_as(&dxf, "AC1032", "AC9999"), dxf_to_dwg_as(&dxf, "AC1032")); + assert!(dxf_to_dwg_kept_as(&dxf, "AC0000", "AC1032").is_err(), "an unwritable version is still an error"); + } + + /// The CLASS names in CLASSES order; nothing for a binary DXF or one without CLASSES. + #[cfg(not(no_dwg_bridge))] + #[test] + fn dxf_class_names_in_classes_order() { + let dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 1\r\nWIDGETA\r\n 2\r\nAcDbWidgetA\r\n 3\r\nApp\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 2\r\nAcDbWidgetB\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\nNOT_A_CLASS\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + assert_eq!(native::dxf_class_names(dxf).unwrap(), ["WIDGETA", "WIDGETB"]); + // A CLASS record without a name keeps its place, so the classes after it keep theirs + // (#2837 review). + let unnamed = b" 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 2\r\nAcDbNoName\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + assert_eq!(native::dxf_class_names(unnamed).unwrap(), ["", "WIDGETB"]); + assert_eq!(native::dxf_class_names(b" 0\nSECTION\n 2\nHEADER\n 0\nENDSEC\n 0\nEOF\n"), Some(Vec::new())); + assert_eq!(native::dxf_class_names(b"AutoCAD Binary DXF\r\n\x1a\0"), None); + } + /// AutoCAD's DWG scale action (BLOCKSCALEACTION) ends with a byte after its three /// connections that DXF doesn't carry. acadrust 0.6.4 neither read nor wrote it, so AutoCAD /// read past the object and refused every DWG CADCraft wrote with a dynamic block that scales /// ("Error Decrypting Data"); 0.6.5 added it and 0.6.6, which this uses, still keeps it (0.6.6 also /// fixes multi-layout DWGs, #1463). The byte reaches the DWG, and a scale action /// from DXF is written whole, with the byte AutoCAD writes (0). - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] #[test] fn scale_actions_keep_the_byte_autocad_reads_after_their_connections() { use acadrust::objects::*; diff --git a/crates/dwg/src/proxy_transport.rs b/crates/dwg/src/proxy_transport.rs new file mode 100644 index 000000000..a8a5647e9 --- /dev/null +++ b/crates/dwg/src/proxy_transport.rs @@ -0,0 +1,632 @@ +//! Another application's entities and their classes through the DWG bridge: on reading a DWG, +//! registered entities acadrust has no model for become proxy entities of their class; on writing +//! one, the DWG gets the source DXF's classes in their places, so every proxy names its own class. + +use std::collections::{HashMap, HashSet}; + +use acadrust::CadDocument; +use acadrust::classes::{DxfClass, ProxyFlags}; +use acadrust::entities::{EntityType, ExtendedEntityData, ProxyEntityData}; +use acadrust::objects::{ObjectType, ProxyPayload}; + +fn class_number(index: usize) -> Result { + index.checked_add(500).and_then(|n| i16::try_from(n).ok()).ok_or_else(|| "DXF: too many application classes".into()) +} + +/// After a DWG read: each registered entity of another application's class that acadrust keeps +/// only as its record and opaque data (no decoded properties) becomes a proxy entity of that class +/// (DXF Reference, ACAD_PROXY_ENTITY), with its graphics, data bits, R2007+ strings and object +/// references, so the DXF keeps it; and every proxy's class number becomes 500 plus its class's +/// place in the classes, as a DXF numbers it. A record that can't be converted (its class is +/// missing or not unique) is left out and named in the notes; one with decoded properties stays as +/// read, also named, as its opaque data has no DXF form beside them. +pub(super) fn prepare(doc: &mut CadDocument) -> Vec { + let classes: Vec<_> = doc.classes.iter().cloned().collect(); + let mut numbers = HashMap::new(); + let mut identities = HashMap::new(); + for (index, class) in classes.iter().enumerate() { + let number = class_number(index).ok(); + numbers.entry(i32::from(class.class_number)).and_modify(|v| *v = None).or_insert(number.map(i32::from)); + let identity = (class.dxf_name.as_str(), class.cpp_class_name.as_str(), class.is_an_entity); + identities.entry(identity).and_modify(|v| *v = None).or_insert(number); + } + let identity = |dxf: &str, cpp: &str, entity: bool| { + identities + .get(&(dxf, cpp, entity)) + .copied() + .flatten() + .map(i32::from) + .ok_or_else(|| format!("missing or ambiguous application CLASS for {dxf:.80} ({cpp:.80})")) + }; + let Some(dwg_version) = super::native::proxy_dwg_version(doc.dwg_source_version.unwrap_or(doc.version)) else { return Vec::new() }; + let maintenance = i32::from(doc.maintenance_version); + let remap = |id: i32| numbers.get(&id).copied().flatten().ok_or_else(|| format!("proxy names missing or ambiguous application class {id}")); + // Only mutate proxies: entities_mut invalidates the decoder's verbatim records for every entity. + let handles: Vec<_> = doc + .entities() + .filter_map(|e| match e { + EntityType::Extended(e) => match &e.data { + ExtendedEntityData::Proxy(_) => Some(e.common.handle), + ExtendedEntityData::RegisteredClass(data) if data.properties.is_empty() || data.payload.bit_count > 0 => Some(e.common.handle), + _ => None, + }, + _ => None, + }) + .collect(); + let mut notes = Vec::new(); + let mut entity_count = 0usize; + let mut object_count = 0usize; + let mut semantic = 0usize; + for handle in handles { + // Ok(None): not an application record; Ok(Some(None)): kept as read, with its properties. + let converted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result>, String> { + let Some(EntityType::Extended(entity)) = doc.get_entity(handle) else { return Ok(None) }; + let data = match &entity.data { + ExtendedEntityData::Proxy(data) => { + let mut proxy = data.clone(); + proxy.class_id = remap(proxy.class_id)?; + ExtendedEntityData::Proxy(proxy) + } + ExtendedEntityData::RegisteredClass(data) => { + if !data.properties.is_empty() { + return Ok(Some(None)); + } + let class_id = identity(&data.dxf_name, &data.cpp_class_name, true)?; + let text_payload = entity.common.raw_record.as_deref().map(registered_text).transpose()?.unwrap_or_default(); + ExtendedEntityData::Proxy(ProxyEntityData { + proxy_id: 498, + class_id, + dxf_subclass: String::new(), + version: (maintenance << 16) | dwg_version, + dwg_version, + maintenance_version: maintenance, + from_dxf: false, + graphics: ProxyPayload::from_bytes(entity.common.graphic_data.as_deref().unwrap_or_default()), + payload: data.payload.clone(), + text_payload, + object_ids: data.object_ids.clone(), + }) + } + _ => return Ok(None), + }; + Ok(Some(Some(data))) + })) + .unwrap_or_else(|_| Err("application record conversion failed".into())); + match converted { + Ok(Some(Some(data))) => { + if let Some(EntityType::Extended(entity)) = doc.get_entity_mut(handle) { + entity.data = data; + } + } + Ok(Some(None)) => semantic = semantic.saturating_add(1), + Ok(None) => {} + Err(why) => { + doc.remove_entity(handle); + entity_count = entity_count.saturating_add(1); + skipped_note(&mut notes, "entity", handle, &why); + } + } + } + doc.objects.retain(|handle, object| { + if let ObjectType::ProxyObject(proxy) = object { + match remap(proxy.class_id) { + Ok(id) => proxy.class_id = id, + Err(why) => { + object_count = object_count.saturating_add(1); + skipped_note(&mut notes, "object", *handle, &why); + return false; + } + } + } + true + }); + if entity_count > 0 || object_count > 0 { + notes.insert(0, format!("DWG: partial read; application proxy records left out (entities: {entity_count}, objects: {object_count})")); + } + if semantic > 0 { + notes.push(format!( + "DWG: {semantic} registered entities with decoded properties keep them, without their other data; saving over the original file would lose it" + )); + } + notes +} + +fn skipped_note(notes: &mut Vec, kind: &str, handle: acadrust::types::Handle, why: &str) { + if notes.len() < 6 { + let why: String = why.chars().take(256).collect(); + notes.push(format!("DWG: proxy {kind} {handle} left out: {why}")); + } +} + +/// The decoder's registered-class representation omits the separate R2007+ string stream. +fn registered_text(raw: &acadrust::entities::RawRecord) -> Result { + use acadrust::io::dwg::DwgVersion; + use acadrust::io::dwg::dwg_stream_readers::object_reader::DwgObjectReader; + use acadrust::io::dwg::dwg_stream_writers::bit_writer::DwgBitWriter; + use acadrust::types::DxfVersion; + + if raw.version < DxfVersion::AC1021 { + return Ok(ProxyPayload::default()); + } + let version = DwgVersion::from_dxf_version(raw.version).map_err(|e| format!("DWG proxy text: {e}"))?; + let handle_bits = usize::try_from(raw.handle_bits).map_err(|_| "DWG proxy text: negative handle stream size")?; + let total_bits = raw.data.len().checked_mul(8).ok_or("DWG proxy text: record too large")?; + if handle_bits > total_bits { + return Err("DWG proxy text: handle stream exceeds record".into()); + } + // Frame the verbatim record for the dependency's checked object reader. + let mut frame = DwgBitWriter::new(version, raw.version); + frame.write_modular_short(raw.data.len()); + if raw.version >= DxfVersion::AC1024 { + frame.write_modular_char(handle_bits); + } + frame.write_bytes(&raw.data); + let reader = DwgObjectReader::new(frame.into_bytes(), raw.version, HashMap::new()).map_err(|e| format!("DWG proxy text: {e}"))?; + let (kind, mut streams) = reader.read_record_at(0).map_err(|e| format!("DWG proxy text: {e}"))?; + reader.read_common_entity_data(&mut streams, kind); + if kind == 498 { + // An existing registered-class envelope is a proxy and carries its class name first. + streams.read_variable_text(); + } else if kind < 500 { + return Err("DWG proxy text: registered entity has no application class".into()); + } + streams.check_error().map_err(|e| format!("DWG proxy text: {e}"))?; + let bits = usize::try_from(streams.text_remaining_bits()).map_err(|_| "DWG proxy text: negative string stream size")?; + if bits > total_bits { + return Err("DWG proxy text: string stream exceeds record".into()); + } + let count = u32::try_from(bits).map_err(|_| "DWG proxy text: string stream too large")?; + let mut bytes = vec![0; bits.div_ceil(8)]; + for (index, byte) in bytes.iter_mut().enumerate() { + for bit in 0..8.min(bits.saturating_sub(index * 8)) { + if streams.read_text_bit() { + *byte |= 0x80 >> bit; + } + } + } + streams.check_error().map_err(|e| format!("DWG proxy text: {e}"))?; + Ok(ProxyPayload::from_bits(&bytes, count)) +} + +/// ASCII DXF pairs decoded with the bridge's public code-page and escape codecs. A malformed +/// pair yields `None`, so both class scans fall back rather than guessing its identity. +pub(super) fn text_pairs(dxf: &[u8]) -> Option> + '_> { + use acadrust::io::dxf::code_page::{decode_legacy_escapes, encoding_from_code_page}; + + if dxf.starts_with(b"AutoCAD Binary DXF") { + return None; + } + let version = + super::native::header_value(dxf, b"$ACADVER").and_then(|(_, v)| std::str::from_utf8(v).ok()).map(acadrust::DxfVersion::from_version_string); + let unicode = version.is_some_and(|v| v >= acadrust::DxfVersion::AC1021); + let encoding = if version.is_some_and(|v| v < acadrust::DxfVersion::AC1021) { + super::native::header_value(dxf, b"$DWGCODEPAGE").and_then(|(_, page)| std::str::from_utf8(page).ok()).and_then(encoding_from_code_page) + } else { + None + }; + let mut lines = dxf.split(|b| *b == b'\n').map(|line| line.strip_suffix(b"\r").unwrap_or(line)); + Some(std::iter::from_fn(move || { + let code = lines.next()?; + let Some(value) = lines.next() else { return (!code.trim_ascii().is_empty()).then_some(None) }; + let pair = || { + let code = std::str::from_utf8(code).ok()?.trim().parse().ok()?; + let text = if let Some(encoding) = encoding { + encoding.decode(value).0.into_owned() + } else if unicode { + String::from_utf8_lossy(value).into_owned() + } else { + // The decoder uses UTF-8 with Latin-1 fallback when no encoding was declared. + std::str::from_utf8(value).map_or_else(|_| value.iter().map(|&b| char::from(b)).collect(), str::to_string) + }; + let text = decode_legacy_escapes(&text); + // DXF's escaped control characters are decoded after CIF/MIF, as in the bridge. + let text = text.replace("^J", "\n").replace("^M", "\r").replace("^I", "\t").replace("^ ", "^"); + Some((code, text)) + }; + Some(pair()) + })) +} + +/// The CLASS records of an ASCII DXF, in CLASSES order and numbered by place from 500 (DXF +/// Reference, CLASSES; a proxy's group 91 is that number). `None` for a binary DXF (CADCraft's own +/// bridge DXF is ASCII), and for one with a record that can't be written back as it is: no names, +/// flags or instance count out of range, more classes than the numbers allow. Then +/// `proxy_classes` matches the classes by name instead. +pub(super) fn source_classes(dxf: &[u8]) -> Option> { + let pairs = text_pairs(dxf)?; + let mut records: Vec> = Vec::new(); + let (mut section, mut in_classes) = (false, false); + for pair in pairs { + let (code, value) = pair?; + match (code, value.as_str()) { + (0, "ENDSEC") if in_classes => break, + (0, "SECTION") => section = true, + (2, name) if section => { + in_classes = name == "CLASSES"; + section = false; + } + (0, kind) if in_classes => { + if kind != "CLASS" { + return None; + } + records.push(Vec::new()); + } + (code, value) if in_classes => records.last_mut()?.push((code, value.to_string())), + _ => section = false, + } + } + records.iter().enumerate().map(|(index, groups)| source_class(groups, class_number(index).ok()?)).collect() +} + +/// One CLASS record's groups as the class `number`, or `None` when it can't be written back. +fn source_class(groups: &[(i32, String)], number: i16) -> Option { + let text = |code| groups.iter().find(|(c, _)| *c == code).map(|(_, v)| v.clone()).unwrap_or_default(); + let integer = |code| groups.iter().find(|(c, _)| *c == code).map_or(Some(0), |(_, v)| v.trim().parse::().ok()); + let mut class = DxfClass::new(text(1), text(2)); + if class.dxf_name.is_empty() || class.cpp_class_name.is_empty() { + return None; + } + class.application_name = text(3); + class.proxy_flags = ProxyFlags(u16::try_from(integer(90)?).ok()?); + class.instance_count = i32::try_from(integer(91)?).ok()?; + class.was_zombie = integer(280)? != 0; + class.is_an_entity = integer(281)? != 0; + class.item_class_id = if class.is_an_entity { 498 } else { 499 }; + class.class_number = number; + Some(class) +} + +/// Give a DWG of 2013 or later the source DXF's classes (`classes`, from [`source_classes`]) in +/// their places, with their metadata and duplicate names, so each proxy's DXF class number names +/// its own class; the decoder's default classes the source lacks follow them. A proxy whose number +/// names no source class is left out, as `proxy_classes` leaves it out. Returns how many proxy objects and +/// entities were left out; nothing changes when the drawing has no proxies. `None`, with nothing +/// changed, when the classes would be more than the class numbers allow. +pub(super) fn restore_classes(doc: &mut CadDocument, classes: Vec) -> Option<(usize, usize)> { + let fits = |number: i32| number.checked_sub(500).and_then(|n| usize::try_from(n).ok()).is_some_and(|i| i < classes.len()); + let mut any = false; + let mut entities = Vec::new(); + for entity in doc.entities() { + if let EntityType::Extended(e) = entity + && let ExtendedEntityData::Proxy(p) = &e.data + { + any = true; + if !fits(p.class_id) { + entities.push(e.common.handle); + } + } + } + let mut objects = Vec::new(); + for (handle, object) in &doc.objects { + if let ObjectType::ProxyObject(p) = object { + any = true; + if !fits(p.class_id) { + objects.push(*handle); + } + } + } + if !any { + return Some((0, 0)); + } + let mut names: HashSet<_> = classes.iter().map(|c| c.dxf_name.to_uppercase()).collect(); + let defaults: Vec<_> = doc.classes.iter().filter(|c| names.insert(c.dxf_name.to_uppercase())).cloned().collect(); + if let Some(last) = classes.len().checked_add(defaults.len())?.checked_sub(1) { + class_number(last).ok()?; + } + for handle in &entities { + doc.remove_entity(*handle); + } + for handle in &objects { + doc.objects.remove(handle); + } + doc.classes.clear(); + for (index, mut class) in classes.into_iter().chain(defaults).enumerate() { + class.class_number = class_number(index).ok()?; + doc.classes.push_preserving(class); + } + Some((objects.len(), entities.len())) +} + +#[cfg(test)] +mod tests { + use super::*; + use acadrust::entities::{EntityCommon, ExtendedEntity, RegisteredClassEntityData}; + use acadrust::types::DxfVersion; + + fn proxy_doc() -> CadDocument { + let mut doc = CadDocument::new(); + doc.version = DxfVersion::AC1032; + doc.add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::Proxy(ProxyEntityData { + proxy_id: 498, + class_id: 501, + dxf_subclass: String::new(), + version: 33, + dwg_version: 33, + maintenance_version: 0, + from_dxf: false, + graphics: ProxyPayload::default(), + payload: ProxyPayload::from_bits(&[0x80], 1), + text_payload: ProxyPayload::default(), + object_ids: vec![], + }), + }))) + .unwrap(); + doc + } + + /// An ASCII DXF of `groups`, `(code, value)` per pair of lines. + fn dxf(groups: &[(i32, &str)]) -> Vec { + groups.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect::().into_bytes() + } + + #[test] + fn source_classes_keep_duplicates_and_metadata_before_defaults() { + let bytes = dxf(&[ + (0, "SECTION"), + (2, "HEADER"), + (9, "$DIMSTYLE"), + (2, "CLASSES"), + (0, "ENDSEC"), + (0, "SECTION"), + (2, "CLASSES"), + (0, "CLASS"), + (1, "Объект"), + (2, "First"), + (3, "Первый"), + (90, "1025"), + (91, "7"), + (280, "1"), + (281, "1"), + (0, "CLASS"), + (1, "Объект"), + (2, "Second"), + (3, "Второй"), + (90, "128"), + (281, "1"), + (0, "ENDSEC"), + (0, "EOF"), + ]); + let classes = source_classes(&bytes).unwrap(); + assert_eq!(classes.len(), 2); + assert_eq!(classes[0].application_name, "Первый"); + assert_eq!(classes[0].proxy_flags.0, 1025); + assert_eq!(classes[0].instance_count, 7); + assert!(classes[0].was_zombie); + assert_eq!((classes[0].class_number, classes[1].class_number), (500, 501)); + assert_eq!(classes[1].cpp_class_name, "Second"); + let mut doc = proxy_doc(); + assert_eq!(restore_classes(&mut doc, classes.clone()), Some((0, 0))); + assert_eq!(doc.classes.iter().take(2).cloned().collect::>(), classes); + // A binary DXF, and a CLASS record that can't be written back as it is, give no classes. + assert!(source_classes(b"AutoCAD Binary DXF\r\n\x1a\0").is_none()); + for (code, value) in [(1, ""), (2, ""), (90, "65536"), (91, "9223372036854775807"), (281, "x")] { + let mut class = vec![(1, "A"), (2, "A")]; + class.retain(|(c, _)| *c != code); + class.push((code, value)); + let mut groups = vec![(0, "SECTION"), (2, "CLASSES"), (0, "CLASS")]; + groups.extend(class); + groups.extend([(0, "ENDSEC"), (0, "EOF")]); + assert!(source_classes(&dxf(&groups)).is_none(), "{code} {value}"); + } + } + + #[test] + fn source_classes_decode_escapes_once_and_respect_legacy_code_pages() { + let body = "0\nCLASS\n1\n\\U+041E\\U+0431\\U+044A\\U+0435\\U+043A\\U+0442\n2\nClass\n3\nCaf\\U+00E9\\U+D83D\\U+DE42\\U+005CU+0041\n281\n1\n0\nENDSEC\n0\nEOF\n"; + let text = format!("0\nSECTION\n2\nCLASSES\n{body}"); + let classes = source_classes(text.as_bytes()).unwrap(); + assert_eq!(classes[0].dxf_name, "Объект"); + assert_eq!(classes[0].application_name, "Café🙂\\U+0041"); + + let prefix = + b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$DWGCODEPAGE\n3\nANSI_1251\n0\nENDSEC\n0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\n"; + let encoded = [prefix.as_slice(), b"\xCF\xF0\xE8\xEC\xE5\xF0", b"\n2\nClass\n3\nApp\n281\n1\n0\nENDSEC\n0\nEOF\n"].concat(); + assert_eq!(source_classes(&encoded).unwrap()[0].dxf_name, "Пример"); + // R2007+ text is UTF-8 even with a legacy code-page declaration. + let modern = String::from_utf8_lossy(prefix).replace("AC1015", "AC1032") + "Пример\n2\nClass\n3\nApp\n281\n1\n0\nENDSEC\n0\nEOF\n"; + assert_eq!(source_classes(modern.as_bytes()).unwrap()[0].dxf_name, "Пример"); + } + + #[test] + fn proxies_of_missing_classes_are_left_out() { + for id in [-1, 499, 501, i32::MAX] { + let mut doc = proxy_doc(); + if let Some(EntityType::Extended(e)) = doc.entities_mut().next() + && let ExtendedEntityData::Proxy(p) = &mut e.data + { + p.class_id = id; + } + let mut class = DxfClass::new_entity("ENTITY", "Entity"); + class.class_number = 500; + assert_eq!(restore_classes(&mut doc, vec![class]), Some((0, 1)), "{id}"); + assert_eq!(doc.entities().count(), 0); + } + // Class 501 is there: the proxy keeps it, in its place. + let mut doc = proxy_doc(); + assert_eq!(restore_classes(&mut doc, vec![DxfClass::new("A", "A"), DxfClass::new_entity("B", "B")]), Some((0, 0))); + assert_eq!(doc.entities().count(), 1); + assert_eq!(doc.classes.iter().nth(1).map(|c| (c.dxf_name.clone(), c.class_number)), Some(("B".to_string(), 501))); + // Without proxies the classes stay the decoder's. + let mut doc = CadDocument::new(); + let before: Vec<_> = doc.classes.iter().cloned().collect(); + assert_eq!(restore_classes(&mut doc, vec![DxfClass::new("A", "A")]), Some((0, 0))); + assert_eq!(doc.classes.iter().cloned().collect::>(), before); + } + + #[test] + fn unrepresentable_proxies_keep_other_geometry_and_bounded_diagnostics() { + use acadrust::entities::{Line, RawRecord}; + use acadrust::objects::ProxyObject; + use acadrust::types::{Handle, Vector3}; + for count in [1, 10] { + let mut doc = proxy_doc(); + if let Some(EntityType::Extended(e)) = doc.entities_mut().next() + && let ExtendedEntityData::Proxy(p) = &mut e.data + { + p.class_id = i32::MAX; + } + let template = doc.entities().next().unwrap().clone(); + for _ in 1..count { + let mut entity = template.clone(); + entity.common_mut().handle = Handle::NULL; + doc.add_entity(entity).unwrap(); + } + let object = Handle::new(u64::MAX - 1); + assert!(!doc.objects.contains_key(&object)); + doc.objects.insert(object, ObjectType::ProxyObject(ProxyObject { handle: object, class_id: i32::MAX, ..Default::default() })); + let line = doc.add_entity(EntityType::Line(Line::from_points(Vector3::new(2.0, 3.0, 0.0), Vector3::new(12.0, 13.0, 0.0)))).unwrap(); + let raw = RawRecord { data: vec![0xAA, 0x55], handle_bits: 0, version: DxfVersion::AC1032 }; + doc.get_entity_mut(line).unwrap().common_mut().raw_record = Some(std::sync::Arc::new(raw.clone())); + let notes = prepare(&mut doc); + assert_eq!(notes.len(), (count + 1).min(6) + 1); + assert!(notes.iter().all(|n| n.starts_with("DWG:"))); + assert!(notes[0].contains(&format!("entities: {count}, objects: 1"))); + assert_eq!(doc.entities().count(), 1); + assert!(!doc.objects.contains_key(&object)); + let Some(EntityType::Line(actual)) = doc.get_entity(line) else { panic!("readable line") }; + assert_eq!(actual.start, Vector3::new(2.0, 3.0, 0.0)); + assert_eq!(actual.end, Vector3::new(12.0, 13.0, 0.0)); + assert_eq!(doc.get_entity(line).unwrap().common().raw_record.as_deref(), Some(&raw)); + } + } + #[test] + fn opaque_registered_class_ambiguity_is_not_guessed() { + let mut doc = CadDocument::new(); + doc.classes.push_preserving(DxfClass::new_entity("CUSTOM", "Custom")); + doc.classes.push_preserving(DxfClass::new_entity("CUSTOM", "Custom")); + doc.add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::RegisteredClass(RegisteredClassEntityData { + dxf_name: "CUSTOM".into(), + cpp_class_name: "Custom".into(), + properties: vec![], + payload: ProxyPayload::from_bits(&[0x80], 1), + object_ids: vec![], + }), + }))) + .unwrap(); + assert!(prepare(&mut doc).iter().any(|n| n.contains("ambiguous"))); + assert_eq!(doc.entities().count(), 0); + assert!(class_number(usize::MAX).is_err()); + } + #[test] + fn semantic_records_keep_verbatim_data_and_mixed_payloads_are_reported() { + use acadrust::entities::RawRecord; + use acadrust::objects::{SemanticProperty, SemanticPropertyValue}; + for payload in [ProxyPayload::default(), ProxyPayload::from_bits(&[0x80], 1)] { + let mut doc = CadDocument::new(); + let raw = RawRecord { data: vec![0xAA], handle_bits: 0, version: DxfVersion::AC1032 }; + let handle = doc + .add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::RegisteredClass(RegisteredClassEntityData { + dxf_name: "SEMANTIC".into(), + cpp_class_name: "Semantic".into(), + properties: vec![SemanticProperty { + subclass: "Semantic".into(), + code: 1, + value: SemanticPropertyValue::Text("value".into()), + }], + payload: payload.clone(), + object_ids: vec![], + }), + }))) + .unwrap(); + doc.get_entity_mut(handle).unwrap().common_mut().raw_record = Some(std::sync::Arc::new(raw.clone())); + assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw)); + if payload.bit_count == 0 { + assert!(prepare(&mut doc).is_empty()); + assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw)); + } else { + // Kept as read, and named: its opaque data has no DXF form beside the properties. + assert!(prepare(&mut doc).iter().any(|n| n.contains("decoded properties"))); + assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw)); + } + } + } +} + +#[cfg(test)] +mod string_stream_tests { + use super::*; + use acadrust::entities::{EntityCommon, ExtendedEntity, RawRecord, RegisteredClassEntityData}; + use acadrust::types::DxfVersion; + use std::io::Cursor; + + #[test] + fn registered_transport_recovers_separate_non_byte_aligned_strings() { + for version in [DxfVersion::AC1027, DxfVersion::AC1032] { + let mut source = CadDocument::new(); + source.version = version; + source.classes.add_or_update(DxfClass::new_entity("CUSTOM_TEXT", "CustomText")); + let class_id = i32::from(source.classes.get_by_name("CUSTOM_TEXT").unwrap().class_number); + let text = ProxyPayload::from_bits(&[0xA5, 0xC7, 0xE0], 19); + let payload = ProxyPayload::from_bits(&[0x80], 1); + source + .add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::Proxy(ProxyEntityData { + proxy_id: 498, + class_id, + dxf_subclass: "CustomText".into(), + version: 33, + dwg_version: 33, + maintenance_version: 0, + from_dxf: false, + graphics: ProxyPayload::default(), + payload: payload.clone(), + text_payload: text.clone(), + object_ids: vec![], + }), + }))) + .unwrap(); + let bytes = acadrust::DwgWriter::write_to_vec(&source).unwrap(); + let mut decoded = acadrust::DwgReader::from_stream(Cursor::new(bytes)).read().unwrap(); + let entity = decoded.entities().next().unwrap(); + let handle = entity.common().handle; + let raw = entity.common().raw_record.clone().unwrap(); + assert_eq!(registered_text(&raw).unwrap().data(), text.data()); + assert_eq!(registered_text(&raw).unwrap().bit_count, 19); + let EntityType::Extended(entity) = decoded.get_entity_mut(handle).unwrap() else { panic!() }; + entity.data = ExtendedEntityData::RegisteredClass(RegisteredClassEntityData { + dxf_name: "CUSTOM_TEXT".into(), + cpp_class_name: "CustomText".into(), + properties: vec![], + payload: payload.clone(), + object_ids: vec![], + }); + entity.common.raw_record = Some(raw); + assert!(prepare(&mut decoded).is_empty()); + for _ in 0..2 { + let mut dxf = Vec::new(); + acadrust::DxfWriter::new(&decoded).write_to_writer(&mut dxf).unwrap(); + let bytes = crate::dxf_to_dwg_as(&dxf, "AC1032").unwrap(); + decoded = acadrust::DwgReader::from_stream(Cursor::new(bytes)).read().unwrap(); + let p = decoded + .entities() + .find_map(|e| match e { + EntityType::Extended(e) => match &e.data { + ExtendedEntityData::Proxy(p) => Some(p), + _ => None, + }, + _ => None, + }) + .unwrap(); + assert_eq!(p.payload.bit_count, 1); + assert_eq!(p.payload.data(), payload.data()); + assert_eq!(p.text_payload.bit_count, 19); + assert_eq!(p.text_payload.data(), text.data()); + } + } + } + + #[test] + fn invalid_string_stream_boundaries_return_errors() { + for handle_bits in [-1, 1000] { + let raw = RawRecord { data: vec![0; 8], handle_bits, version: DxfVersion::AC1032 }; + assert!(registered_text(&raw).is_err()); + } + } +} diff --git a/crates/dwg/src/worker.rs b/crates/dwg/src/worker.rs index f55c7d170..9485c23f1 100644 --- a/crates/dwg/src/worker.rs +++ b/crates/dwg/src/worker.rs @@ -26,7 +26,7 @@ use super::Limits; /// The argument that makes the app a worker. pub const WORKER_ARG: &str = "--dwg-worker"; /// Bumped when the messages change: an app updated while running may start a newer copy. -const PROTOCOL: u8 = 1; +const PROTOCOL: u8 = 2; const DECODE: u8 = 1; const ENCODE: u8 = 2; const CRASH: u8 = 0xff; @@ -88,11 +88,29 @@ pub fn encode_as(dxf: &[u8], version: &str) -> Result, String> { /// [`super::dxf_to_dwg_noted`] in the worker, when there is one. What the writer left out comes /// back as notes of `TYPEcount`. pub fn encode_noted(dxf: &[u8], version: &str) -> Result<(Vec, super::Unwritten), String> { + encode_kept_noted(dxf, version, None) +} + +/// [`encode_noted`] for a DXF whose carried-over groups were read from a file of version `kept` +/// ([`super::dxf_to_dwg_kept_noted`]); `None` is [`encode_noted`]. +pub fn encode_kept_noted(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec, super::Unwritten), String> { if u8::try_from(version.len()).is_err() { return Err(super::unsupported(version)); } - match call(&request(ENCODE, Limits::DEFAULT, version), dxf, MAX_DWG_REPLY, "writing this file") { + // A kept version too long to send is no version CADCraft knows: it changes nothing. + let kept = kept.filter(|k| u8::try_from(k.len()).is_ok()); + let mut header = request(ENCODE, Limits::DEFAULT, version); + push_str(&mut header, kept.unwrap_or("")); + match call(&header, dxf, MAX_DWG_REPLY, "writing this file") { Some(reply) => reply?.map(|(dwg, notes)| (dwg, unwritten_from(¬es))), + None => encode_here(dxf, version, kept), + } +} + +/// The conversion in this process. +fn encode_here(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec, super::Unwritten), String> { + match kept { + Some(kept) => super::dxf_to_dwg_kept_noted(dxf, version, kept), None => super::dxf_to_dwg_noted(dxf, version), } } @@ -117,11 +135,16 @@ fn request(op: u8, limits: Limits, version: &str) -> Vec { let mut r = vec![PROTOCOL, op]; r.extend((limits.max_dwg_bytes as u64).to_le_bytes()); r.extend((limits.max_dxf_bytes as u64).to_le_bytes()); - r.push(u8::try_from(version.len()).unwrap_or(0)); - r.extend(version.as_bytes()); + push_str(&mut r, version); r } +/// `text` with a one-byte length before it; callers keep it under 256 bytes. +fn push_str(r: &mut Vec, text: &str) { + r.push(u8::try_from(text.len()).unwrap_or(0)); + r.extend(text.as_bytes()); +} + type Reply = Result<(Vec, Vec), String>; /// Run one request in a worker. `None`: none could be started, so the caller does the work. @@ -257,7 +280,13 @@ fn handle(mut b: &[u8]) -> Reply { let version = take(&mut b, usize::from(version_len)).and_then(|v| std::str::from_utf8(v).ok()).ok_or_else(bad)?; match op { DECODE => super::dwg_to_dxf_noted(b, Limits { max_dwg_bytes, max_dxf_bytes }), - ENCODE => super::dxf_to_dwg_noted(b, version).map(|(dwg, left_out)| (dwg, left_out.iter().map(|(kind, n)| format!("{kind}\t{n}")).collect())), + ENCODE => { + // The version the DXF's carried-over groups were read from; empty for none. + let kept_len = take(&mut b, 1).and_then(<[u8]>::first).copied().ok_or_else(bad)?; + let kept = take(&mut b, usize::from(kept_len)).and_then(|v| std::str::from_utf8(v).ok()).ok_or_else(bad)?; + encode_here(b, version, (!kept.is_empty()).then_some(kept)) + .map(|(dwg, left_out)| (dwg, left_out.iter().map(|(kind, n)| format!("{kind}\t{n}")).collect())) + } CRASH => std::process::abort(), _ => Err(bad()), } @@ -322,6 +351,22 @@ mod tests { } } + /// An encode request carries the kept version after the target one; a request without it is + /// one it can't read, and one with it reaches the converter. + #[test] + fn an_encode_request_carries_the_kept_version() { + let bad = "the DWG worker got a request it can't read (a different CADCraft version?)"; + let short = self::request(ENCODE, Limits::DEFAULT, "AC1032"); + assert_eq!(handle(&short).unwrap_err(), bad); + for kept in ["", "AC1032"] { + let mut request = self::request(ENCODE, Limits::DEFAULT, "AC1032"); + push_str(&mut request, kept); + request.extend(b"not a drawing"); + let err = handle(&request).unwrap_err(); + assert_ne!(err, bad, "kept {kept:?}"); + } + } + #[test] fn serving_reports_a_decode_failure_as_a_reply() { let mut request = self::request(DECODE, Limits::DEFAULT, ""); diff --git a/crates/dxf/src/codepage.rs b/crates/dxf/src/codepage.rs index 9377404d9..11abc766f 100644 --- a/crates/dxf/src/codepage.rs +++ b/crates/dxf/src/codepage.rs @@ -129,7 +129,7 @@ pub(crate) fn decode(bytes: &[u8], d: Decoder) -> Cow<'_, str> { /// line (the group code `3` between them), looked for in the HEADER section only (the scan stops /// at the first `ENDSEC`). Works on the raw bytes, before they are decoded. fn ascii_code_page(bytes: &[u8]) -> Option<&[u8]> { - let mut lines = bytes.split(|&b| b == b'\n').map(<[u8]>::trim_ascii); + let mut lines = bytes.split(|&b| b == b'\n' || b == b'\r').map(<[u8]>::trim_ascii).filter(|l| !l.is_empty()); while let Some(line) = lines.next() { if line == b"ENDSEC" { return None; @@ -144,10 +144,35 @@ fn ascii_code_page(bytes: &[u8]) -> Option<&[u8]> { None } -/// Decode a whole ASCII DXF file. Valid UTF-8 is read as UTF-8: R2007+ files, pure-ASCII files, -/// and older files from writers that ignored the code page. Anything else is decoded from the -/// file's `$DWGCODEPAGE`, or from Windows-1252 (the usual `ANSI_1252`) when the header has none -/// or names a code page CADCraft doesn't know, which is logged as a warning. +impl Decoder { + /// True for the multi-byte East Asian code pages (Shift-JIS, GBK, EUC-KR/Wansung, Big5). + /// Their short double-byte strings are often also valid UTF-8, so UTF-8 is only trusted for + /// a whole file there (see [`decode_ascii_file`] and [`BinaryText`]). + fn is_east_asian(self) -> bool { + use encoding_rs as e; + matches!(self, Decoder::Encoding(x) if x == e::SHIFT_JIS || x == e::GBK || x == e::EUC_KR || x == e::BIG5) + } +} + +/// Decode one line of an ASCII DXF file: valid UTF-8 is read as UTF-8 (R2007+ files, pure-ASCII +/// text, and older files from writers that ignored the code page); anything else comes from the +/// code page `d`, so one stray byte spoils one line, not the whole file. Binary strings don't use +/// this rule: a pre-R2007 binary file has no way to escape to UTF-8, so its strings are read +/// from the code page (see [`BinaryText::string`]). +pub(crate) fn decode_text(bytes: &[u8], d: Decoder) -> Cow<'_, str> { + match std::str::from_utf8(bytes) { + Ok(s) => Cow::Borrowed(s), + Err(_) => decode(bytes, d), + } +} + +/// Decode a whole ASCII DXF file. A file that is valid UTF-8 throughout is UTF-8. Otherwise, for +/// a single-byte code page, each line is decoded on its own (see [`decode_text`]): lines that +/// aren't valid UTF-8 come from the file's `$DWGCODEPAGE`, or from Windows-1252 (the usual +/// `ANSI_1252`) when the header has none or names a code page CADCraft doesn't know, which is +/// logged as a warning. For a multi-byte East Asian code page the whole file is decoded from +/// that code page, because a short double-byte string (two half-width katakana, many kanji +/// pairs) can be valid UTF-8 by accident and must not be misread line by line. pub(crate) fn decode_ascii_file(bytes: &[u8]) -> Cow<'_, str> { if let Ok(s) = std::str::from_utf8(bytes) { return Cow::Borrowed(s); @@ -162,10 +187,19 @@ pub(crate) fn decode_ascii_file(bytes: &[u8]) -> Cow<'_, str> { } None => Decoder::Utf8, }; - decode(bytes, d) + if d.is_east_asian() { + return decode(bytes, d); + } + // Split after each line terminator (CR, LF or CRLF are all ASCII, so they never occur inside + // a multi-byte character of the supported code pages) and decode each line on its own. + let mut out = String::with_capacity(bytes.len()); + for line in bytes.split_inclusive(|&b| b == b'\n' || b == b'\r') { + out.push_str(&decode_text(line, d)); + } + Cow::Owned(out) } -/// The text state of a binary DXF file, learnt from its header as the tags go by: `$ACADVER` +/// The text state of a binary DXF file, learnt from the header as the tags go by: `$ACADVER` /// (R2007+ strings are UTF-8) and `$DWGCODEPAGE` (the code page of older files). Both come /// first in the HEADER section and are ASCII, so every later string is decoded right. #[derive(Default)] @@ -174,6 +208,12 @@ pub(crate) struct BinaryText { var: Option, utf8: bool, code_page: Option, + /// Decode every string of an East Asian code page file from the code page, never as UTF-8 + /// (the second pass of [`BinaryText::needs_code_page_pass`]). + code_page_only: bool, + /// Non-ASCII strings seen under an East Asian code page: valid UTF-8 / not valid UTF-8. + ea_utf8: bool, + ea_other: bool, } #[derive(Clone, Copy, PartialEq)] @@ -183,12 +223,40 @@ enum HeaderVar { } impl BinaryText { + /// The state for the second pass over a file whose strings are a mix of valid UTF-8 and + /// not: every string of an East Asian code page is decoded from that code page. + pub(crate) fn code_page_pass() -> Self { + Self { code_page_only: true, ..Self::default() } + } + + /// True when the file declared a multi-byte East Asian code page and its non-ASCII strings are + /// not all valid UTF-8 although some are: those can be short double-byte strings that look + /// like UTF-8 by accident, so the file must be parsed again with [`Self::code_page_pass`]. (A + /// file whose strings are all valid UTF-8 is UTF-8; one with none is plainly the code page.) + pub(crate) fn needs_code_page_pass(&self) -> bool { + !self.code_page_only && self.ea_utf8 && self.ea_other + } + /// Decode one string value of group `code` and update the state from it. Strings of R2007+ - /// files, and of files without a code page, are UTF-8 when valid (else Windows-1252); older - /// files' strings are in their code page. + /// files, and of files without a code page, are UTF-8 when valid (else Windows-1252); a + /// pre-R2007 file's strings are in its code page, which a binary DXF cannot escape to, so + /// they are read from the code page even when their bytes are valid UTF-8 by accident — + /// except under an East Asian code page, where a file of all-valid-UTF-8 strings is taken + /// as UTF-8 (see [`Self::needs_code_page_pass`]). pub(crate) fn string(&mut self, code: i32, raw: &[u8]) -> String { let d = if self.utf8 { Decoder::Utf8 } else { self.code_page.unwrap_or(Decoder::Utf8) }; - let s = decode(raw, d).into_owned(); + let s = if d.is_east_asian() && !self.code_page_only { + if !raw.is_ascii() { + if std::str::from_utf8(raw).is_ok() { + self.ea_utf8 = true; + } else { + self.ea_other = true; + } + } + decode_text(raw, d).into_owned() + } else { + decode(raw, d).into_owned() + }; match (code, self.var.take()) { (9, _) => { self.var = match s.trim() { diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index c31defc21..6de74d3c5 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -65,7 +65,9 @@ impl Value { match self { Value::Int(i) => *i, Value::Real(r) if r.is_finite() => *r as i64, - Value::Str(s) => s.trim().parse::().unwrap_or_else(|_| s.trim().parse::().map(|f| f as i64).unwrap_or(0)), + Value::Str(s) => { + s.trim().parse::().unwrap_or_else(|_| s.trim().parse::().ok().filter(|f| f.is_finite()).map_or(0, |f| f as i64)) + } Value::Bool(b) => i64::from(*b), _ => 0, } @@ -157,15 +159,26 @@ fn typed(code: i32, text: &str) -> Value { match kind_of(code) { Kind::Real => t.parse::().ok().filter(|v| v.is_finite()).map(Value::Real).unwrap_or(Value::Real(0.0)), Kind::Int16 | Kind::Int32 | Kind::Int64 => { - t.parse::().map(Value::Int).unwrap_or_else(|_| Value::Int(t.parse::().map(|f| f as i64).unwrap_or(0))) + // A float spelling ("1e3", "12.0") is accepted when finite, clamped to what the + // group's width holds, signed or unsigned (files write 16-bit flags up to 65535, as + // the integer spelling reads them); NaN, inf and text become 0. + let (lo, hi) = match kind_of(code) { + Kind::Int16 => (i64::from(i16::MIN), i64::from(u16::MAX)), + Kind::Int32 => (i64::from(i32::MIN), i64::from(u32::MAX)), + _ => (i64::MIN, i64::MAX), + }; + t.parse::() + .map(Value::Int) + .unwrap_or_else(|_| Value::Int(t.parse::().ok().filter(|f| f.is_finite()).map_or(0, |f| (f as i64).clamp(lo, hi)))) } Kind::Bool => Value::Bool(t.parse::().unwrap_or(0) != 0), - Kind::Hex => Value::Hex(t.to_string()), + Kind::Hex => Value::Hex(normalize_hex(t)), Kind::Str => Value::Str(text.trim_end_matches(['\r', '\n']).to_string()), } } const BINARY_SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0"; +const UTF8_BOM: &[u8] = b"\xEF\xBB\xBF"; /// Most group codes read from one file by default. A `Tag` takes 40 bytes plus its text, so this /// bounds the tag list to about 4 GB plus text. 50 million rejected large DWGs that converted fine /// (a 172 MB drawing has 56 million, issue #1948). The file-size limits bound memory too: 512 MB @@ -201,8 +214,10 @@ pub fn parse_with_limit(bytes: &[u8], max_tags: usize) -> Result> { if let Some(body) = bytes.strip_prefix(BINARY_SENTINEL) { return parse_binary_with_limit(body, max_tags); } - // Count nonblank group-code/value pairs, stopping at EOF just as the parser does. - let mut lines = bytes.split(|&b| b == b'\n'); + let bytes = bytes.strip_prefix(UTF8_BOM).unwrap_or(bytes); + // Count nonblank group-code/value pairs (LF, CRLF and a lone CR each end a line), stopping at + // EOF just as the parser does. Blank lines do not count toward the limit. + let mut lines = byte_lines(bytes); let mut tags = 0; while let Some(code) = lines.next() { let code = code.trim_ascii(); @@ -235,7 +250,7 @@ fn escape_at(chars: &[char], i: usize) -> Option { /// The character of a `\M+nXXXX` escape starting at `chars[i]`, if there is one: `n` names a /// double-byte code page and `XXXX` is the character's two bytes in hex. -fn mif_escape_at(chars: &[char], i: usize) -> Option { +pub fn mif_escape_at(chars: &[char], i: usize) -> Option { if chars.get(i) != Some(&'\\') || chars.get(i + 1) != Some(&'M') || chars.get(i + 2) != Some(&'+') { return None; } @@ -289,6 +304,39 @@ fn unescape_unicode(s: &str) -> String { out } +/// The lines of an ASCII DXF text: LF, CRLF and a lone CR (old Mac files) all end a line, like +/// [`str::lines`] otherwise (no empty line after a final terminator). +fn ascii_lines(text: &str) -> impl Iterator { + let mut rest = text; + std::iter::from_fn(move || { + if rest.is_empty() { + return None; + } + let end = rest.find(['\r', '\n']).unwrap_or(rest.len()); + let line = rest.get(..end).unwrap_or_default(); + let after = rest.get(end..).unwrap_or_default(); + rest = after.strip_prefix("\r\n").or_else(|| after.strip_prefix(['\r', '\n'])).unwrap_or(after); + Some(line) + }) +} + +/// Byte-level twin of [`ascii_lines`] for the up-front limit check, so the count matches the parser. +fn byte_lines(mut rest: &[u8]) -> impl Iterator { + std::iter::from_fn(move || { + if rest.is_empty() { + return None; + } + let end = rest.iter().position(|&b| b == b'\r' || b == b'\n').unwrap_or(rest.len()); + let line = &rest[..end]; + let after = &rest[end..]; + rest = match after { + [b'\r', b'\n', tail @ ..] | [b'\r' | b'\n', tail @ ..] => tail, + _ => after, + }; + Some(line) + }) +} + pub fn parse_ascii(text: &str) -> Result> { parse_ascii_counted(text, max_tags(), 0) } @@ -301,7 +349,7 @@ pub fn parse_ascii(text: &str) -> Result> { fn parse_ascii_counted(text: &str, max_tags: usize, expected: usize) -> Result> { let mut tags = Vec::new(); tags.try_reserve_exact(expected.min(max_tags)).map_err(|_| DxfError::OutOfMemory { tags: expected })?; - let mut lines = text.strip_prefix('\u{feff}').unwrap_or(text).lines().enumerate(); + let mut lines = ascii_lines(text.strip_prefix('\u{feff}').unwrap_or(text)).enumerate(); loop { let Some((ln, code_line)) = lines.next() else { break }; let ct = code_line.trim(); @@ -319,7 +367,7 @@ fn parse_ascii_counted(text: &str, max_tags: usize, expected: usize) -> Result max_tags { return Err(DxfError::TooLarge { tags: tags.len(), limit: max_tags }); } - if code == 0 && tags.last().is_some_and(|t| t.str() == "EOF") { + if code == 0 && tags.last().is_some_and(|t| t.str().trim_end() == "EOF") { break; } } @@ -385,8 +433,19 @@ pub fn parse_binary(b: &[u8]) -> Result> { } fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result> { - let mut c = Cur { b, p: 0 }; let mut text = codepage::BinaryText::default(); + let tags = parse_binary_pass(b, max_tags, &mut text)?; + if !text.needs_code_page_pass() { + return Ok(tags); + } + // The first pass's tags go before the second pass runs: both held at once would double + // the peak near the tag limit. + drop(tags); + parse_binary_pass(b, max_tags, &mut codepage::BinaryText::code_page_pass()) +} + +fn parse_binary_pass(b: &[u8], max_tags: usize, text: &mut codepage::BinaryText) -> Result> { + let mut c = Cur { b, p: 0 }; let mut tags = Vec::new(); while c.p < b.len() { let mut code = i32::from(c.i16()?); @@ -395,7 +454,7 @@ fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result> { } let v = match kind_of(code) { Kind::Str => Value::Str(unescape_unicode(&text.string(code, c.cstr()?))), - Kind::Real => Value::Real(c.f64()?), + Kind::Real => Value::Real(Some(c.f64()?).filter(|v| v.is_finite()).unwrap_or(0.0)), Kind::Int16 => Value::Int(i64::from(c.i16()?)), Kind::Int32 => Value::Int(i64::from(c.i32()?)), Kind::Int64 => Value::Int(c.i64()?), @@ -410,7 +469,7 @@ fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result> { Value::Hex(s) } }; - let eof = code == 0 && matches!(&v, Value::Str(s) if s == "EOF"); + let eof = code == 0 && matches!(&v, Value::Str(s) if s.trim_end() == "EOF"); tags.push(Tag { code, value: v }); if tags.len() > max_tags { return Err(DxfError::TooLarge { tags: tags.len(), limit: max_tags }); @@ -485,7 +544,22 @@ fn ascii(tags: &[Tag], strings: Strings) -> Vec { Value::Real(r) => out.extend_from_slice(format_real(*r).as_bytes()), Value::Int(i) => out.extend_from_slice(i.to_string().as_bytes()), Value::Bool(b) => out.extend_from_slice(i64::from(*b).to_string().as_bytes()), - Value::Hex(h) => out.extend_from_slice(h.as_bytes()), + Value::Hex(h) => { + // The DXF Reference limits a binary chunk line to 254 hex digits (127 bytes); + // longer data continues in further groups of the same code. Only hex digits are + // written, so a hostile value can't inject tags. + let digits = normalize_hex(h); + let mut chunks: Vec<&str> = digits.as_bytes().chunks(254).map(|c| std::str::from_utf8(c).unwrap_or_default()).collect(); + if chunks.is_empty() { + chunks.push(""); + } + for (n, chunk) in chunks.into_iter().enumerate() { + if n > 0 { + let _ = write!(out, "\r\n{:>3}\r\n", t.code); + } + out.extend_from_slice(chunk.as_bytes()); + } + } } out.extend_from_slice(b"\r\n"); } @@ -533,13 +607,11 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec { } Kind::Int16 => { out.extend_from_slice(&code_bytes); - let v = t.value.as_i64().clamp(i64::from(i16::MIN), i64::from(i16::MAX)); - out.extend_from_slice(&i16::try_from(v).unwrap_or_default().to_le_bytes()); + out.extend_from_slice(&wrap_i16(t.value.as_i64())); } Kind::Int32 => { out.extend_from_slice(&code_bytes); - let v = t.value.as_i64().clamp(i64::from(i32::MIN), i64::from(i32::MAX)); - out.extend_from_slice(&i32::try_from(v).unwrap_or_default().to_le_bytes()); + out.extend_from_slice(&wrap_i32(t.value.as_i64())); } Kind::Int64 => { out.extend_from_slice(&code_bytes); @@ -567,12 +639,38 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec { out } -/// The bytes of hex text, two digits each; anything that isn't a pair of hex digits is skipped. +/// Hex text cleaned up: only the hex digits are kept, and an odd trailing digit is padded with +/// `0` (so the bytes before it are never shifted). Used by the reader and both writers. +fn normalize_hex(s: &str) -> String { + let mut out: String = s.chars().filter(char::is_ascii_hexdigit).collect(); + if out.len() % 2 == 1 { + out.push('0'); + } + out +} + +/// The bytes of hex text, two digits each (see [`normalize_hex`]). fn hex_bytes(s: &str) -> Vec { - let digits: Vec = s.bytes().filter_map(|b| char::from(b).to_digit(16).and_then(|d| u8::try_from(d).ok())).collect(); + let digits: Vec = normalize_hex(s).bytes().filter_map(|b| char::from(b).to_digit(16).and_then(|d| u8::try_from(d).ok())).collect(); digits.as_chunks::<2>().0.iter().map(|[hi, lo]| (hi << 4) | lo).collect() } +/// A 16- or 32-bit integer for binary DXF: values that fit the unsigned width wrap into the +/// signed one (65535 is -1, as writers that store unsigned flags expect); anything else clamps. +fn wrap_i16(v: i64) -> [u8; 2] { + match u16::try_from(v) { + Ok(u) => u.to_le_bytes(), + Err(_) => i16::try_from(v.clamp(i64::from(i16::MIN), i64::from(i16::MAX))).unwrap_or_default().to_le_bytes(), + } +} + +fn wrap_i32(v: i64) -> [u8; 4] { + match u32::try_from(v) { + Ok(u) => u.to_le_bytes(), + Err(_) => i32::try_from(v.clamp(i64::from(i32::MIN), i64::from(i32::MAX))).unwrap_or_default().to_le_bytes(), + } +} + /// Whether `bytes` are a binary DXF file (they start with the binary sentinel). pub fn is_binary(bytes: &[u8]) -> bool { bytes.starts_with(BINARY_SENTINEL) @@ -634,12 +732,12 @@ pub fn sections(tags: &[Tag]) -> Vec
{ let mut out = Vec::new(); let mut i = 0; while i < tags.len() { - let is_sec = tags.get(i).is_some_and(|t| t.code == 0 && t.str() == "SECTION"); + let is_sec = tags.get(i).is_some_and(|t| t.code == 0 && t.str().trim_end() == "SECTION"); if is_sec { - let name = tags.get(i + 1).filter(|t| t.code == 2).map(Tag::str).unwrap_or_default(); + let name = tags.get(i + 1).filter(|t| t.code == 2).map(|t| t.str().trim_end().to_string()).unwrap_or_default(); let start = i + 2; let mut j = start; - while j < tags.len() && !(tags.get(j).is_some_and(|t| t.code == 0 && t.str() == "ENDSEC")) { + while j < tags.len() && !(tags.get(j).is_some_and(|t| t.code == 0 && t.str().trim_end() == "ENDSEC")) { j += 1; } out.push(Section { name, tags: tags.get(start..j).unwrap_or(&[]).to_vec() }); diff --git a/crates/dxf/tests/hardening.rs b/crates/dxf/tests/hardening.rs new file mode 100644 index 000000000..1bff0d97f --- /dev/null +++ b/crates/dxf/tests/hardening.rs @@ -0,0 +1,220 @@ +//! Hostile-input hardening of the DXF reader and writer (#1025): one regression test per finding. + +use cadcraft_dxf::{Tag, Value, parse, parse_with_limit, sections, write_ascii, write_binary}; + +const SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0"; + +fn bin_with(f: impl FnOnce(&mut Vec)) -> Vec { + let mut b = SENTINEL.to_vec(); + f(&mut b); + b.extend_from_slice(&0i16.to_le_bytes()); + b.extend_from_slice(b"EOF\0"); + b +} + +#[test] +fn binary_reals_that_are_not_finite_become_zero() { + for bits in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let b = bin_with(|b| { + b.extend_from_slice(&10i16.to_le_bytes()); + b.extend_from_slice(&bits.to_le_bytes()); + }); + let tags = parse(&b).unwrap(); + assert_eq!(tags[0], Tag::f(10, 0.0), "{bits}"); + } +} + +#[test] +fn ascii_accepts_bom_and_cr_only_line_ends() { + let want = vec![Tag::s(0, "SECTION"), Tag::s(2, "ENTITIES"), Tag::s(0, "ENDSEC"), Tag::s(0, "EOF")]; + let text = "0\rSECTION\r2\rENTITIES\r0\rENDSEC\r0\rEOF\r"; + assert_eq!(parse(text.as_bytes()).unwrap(), want); + let mut bom = b"\xEF\xBB\xBF".to_vec(); + bom.extend_from_slice(text.replace('\r', "\r\n").as_bytes()); + assert_eq!(parse(&bom).unwrap(), want); + // Mixed terminators. + assert_eq!(parse(b"0\r\nSECTION\r2\nENTITIES\n0\rENDSEC\r\n0\nEOF").unwrap(), want); +} + +#[test] +fn cr_only_files_count_against_the_tag_limit() { + let mut text = String::new(); + for _ in 0..50 { + text.push_str("999\rcomment\r"); + } + text.push_str("0\rEOF\r"); + assert!(parse_with_limit(text.as_bytes(), 10).is_err()); + assert_eq!(parse_with_limit(text.as_bytes(), 100).unwrap().len(), 51); +} + +#[test] +fn one_bad_byte_spoils_one_line_not_the_file() { + // Header says ANSI_1251; one line is UTF-8, one is Windows-1251, one has a stray byte. + let mut b = b"9\n$DWGCODEPAGE\n3\nANSI_1251\n1\n".to_vec(); + b.extend_from_slice("Größe".as_bytes()); + b.extend_from_slice(b"\n1\n\xCF\xF0\xE8\xE2\xE5\xF2\n0\nEOF\n"); + let t = parse(&b).unwrap(); + assert_eq!(t[1].str(), "ANSI_1251"); + assert_eq!(t[2].str(), "Größe"); + assert_eq!(t[3].str(), "Привет"); +} + +#[test] +fn ascii_uses_utf8_per_line_and_binary_stays_in_the_code_page() { + // ANSI_1252 file with UTF-8 bytes in one string and a Latin-1 byte in another. The ASCII + // reader takes a line that is valid UTF-8 as UTF-8; the binary reader reads every string + // from the code page, because a pre-R2007 binary file has no way to escape to UTF-8. + let utf8 = "Größe".as_bytes(); + let latin = b"Caf\xE9"; + let mut a = b"9\n$DWGCODEPAGE\n3\nANSI_1252\n1\n".to_vec(); + a.extend_from_slice(utf8); + a.extend_from_slice(b"\n1\n"); + a.extend_from_slice(latin); + a.extend_from_slice(b"\n0\nEOF\n"); + let from_ascii = parse(&a).unwrap(); + let b = bin_with(|b| { + for (code, s) in [(9i16, &b"$DWGCODEPAGE"[..]), (3, b"ANSI_1252"), (1, utf8), (1, latin)] { + b.extend_from_slice(&code.to_le_bytes()); + b.extend_from_slice(s); + b.push(0); + } + }); + let from_binary = parse(&b).unwrap(); + assert_eq!(from_ascii[2].str(), "Größe"); + assert_eq!(from_ascii[3].str(), "Café"); + assert_eq!(from_binary[2].str(), "Größe"); + assert_eq!(from_binary[3].str(), "Café"); +} + +#[test] +fn trailing_spaces_keep_sections_and_eof() { + let t = parse(b"0\nSECTION \n2\nENTITIES \n0\nLINE\n0\nENDSEC \n0\nEOF \n0\nSECTION\n2\nX\n0\nENDSEC\n").unwrap(); + // The EOF with a trailing space still ends the file. + assert_eq!(t.len(), 5); + let s = sections(&t); + assert_eq!(s.len(), 1); + assert_eq!(s[0].name, "ENTITIES"); + assert_eq!(s[0].tags.len(), 1); + // Binary EOF too. + let mut b = SENTINEL.to_vec(); + b.extend_from_slice(&0i16.to_le_bytes()); + b.extend_from_slice(b"EOF \0"); + b.extend_from_slice(&1i16.to_le_bytes()); + b.extend_from_slice(b"after\0"); + assert_eq!(parse(&b).unwrap().len(), 1); +} + +#[test] +fn integer_groups_reject_non_finite_and_clamp() { + let t = parse(b"70\ninf\n70\nNaN\n70\n1e30\n70\n-1e30\n90\n1e30\n160\n1e30\n160\n-inf\n62\n12.0\n0\nEOF\n").unwrap(); + assert_eq!(t[0], Tag::i(70, 0)); + assert_eq!(t[1], Tag::i(70, 0)); + // Clamped to what the group's width holds, unsigned values included (the binary writer + // keeps up to 65535 and 4294967295 as their bit patterns). + assert_eq!(t[2], Tag::i(70, i64::from(u16::MAX))); + assert_eq!(t[3], Tag::i(70, i64::from(i16::MIN))); + assert_eq!(t[4], Tag::i(90, i64::from(u32::MAX))); + assert_eq!(t[5], Tag::i(160, i64::MAX)); + assert_eq!(t[6], Tag::i(160, 0)); + assert_eq!(t[7], Tag::i(62, 12)); + assert_eq!(Value::Str("inf".into()).as_i64(), 0); +} + +/// An unsigned value spelled as a float reads as the same spelled as an integer (#1026 review): +/// `65535.0` is 65535 like `65535`, not 32767. +#[test] +fn unsigned_values_read_the_same_in_either_spelling() { + let t = parse(b"70\n65535.0\n70\n65535\n90\n4294967295.0\n90\n4294967295\n0\nEOF\n").unwrap(); + assert_eq!(t[0], t[1]); + assert_eq!(t[0], Tag::i(70, 65535)); + assert_eq!(t[2], t[3]); + assert_eq!(t[2], Tag::i(90, 4_294_967_295)); +} + +#[test] +fn hex_groups_pad_odd_digits_and_drop_junk() { + let t = parse(b"310\nABC\n310\nA-B zC1\n310\n\n1004\n0aF\n0\nEOF\n").unwrap(); + assert_eq!(t[0].value, Value::Hex("ABC0".into())); + assert_eq!(t[1].value, Value::Hex("ABC1".into())); + assert_eq!(t[2].value, Value::Hex(String::new())); + assert_eq!(t[3].value, Value::Hex("0aF0".into())); + // The binary writer agrees with the reader: the odd digit is padded, nothing shifts. + let back = parse(&write_binary(&[Tag::new(310, Value::Hex("ABC".into())), Tag::s(0, "EOF")], true)).unwrap(); + assert_eq!(back[0].value, Value::Hex("ABC0".into())); +} + +#[test] +fn ascii_hex_cannot_inject_tags_and_is_split_at_254_digits() { + let evil = Tag::new(310, Value::Hex("AB\r\n0\r\nEOF".into())); + let text = write_ascii(&[evil, Tag::s(0, "EOF")]); + let back = parse(text.as_bytes()).unwrap(); + assert_eq!(back.len(), 2, "{text:?}"); + assert_eq!(back[0].value, Value::Hex("AB0EF0".into())); + let long = "AB".repeat(300); + let back = parse(write_ascii(&[Tag::new(310, Value::Hex(long)), Tag::s(0, "EOF")]).as_bytes()).unwrap(); + let sizes: Vec = back.iter().filter(|t| t.code == 310).map(|t| t.str().len()).collect(); + assert_eq!(sizes, vec![254, 254, 92]); + // An empty chunk is still one group. + let back = parse(write_ascii(&[Tag::new(310, Value::Hex(String::new())), Tag::s(0, "EOF")]).as_bytes()).unwrap(); + assert_eq!(back[0].code, 310); +} + +#[test] +fn binary_sixteen_and_thirty_two_bit_values_wrap_in_range_and_clamp_outside() { + let tags = [ + Tag::i(70, 65535), + Tag::i(70, 40000), + Tag::i(70, 70000), + Tag::i(70, -40000), + Tag::i(90, 0xFFFF_FFFF), + Tag::i(90, 1 << 40), + Tag::i(90, -(1 << 40)), + Tag::s(0, "EOF"), + ]; + let back = parse(&write_binary(&tags, true)).unwrap(); + assert_eq!(back[0], Tag::i(70, -1)); + assert_eq!(back[1], Tag::i(70, 40000 - 65536)); + assert_eq!(back[2], Tag::i(70, i64::from(i16::MAX))); + assert_eq!(back[3], Tag::i(70, i64::from(i16::MIN))); + assert_eq!(back[4], Tag::i(90, -1)); + assert_eq!(back[5], Tag::i(90, i64::from(i32::MAX))); + assert_eq!(back[6], Tag::i(90, i64::from(i32::MIN))); +} + +/// Strings of a `$DWGCODEPAGE`-declared file as ASCII text and as a binary file. +fn both_forms(code_page: &str, strings: &[&[u8]]) -> [Vec; 2] { + let mut a = format!("9\n$DWGCODEPAGE\n3\n{code_page}\n").into_bytes(); + for s in strings { + a.extend_from_slice(b"1\n"); + a.extend_from_slice(s); + a.push(b'\n'); + } + a.extend_from_slice(b"0\nEOF\n"); + let b = bin_with(|b| { + for (code, s) in [(9i16, &b"$DWGCODEPAGE"[..]), (3, code_page.as_bytes())].into_iter().chain(strings.iter().map(|s| (1, *s))) { + b.extend_from_slice(&code.to_le_bytes()); + b.extend_from_slice(s); + b.push(0); + } + }); + [parse(&a).unwrap(), parse(&b).unwrap()] +} + +#[test] +fn east_asian_short_strings_that_look_like_utf8_stay_in_the_code_page() { + // C3 B1 is valid UTF-8 ("ñ") but is also two half-width katakana in Shift-JIS; the second + // string is plainly Shift-JIS, so the file is not UTF-8. + for t in both_forms("ANSI_932", &[b"\xC3\xB1", b"\x90\x7D\x96\xCA"]) { + assert_eq!(t[2].str(), "\u{FF83}\u{FF71}"); + assert_eq!(t[3].str(), "図面"); + } +} + +#[test] +fn east_asian_file_that_is_all_utf8_reads_as_utf8() { + for t in both_forms("ANSI_932", &["図面".as_bytes(), b"\xC3\xB1", b"plain"]) { + assert_eq!(t[2].str(), "図面"); + assert_eq!(t[3].str(), "ñ"); + assert_eq!(t[4].str(), "plain"); + } +} diff --git a/crates/engine/src/assoc.rs b/crates/engine/src/assoc.rs index f17cd1e80..389745dcc 100644 --- a/crates/engine/src/assoc.rs +++ b/crates/engine/src/assoc.rs @@ -40,8 +40,12 @@ fn arc_geom(a: &cadcraft_doc::Arc) -> cadcraft_geom::Arc { /// Where a snap sits on an object now. pub fn snap_point(d: &Drawing, a: &DimAssoc) -> Option { - let e = d.entity(a.handle)?; - match (&e.kind, &a.snap) { + snap_on(d, &d.entity(a.handle)?.kind, &a.snap) +} + +/// Where `snap` sits on an object of kind `kind` (an intersection finds its other line in `d`). +fn snap_on(d: &Drawing, kind: &EntityKind, snap: &AssocSnap) -> Option { + match (kind, snap) { (EntityKind::Line(l), AssocSnap::Start) => Some(l.a.xy()), (EntityKind::Line(l), AssocSnap::End) => Some(l.b.xy()), (EntityKind::Line(l), AssocSnap::Mid) => Some(l.a.xy().mid(l.b.xy())), @@ -88,6 +92,61 @@ fn candidates(kind: &EntityKind) -> Vec<(AssocSnap, Vec2)> { } } +/// Whether two snaps are the same kind of object point: an endpoint or vertex, a centre, or a +/// midpoint. +fn same_kind(a: &AssocSnap, b: &AssocSnap) -> bool { + matches!( + (a, b), + (AssocSnap::Start | AssocSnap::End | AssocSnap::Vertex { .. }, AssocSnap::Start | AssocSnap::End | AssocSnap::Vertex { .. }) + | (AssocSnap::Center, AssocSnap::Center) + | (AssocSnap::Mid, AssocSnap::Mid) + ) +} + +/// BREAK or TRIM reshaped the object `pieces[0]` (which was `old`) and added the other pieces: +/// move the dimension attachments on it as AutoCAD 2024 does. An attachment whose point is still +/// a point of the same kind on the object stays there (a closed polyline opened by BREAK numbers +/// its vertices from the break); one whose point is on a new piece moves to that piece, so a +/// dimension across a line broken in its middle stays where it was; any other is left as it was, +/// so the dimension follows the object's new end when that end was cut off. Attachments at an +/// angle on a circle or arc and at an intersection stay on the object. [`update`] moves the +/// definition points after the command. +pub fn follow_pieces(d: &mut Drawing, old: &EntityKind, pieces: &[Handle]) { + let Some(&h) = pieces.first() else { return }; + let mut changes: Vec<(Handle, Vec)> = Vec::new(); + for store in std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)) { + for e in store.iter() { + let EntityKind::Dimension(dm) = &e.kind else { continue }; + if !dm.assoc.iter().any(|a| a.handle == h) { + continue; + } + let assoc: Vec = dm.assoc.iter().map(|a| on_piece(d, old, pieces, a).unwrap_or_else(|| a.clone())).collect(); + if assoc != dm.assoc { + changes.push((e.handle, assoc)); + } + } + } + for (dh, assoc) in changes { + let _ = d.modify_entity(dh, |e| { + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.assoc = assoc; + } + }); + } +} + +/// The piece attachment `a` moves to when its object became `pieces` (see [`follow_pieces`]). +fn on_piece(d: &Drawing, old: &EntityKind, pieces: &[Handle], a: &DimAssoc) -> Option { + if pieces.first() != Some(&a.handle) || matches!(a.snap, AssocSnap::OnCircle { .. } | AssocSnap::Intersection { .. }) { + return None; + } + let p = snap_on(d, old, &a.snap)?; + pieces.iter().find_map(|&ph| { + let (snap, _) = candidates(&d.entity(ph)?.kind).into_iter().find(|(s, q)| same_kind(&a.snap, s) && close(p, *q))?; + Some(DimAssoc { point: a.point.clone(), handle: ph, snap }) + }) +} + /// An object point exactly at `p` (an endpoint, vertex, centre or midpoint) to attach to. pub fn find_snap(d: &Drawing, space: &Space, p: Vec2) -> Option<(Handle, AssocSnap)> { if !p.is_finite() { @@ -244,8 +303,10 @@ pub fn recompute(dm: &Dimension, prev: Option<&Dimension>, before: &Drawing, aft let was = prev.unwrap_or(dm); nd.assoc.retain(|a| { let Some(old) = def_point(was, &a.point) else { return false }; - // Only follow if the point sat on the object before the change. - if let Some(prev) = snap_point(before, a) + // Only follow if the point sat on the object before the change, as attached then (BREAK + // and TRIM may have moved the attachment to a piece of the object since). + let held = was.assoc.iter().find(|o| o.point == a.point).unwrap_or(a); + if let Some(prev) = snap_point(before, held) && !close(prev, old.xy()) { return false; @@ -304,16 +365,20 @@ pub fn update(after: &mut Arc, before: &Drawing) -> usize { if dm.assoc.is_empty() { continue; } - let touched = dm.assoc.iter().any(|a| { - src_changed(before, d, a.handle) || matches!(a.snap, AssocSnap::Intersection { other } if src_changed(before, d, other)) - }); - if !touched { - continue; - } let prev = match before.entity(e.handle).map(|x| &x.kind) { Some(EntityKind::Dimension(p)) => Some(p), _ => None, }; + // Its objects changed, or the command moved an attachment (BREAK and TRIM move them + // to new pieces, which a later pick of the same TRIM may reshape again). + let touched = dm.assoc.iter().any(|a| { + src_changed(before, d, a.handle) + || matches!(a.snap, AssocSnap::Intersection { other } if src_changed(before, d, other)) + || prev.is_some_and(|p| !p.assoc.contains(a)) + }); + if !touched { + continue; + } let nd = recompute(dm, prev, before, d); if nd != *dm { changes.push((e.handle, nd)); diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index 452cf176f..1cc97a496 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -178,14 +178,34 @@ fn create(s: &mut Session, objs: &[Handle], base: Vec2, p: ArrayParams, assoc: b Ok(json!({ "created": n })) } +/// The most objects EXPLODE of one associative array makes from its source objects (ten times the +/// default MAXARRAY). +const MAX_EXPLODED_OBJECTS: usize = 1_000_000; + /// EXPLODE of an associative array: every item becomes the objects of its block (the source /// objects, or a replacement block's reference), in world coordinates. `None` for other objects. +/// +/// An array that would explode into more than [`MAX_EXPLODED_OBJECTS`] objects (items times the +/// objects of the source block, which a file sets freely) is not expanded here: `None`, so EXPLODE +/// takes the array block's own items. pub(crate) fn explode_array(d: &Drawing, e: &Entity) -> Option> { let EntityKind::Insert(ins) = &e.kind else { return None }; let p = d.array_params(e)?; let blk = d.block(&ins.block)?; let m = ins.transform(blk.base.xy()); - let mut out = Vec::new(); + // Count first: a hostile array must be refused before any entity is cloned. + let total = blk + .entities + .iter() + .map(|it| match &it.kind { + EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(&p.source) => d.block(&i.block).map_or(1, |b| b.entities.len()), + _ => 1, + }) + .fold(0usize, usize::saturating_add); + if total > MAX_EXPLODED_OBJECTS { + return None; + } + let mut out = Vec::with_capacity(total); for item in blk.entities.iter() { let item = placed(e, item, &m); let source = match &item.kind { @@ -193,7 +213,9 @@ pub(crate) fn explode_array(d: &Drawing, e: &Entity) -> Option> { _ => None, }; match source { - Some((im, b)) => out.extend(b.entities.iter().map(|se| placed(&item, se, &im))), + Some((im, b)) => { + out.extend(b.entities.iter().map(|se| placed(&item, se, &im))); + } None => out.push(item), } } @@ -248,9 +270,16 @@ fn max_count(s: &Session, others: u64, objs: usize) -> u64 { } fn copy_all(s: &mut Session, hs: &[Handle], mats: impl Iterator) -> Result { + // Every copy is checked before the first is made: a refusal part way would leave the copies + // already added in the drawing (a failed command is not rolled back). + let mats: Vec = mats.collect(); + // A matrix every frame accepts needs no look at the objects; otherwise they are looked at once. + if mats.iter().any(|m| !cadcraft_doc::ole_frame_accepts(m)) && super::modify::holds_ole_frame(s, hs, true)? { + return Err(super::modify::ole_refusal()); + } let mut n = 0; - for m in mats { - n += transform_entities(s, hs, &m, true)?.len(); + for m in &mats { + n += transform_entities(s, hs, m, true)?.len(); } Ok(n) } diff --git a/crates/engine/src/cmd/array/edit.rs b/crates/engine/src/cmd/array/edit.rs index 21bf6b132..93b515b4a 100644 --- a/crates/engine/src/cmd/array/edit.rs +++ b/crates/engine/src/cmd/array/edit.rs @@ -188,8 +188,9 @@ fn item_at(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Option<(u32, u32, u32) let mut best: Option<((u32, u32, u32), f64)> = None; // Each block's own extents, measured once. let mut extents: HashMap = HashMap::new(); + let block_for = p.block_lookup(); for it in p.items()? { - let name = p.block_for(it.i, it.j, it.level); + let name = block_for(it.i, it.j, it.level); let (base, local) = match extents.get(name) { Some(x) => *x, None => { diff --git a/crates/engine/src/cmd/audit.rs b/crates/engine/src/cmd/audit.rs index fa3cc2f98..6bd068c11 100644 --- a/crates/engine/src/cmd/audit.rs +++ b/crates/engine/src/cmd/audit.rs @@ -157,7 +157,7 @@ fn write_audit_log(_: &Session, _: &crate::audit::Report) {} #[cfg(not(target_arch = "wasm32"))] fn read_path(cmd: &str, path: &str) -> Result> { - std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}"))) + crate::capped_read::read_capped(std::path::Path::new(path), file::MAX_DRAWING_BYTES).map_err(|e| bad(cmd, format!("{path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/blocks/extract.rs b/crates/engine/src/cmd/blocks/extract.rs index 10785f08f..de85956c7 100644 --- a/crates/engine/src/cmd/blocks/extract.rs +++ b/crates/engine/src/cmd/blocks/extract.rs @@ -2,9 +2,9 @@ //! block name and values, or one row per reference with its handle, layer, position and //! rotation — returned, written to a CSV file and/or inserted as a table. Tags match in any case. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; -use cadcraft_doc::{EntityKind, Insert}; +use cadcraft_doc::{Drawing, EntityKind, Insert}; use cadcraft_geom::Vec2; use serde_json::{Value, json}; @@ -88,22 +88,75 @@ fn matches(spec: &str, text: &str) -> bool { spec.split(',').any(|p| wildcard(p.trim(), text)) } -/// The attribute values of `ins`: its own, then the constant ones of its block. -fn values(d: &cadcraft_doc::Drawing, ins: &Insert) -> Vec<(String, String)> { - let mut v: Vec<(String, String)> = ins.attribs.iter().map(|a| (a.tag.to_ascii_uppercase(), a.text.value.clone())).collect(); - if let Some(b) = d.block(&ins.block) { - for e in b.entities.iter() { - if let EntityKind::AttDef(a) = &e.kind - && a.constant - && !v.iter().any(|(t, _)| t.eq_ignore_ascii_case(&a.tag)) - { - v.push((a.tag.to_ascii_uppercase(), a.text.value.clone())); - } +/// The constant attribute values of a block definition whose tags are selected for output. +fn constants(b: &cadcraft_doc::Block, selected: &[String]) -> Vec<(String, String)> { + let mut v: Vec<(String, String)> = Vec::new(); + for e in b.entities.iter() { + if let EntityKind::AttDef(a) = &e.kind + && a.constant + && selected.iter().any(|tag| tag == &a.tag.to_ascii_uppercase()) + && !v.iter().any(|(t, _)| t.eq_ignore_ascii_case(&a.tag)) + { + v.push((a.tag.to_ascii_uppercase(), a.text.value.clone())); } } v } +/// The attribute values of `ins` that `o.tags` selects: its own, then the constant ones of its +/// block (`consts`, read once per block). Values no column shows are not copied. +fn values(ins: &Insert, consts: &[(String, String)], selected: &[String]) -> Vec<(String, String)> { + let mut v: Vec<(String, String)> = ins + .attribs + .iter() + .map(|a| (a.tag.to_ascii_uppercase(), a)) + .filter(|(t, _)| selected.contains(t)) + .map(|(t, a)| (t, a.text.value.clone())) + .collect(); + for (t, val) in consts { + if !v.iter().any(|(k, _)| k.eq_ignore_ascii_case(t)) { + v.push((t.clone(), val.clone())); + } + } + v +} + +/// Select the output columns before copying any attribute text. A block definition can contain +/// many large constants that do not survive the table's 190-column limit. +fn selected_tags(ents: &[std::sync::Arc], d: &Drawing, o: &Options) -> Vec { + let mut selected = Vec::new(); + let mut add = |tag: &str| { + let tag = tag.to_ascii_uppercase(); + if selected.len() < MAX_TAGS && matches(&o.tags, &tag) && !selected.contains(&tag) { + selected.push(tag); + } + }; + let mut scanned = std::collections::HashSet::new(); + for entity in ents { + let EntityKind::Insert(ins) = &entity.kind else { continue }; + let anonymous = ins.block.starts_with('*') || d.block(&ins.block).is_some_and(|b| b.anonymous); + if anonymous || !matches(&o.blocks, &ins.block) { + continue; + } + for attribute in &ins.attribs { + add(&attribute.tag); + } + // A block's constants are read once, however many inserts reference it. + if scanned.insert(ins.block.as_str()) + && let Some(block) = d.block(&ins.block) + { + for entity in block.entities.iter() { + if let EntityKind::AttDef(attribute) = &entity.kind + && attribute.constant + { + add(&attribute.tag); + } + } + } + } + selected +} + /// The block references to extract from: `handles` when given, else model space and the layouts. fn found(s: &Session, p: &Value, o: &Options) -> Result> { let d = s.doc()?; @@ -112,7 +165,9 @@ fn found(s: &Session, p: &Value, o: &Options) -> Result> { } else { d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).cloned().collect() }; + let selected = selected_tags(&ents, d, o); let mut out = Vec::new(); + let mut consts: HashMap> = HashMap::new(); for e in &ents { let EntityKind::Insert(ins) = &e.kind else { continue }; let anonymous = ins.block.starts_with('*') || d.block(&ins.block).is_some_and(|b| b.anonymous); @@ -121,12 +176,17 @@ fn found(s: &Session, p: &Value, o: &Options) -> Result> { } let block = d.block(&ins.block).map(|b| b.name.clone()).unwrap_or_else(|| ins.block.clone()); out.push(Found { - block, handle: e.handle.hex(), layer: e.common.layer.clone(), at: ins.insert.xy(), rotation: ins.rotation.to_degrees(), - values: values(d, ins), + block: block.clone(), + values: values( + ins, + // Keyed by the resolved definition's exact name: `Part` and `PART` can both exist. + consts.entry(block.clone()).or_insert_with(|| d.block(&ins.block).map(|b| constants(b, &selected)).unwrap_or_default()), + &selected, + ), }); } Ok(out) diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index 7a0492fad..e39dc06bb 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -85,7 +85,8 @@ fn read_drawing(path: &str) -> Result { fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { - std::fs::read(_path).map_err(|e| bad("insert", format!("{_path}: {e}"))) + crate::capped_read::read_capped(std::path::Path::new(_path), crate::cmd::file::MAX_DRAWING_BYTES) + .map_err(|e| bad("insert", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] Err(bad("insert", "paths are not available on the web")) diff --git a/crates/engine/src/cmd/blocks/xref.rs b/crates/engine/src/cmd/blocks/xref.rs index 18da7fa0f..3b91809e5 100644 --- a/crates/engine/src/cmd/blocks/xref.rs +++ b/crates/engine/src/cmd/blocks/xref.rs @@ -50,7 +50,7 @@ pub(super) fn specs() -> Vec { } /// Load the xrefs of drawing `i`, just opened (OPEN): the opened state counts as saved, and the -/// view frames the drawing with them. +/// view frames the drawing with them, unless the drawing opened on the view it was saved at. pub(crate) fn after_open(s: &mut Session, i: usize) { let px = s.viewport_px; let Some(st) = s.docs.get_mut(i) else { return }; @@ -61,7 +61,7 @@ pub(crate) fn after_open(s: &mut Session, i: usize) { let out = load::load_all(Arc::make_mut(&mut st.doc), path.as_deref()); st.saved = st.doc.clone(); let ext = st.doc.extents(&cadcraft_doc::Space::Model); - if !ext.is_empty() { + if !ext.is_empty() && crate::view::saved_view(&st.doc).is_none() { // Fit in the frame of the saved twist, which open_drawing has restored. let twist = st.view().twist; let (center, w, h) = crate::View::twisted_box(ext, twist); diff --git a/crates/engine/src/cmd/curves.rs b/crates/engine/src/cmd/curves.rs index ca918834a..218a512ed 100644 --- a/crates/engine/src/cmd/curves.rs +++ b/crates/engine/src/cmd/curves.rs @@ -453,14 +453,32 @@ impl Chain { } /// Point and unit tangent at arc length `d` from the start (clamped). pub fn at_length(&self, d: f64) -> Option<(Vec2, Vec2)> { - let mut acc = 0.0; - for s in &self.segs { - let l = s.len(); - if d <= acc + l + 1e-12 && l > 0.0 { - let t = ((d - acc) / l).clamp(0.0, 1.0); - return Some((s.at(t), s.tangent(t))); - } - acc += l; + self.at_length_in(&self.end_lengths(), d) + } + /// The arc length from the chain's start to the end of each segment, for [`Self::at_length_in`]. + pub fn end_lengths(&self) -> Vec { + self.segs + .iter() + .scan(0.0, |acc, s| { + *acc += s.len(); + Some(*acc) + }) + .collect() + } + /// [`Self::at_length`] with the segment end lengths computed once (`ends` from + /// [`Self::end_lengths`]), so many samples along one chain each cost a binary search. + pub fn at_length_in(&self, ends: &[f64], d: f64) -> Option<(Vec2, Vec2)> { + let first = ends.partition_point(|e| d > e + 1e-12); + // A segment of no length can't hold the point; the next one that has length does. + // `ends` never decreases, so the first segment past `first` with length is found by search + // (a run of zero-length segments can be long) instead of a scan. + let base = first.checked_sub(1).and_then(|p| ends.get(p)).copied().unwrap_or(0.0); + let i = first + ends.get(first..).unwrap_or_default().partition_point(|e| *e <= base); + let i = (i < self.segs.len()).then_some(i); + if let Some(s) = i.and_then(|i| self.segs.get(i)) { + let start = i.and_then(|i| i.checked_sub(1)).and_then(|p| ends.get(p)).copied().unwrap_or(0.0); + let t = ((d - start) / s.len()).clamp(0.0, 1.0); + return Some((s.at(t), s.tangent(t))); } self.segs.last().map(|s| (s.end(), s.tangent(1.0))) } @@ -640,6 +658,34 @@ pub fn reverse_vertices(vs: &[PolyVertex], closed: bool) -> Vec { mod tests { use super::*; + /// The indexed lookup gives the point and tangent a scan from the start gives, also past the + /// ends and over a segment of no length. + #[test] + fn at_length_in_matches_a_scan() { + let l = |a: (f64, f64), b: (f64, f64)| Segment::Line(Line::new(Vec2::new(a.0, a.1), Vec2::new(b.0, b.1))); + let c = Chain { + segs: vec![l((0.0, 0.0), (0.0, 0.0)), l((0.0, 0.0), (4.0, 0.0)), l((4.0, 0.0), (4.0, 0.0)), l((4.0, 0.0), (4.0, 3.0))], + closed: false, + }; + let ends = c.end_lengths(); + for d in [-1.0, 0.0, 1.5, 4.0, 4.0 + 1e-13, 5.0, 7.0, 9.0] { + // The scan this replaced. + let mut acc = 0.0; + let mut want = c.segs.last().map(|s| (s.end(), s.tangent(1.0))); + for s in &c.segs { + let len = s.len(); + if d <= acc + len + 1e-12 && len > 0.0 { + let t = ((d - acc) / len).clamp(0.0, 1.0); + want = Some((s.at(t), s.tangent(t))); + break; + } + acc += len; + } + assert_eq!(c.at_length_in(&ends, d), want, "d = {d}"); + assert_eq!(c.at_length(d), want); + } + } + #[test] fn arc_builders() { let a = arc_sca(Vec2::new(1.0, 0.0), Vec2::ZERO, std::f64::consts::FRAC_PI_2).unwrap(); diff --git a/crates/engine/src/cmd/draw2/divide.rs b/crates/engine/src/cmd/draw2/divide.rs index 4e92f561f..d6c3dd612 100644 --- a/crates/engine/src/cmd/draw2/divide.rs +++ b/crates/engine/src/cmd/draw2/divide.rs @@ -36,16 +36,18 @@ fn check_block(s: &Session, b: Option<&str>) -> Result<()> { pub(crate) fn divide_points(c: &Chain, n: usize) -> Vec<(Vec2, Vec2)> { let l = c.len(); let range = if c.closed { 0..n } else { 1..n }; - range.filter_map(|i| c.at_length(l * i as f64 / n as f64)).collect() + let ends = c.end_lengths(); + range.filter_map(|i| c.at_length_in(&ends, l * i as f64 / n as f64)).collect() } pub(crate) fn measure_points(c: &Chain, step: f64) -> Vec<(Vec2, Vec2)> { let l = c.len(); + let ends = c.end_lengths(); let mut out = Vec::new(); let mut k = 1usize; while (k as f64) * step < l - 1e-9 && out.len() < MAX_GEN { let d = k as f64 * step; - out.extend(c.at_length(d)); + out.extend(c.at_length_in(&ends, d)); k += 1; } out diff --git a/crates/engine/src/cmd/draw2/revcloud.rs b/crates/engine/src/cmd/draw2/revcloud.rs index 634456b05..9baaee917 100644 --- a/crates/engine/src/cmd/draw2/revcloud.rs +++ b/crates/engine/src/cmd/draw2/revcloud.rs @@ -58,8 +58,9 @@ pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, re closed: true, }; let k = ((perim / arc_len).round() as usize).clamp(3, MAX_GEN); + let ends = chain.end_lengths(); for j in 0..k { - out.extend(chain.at_length(perim * j as f64 / k as f64).map(|x| x.0)); + out.extend(chain.at_length_in(&ends, perim * j as f64 / k as f64).map(|x| x.0)); } } let b = if reverse { -0.5 } else { 0.5 }; diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index 6148a0446..1b8d7c72e 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -204,7 +204,8 @@ fn import_drawing(s: &mut Session, src: &Drawing, at: Vec2, scale: f64, file: &s fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { - std::fs::read(_path).map_err(|e| bad("import", format!("{_path}: {e}"))) + crate::capped_read::read_capped(std::path::Path::new(_path), crate::cmd::file::MAX_DRAWING_BYTES) + .map_err(|e| bad("import", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] Err(bad("import", "paths are not available on the web; pass `data`")) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e2a9c1be7..27bd2fdc4 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -24,7 +24,7 @@ pub use template::{qnew_template, set_qnew_template}; /// endless device must be rejected before it exhausts memory (CWE-400), so native opens read /// through [`crate::capped_read`] rather than buffering to EOF. #[cfg(not(target_arch = "wasm32"))] -const MAX_DRAWING_BYTES: usize = 512 << 20; +pub(crate) const MAX_DRAWING_BYTES: usize = 512 << 20; /// Largest `.scr` script accepted from a local path. #[cfg(not(target_arch = "wasm32"))] const MAX_SCRIPT_BYTES: usize = 64 << 20; @@ -365,10 +365,12 @@ pub(crate) fn open_bytes(s: &mut Session, bytes: &[u8], name: &str, path: Option fn opened(s: &Session, i: usize, entities: bool) -> Value { let d = s.docs.get(i).map(|st| &st.doc); let warnings = d.map(|d| d.read_notes.clone()).unwrap_or_default(); + // Opened on the view it was saved at: a viewer keeps it instead of fitting the extents. + let saved_view = d.is_some_and(|d| crate::view::saved_view(d).is_some()); if entities { - json!({ "index": i, "entities": d.map(|d| d.entity_count()), "warnings": warnings }) + json!({ "index": i, "entities": d.map(|d| d.entity_count()), "warnings": warnings, "saved_view": saved_view }) } else { - json!({ "index": i, "warnings": warnings }) + json!({ "index": i, "warnings": warnings, "saved_view": saved_view }) } } @@ -777,7 +779,10 @@ const MODELER_TYPES: [&str; 3] = ["3DSOLID", "REGION", "BODY"]; const DWG_WRITES: [&str; 1] = ["OLE2FRAME"]; /// [`not_saved`] for a file saved as `version`. From 2013 on, a 3D solid, region or body the data -/// store has a record for keeps its geometry and is not counted; neither are [`DWG_WRITES`]. +/// store has a record for keeps its geometry and is not counted; neither are [`DWG_WRITES`], nor +/// another program's proxy entity whose class the file names: the DWG writes it with that class. +/// Before 2013, or when its group 91 names no class of the file, the DWG leaves the proxy out and +/// it is counted. pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap { let mut out: std::collections::BTreeMap = std::collections::BTreeMap::new(); let stored = if version >= Version::R2013 { d.foreign.data_store_entities() } else { Default::default() }; @@ -794,10 +799,21 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap if DWG_WRITES.contains(&u.dxf_type.as_str()) { continue; } + if version >= Version::R2013 && u.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") && d.foreign.proxy_class(&u.tags).is_some() { + continue; + } let n = out.entry(u.dxf_type.clone()).or_insert(0); *n = n.saturating_add(1); } } + // Another program's proxy objects (in the OBJECTS section) follow the same rule as its proxy + // entities: the DWG writer leaves them out before 2013, or when their class can't be named. + for o in d.foreign.objects.iter().filter(|o| o.kind.eq_ignore_ascii_case("ACAD_PROXY_OBJECT")) { + if version < Version::R2013 || d.foreign.proxy_class(&o.tags).is_none() { + let n = out.entry("ACAD_PROXY_OBJECT".to_string()).or_insert(0); + *n = n.saturating_add(1); + } + } out } diff --git a/crates/engine/src/cmd/file/compare.rs b/crates/engine/src/cmd/file/compare.rs index 295b472b1..5de5d8387 100644 --- a/crates/engine/src/cmd/file/compare.rs +++ b/crates/engine/src/cmd/file/compare.rs @@ -8,7 +8,7 @@ use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::sync::Arc; -use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, MAX_BLOCK_DEPTH, Space, entity_bounds}; +use cadcraft_doc::{BlockBoundsCache, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_DEPTH, Space, entity_bounds_cached}; use cadcraft_geom::{Bounds2, Vec2}; use serde_json::{Value, json}; @@ -110,7 +110,7 @@ fn other_drawing(s: &Session, p: &Value) -> Result<(Arc, String)> { fn read_path(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { - std::fs::read(_path).map_err(|e| bad("compare", format!("{_path}: {e}"))) + crate::capped_read::read_capped(std::path::Path::new(_path), super::MAX_DRAWING_BYTES).map_err(|e| bad("compare", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] Err(bad("compare", "paths are not available on the web: open the other drawing and compare with it by name (`document`)")) @@ -375,16 +375,20 @@ fn run_compare(s: &mut Session, p: &Value) -> Result { } let Diff { added, removed, changed, common, truncated } = diff(&cur, &other, &space); let mut boxes = Vec::new(); - let mut bound = |d: &Drawing, h: Handle| { - if let Some(b) = d.entity(h).map(|e| entity_bounds(d, e, 0)).filter(|b| !b.is_empty() && b.min.is_finite() && b.max.is_finite()) { + // One block-bounds cache for each drawing, so a block many differing entities refer to is + // measured once, not once per entity. + let (mut cur_cache, mut other_cache) = (BlockBoundsCache::default(), BlockBoundsCache::default()); + fn bound<'a>(boxes: &mut Vec, d: &'a Drawing, h: Handle, cache: &mut BlockBoundsCache<'a>) { + if let Some(b) = d.entity(h).map(|e| entity_bounds_cached(d, e, 0, cache)).filter(|b| !b.is_empty() && b.min.is_finite() && b.max.is_finite()) + { boxes.push(b); } - }; - added.iter().for_each(|h| bound(&cur, *h)); - removed.iter().for_each(|h| bound(&other, *h)); + } + added.iter().for_each(|h| bound(&mut boxes, &cur, *h, &mut cur_cache)); + removed.iter().for_each(|h| bound(&mut boxes, &other, *h, &mut other_cache)); for (a, b, _, _) in &changed { - bound(&cur, *a); - bound(&other, *b); + bound(&mut boxes, &cur, *a, &mut cur_cache); + bound(&mut boxes, &other, *b, &mut other_cache); } let regions = regions(&boxes); let ch: Vec = changed diff --git a/crates/engine/src/cmd/file/pgp.rs b/crates/engine/src/cmd/file/pgp.rs index 8981e5e83..9d39b751e 100644 --- a/crates/engine/src/cmd/file/pgp.rs +++ b/crates/engine/src/cmd/file/pgp.rs @@ -1,11 +1,16 @@ //! The user's command alias file (the publicly documented `.pgp` format: `ALIAS, *COMMAND` lines, //! `;` comments): ALIASEDIT and REINIT. //! -//! A loaded file adds aliases or overrides the built-in ones for the rest of the session, for -//! every drawing; command names themselves always win. Lines that define external commands +//! A loaded file replaces the user aliases, which add to or override the built-in ones for every +//! drawing; command names themselves always win. Lines that define external commands //! (programs the file would have the application start) are never run: they are skipped with a //! note. CADCraft ships no alias file; the aliases built into the command catalog stay the //! defaults. +//! +//! The aliases are user settings, never part of a drawing: [`alias_profile`] gives them (and the +//! file REINIT reads) to the host's user profile, and [`restore_aliases`] brings them back on the +//! next start. The desktop and web hosts keep that profile; the headless CLI has no profile, so +//! aliases set in a script last for that session only. use std::collections::BTreeMap; use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; @@ -20,10 +25,21 @@ use super::{CommandSpec, Result, Session, bad, bool_or, find_command}; pub const MAX_ALIASES: usize = 10_000; /// Longest alias name. const MAX_ALIAS_CHARS: usize = 64; +/// Longest command id (the catalog's longest is `texttofront.dimensions`; a test keeps it true). +const MAX_COMMAND_ID_CHARS: usize = 32; /// Longest line read. const MAX_LINE_CHARS: usize = 4096; /// Most warnings reported. const MAX_WARNINGS: usize = 100; +/// Longest alias file path kept in the user profile. +const MAX_ALIAS_FILE_CHARS: usize = 1024; + +/// The largest alias section [`alias_profile`] can produce: [`MAX_ALIASES`] entries, each a +/// [`MAX_ALIAS_CHARS`]-character name (up to four UTF-8 bytes per character, and JSON adds its +/// quotes) mapped to a command id, plus the alias file path and the section's keys. A host that +/// keeps the section in its user profile allows at least this much, so a full set always comes +/// back after a restart. +pub const MAX_ALIAS_PROFILE_BYTES: usize = MAX_ALIASES * (MAX_ALIAS_CHARS * 4 + MAX_COMMAND_ID_CHARS + 6) + MAX_ALIAS_FILE_CHARS * 4 + 64; #[derive(Default)] struct Aliases { @@ -206,3 +222,25 @@ pub(crate) fn specs() -> Vec { CommandSpec::new("reinit", "Reinitialize", run_reinit).params("{file? | text?} (default: the alias file loaded last)").enabled(always).noundo(), ] } + +#[cfg(test)] +mod tests { + use super::MAX_COMMAND_ID_CHARS; + + /// [`super::MAX_ALIAS_PROFILE_BYTES`] bounds a saved alias's command id by the longest id in + /// the catalog: keep that true as commands are added. + #[test] + fn every_command_id_fits_the_saved_alias_bound() { + for spec in crate::cmd::command_specs() { + assert!(spec.id.chars().count() <= MAX_COMMAND_ID_CHARS, "`{}` exceeds the alias profile bound", spec.id); + } + } + + /// An alias file path the profile couldn't restore isn't saved in it. + #[test] + fn only_paths_the_profile_restores_are_saved() { + assert!(super::keepable_path("C:\\support\\mine.pgp")); + assert!(!super::keepable_path(&"x".repeat(super::MAX_ALIAS_FILE_CHARS + 1))); + assert!(!super::keepable_path("mine\n.pgp")); + } +} diff --git a/crates/engine/src/cmd/file/template.rs b/crates/engine/src/cmd/file/template.rs index 11d6f2926..908e320a0 100644 --- a/crates/engine/src/cmd/file/template.rs +++ b/crates/engine/src/cmd/file/template.rs @@ -74,7 +74,7 @@ fn read_template(path: &str) -> Result { #[cfg(not(target_arch = "wasm32"))] fn read_bytes(path: &str) -> Result> { - std::fs::read(path).map_err(|e| bad("new", format!("template {path}: {e}"))) + crate::capped_read::read_capped(std::path::Path::new(path), super::MAX_DRAWING_BYTES).map_err(|e| bad("new", format!("template {path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index f6b519a3c..e4b497efe 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -786,10 +786,28 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { // Checked here for a clear error; the plotter resolves the names the same way. let sheets = p.get("layouts").map(|v| plot_sheets(cmd, s.doc()?, v)).transpose()?; + // `layout` and `layouts` must name the same sheet(s), or the reply would name one sheet and the render another. + if let (Some(n), Some(names)) = (str_param(p, "layout"), sheets.as_deref()) + && !matches!(names, [only] if only.eq_ignore_ascii_case(n)) + { + return Err(bad(cmd, "`layout` and `layouts` name different sheets; give only one of them")); + } + let is_image = p.get("output").and_then(Value::as_str).is_some_and(|o| o.eq_ignore_ascii_case("png") || o.eq_ignore_ascii_case("svg")); let space = match str_param(p, "layout") { Some(n) if n.eq_ignore_ascii_case("model") => Space::Model, Some(n) => Space::Paper(layout_name(cmd, s.doc()?, n)?), - None => s.space(), + // A PNG or SVG holds one render: a single `layouts` entry names the sheet to draw (the PDF + // path resolves `layouts` itself), not whatever space the session happens to show. + None => match sheets.as_deref() { + Some([only]) if is_image => { + if only.eq_ignore_ascii_case("model") { + Space::Model + } else { + Space::Paper(only.clone()) + } + } + _ => s.space(), + }, }; let mut opts = if p.is_object() { p.clone() } else { json!({}) }; if let Some(raw) = p.get("offset") { @@ -828,12 +846,17 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { None => o.remove("plotTransparency"), }; } + // A PNG or SVG holds one render: several sheets would report `pages: N` but write only one. + if is_image && sheets.as_ref().is_some_and(|names| names.len() > 1) { + return Err(bad(cmd, "`layouts` with several sheets needs PDF output; PNG and SVG hold one sheet, so plot each layout separately")); + } let bytes = hook(s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?; let layout = match &sheets { Some(names) => names.first().cloned().unwrap_or_default(), None => space.tab_name().to_string(), }; let pages = sheets.as_ref().map_or(1, Vec::len); + let format = opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).unwrap_or_else(|| "pdf".into()); match str_param(p, "path") { Some(_path) => { #[cfg(not(target_arch = "wasm32"))] @@ -843,17 +866,17 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { // `.cadcraft-tmp` symlink cannot redirect the plot write (CWE-59). let folder = super::file::new_folder(path); crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages }); + let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format }); super::file::report_new_folder(s, &mut r, folder); Ok(r) } #[cfg(target_arch = "wasm32")] { super::exchange::deliver_file(cmd, _path, &bytes, super::file::deliver())?; - Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages })) + Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })) } } - None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages })), + None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })), } } diff --git a/crates/engine/src/cmd/layout/plotstyle.rs b/crates/engine/src/cmd/layout/plotstyle.rs index d432343c2..d5d4f3b1c 100644 --- a/crates/engine/src/cmd/layout/plotstyle.rs +++ b/crates/engine/src/cmd/layout/plotstyle.rs @@ -303,11 +303,9 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { (None, Some(_path)) => { #[cfg(not(target_arch = "wasm32"))] { - let meta = std::fs::metadata(_path).map_err(|e| bad(cmd, format!("{_path}: {e}")))?; - if meta.len() > cadcraft_doc::MAX_TABLE_FILE as u64 { - return Err(bad(cmd, format!("{_path}: the plot style table file is too large"))); - } - std::fs::read_to_string(_path).map_err(|e| bad(cmd, format!("{_path}: {e}")))? + let bytes = crate::capped_read::read_capped(std::path::Path::new(_path), cadcraft_doc::MAX_TABLE_FILE) + .map_err(|e| bad(cmd, format!("{_path}: {e}")))?; + String::from_utf8(bytes).map_err(|e| bad(cmd, format!("{_path}: {e}")))? } #[cfg(target_arch = "wasm32")] return Err(bad(cmd, "files can't be read here: pass `text`")); diff --git a/crates/engine/src/cmd/layout/tests.rs b/crates/engine/src/cmd/layout/tests.rs index e8733786f..57d52a7ef 100644 --- a/crates/engine/src/cmd/layout/tests.rs +++ b/crates/engine/src/cmd/layout/tests.rs @@ -230,6 +230,24 @@ fn plot_goes_through_the_hook() { assert!(s.execute("plot", &json!({"layout": "Model", "plotArea": "window"})).is_err(), "window needs corners"); assert!(s.execute("plot", &json!({"layout": "Layout1", "plotArea": "display"})).is_err(), "layouts plot their sheet"); assert!(s.execute("plot", &json!({"layout": "Model", "scale": -1})).is_err()); + // Image output holds one sheet: several `layouts` would report pages:N but write one render. + for out in ["x.png", "x.svg"] { + let e = s.execute("plot", &json!({"path": out, "layouts": ["Layout1", "Layout2"]})).unwrap_err(); + assert!(e.to_string().contains("layouts"), "{e}"); + } + assert!(s.execute("plot", &json!({"output": "png", "layouts": ["Layout1", "Layout2"]})).is_err()); + // `layout` and `layouts` naming different sheets are refused (the reply would name one sheet and the render another); agreeing ones pass. + for p in + [json!({"output": "png", "layout": "Model", "layouts": ["Layout1"]}), json!({"output": "pdf", "layout": "Layout1", "layouts": ["Model"]})] + { + let e = s.execute("plot", &p).unwrap_err().to_string(); + assert!(e.contains("different"), "{e}"); + } + assert_eq!(s.execute("plot", &json!({"output": "png", "layout": "layout1", "layouts": ["Layout1"]})).unwrap()["layout"], "Layout1"); + let one = s.execute("plot", &json!({"output": "png", "layouts": ["Layout1"]})).unwrap(); + assert_eq!(one["layout"], "Layout1"); + let text = String::from_utf8(super::super::file::base64_decode(one["data"].as_str().unwrap()).unwrap()).unwrap(); + assert!(text.contains("Paper(\"Layout1\")"), "one sheet renders that layout, not the session space: {text}"); #[cfg(not(target_arch = "wasm32"))] { let path = std::env::temp_dir().join(format!("cadcraft-plot-test-{}.pdf", std::process::id())); @@ -307,3 +325,50 @@ fn plot_help_names_the_device_and_the_built_in_devices() { assert!(help.contains(name), "plot help lacks {name}"); } } + +/// The path's extension picks the plot format as EXPORT does, in any case; one that names no +/// format (or none) is refused instead of writing a PDF under that name, and a device that writes +/// another format is refused. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn plot_path_extension_picks_the_format_like_export() { + super::super::file::set_io(super::super::file::IoHooks { + read: |_, _| Err("no reader in tests".into()), + write: |_, _| Err("no writer in tests".into()), + plot: Some(fake_plot), + }); + if io().and_then(|h| h.plot).is_none() { + return; // another test installed hooks without a plotter first + } + let mut s = session_with_model(); + let dir = std::env::temp_dir().join(format!("cadcraft-plot-ext-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = |n: &str| dir.join(n).to_string_lossy().to_string(); + let upper = s.execute("plot", &json!({"path": path("X.PNG")})).unwrap(); + assert_eq!(upper["format"], "png", "an upper-case extension still picks png"); + let e = s.execute("plot", &json!({"path": path("x.txt")})).unwrap_err().to_string(); + assert!(e.contains("png") && e.contains("svg") && e.contains("pdf"), "{e}"); + assert!(!dir.join("x.txt").exists(), "nothing written under an unknown extension"); + let e = s.execute("plot", &json!({"path": path("noext")})).unwrap_err().to_string(); + assert!(e.contains("png") && e.contains("svg") && e.contains("pdf"), "{e}"); + assert!(!dir.join("noext").exists()); + let e = s.execute("plot", &json!({"path": path("y.png"), "device": "CADCraft PDF"})).unwrap_err().to_string(); + assert!(e.contains("writes pdf") && e.contains("png"), "{e}"); + // A device that resolves to none, or a null/unknown `output`, names no format: the refusal stands. + for p in [ + json!({"path": path("x.txt"), "device": "None"}), + json!({"path": path("x.txt"), "output": null}), + json!({"path": path("x.txt"), "output": "bogus"}), + ] { + let e = s.execute("plot", &p).unwrap_err().to_string(); + assert!(e.contains("png") && e.contains("svg") && e.contains("pdf"), "{e}"); + assert!(!dir.join("x.txt").exists(), "nothing written under an unknown extension"); + } + // An explicit output still decides for an odd name. + assert_eq!(s.execute("plot", &json!({"path": path("z.txt"), "output": "pdf"})).unwrap()["format"], "pdf"); + // But one that contradicts the extension is refused, as a device that does is (#2585 review). + let e = s.execute("plot", &json!({"path": path("w.png"), "output": "svg"})).unwrap_err().to_string(); + assert!(e.contains("svg") && e.contains("png"), "{e}"); + assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree"); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index f68d08ebb..367dacc65 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -35,7 +35,7 @@ use oops::run_oops; pub(crate) use oops::{Erased, erase_kept}; use select_then::{DisplaceM, Op, SelectThen}; use stretch::{StretchM, run_stretch}; -pub(crate) use transform::transform_entities; +pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities}; use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale}; pub(crate) use trim::{Edges, extend, trim}; @@ -86,7 +86,7 @@ pub fn specs() -> Vec { .menu(&["Modify", "Trim"]) .alias(&["tr"]) .params( - "{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"}", + "{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"} → {handles: the object (kept, reshaped) then the new pieces; none when it was erased} (pick) | {trimmed} (fence, crossing)", ) .interactive(|_| Ok(Box::new(TrimM::new(false)))), CommandSpec::new("extend", "Extend", trimextend::run_extend) @@ -112,9 +112,9 @@ pub fn specs() -> Vec { CommandSpec::new("break", "Break", run_break) .menu(&["Modify", "Break"]) .alias(&["br"]) - .params("{handle, p1, p2}") + .params("{handle, p1, p2} → {handles: the object (kept, reshaped) then the new pieces; none when nothing is left}") .interactive(|_| Ok(Box::new(BreakM::default()))), - CommandSpec::new("breakatpoint", "Break At Point", run_breakat).menu(&["Modify", "Break At Point"]).params("{handle, at}"), + CommandSpec::new("breakatpoint", "Break At Point", run_breakat).menu(&["Modify", "Break At Point"]).params("{handle, at} → {handles: the object (kept, reshaped) then the new piece}"), CommandSpec::new("join", "Join", run_join) .menu(&["Modify", "Join"]) .alias(&["j"]) diff --git a/crates/engine/src/cmd/modify/break_join.rs b/crates/engine/src/cmd/modify/break_join.rs index 74fd482a2..0309fe972 100644 --- a/crates/engine/src/cmd/modify/break_join.rs +++ b/crates/engine/src/cmd/modify/break_join.rs @@ -1,4 +1,4 @@ -use super::trim::{param_on, sub_polyline}; +use super::trim::{param_on, replace_with_pieces, sub_polyline}; use super::{ Accept, Arc, EngineError, Entity, EntityKind, Handle, Input, Interactive, Line, PolyVertex, Polyline, Prompt, Result, Segment, Session, Step, Value, Vec2, arc, bad, json, lwpoly, norm_angle, point_param, point_req, targets, @@ -105,19 +105,7 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re } _ => return Err(EngineError::Other("Cannot break that object.".into())), }; - let common = e.common.clone(); - let space = s.space(); - let d = s.doc_mut()?; - d.remove_entity(h); - let mut out = Vec::new(); - for k in pieces { - let nh = d.new_handle(); - if let Some(st) = d.space_mut(&space) { - st.push(Entity { handle: nh, common: common.clone(), kind: k }); - out.push(nh); - } - } - Ok(out) + replace_with_pieces(s, h, pieces) } pub(super) fn run_break(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 11e52ea23..df43f782c 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -5,6 +5,7 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, er // ---------------- core operations ---------------- pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result> { + refuse_ole_frames(s, hs, m, copy)?; edit_entities(s, hs, copy, |e| e.kind.transform(m)) } @@ -12,6 +13,7 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: /// and every height of the objects about its Z, their thickness too. pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, copy: bool) -> Result> { let m = Mat3::scale_about(base.xy(), f); + refuse_ole_frames(s, hs, &m, copy)?; edit_entities(s, hs, copy, |e| { e.kind.transform(&m); e.kind.scale_heights(base.z, f); @@ -19,6 +21,34 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, }) } +/// An OLE2FRAME only translates or scales uniformly (its corners stay axis aligned): refuse any other `m` before anything +/// changes, instead of reporting success and leaving the frame where it was. +pub(crate) fn refuse_ole_frames(s: &Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<()> { + if cadcraft_doc::ole_frame_accepts(m) || !holds_ole_frame(s, hs, copy)? { + return Ok(()); + } + Err(ole_refusal()) +} + +/// The refusal for a transform an OLE2FRAME cannot take. +pub(crate) fn ole_refusal() -> crate::EngineError { + crate::EngineError::Other( + "An OLE object can only be moved, copied or scaled uniformly; other transforms (rotation, mirroring, non-uniform scale, alignment) are not supported.".into(), + ) +} + +/// Whether `hs` holds an OLE2FRAME a transform would touch. An in-place edit (`copy` false) skips +/// an object on a locked layer (see edit_entities), so such a frame cannot be refused. +pub(crate) fn holds_ole_frame(s: &Session, hs: &[Handle], copy: bool) -> Result { + let d = s.doc()?; + Ok(hs.iter().any(|h| { + d.entity(*h).is_some_and(|e| { + let locked = !copy && d.layer(&e.common.layer).is_some_and(|l| l.locked); + !locked && matches!(&e.kind, cadcraft_doc::EntityKind::Unknown(u) if u.is_ole_frame()) + }) + })) +} + /// `p` at the current elevation (ELEVATION), the Z AutoCAD gives a point entered without one. pub(crate) fn at_elevation(s: &Session, p: Vec2) -> Vec3 { let z = s.doc().map(|d| d.header.f64("ELEVATION", 0.0)).ok().filter(|z| z.is_finite()); diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 9f8e856dd..437785acb 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -170,18 +170,46 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick)?, k => crate::cmd::modify2::trim_other(k, &cut, pick)?, }; - let common = e.common.clone(); - let space = s.space(); + replace_with_pieces(s, h, pieces) +} + +/// Put `pieces` in place of object `h` as AutoCAD 2024's BREAK and TRIM leave them: the first +/// piece (the one holding the object's start, or the only piece of a circle or closed polyline) +/// is the object itself, keeping its handle, its place in the drawing order, its groups and its +/// extended data; the others are new objects with its properties, added at the end of its space +/// (`entlast`); with no pieces the object is erased. Returns the pieces' handles. (A line broken +/// in its middle keeps its handle on the piece from its start point, the piece to its end point is +/// new; a circle broken or trimmed becomes an arc with the circle's handle.) +/// +/// Dimensions attached to the object follow [`crate::assoc::follow_pieces`]. Its parametric +/// constraints are removed: its new shape no longer meets them, and solving them again would move +/// the objects they tie it to. +pub(super) fn replace_with_pieces(s: &mut Session, h: Handle, pieces: Vec) -> Result> { let d = s.doc_mut()?; - d.remove_entity(h); - let mut out = Vec::new(); - for k in pieces { - let nh = d.new_handle(); + let mut pieces = pieces.into_iter(); + let Some(first) = pieces.next() else { + d.remove_entity(h); + return Ok(Vec::new()); + }; + let (Some(space), Some(old)) = (d.space_of(h), d.entity(h).cloned()) else { + return Err(EngineError::Other("no such object".into())); + }; + d.modify_entity(h, |e| e.kind = first)?; + let mut out = vec![h]; + for kind in pieces { + let handle = d.new_handle(); if let Some(st) = d.space_mut(&space) { - st.push(Entity { handle: nh, common: common.clone(), kind: k }); - out.push(nh); + st.push(Entity { handle, common: old.common.clone(), kind }); + out.push(handle); } } + crate::assoc::follow_pieces(d, &old.kind, &out); + let n = d.constraints.len(); + d.constraints.retain(|c| c.refs.iter().all(|r| r.handle != h)); + let removed = n - d.constraints.len(); + if removed > 0 { + s.echo(format!("{removed} constraint(s) of the broken or trimmed object removed.")); + } Ok(out) } diff --git a/crates/engine/src/cmd/modify2/mocoro.rs b/crates/engine/src/cmd/modify2/mocoro.rs index c701e24ae..6954919bf 100644 --- a/crates/engine/src/cmd/modify2/mocoro.rs +++ b/crates/engine/src/cmd/modify2/mocoro.rs @@ -16,7 +16,7 @@ use super::other; use crate::cmd::curves::KW; use crate::cmd::helpers::line; use crate::cmd::machines::{SelOutcome, SelectPhase, number}; -use crate::cmd::modify::transform_entities; +use crate::cmd::modify::{refuse_ole_frames, transform_entities}; use crate::cmd::{bad, point_req, point_value, targets}; use crate::prompt::Drag; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; @@ -108,6 +108,21 @@ pub(super) fn run_mocoro(s: &mut Session, p: &Value) -> Result { } // Every option is checked before the drawing changes. let ops = list.iter().enumerate().map(|(i, v)| parse_op(i, v)).collect::>>()?; + // An OLE frame only translates or scales uniformly: a rotate step (or any step) that would refuse it must do so before an + // earlier move or copy changes the drawing (a refused command is not rolled back). + for op in &ops { + match *op { + Op::Rotate(a) => refuse_ole_frames(s, &objs, &Mat3::rotate_about(base, a), false)?, + Op::Scale(f) => refuse_ole_frames(s, &objs, &Mat3::scale_about(base, f), false)?, + _ => {} + } + } + // Each Copy clones every selected object: the copies together stay within MAXARRAY, as an array's do. + // Erased handles are skipped by `apply`, so only live objects count (none: nothing is copied). + let live = counts(s, &objs)?.0; + if live > 0 { + crate::cmd::array::check_size(s, ops.iter().filter(|o| matches!(o, Op::Copy(_))).count() as u64, live)?; + } let mut copies = Vec::new(); for op in ops { copies.extend(apply(s, &objs, &mut base, op)?); @@ -141,6 +156,12 @@ pub(super) struct MocoroM { impl MocoroM { fn run(&mut self, s: &mut Session, op: Op) -> Result { + if matches!(op, Op::Copy(_)) { + let live = counts(s, &self.objs)?.0; + if live > 0 { + crate::cmd::array::check_size(s, 1, live)?; + } + } let before = s.state()?.doc.clone(); let base = self.base; apply(s, &self.objs, &mut self.base, op)?; diff --git a/crates/engine/src/cmd/modify2/patharray.rs b/crates/engine/src/cmd/modify2/patharray.rs index 3f9445249..f06c85701 100644 --- a/crates/engine/src/cmd/modify2/patharray.rs +++ b/crates/engine/src/cmd/modify2/patharray.rs @@ -34,15 +34,26 @@ pub(crate) fn arraypath( _ => (6, if c.closed { l / 6.0 } else { l / 5.0 }), }; crate::cmd::array::check_size(s, n as u64, objs.len())?; - let Some((p0, t0)) = c.at_length(0.0) else { return Ok(Vec::new()) }; - let mut out = Vec::new(); + // Segment end lengths once: each sample is then a binary search, not a scan from the start. + let ends = c.end_lengths(); + let Some((p0, t0)) = c.at_length_in(&ends, 0.0) else { return Ok(Vec::new()) }; + let mut mats = Vec::new(); for i in 1..n { - let Some((p, t)) = c.at_length(step * i as f64) else { continue }; + let Some((p, t)) = c.at_length_in(&ends, step * i as f64) else { continue }; let mut m = Mat3::translate(p - p0); if align { m = Mat3::rotate_about(p, t.angle() - t0.angle()).then_before(m); } - out.extend(crate::cmd::modify::transform_entities(s, &objs, &m, true)?); + mats.push(m); + } + // Every copy is checked before the first is made: a refusal part way would leave the copies + // already added in the drawing (a failed command is not rolled back). + if mats.iter().any(|m| !cadcraft_doc::ole_frame_accepts(m)) && crate::cmd::modify::holds_ole_frame(s, &objs, true)? { + return Err(crate::cmd::modify::ole_refusal()); + } + let mut out = Vec::new(); + for m in &mats { + out.extend(crate::cmd::modify::transform_entities(s, &objs, m, true)?); } Ok(out) } diff --git a/crates/engine/src/cmd/modify2/textedit.rs b/crates/engine/src/cmd/modify2/textedit.rs index 10ca46245..081737a7b 100644 --- a/crates/engine/src/cmd/modify2/textedit.rs +++ b/crates/engine/src/cmd/modify2/textedit.rs @@ -11,6 +11,8 @@ fn text_of(k: &EntityKind) -> Option { EntityKind::Text(t) => Some(t.value.clone()), EntityKind::AttDef(a) => Some(a.text.value.clone()), EntityKind::MText(t) => Some(t.contents.replace("\\P", "\n")), + // A multileader's text (one with a block instead has none, #1081). + EntityKind::MLeader(m) => m.text.as_ref().map(|t| t.contents.replace("\\P", "\n")), EntityKind::Dimension(d) => Some(if d.text.is_empty() { "<>".into() } else { d.text.clone() }), _ => None, } @@ -25,11 +27,16 @@ pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { EntityKind::Text(t) => t.value = text.to_string(), EntityKind::AttDef(a) => a.text.value = text.to_string(), EntityKind::MText(t) => t.contents = text.replace('\n', "\\P"), + EntityKind::MLeader(m) if m.text.is_some() => { + if let Some(t) = &mut m.text { + t.contents = text.replace('\n', "\\P"); + } + } EntityKind::Dimension(d) => { d.text = if text == "<>" { String::new() } else { text.to_string() }; d.block = None; } - _ => return Err(other("Select a text, mtext, attribute definition or dimension.")), + _ => return Err(other("Select a text, mtext, multileader, attribute definition or dimension.")), } set_kind(s, h, k) } @@ -53,12 +60,18 @@ 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, } impl Interactive for TextEditM { fn name(&self) -> &'static str { "TEXTEDIT" } + /// An MTEXT asking for its new text opens in the in-place editor with its contents. + fn editing_mtext(&self) -> Option { + self.h.as_ref().and(self.mtext.clone()) + } fn prompt(&self, _s: &Session) -> Prompt { if self.mode { let current = if self.single { "Single" } else { "Multiple" }; @@ -83,7 +96,24 @@ impl Interactive for TextEditM { match (&self.h, i) { (None, Input::Point(p)) => { let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?; - let old = text_of(&curves::entity(s, h)?.kind).ok_or_else(|| other("Select a text, mtext, attribute definition or dimension."))?; + // Refused when picked, not after the new text has been typed. + 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, + }; + // 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; + s.echo("This text is too long for the editor; enter the new text at the command line."); + } self.h = Some((h, old)); Ok(Step::Continue) } @@ -93,10 +123,12 @@ impl Interactive for TextEditM { set_text(s, h, &t)?; self.edits.push((h, before)); self.h = None; + self.mtext = None; Ok(if self.single { Step::Done } else { Step::Continue }) } (Some(_), Input::Enter) => { self.h = None; + self.mtext = None; Ok(if self.single { Step::Done } else { Step::Continue }) } (None, Input::Enter) => Ok(Step::Done), diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index 95ead78fc..457a098b4 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -265,6 +265,11 @@ pub fn page_device(cmd: &str, p: &Value, page: &mut PageSetup) -> Result { Ok(false) } +/// The output a path's extension (any case) asks for: png, svg or pdf; other extensions ask for none. +fn path_output(path: &str) -> Option { + PlotOutput::parse(&std::path::Path::new(path).extension()?.to_string_lossy()) +} + /// The options PLOT / EXPORTPDF hand the plotter with `device` and the device's papers /// resolved: `device` (else the layout's page setup device) picks the output (`output`: pdf, /// png or svg; EXPORTPDF always writes PDF) and `resolution`; a paper of the device becomes @@ -286,9 +291,42 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result { None => layout.as_ref().and_then(|pg| find_device(&pg.device)), }; let mut out = if p.is_object() { p.clone() } else { json!({}) }; - let (Some(dev), Some(o)) = (dev, out.as_object_mut()) else { return Ok(out) }; + // The path's extension names the format, like EXPORT, unless a device is given; a given + // device that writes another format is refused. EXPORTPDF always writes PDF. + let by_path = if cmd == "exportpdf" { None } else { str_param(p, "path").and_then(path_output) }; + // A path whose extension names no format (or has none) would hold a PDF under that name: + // refuse it, as EXPORT does, unless `output` or a device says what to write. + if cmd == "plot" + && by_path.is_none() + && !p.get("output").and_then(Value::as_str).is_some_and(|o| PlotOutput::parse(o).is_some()) + && !(dev.is_some() && given.is_some_and(|n| !n.is_empty())) + && let Some(path) = str_param(p, "path") + { + return Err(bad( + cmd, + format!("can't tell the format of `{path}`: give a path ending in .png, .svg or .pdf, or set `output` to png, svg or pdf"), + )); + } + if let (Some(want), Some(dev), true) = (by_path, &dev, given.is_some_and(|n| !n.is_empty())) + && dev.output != want + { + return Err(bad(cmd, format!("plotter `{}` writes {}, but the path asks for {}", dev.name, dev.output.as_str(), want.as_str()))); + } + // An `output` that says another format than the path's extension is refused too, as a device + // that does is: either way the file would not hold what its name says. + if let (Some(want), Some(asked)) = (by_path, p.get("output").and_then(Value::as_str).and_then(PlotOutput::parse)) + && asked != want + { + return Err(bad(cmd, format!("`output` is {}, but the path asks for {}", asked.as_str(), want.as_str()))); + } + let (Some(dev), Some(o)) = (dev, out.as_object_mut()) else { + if let (Some(want), Some(o)) = (by_path, out.as_object_mut()) { + o.insert("output".into(), json!(want.as_str())); + } + return Ok(out); + }; o.remove("device"); - let output = if cmd == "exportpdf" { PlotOutput::Pdf } else { dev.output }; + let output = if cmd == "exportpdf" { PlotOutput::Pdf } else { by_path.unwrap_or(dev.output) }; o.insert("output".into(), json!(output.as_str())); o.insert("resolution".into(), json!(dev.resolution)); let paper = match str_param(p, "paper") { diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 018e2dbf6..bbe6847d0 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -10,7 +10,7 @@ mod rename; pub use matchprop::MatchProps; use cadcraft_color::Color; -use cadcraft_doc::{EntityKind, Lineweight, Transparency}; +use cadcraft_doc::{EntityKind, Handle, Lineweight, Transparency}; use cadcraft_geom::Vec3; use serde_json::{Value, json}; @@ -21,9 +21,9 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; pub fn specs() -> Vec { vec![ CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(), - CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)}"), - CommandSpec::new("chprop", "Change Properties", chprop::run_chprop) - .params("as properties.set, leaving out objects on locked layers → {changed, locked} (the command line asks Color, LAyer, LType, ltScale, LWeight, Thickness and TRansparency in turn)") + CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)} → {changed, locked, message?}: objects on locked layers (and, during REFEDIT, outside the working set) are left out, and `message` says how many"), + CommandSpec::new("chprop", "Change Properties", run_set) + .params("as properties.set, leaving out objects on locked layers (and, during REFEDIT, outside the working set) → {changed, locked, message?} (the command line asks Color, LAyer, LType, ltScale, LWeight, Thickness and TRansparency in turn)") .interactive(|_| Ok(Box::new(chprop::ChpropM::new()))), CommandSpec::new("change", "Change", change::run_change) .alias(&["-ch"]) @@ -196,11 +196,74 @@ fn set_xy(p: &mut Vec3, v: &Value) { } } +/// The objects `properties.set` leaves alone, as CHPROP, MATCHPROP and MOVE do: those on locked +/// layers and, while a reference is edited in place, those outside the working set. +#[derive(Default)] +struct LeftOut { + locked: usize, + outside: usize, +} + +impl LeftOut { + /// `hs` without the objects that can't be edited, each object once, and how many those were. A + /// handle that names no object is an error, before anything changes. + fn split(s: &Session, hs: Vec) -> Result<(Vec, LeftOut)> { + let d = s.doc()?; + // The working set, once: `RefEdit::is_working` searches a list. + let working: Option> = d.refedit.as_ref().map(|r| r.items.iter().map(|i| i.copy).collect()); + let mut seen = std::collections::HashSet::new(); + let mut out = LeftOut::default(); + let mut free = Vec::new(); + for h in hs { + let Some(e) = d.entity(h) else { + return Err(cadcraft_doc::DocError::NoEntity(h).into()); + }; + if !seen.insert(h) { + continue; + } + if working.as_ref().is_some_and(|w| !w.contains(&h)) { + out.outside += 1; + } else if d.layer(&e.common.layer).is_some_and(|l| l.locked) { + out.locked += 1; + } else { + free.push(h); + } + } + Ok((free, out)) + } + + /// `{changed, locked}`, and a message saying how many were left out when any were. + fn result(&self, changed: usize) -> Value { + let mut notes = Vec::new(); + match self.locked { + 0 => {} + 1 => notes.push("1 object was on a locked layer.".to_string()), + n => notes.push(format!("{n} objects were on a locked layer.")), + } + match self.outside { + 0 => {} + 1 => notes.push("1 object was not in the working set.".to_string()), + n => notes.push(format!("{n} objects were not in the working set.")), + } + if changed == 0 && !notes.is_empty() { + notes.push("Nothing was changed.".to_string()); + } + let mut r = json!({ "changed": changed, "locked": self.locked + self.outside }); + if !notes.is_empty() + && let Some(o) = r.as_object_mut() + { + o.insert("message".into(), json!(notes.join(" "))); + } + r + } +} + fn run_set(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; if hs.is_empty() { return Err(bad("properties.set", "nothing selected")); } + let (hs, left_out) = LeftOut::split(s, hs)?; let color = p.get("color").map(|c| parse_color(c).ok_or_else(|| bad("properties.set", "bad colour"))).transpose()?; let transparency = p .get("transparency") @@ -211,7 +274,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { .map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number"))) .transpose()?; let lw = p.get("lineweight").map(|v| super::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?; - let d = s.doc_mut()?; + let d = s.doc()?; // An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires). let linetype = str_param(p, "linetype") .map(|n| { @@ -222,13 +285,18 @@ fn run_set(s: &mut Session, p: &Value) -> Result { } }) .transpose()?; - if let Some(l) = str_param(p, "layer") { - d.ensure_layer(l); - } let dim_style = str_param(p, "dimStyle") .map(|n| d.dim_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("dimension style `{n}` not found")))) .transpose()?; let dim_over = dim_overrides(p)?; + if hs.is_empty() { + // Every object was left out: the drawing stays as it was, with no undo step. + return Ok(left_out.result(0)); + } + let d = s.doc_mut()?; + if let Some(l) = str_param(p, "layer") { + d.ensure_layer(l); + } let anno_scale = d.current_anno_scale(); let common = CommonEntityProperties { anno_scale: &anno_scale, color, linetype: linetype.as_deref(), lineweight: lw, transparency, thickness }; for h in &hs { @@ -237,7 +305,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { apply_kind_properties(e, p, dim_style.as_ref(), &dim_over); })?; } - Ok(json!({ "changed": hs.len() })) + Ok(left_out.result(hs.len())) } fn apply_kind_properties( @@ -334,6 +402,17 @@ fn apply_kind_properties( t.rotation = x.to_radians(); } } + // A multileader's text: its contents (#1081) and height. + EntityKind::MLeader(m) => { + if let Some(t) = &mut m.text { + if let Some(v) = str_param(params, "text") { + t.contents = v.replace('\n', "\\P"); + } + if let Some(x) = num("height").filter(|x| *x > 0.0) { + t.height = x; + } + } + } EntityKind::LwPolyline(pl) => { if let Some(x) = num("width").filter(|x| *x >= 0.0) { pl.const_width = x; diff --git a/crates/engine/src/cmd/props/chprop.rs b/crates/engine/src/cmd/props/chprop.rs index fac500ecd..50fb94597 100644 --- a/crates/engine/src/cmd/props/chprop.rs +++ b/crates/engine/src/cmd/props/chprop.rs @@ -23,7 +23,6 @@ use serde_json::{Value, json}; use super::super::curves::{KW, is_locked}; use super::super::machines::{SelOutcome, SelectPhase, number}; -use super::super::targets; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; const PROPERTIES: [&str; 7] = ["Color", "LAyer", "LType", "ltScale", "LWeight", "Thickness", "TRansparency"]; @@ -90,13 +89,18 @@ impl ChpropM { if vals.all(|v| v == first) { first } else { "varies".into() } } - /// Apply `props` to the selection through `properties.set`. + /// Apply `props` to the selection through `properties.set`, saying what it left out: objects + /// this command moved onto a locked layer, say. fn apply(&self, s: &mut Session, props: Value) -> Result<()> { let mut p = json!({ "handles": self.handles.iter().map(|h| h.hex()).collect::>() }); if let (Some(p), Value::Object(props)) = (p.as_object_mut(), props) { p.extend(props); } - super::run_set(s, &p).map(|_| ()) + let r = super::run_set(s, &p)?; + if let Some(m) = r.get("message").and_then(Value::as_str) { + s.echo(m.to_string()); + } + Ok(()) } /// Take an answer to `ask`; `false` when it was refused (the prompt comes again). @@ -237,33 +241,6 @@ pub(super) fn feed_unlocked(select: &mut SelectPhase, s: &mut Session, i: Input) Ok(outcome) } -/// CHPROP's JSON form: `properties.set` on the objects that are not on locked layers, which the -/// command leaves out too; "locked" says how many were. -pub(super) fn run_chprop(s: &mut Session, p: &Value) -> Result { - let hs = targets(s, p)?; - let locked = locked(s, &hs); - if locked.is_empty() { - return super::run_set(s, p).map(|r| with_locked(r, 0)); - } - let free: Vec = hs.into_iter().filter(|h| !locked.contains(h)).collect(); - let r = if free.is_empty() { - json!({ "changed": 0 }) - } else { - let mut q = p.as_object().cloned().unwrap_or_default(); - q.insert("handles".into(), json!(free.iter().map(|h| h.hex()).collect::>())); - super::run_set(s, &Value::Object(q))? - }; - Ok(with_locked(r, locked.len())) -} - -/// `r` with how many objects were left out on locked layers. -fn with_locked(mut r: Value, n: usize) -> Value { - if let Some(o) = r.as_object_mut() { - o.insert("locked".into(), json!(n)); - } - r -} - /// A colour typed at CHPROP: 1–255, a name, BYLAYER or BYBLOCK (not 0 or 256, which COLOR takes). fn color(t: &str) -> Option { if t.bytes().all(|b| b.is_ascii_digit()) { diff --git a/crates/engine/src/cmd/qselect.rs b/crates/engine/src/cmd/qselect.rs index 2c5330371..469a0895f 100644 --- a/crates/engine/src/cmd/qselect.rs +++ b/crates/engine/src/cmd/qselect.rs @@ -175,8 +175,14 @@ pub fn compare(prop: &Value, op: Op, value: &Value) -> bool { if ptxt.eq_ignore_ascii_case(vtxt.trim()) { return true; } - // Colours: `red` = `1` = `Red`; `bylayer` = `ByLayer`. - match (Color::parse(&ptxt), Color::parse(vtxt.trim())) { + // Colours: `red` = `1` = `Red`; `bylayer` = `ByLayer`. No colour spelling is long, so a + // long text (a layer name from a file) isn't parsed, copied and split per entity. + const MAX_COLOR_TEXT: usize = 64; + let (pc, vc) = (ptxt.trim(), vtxt.trim()); + if pc.len() > MAX_COLOR_TEXT || vc.len() > MAX_COLOR_TEXT { + return false; + } + match (Color::parse(pc), Color::parse(vc)) { (Some(a), Some(b)) => a == b, _ => false, } @@ -400,3 +406,26 @@ mod tests { assert!(!wildcard(&"*a".repeat(500), &"b".repeat(4000))); } } + +#[cfg(test)] +mod long_text_tests { + use super::*; + + /// A long string property is compared as text only, and a colour name still equals its index. + #[test] + fn long_values_skip_colour_parsing() { + let long = Value::String("x".repeat(100_000)); + assert!(compare(&long, Op::Eq, &long)); + assert!(!compare(&long, Op::Eq, &Value::String("red".into()))); + assert!(compare(&Value::String("red".into()), Op::Eq, &Value::String("1".into()))); + } + + /// Padding is trimmed before the length limit, so a padded colour still matches. + #[test] + fn padded_colours_still_match() { + let padded = |c: &str| Value::String(format!("{}{c}{}", " ".repeat(100), " ".repeat(100))); + assert!(compare(&padded("red"), Op::Eq, &Value::String("1".into()))); + assert!(compare(&Value::String("red".into()), Op::Eq, &padded("1"))); + assert!(!compare(&padded("red"), Op::Ne, &padded("1"))); + } +} diff --git a/crates/engine/src/cmd/table/breaks.rs b/crates/engine/src/cmd/table/breaks.rs index 6f207ec50..206ac1ef0 100644 --- a/crates/engine/src/cmd/table/breaks.rs +++ b/crates/engine/src/cmd/table/breaks.rs @@ -12,7 +12,7 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; /// Largest linked file read (bytes). #[cfg(not(target_arch = "wasm32"))] -const MAX_LINK_BYTES: u64 = 8 << 20; +const MAX_LINK_BYTES: usize = 8 << 20; pub fn specs() -> Vec { vec![ @@ -238,11 +238,9 @@ fn read_link(id: &str, file: &std::path::Path) -> Result { let path = file.display(); #[cfg(not(target_arch = "wasm32"))] { - let meta = std::fs::metadata(file).map_err(|e| bad(id, format!("{path}: {e}")))?; - if meta.len() > MAX_LINK_BYTES { - return Err(bad(id, format!("{path}: larger than {} MB", MAX_LINK_BYTES >> 20))); - } - let bytes = std::fs::read(file).map_err(|e| bad(id, format!("{path}: {e}")))?; + // The limit is enforced on the bytes read, not on reported metadata, so a device or FIFO + // that misreports its length can't be buffered to EOF. + let bytes = crate::capped_read::read_capped(file, MAX_LINK_BYTES).map_err(|e| bad(id, format!("{path}: {e}")))?; let text = String::from_utf8_lossy(&bytes); Ok(text.strip_prefix('\u{feff}').unwrap_or(&text).to_owned()) } @@ -370,6 +368,16 @@ fn run_update(s: &mut Session, p: &Value) -> Result { mod tests { use super::*; + /// A linked path naming an endless device is refused instead of buffered to EOF. + #[cfg(all(unix, not(target_arch = "wasm32")))] + #[test] + fn link_to_endless_device_is_rejected() { + let dev = std::path::Path::new("/dev/zero"); + if dev.exists() { + assert!(read_link("datalink", dev).is_err()); + } + } + #[test] fn csv_parsing() { assert_eq!(parse_csv("a,b\r\n\"c,d\",\"e\"\"f\"\n", ','), vec![vec!["a", "b"], vec!["c,d", "e\"f"]]); diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index ab03d5c31..eab957589 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -36,7 +36,7 @@ fn misses_edges(e: &EngineError) -> bool { } /// Trim or extend `h` at `at`. A Quick-mode (`quick`) trim of an object no cutting edge crosses -/// erases it. Returns the handles that replace `h` (none when it was erased). +/// erases it. Returns what `h` became: its pieces, `h` itself first (none when it was erased). fn apply(s: &mut Session, h: Handle, at: Vec2, extending: bool, edges: Edges, quick: bool) -> Result> { if extending { extend(s, h, at, edges)?; @@ -118,8 +118,8 @@ fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, qu run_picks(s, work, extending, edges, quick, tol) } -/// Trim (or extend) each object at its pick points. A trim replaces the object with pieces, so -/// later picks go to the piece within `tol` of the point (none: that part is already gone). +/// Trim (or extend) each object at its pick points. A trim leaves the object in pieces, so later +/// picks go to the piece within `tol` of the point (none: that part is already gone). fn run_picks(s: &mut Session, work: Vec<(Handle, Vec)>, extending: bool, edges: Edges, quick: bool, tol: f64) -> Result { let mut n = 0; let mut last_err = None; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 139c5c339..662c68a8b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -28,6 +28,7 @@ pub mod mtext_edit; pub mod pointmod; pub mod prompt; mod recent; +pub mod render_look; pub mod sample; pub mod select; pub mod settings_dir; diff --git a/crates/engine/src/lisp.rs b/crates/engine/src/lisp.rs index 977d4f551..4d95faf77 100644 --- a/crates/engine/src/lisp.rs +++ b/crates/engine/src/lisp.rs @@ -123,6 +123,12 @@ pub struct LispState { acad_loaded: bool, /// Memory caps (lowered by tests). pub(crate) limits: Limits, + /// Interpreter steps all synchronous callbacks have run, nested ones included. A callback's + /// allowance counts what ran since it started, so the callbacks it calls spend its steps. + pub(crate) callback_used: u64, + /// The `callback_used` value the callback running now (and so every one it calls) must not + /// pass: the lowest of its own and its callers' allowances. + pub(crate) callback_ceiling: Option, } /// What U and REDO inside the running routine take back: the commands it ran, each as the drawing @@ -415,9 +421,12 @@ impl Session { /// Move printed text to the command history: complete lines, and with `all` the rest too. fn lisp_flush(&mut self, env: &mut Env, all: bool) { - while let Some(i) = env.out.find('\n') { - let line: String = env.out.drain(..=i).collect(); - let line = line.trim_end_matches(['\n', '\r']).to_string(); + // One pass over the buffer, dropping the printed lines once at the end: draining each line + // from the front shifted the rest every time, quadratic in newline-dense output. + let mut done = 0; + while let Some(i) = env.out.get(done..).and_then(|rest| rest.find('\n')) { + let line = env.out.get(done..done + i).unwrap_or_default().trim_end_matches('\r').to_string(); + done += i + 1; // `(princ "\nText")` after a prompt or a command's echo ends that line instead of // leaving an empty one; after LISP's own line it does print an empty line. if line.is_empty() && env.printed_at != Some(self.log.len()) { @@ -427,6 +436,7 @@ impl Session { self.echo(line); env.printed_at = Some(self.log.len()); } + env.out.drain(..done); if all && !env.out.is_empty() { let line = std::mem::take(&mut env.out); self.echo(line); diff --git a/crates/engine/src/lisp/builtins/strings.rs b/crates/engine/src/lisp/builtins/strings.rs index 853e0656f..362183bd2 100644 --- a/crates/engine/src/lisp/builtins/strings.rs +++ b/crates/engine/src/lisp/builtins/strings.rs @@ -1,5 +1,5 @@ use super::args::{R, arity, int, list_arg, string}; -use super::{LispError, OsStr, Value, check_string_len, read, to_text}; +use super::{LispError, OsStr, Value, charge_bytes, check_string_len, read, to_text}; // ---------------- strings ---------------- @@ -114,7 +114,13 @@ pub(super) fn read_fn(a: &[Value]) -> R { arity(a, 0, 1)?; match a.first() { None | Some(Value::Nil) => Ok(Value::Nil), - Some(v) => read::read_one(&string(v)?), + Some(v) => { + // The strings in the list it makes are new, each as long as its text at most: the + // text is charged, though a list result isn't inspected by `charge_result`. + let text = string(v)?; + charge_bytes(text.len())?; + read::read_one(&text) + } } } diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 238551094..d1ef57447 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -179,7 +179,12 @@ fn to_json_bounded(v: &Value, depth: usize, budget: &mut u64) -> Option serde_json::Value::Null, Value::Int(i) => serde_json::json!(i), Value::Real(r) => serde_json::json!(r), - Value::Str(s) => serde_json::json!(&**s), + Value::Str(s) => { + // A string is copied whole each time it occurs: it spends the allowance by its length + // (one unit per 16 bytes, so about 32 MB in all), shared or not. + *budget = budget.checked_sub(s.len() as u64 / 16)?; + serde_json::json!(&**s) + } Value::Cons(_) => { let mut arr = Vec::new(); for x in v.iter() { @@ -296,12 +301,16 @@ fn groups_to_list(tags: &[Tag]) -> Vec { out } +/// The most string bytes an entity list may hold (counted per occurrence, shared or not). +const MAX_GROUP_TEXT: usize = 32 << 20; + /// An association list back to DXF groups (points split into x, y, z groups). The type /// (`0`), the entity name (`-1`), the handle (`5`), the owner (`330`) and the layout (`410`) are /// left out: they aren't the entity's to set. fn list_to_groups(list: &Value) -> Result<(String, Vec), LispError> { let mut kind = None; let mut tags = Vec::new(); + let mut text_left = MAX_GROUP_TEXT; for item in list.iter() { let Value::Cons(c) = &item else { return Err(LispError::bad_arg("listp", &item)) }; let Value::Int(code) = c.car else { return Err(LispError::bad_arg("fixnump", &c.car)) }; @@ -323,7 +332,11 @@ fn list_to_groups(list: &Value) -> Result<(String, Vec), LispError> { _ => tags.push(match &v { Value::Int(i) => Tag::i(code, i64::from(*i)), Value::Real(r) => Tag::f(code, *r), - Value::Str(s) => Tag::s(code, &**s), + Value::Str(s) => { + // Each occurrence of a shared string becomes its own copy in the tag. + text_left = text_left.checked_sub(s.len()).ok_or_else(|| LispError::new("out of memory: the entity list holds too much text"))?; + Tag::s(code, &**s) + } Value::Ename(h) => Tag::s(code, h.hex()), other => return Err(LispError::bad_arg("DXF group value", other)), }), @@ -1125,3 +1138,27 @@ pub fn load_source(s: &Session, name: &str) -> Option { s.lisp_support_dir().map(|d| candidates.iter().map(|c| d.join(c).to_string_lossy().into_owned()).collect::>()).unwrap_or_default(); candidates.iter().chain(&support).find_map(super::builtins::read_text_file) } + +#[cfg(test)] +mod budget_tests { + use super::*; + + /// One 64 KB string occurring many times is charged by its length each time. + #[test] + fn shared_strings_spend_the_conversion_budgets() { + let big = Value::str(&"x".repeat(64 << 10)); + // 600 x 64 KB is over the 32 MiB an entity list may hold; 100 x 64 KB is not. + let list = |n: usize| { + let mut items = vec![Value::cons(Value::Int(0), Value::str("TEXT"))]; + items.extend(std::iter::repeat_n(Value::cons(Value::Int(1), big.clone()), n)); + Value::list(items) + }; + assert!(list_to_groups(&list(600)).is_err()); + assert!(list_to_groups(&list(100)).is_ok()); + // 1,000 x 64 KB is 4,096,000 units of the 2,000,000 SETVAR allows; 100 x 64 KB is not. + let mut budget = TO_JSON_BUDGET; + assert!(to_json_bounded(&Value::list(vec![big.clone(); 1_000]), 0, &mut budget).is_none()); + let mut budget = TO_JSON_BUDGET; + assert!(to_json_bounded(&Value::list(vec![big; 100]), 0, &mut budget).is_some()); + } +} diff --git a/crates/engine/src/lisp/eval.rs b/crates/engine/src/lisp/eval.rs index 3101b3933..dc7bb0719 100644 --- a/crates/engine/src/lisp/eval.rs +++ b/crates/engine/src/lisp/eval.rs @@ -201,6 +201,10 @@ impl Machine { if n > budget { return Outcome::Wait(Need::Yield); } + // Charge a callback's step as it runs, so callbacks it calls see what it already spent. + if ctx.depth > 0 { + ctx.s.lisp.callback_used = ctx.s.lisp.callback_used.saturating_add(1); + } let r = match std::mem::replace(&mut self.state, State::Ret(Value::Nil)) { State::Eval(expr) => self.eval(ctx, expr), State::Call(f, args) => self.call(ctx, f, args), @@ -646,29 +650,44 @@ impl Ctx<'_> { super::value::charge_result(&v)?; return Ok(v); } + let cap = self.s.lisp.limits.callback_steps; + let start = self.s.lisp.callback_used; + // This callback may run until `callback_used` reaches `ceiling`: `cap` steps from now, or + // sooner where a caller's allowance ends, so callbacks nested in callbacks share one + // allowance instead of each taking a fresh one (an exponential tree otherwise). + let outer = self.s.lisp.callback_ceiling; + let ceiling = start.saturating_add(cap).min(outer.unwrap_or(u64::MAX)); + self.s.lisp.callback_ceiling = Some(ceiling); + let r = self.drive_callback(f, args, ceiling); + self.s.lisp.callback_ceiling = outer; + r + } + + /// Run callback `f` in slices until it finishes or `callback_used` reaches `ceiling`. + fn drive_callback(&mut self, f: &Value, args: Vec, ceiling: u64) -> Result { let cap = self.s.lisp.limits.callback_steps; let mut m = Machine::calling(f.clone(), args); let mut sub = Ctx { s: &mut *self.s, env: &mut *self.env, depth: self.depth + 1 }; // Drive the callback in bounded slices instead of granting it `u64::MAX` fuel. A `Yield` - // (the step budget ran out) is retried until a hard cap, so a constant-memory infinite + // (the step budget ran out) is retried until the ceiling, so a constant-memory infinite // loop inside a comparator or predicate terminates with an error rather than hanging the - // thread and bypassing the blocking execution cap (CWE-400). - let mut spent: u64 = 0; + // thread and bypassing the blocking execution cap (CWE-400). The steps of callbacks this + // one calls are counted in `callback_used` too. loop { - let remaining = cap.saturating_sub(spent); + let remaining = ceiling.saturating_sub(sub.s.lisp.callback_used); if remaining == 0 { return Err(LispError::new(format!("callback stopped after {cap} steps"))); } let slice = remaining.min(SYNC_SLICE); - match m.run(&mut sub, slice) { + let outcome = m.run(&mut sub, slice); + match outcome { + // The steps were charged as they ran; finishing past the shared allowance is a failure too. + Outcome::Done(_) if sub.s.lisp.callback_used > ceiling => { + return Err(LispError::new(format!("callback stopped after {cap} steps"))); + } Outcome::Done(v) => return Ok(v), Outcome::Error(e) => return Err(e), - Outcome::Wait(Need::Yield) => { - spent = spent.saturating_add(slice); - if spent >= cap { - return Err(LispError::new(format!("callback stopped after {cap} steps"))); - } - } + Outcome::Wait(Need::Yield) => {} Outcome::Wait(_) => return Err(LispError::new("this function can't ask for input here")), } } diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index 0ed4b22fd..8c6eeb0e3 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -286,6 +286,35 @@ fn reaching_a_callback_slice_boundary_does_not_grant_another_slice() { assert!(counts[1] >= counts[0] && counts[1] - counts[0] <= 1, "{counts:?}"); } +/// Callbacks that call callbacks share one allowance: a branching routine can't multiply it. +#[test] +fn nested_callbacks_share_one_step_allowance() { + let mut s = session(); + s.lisp.limits.callback_steps = 1_000_000; + // 4^14 leaf calls if every callback took a fresh allowance; the whole tree gets one. + let started = std::time::Instant::now(); + let e = eval(&mut s, "(defun f (n) (if (> n 0) (vl-every '(lambda (x) (f (1- n)) t) '(1 2 3 4)) t)) (f 14)").unwrap_err(); + assert!(e.contains("callback stopped after 1000000 steps"), "{e}"); + assert!(started.elapsed() < std::time::Duration::from_secs(60)); + // The next run starts afresh. + assert_eq!(ok(&mut s, "(f 1)"), "T"); +} + +/// An outer callback's own steps count against the allowance before the callbacks it calls run. +#[test] +fn an_outer_callbacks_steps_are_charged_before_a_nested_one() { + let mut s = session(); + s.lisp.limits.callback_steps = 1_000; + ok(&mut s, "(setq inner-steps 0)"); + // The outer callback spends ~600 steps, then a nested one tries to spend ~600 more. + let r = eval( + &mut s, + "(vl-remove-if '(lambda (x) (repeat 150 (setq a 1)) (vl-remove-if '(lambda (y) (repeat 150 (setq inner-steps (1+ inner-steps)))) '(1)) nil) '(1))", + ); + assert_eq!(r, Err("callback stopped after 1000 steps".into())); + assert!(ok(&mut s, "inner-steps").parse::().unwrap() < 150); +} + /// System-variable conversion rejects a shared list whose owned JSON expansion would exceed its budget. #[test] fn setvar_rejects_an_oversized_shared_structure() { @@ -307,6 +336,16 @@ fn printing() { assert_eq!(ok(&mut s, "(rtos 12.5 2 2)"), "\"12.50\""); } +/// Output with many lines moves to the history in one pass, not one buffer shift per line. +#[test] +fn printing_many_lines_is_linear() { + let mut s = session(); + let started = std::time::Instant::now(); + ok(&mut s, "(setq x \"a\\r\\n\") (repeat 17 (setq x (strcat x x))) (princ x) (princ)"); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed()); + assert_eq!(s.log.last().map(String::as_str), Some("a")); +} + #[test] fn command_draws_and_one_routine_is_one_undo_step() { let mut s = session(); @@ -977,6 +1016,9 @@ fn strings_are_capped() { assert!(e.contains("too much text"), "{e}"); let e = eval(&mut s, "(repeat 200000 (princ \"0123456789\"))").unwrap_err(); assert!(e.contains("too much text"), "{e}"); + // READ makes new strings inside the list it returns: they count, though the result is a list. + let e = eval(&mut s, "(setq a \"(\\\"0123456789\\\")\") (repeat 100000 (setq b (read a)))").unwrap_err(); + assert!(e.contains("too much text"), "{e}"); // The budget is per run: the next one starts afresh. assert_eq!(ok(&mut s, "(strcat \"a\" \"b\")"), "\"ab\""); } diff --git a/crates/engine/src/lisp/value.rs b/crates/engine/src/lisp/value.rs index 09da1d27a..afae124e6 100644 --- a/crates/engine/src/lisp/value.rs +++ b/crates/engine/src/lisp/value.rs @@ -346,7 +346,11 @@ pub fn equal(a: &Value, b: &Value, fuzz: f64) -> bool { // A shared cons DAG can expand into exponentially many node visits when compared as a tree. // Bound the total comparisons so `equal` on adversarial shared structure cannot monopolise the // thread (CWE-407); exhausting the budget reports "not equal" rather than looping. - let mut budget: u64 = EQUAL_BUDGET; + equal_within(a, b, fuzz, EQUAL_BUDGET) +} + +/// [`equal`] with its work allowance (node visits plus string bytes / 64) given. +fn equal_within(a: &Value, b: &Value, fuzz: f64, mut budget: u64) -> bool { equal_depth(a, b, fuzz, 0, &mut budget) } @@ -373,7 +377,19 @@ fn equal_depth(a: &Value, b: &Value, fuzz: f64, depth: usize, budget: &mut u64) a = na; b = nb; } - _ => return atom_equal(&a, &b, fuzz), + _ => { + // Comparing two strings costs their length, not one visit: a shared list of long + // equal strings must spend the allowance by the bytes it compares (one unit per 64). + if let (Value::Str(x), Value::Str(y)) = (&a, &b) { + let cost = (x.len().min(y.len()) / 64) as u64; + if cost >= *budget { + *budget = 0; + return false; + } + *budget -= cost; + } + return atom_equal(&a, &b, fuzz); + } } } } @@ -540,6 +556,20 @@ fn write_value(out: &mut String, v: &Value, escape: bool, depth: usize) { mod tests { use super::*; + /// `equal` charges the bytes of the strings it compares: a list of long equal strings fits a + /// big allowance but not a small one, though it has few nodes. + #[test] + fn equal_spends_its_allowance_on_string_bytes() { + let long = Value::str(&"x".repeat(6_400)); + let other = Value::str(&"x".repeat(6_400)); + let list = |v: &Value| Value::list(vec![v.clone(); 100]); + let (a, b) = (list(&long), list(&other)); + // 100 strings x 100 units each, plus about 100 node visits. + assert!(equal_within(&a, &b, 0.0, 20_000)); + assert!(!equal_within(&a, &b, 0.0, 5_000)); + assert!(equal(&a, &b, 0.0)); + } + #[test] fn reals_print_with_six_significant_digits() { assert_eq!(real_text(1.0), "1.0"); diff --git a/crates/engine/src/mtext_edit.rs b/crates/engine/src/mtext_edit.rs index 97ecede6f..103178472 100644 --- a/crates/engine/src/mtext_edit.rs +++ b/crates/engine/src/mtext_edit.rs @@ -33,6 +33,9 @@ pub struct CharFmt { pub font: Option, /// Absolute character height set inline (`\H`); `None`: the text's. pub height: Option, + /// The inline height was set relative to the text's own (`\H2x;`): this multiplier, written + /// back as it was so the part keeps scaling with the text's height. + pub height_rel: Option, /// Colour set inline (`\C`, `\c`); `None`: the entity's (ByLayer/ByBlock). pub color: Option, } @@ -99,26 +102,60 @@ fn arg_end(chars: &[char], from: usize) -> usize { impl Formatted { /// Parse MTEXT contents. Never fails: what isn't understood is kept as atoms or dropped. pub fn from_contents(contents: &str) -> Formatted { + Self::from_contents_with_height(contents, None) + } + + /// [`Self::from_contents`] for a text `height` high: a relative height code (`\H2x;`) with no + /// inline height before it scales that one instead of being dropped. + pub fn from_contents_with_height(contents: &str, height: Option) -> Formatted { + Self::parse(contents, height).0 + } + + /// Whether the editor holds all of `contents`: past [`MAX_CHARS`] characters, [`MAX_PARAS`] + /// paragraphs or [`MAX_ATOMS`] kept codes the rest would be dropped, and saving would lose it. + pub fn fits(contents: &str) -> bool { + Self::parse(contents, None).1 + } + + /// Whether `edited`, what the editor gives back for `original` (a text `height` high), is the + /// text as it was: the same, or what opening it and pressing OK without an edit gives (a + /// non-canonical `{\fArial|b1;first}` comes back written another way). + pub fn leaves_unchanged(original: &str, height: Option, edited: &str) -> bool { + edited == original || edited == Self::from_contents_with_height(original, height).to_contents() + } + + /// The parse, and whether it took in all of `contents`. + fn parse(contents: &str, height: Option) -> (Formatted, bool) { let mut f = Formatted::default(); let chars: Vec = contents.chars().collect(); let mut stack: Vec = Vec::new(); let mut cur = CharFmt::default(); let mut props = ParaProps::default(); f.paras = vec![props.clone()]; + // Cleared when a paragraph, a kept code or a nesting level doesn't fit. + let mut whole = true; + // Groups opened past the 64 levels kept: their closing braces pop nothing. + let mut unkept = 0usize; let mut i = 0; while let Some(&c) = chars.get(i) { - if f.fmt.len() >= MAX_CHARS { - break; + // Braces after the last character the editor holds add no text. + if f.fmt.len() >= MAX_CHARS && !matches!(c, '{' | '}' | '\r') { + return (f, false); } match c { '{' => { if stack.len() < 64 { stack.push(cur.clone()); + } else { + unkept = unkept.saturating_add(1); + whole = false; } i += 1; } '}' => { - if let Some(p) = stack.pop() { + if unkept > 0 { + unkept -= 1; + } else if let Some(p) = stack.pop() { cur = p; } i += 1; @@ -128,6 +165,8 @@ impl Formatted { if f.paras.len() < MAX_PARAS { f.push_char('\n', &cur); f.paras.push(props.clone()); + } else { + whole = false; } i += 1; } @@ -140,6 +179,7 @@ impl Formatted { f.push_char('\n', &cur); f.paras.push(props.clone()); } + Some('P') => whole = false, Some(c @ ('\\' | '{' | '}')) => f.push_char(c, &cur), Some('L') => cur.underline = true, Some('l') => cur.underline = false, @@ -151,7 +191,7 @@ impl Formatted { i = end + 1; match k { 'f' | 'F' => apply_font(&mut cur, &a), - 'H' => cur.height = parse_height(&a, cur.height), + 'H' => apply_height(&mut cur, &a, height), 'C' => { cur.color = a.trim().parse::().ok().and_then(|v| (v > 0 && v < 256).then_some(MTextColor::Aci(v))); } @@ -177,6 +217,7 @@ impl Formatted { code.extend(chars.get(i..=end.min(chars.len().saturating_sub(1))).unwrap_or_default().iter()); i = end + 1; } + whole &= f.atoms.len() < MAX_ATOMS; f.push_atom(code, &cur); } } @@ -187,7 +228,7 @@ impl Formatted { } } } - f + (f, whole) } fn push_char(&mut self, c: char, fmt: &CharFmt) { @@ -445,7 +486,9 @@ impl Formatted { let fam: String = fam.chars().filter(|c| !matches!(c, ';' | '|' | '{' | '}' | '\\')).collect(); s.push_str(&format!("\\f{fam}|b{}|i{};", u8::from(f.bold), u8::from(f.italic))); } - if let Some(h) = f.height { + if let Some(m) = f.height_rel { + s.push_str(&format!("\\H{}x;", trim(m))); + } else if let Some(h) = f.height { s.push_str(&format!("\\H{};", trim(h))); } match f.color { @@ -462,12 +505,32 @@ fn trim(v: f64) -> String { s.trim_end_matches('0').trim_end_matches('.').to_string() } -fn parse_height(a: &str, cur: Option) -> Option { +/// A `\H` code on `cur`, for a text `base` high. A relative height over the text's own (no +/// inline height before it, or a relative one) stays relative; over an inline absolute height it +/// becomes absolute. +fn apply_height(cur: &mut CharFmt, a: &str, base: Option) { + let valid = |h: f64| (h.is_finite() && h > 0.0 && h < 1e6).then_some(h); let a = a.trim(); - match a.strip_suffix(['x', 'X']) { - // A relative height needs the current one; without it the code is dropped. - Some(r) => r.trim().parse::().ok().zip(cur).map(|(m, h)| h * m).filter(|h| h.is_finite() && *h > 0.0 && *h < 1e6), - None => a.parse::().ok().filter(|h| h.is_finite() && *h > 0.0 && *h < 1e6).or(cur), + let Some(r) = a.strip_suffix(['x', 'X']) else { + if let Some(h) = a.parse::().ok().and_then(valid) { + cur.height = Some(h); + cur.height_rel = None; + } + return; + }; + let Some(m) = r.trim().parse::().ok().and_then(valid) else { return }; + match (cur.height, cur.height_rel) { + (_, Some(r0)) => { + if let Some(m) = valid(r0 * m) { + cur.height_rel = Some(m); + cur.height = base.and_then(|b| valid(b * m)); + } + } + (None, None) => { + cur.height_rel = Some(m); + cur.height = base.and_then(|b| valid(b * m)); + } + (Some(h), None) => cur.height = valid(h * m).or(cur.height), } } @@ -493,6 +556,22 @@ fn apply_font(cur: &mut CharFmt, a: &str) { mod tests { use super::*; + #[test] + fn a_relative_height_is_written_back_relative() { + let f = Formatted::from_contents_with_height("{\\H2x;big} small {\\H3;abs}", Some(5.0)); + assert_eq!(f.fmt_at(0).height, Some(10.0), "shown at twice the text's height"); + let out = f.to_contents(); + assert!(out.contains("\\H2x;big"), "{out}"); + assert!(out.contains("\\H3;abs"), "an absolute height stays absolute: {out}"); + // Opened again for a taller text, the part scales with it. + assert_eq!(Formatted::from_contents_with_height(&out, Some(8.0)).fmt_at(0).height, Some(16.0)); + // Relative over relative multiplies; over an absolute one it is absolute. + let n = Formatted::from_contents_with_height("{\\H2x;a{\\H1.5x;b}}{\\H4;c{\\H2x;d}}", Some(1.0)).to_contents(); + assert!(n.contains("\\H3x;b") && n.contains("\\H8;d"), "{n}"); + // With no height known it is still kept. + assert!(Formatted::from_contents("{\\H2x;x}").to_contents().contains("\\H2x;x")); + } + #[test] fn round_trips_formats_and_atoms() { for src in [ @@ -563,4 +642,26 @@ mod tests { let _ = f.fmt_at(usize::MAX); let _ = Formatted::from_contents(&"{".repeat(100_000)); } + + /// A text with more paragraphs or kept codes than the editor holds doesn't fit, so TEXTEDIT + /// leaves it to the command line instead of dropping the rest on save. + #[test] + fn too_many_paragraphs_or_codes_do_not_fit() { + assert!(Formatted::fits("one\\Ptwo\\A1;three")); + assert!(!Formatted::fits(&"a\\P".repeat(MAX_PARAS))); + assert!(!Formatted::fits(&"a\n".repeat(MAX_PARAS))); + assert!(!Formatted::fits(&"\\A1;".repeat(MAX_ATOMS + 1))); + assert!(Formatted::fits(&"\\A1;".repeat(MAX_ATOMS))); + // A full formatted run's closing brace adds no text: it still fits. + assert!(Formatted::fits(&format!("{{\\L{}}}", "x".repeat(MAX_CHARS)))); + assert!(!Formatted::fits(&format!("{{\\L{}}}y", "x".repeat(MAX_CHARS)))); + // OK without an edit leaves a text alone, also one the editor writes another way. + let odd = "{\\fArial|b1;first}"; + assert!(Formatted::leaves_unchanged(odd, Some(2.5), &Formatted::from_contents_with_height(odd, Some(2.5)).to_contents())); + assert!(Formatted::leaves_unchanged(odd, Some(2.5), odd)); + assert!(!Formatted::leaves_unchanged(odd, Some(2.5), "second")); + // Nesting past the 64 levels the editor keeps doesn't fit. + assert!(Formatted::fits(&format!("{}a{}", "{".repeat(64), "}".repeat(64)))); + assert!(!Formatted::fits(&format!("{}a{}", "{".repeat(65), "}".repeat(65)))); + } } diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index 6181ddb6c..4b994c27c 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -313,8 +313,9 @@ pub trait Interactive: Send { fn drag(&self, _s: &Session, _cursor: Vec2) -> Option { None } - /// The multiline text being typed (MTEXT, once its box is known) with empty contents: where - /// the UI places its in-place editor and with which height, width and justification. + /// The multiline text being typed (MTEXT, once its box is known, with empty contents) or edited + /// (TEXTEDIT on an MTEXT or a multileader's text, with its contents): where the UI places its + /// in-place editor and with which height, width, justification and starting text. fn editing_mtext(&self) -> Option { None } diff --git a/crates/engine/src/render_look.rs b/crates/engine/src/render_look.rs new file mode 100644 index 000000000..524d288e9 --- /dev/null +++ b/crates/engine/src/render_look.rs @@ -0,0 +1,196 @@ +//! How a render request draws: its `background` and `plot_style` (#803). The app's control +//! channel and the headless MCP backend both answer `ui.render`, and both read these here. +//! +//! Colour 7 (white/black) follows the background, as on a plot: the rasteriser draws it white on +//! a dark background and black on a light one ([`cadcraft_color::display_rgb`]). +//! +//! A render with a plot style table draws on white unless `background` says otherwise, as a plot +//! prints on paper: the tables that change colours print colour 7 (and, in `monochrome.ctb`, +//! every colour) black, which can hardly be seen on the dark canvas. +//! +//! `plot_style: "none"` (or `""`) draws every object with its own properties, also in a layout +//! whose page setup has "Display plot styles" on; without `plot_style` such a layout draws with +//! its own table, as on screen. + +use std::sync::Arc; + +use cadcraft_color::Rgb; +use cadcraft_doc::{Drawing, PlotStyleTable}; +use cadcraft_render::raster::RasterOptions; +use serde_json::Value; + +/// The background a render draws on without `background`: the dark canvas. +pub const DARK: Rgb = RasterOptions::DARK_BACKGROUND; +/// The background of `"white"` and `"paper"`. +pub const WHITE: Rgb = Rgb(255, 255, 255); + +/// What `background` accepts, for the error message and the docs. +pub const BACKGROUNDS: &str = "\"dark\" (the default without a plot style), \"white\" (the default with one), \"paper\" or \"#rrggbb\""; + +/// Most table names an unknown `plot_style` error lists from the drawing's own tables (the +/// built-in ones are always listed). +const MAX_LISTED_TABLES: usize = 10; + +/// Longest part of a refused value repeated in its error message, in characters. +const MAX_ECHO_CHARS: usize = 40; + +/// The look of a render: what it draws on and with which plot style table. +#[derive(Clone, Debug)] +pub struct RenderLook { + pub background: Rgb, + /// `None` = draw with the objects' own properties (or, in a layout showing plot styles, its + /// page setup's table). `plot_style: "none"` is a table that keeps every property, so such a + /// layout's table doesn't apply either. + pub plot_style_table: Option>, +} + +impl Default for RenderLook { + fn default() -> Self { + RenderLook { background: DARK, plot_style_table: None } + } +} + +impl RenderLook { + /// `background` and `plot_style` of a request's params for drawing `d`; absent or `null` + /// keeps the default. `Err` says what is accepted. + pub fn from_params(d: &Drawing, p: &Value) -> Result { + let text = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) => Ok(Some(s.as_str())), + Some(_) => Err(format!("`{key}` must be a string")), + }; + let mut look = RenderLook::default(); + if let Some(name) = text("plot_style")? { + look.plot_style_table = Some(Arc::new(match plot_style(d, name)? { + Some(t) => { + // Plotted on paper, unless `background` says otherwise. + look.background = WHITE; + t + } + None => object_properties(), + })); + } + if let Some(b) = text("background")? { + look.background = background(b).ok_or_else(|| format!("unknown background `{}`: use {BACKGROUNDS}", echo(b)))?; + } + Ok(look) + } + + /// The raster options of a render with this look. + pub fn raster(&self) -> RasterOptions { + RasterOptions { background: self.background, ..RasterOptions::default() } + } +} + +/// The colour of a `background` value (any case): `dark`, `white`, `paper` or `#rrggbb`. +pub fn background(v: &str) -> Option { + let v = v.trim(); + match v.to_ascii_lowercase().as_str() { + "dark" => Some(DARK), + "white" | "paper" => Some(WHITE), + hex if hex.starts_with('#') => Rgb::parse_hex(hex), + _ => None, + } +} + +/// The plot style table `name` names: one the drawing holds, or a built-in one (`.ctb` may be +/// left out); `none` or an empty name is no table. `Err` lists the tables there are. +fn plot_style(d: &Drawing, name: &str) -> Result, String> { + if cadcraft_doc::no_plot_style_table(name) { + return Ok(None); + } + cadcraft_doc::plot_style_table(d, name.trim()) + .map(Some) + .ok_or_else(|| format!("unknown plot style table `{}`: use none or one of {}", echo(name), table_list(d))) +} + +/// The tables a drawing can use, for an error message: the built-in ones, then at most +/// [`MAX_LISTED_TABLES`] of the drawing's own and how many more there are. +fn table_list(d: &Drawing) -> String { + let builtin = |n: &String| cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES.iter().any(|b| b.eq_ignore_ascii_case(n)); + let names = cadcraft_doc::plot_style_table_names(d); + let own: Vec = names.iter().filter(|n| !builtin(n)).map(|n| echo(n)).collect(); + let mut list: Vec = cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES.iter().map(|b| (*b).to_string()).collect(); + list.extend(own.iter().take(MAX_LISTED_TABLES).cloned()); + let mut text = list.join(", "); + if own.len() > MAX_LISTED_TABLES { + text.push_str(&format!(" and {} more of the drawing's", own.len() - MAX_LISTED_TABLES)); + } + text +} + +/// A table that prints every object with its own properties: what `plot_style: "none"` draws +/// with, so a layout's own table doesn't apply either. +fn object_properties() -> PlotStyleTable { + PlotStyleTable::color_dependent("None", "Object properties", |_| None) +} + +/// The start of a refused value, to repeat in its error message. +fn echo(v: &str) -> String { + v.chars().take(MAX_ECHO_CHARS).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn backgrounds() { + assert_eq!(background("dark"), Some(DARK)); + assert_eq!(DARK, RasterOptions::default().background, "the default is the rasteriser's canvas"); + assert_eq!(background(" Paper "), Some(WHITE)); + assert_eq!(background("WHITE"), Some(WHITE)); + assert_eq!(background("#336699"), Some(Rgb(0x33, 0x66, 0x99))); + for bad in ["", "purple", "336699", "#12345", "#1234567", "##336699", "#33669g"] { + assert_eq!(background(bad), None, "{bad}"); + } + } + + #[test] + fn from_params() { + let d = Drawing::new_imperial(); + let look = RenderLook::from_params(&d, &json!({})).unwrap(); + assert_eq!(look.background, DARK); + assert!(look.plot_style_table.is_none()); + // "none" keeps the dark canvas and draws every object with its own properties, also in a + // layout that shows its own plot styles. + for none in ["none", "", " None "] { + let look = RenderLook::from_params(&d, &json!({"background": null, "plot_style": none})).unwrap(); + assert_eq!(look.background, DARK, "{none:?}"); + let t = look.plot_style_table.unwrap(); + assert!(t.is_color_dependent() && t.styles.iter().all(|s| s.keeps_color() && s.lineweight.is_none()), "{none:?}"); + } + let look = RenderLook::from_params(&d, &json!({"background": "white", "plot_style": "Monochrome"})).unwrap(); + assert_eq!(look.raster().background, WHITE); + assert_eq!(look.plot_style_table.map(|t| t.name.clone()).as_deref(), Some("monochrome.ctb")); + // A plot style plots on paper unless `background` says otherwise. + for table in ["monochrome.ctb", "grayscale.ctb", "default.stb"] { + assert_eq!(RenderLook::from_params(&d, &json!({"plot_style": table})).unwrap().background, WHITE, "{table}"); + let look = RenderLook::from_params(&d, &json!({"plot_style": table, "background": "dark"})).unwrap(); + assert_eq!(look.background, DARK, "{table}"); + } + let e = RenderLook::from_params(&d, &json!({"plot_style": "nope.ctb"})).unwrap_err(); + assert!(e.contains("nope.ctb") && e.contains("grayscale.ctb") && e.contains("none"), "{e}"); + let e = RenderLook::from_params(&d, &json!({"background": "x".repeat(10_000)})).unwrap_err(); + assert!(e.len() < 200 && e.contains("#rrggbb"), "{e}"); + assert!(RenderLook::from_params(&d, &json!({"background": 1})).is_err()); + assert!(RenderLook::from_params(&d, &json!({"plot_style": {}})).is_err()); + } + + /// An unknown plot style lists the built-in tables and only some of the drawing's own. + #[test] + fn unknown_plot_style_lists_a_few_tables() { + let mut d = Drawing::new_imperial(); + for i in 0..500 { + d.plot_style_tables.push(PlotStyleTable::color_dependent(&format!("{}{i}.ctb", "own".repeat(30)), "", |_| None)); + } + let e = RenderLook::from_params(&d, &json!({"plot_style": "nope.ctb"})).unwrap_err(); + for b in cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES { + assert!(e.contains(b), "{b}: {e}"); + } + assert!(e.contains("and 490 more"), "{e}"); + assert!(e.len() < 1000, "{} bytes: {e}", e.len()); + assert!(RenderLook::from_params(&d, &json!({"plot_style": d.plot_style_tables[7].name.clone()})).is_ok()); + } +} diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index b92c6b14f..b5ef2dc9f 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -36,6 +36,13 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec> { } v } + // An OLE object's frame is drawn, so it is picked on its outline (the corners the extents and + // the renderer use); a frame with no width or height is drawn as a line, so it is picked as + // one. It stays out of prims(), which TRIM, object snap and the dimension commands read. + EntityKind::Unknown(u) if u.is_ole_frame() => match cadcraft_doc::ole_frame(&u.tags) { + Some(q) => vec![q.to_vec()], + None => Vec::new(), + }, kind => { let mut out = Vec::new(); for p in kind.prims() { @@ -507,6 +514,23 @@ mod tests { assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line)); } + /// An OLE2FRAME draws as its frame, so a click on an edge picks it (review on #2587); a click in + /// the middle of the frame, or on a frame without both corners, does not. + #[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| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags }); + let mut d = Drawing::new_metric(); + let h = d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap(); + d.add(&Space::Model, Common::default(), frame(vec![tag(10, "80"), tag(20, "80")])).unwrap(); + let line = d.add(&Space::Model, Common::default(), frame(vec![tag(10, "60"), tag(20, "-19"), tag(11, "60"), tag(21, "-22")])).unwrap(); + assert_eq!(pick(&d, &Space::Model, Vec2::new(32.5, -19.0), 0.2), Some(h), "top edge"); + assert_eq!(pick(&d, &Space::Model, Vec2::new(35.0, -20.5), 0.2), Some(h), "right edge"); + assert_eq!(pick(&d, &Space::Model, Vec2::new(32.5, -20.5), 0.2), None, "inside the frame"); + assert_eq!(pick(&d, &Space::Model, Vec2::new(80.0, 80.0), 0.2), None, "a frame without a second corner"); + assert_eq!(pick(&d, &Space::Model, Vec2::new(60.0, -20.0), 0.2), Some(line), "a frame with no width is drawn as a line and picked as one"); + } + /// A block holding a diagonal dashed line, inserted at `scale`. fn dashed_block(length: f64, scale: f64) -> (Drawing, Handle) { let mut d = Drawing::new_imperial(); diff --git a/crates/engine/src/session/files.rs b/crates/engine/src/session/files.rs index 6704b2674..9707086c4 100644 --- a/crates/engine/src/session/files.rs +++ b/crates/engine/src/session/files.rs @@ -17,10 +17,17 @@ impl Session { /// Append a loaded drawing, fit the view to its model extents (aspect-corrected, minimum height 1e-6) when non-empty, end a running command, make it active, bump the epoch and return its index. pub fn open_drawing(&mut self, d: Drawing, title: &str, path: Option) -> usize { let mut st = DocState::new(d, title, path); + // The view the file was saved at is the one every other reader opens on. Fitting the + // extents instead showed a drawing whose extents are dominated by far-off geometry at a + // view hundreds of times its content, with the drawing sub-pixel and no way to zoom in + // (#1602). The extents remain the fallback for a drawing that stores no view. + let saved = crate::view::saved_view(&st.doc); let ext = st.doc.extents(&Space::Model); // The current tile (the first), or the lone untiled view, keeps its saved twist. let twist = cadcraft_geom::norm_angle(st.doc.vports.iter().find(|c| c.is_active()).and_then(|c| c.tiles.first()).map_or(0.0, |t| t.twist)); - if ext.is_empty() { + if let Some(v) = saved { + st.set_view_quiet(View { twist, ..v }); + } else if ext.is_empty() { st.set_view_quiet(View { twist, ..st.view() }); } else { let (center, w, h) = View::twisted_box(ext, twist); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 35573df6a..4d8081d7a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -179,6 +179,67 @@ fn json_execute_and_errors() { assert_eq!(s.state().unwrap().undo.len(), 1); } +/// A drawing is opened on the view it was saved at, as every other reader opens it. Fitting the +/// extents instead showed a drawing whose extents are dominated by far-off geometry at a view +/// hundreds of thousands of times its content: sub-pixel, and `ZOOM Extents` fits the same box +/// (#1602). The extents are still the fallback for a drawing that stores no view. +#[test] +fn a_drawing_opens_on_the_view_it_was_saved_at() { + let mut d = cadcraft_doc::Drawing::new_metric(); + for (a, b) in [([0.0, 0.0], [100.0, 60.0]), ([5e6, 5e6], [5e6 + 100.0, 5e6 + 60.0])] { + let line = cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(a[0], a[1], 0.0), b: cadcraft_geom::Vec3::new(b[0], b[1], 0.0) }; + d.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap(); + } + d.header.set_saved_view(Vec2::new(50.0, 50.0), 20.0); + + let mut s = Session::new(); + s.open_drawing(d.clone(), "saved-view.dxf", None); + assert_eq!(s.state().unwrap().view(), View { center: Vec2::new(50.0, 50.0), height: 20.0, twist: 0.0 }); + + // No stored view: the extents, as before. They are what makes this drawing unusable without + // the stored one -- the fit is more than a hundred thousand times taller than the detail. + let mut plain = d.clone(); + plain.header.vars.remove("VIEWCTR"); + plain.header.vars.remove("VIEWSIZE"); + let mut s = Session::new(); + s.open_drawing(plain, "no-view.dxf", None); + assert!(s.state().unwrap().view().height > 5e6, "{:?}", s.state().unwrap().view()); + + // A stored view that cannot be shown is no view at all. + let mut broken = d; + broken.header.set("VIEWSIZE", cadcraft_doc::HVal::Real(0.0)); + let mut s = Session::new(); + s.open_drawing(broken, "broken-view.dxf", None); + assert!(s.state().unwrap().view().height > 5e6, "{:?}", s.state().unwrap().view()); +} + +/// Resolving a drawing's xrefs after OPEN refits the view only for a drawing that stores none: +/// one saved at a view keeps it, xref or not (#1626 review). +#[test] +fn a_drawing_with_an_xref_keeps_the_view_it_was_saved_at() { + let mut d = cadcraft_doc::Drawing::new_metric(); + let line = cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(5e6, 5e6, 0.0) }; + d.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap(); + let mut xref = cadcraft_doc::Block::new("XR"); + xref.xref_path = Some("missing-xref.dxf".into()); + d.blocks.insert("XR".into(), std::sync::Arc::new(xref)); + let mut plain = d.clone(); + d.header.set_saved_view(Vec2::new(50.0, 50.0), 20.0); + + let mut s = Session::new(); + let i = s.open_drawing(d, "saved-view.dxf", None); + crate::cmd::blocks::xref::after_open(&mut s, i); + assert_eq!(s.state().unwrap().view(), View { center: Vec2::new(50.0, 50.0), height: 20.0, twist: 0.0 }); + + // With no stored view, the xrefs' pass still frames the drawing. + plain.header.vars.remove("VIEWCTR"); + plain.header.vars.remove("VIEWSIZE"); + let mut s = Session::new(); + let i = s.open_drawing(plain, "no-view.dxf", None); + crate::cmd::blocks::xref::after_open(&mut s, i); + assert!(s.state().unwrap().view().height > 5e6, "{:?}", s.state().unwrap().view()); +} + #[test] fn move_with_pickfirst_and_window_selection() { let mut s = Session::new(); diff --git a/crates/engine/src/view.rs b/crates/engine/src/view.rs index bbfc4f972..5514b968c 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -35,6 +35,12 @@ pub(crate) fn usable_view(v: &View) -> bool { v.center.is_finite() && v.height.is_finite() && v.height > 1e-12 && v.twist.is_finite() } +/// The view drawing `d` was saved at, when it records a usable one: OPEN opens on it, and nothing +/// after the open (resolving xrefs, the UI's first frame) fits the extents over it. +pub(crate) fn saved_view(d: &cadcraft_doc::Drawing) -> Option { + d.header.saved_view().map(|(center, height)| View { center, height, twist: 0.0 }).filter(usable_view) +} + /// Tiled model viewports (VPORTS): the session side of the drawing's `*Active` configuration. #[derive(Clone, Debug, Default, PartialEq)] pub struct ModelTiles { diff --git a/crates/engine/tests/aliases.rs b/crates/engine/tests/aliases.rs index d1b39bb81..dba5b1791 100644 --- a/crates/engine/tests/aliases.rs +++ b/crates/engine/tests/aliases.rs @@ -75,6 +75,57 @@ fn reinit_reads_the_alias_file_again() { s.execute("aliasedit", &json!({ "clear": true })).unwrap(); } +#[test] +fn a_saved_alias_profile_restores_without_overriding_commands() { + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = Session::new(); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + s.execute("aliasedit", &json!({ "set": { "zzp": "qsave", "zzcmd": "line" } })).unwrap(); + let saved = cadcraft_engine::cmd::file::alias_profile(); + assert_eq!(saved["aliases"]["zzp"], json!("qsave")); + + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + assert_eq!(resolve_alias("zzp"), "zzp"); + cadcraft_engine::cmd::file::restore_aliases(&saved); + assert_eq!(resolve_alias("zzp"), "qsave"); + assert_eq!(resolve_alias("zzcmd"), "line"); + assert_eq!(resolve_alias("line"), "line", "command names win"); + assert_eq!(resolve_alias("c"), "circle", "built-in aliases still resolve"); + + // Hostile saved entries are skipped, and an oversized set is capped without panicking. + let mut hostile = serde_json::Map::new(); + for i in 0..12_000 { + hostile.insert(format!("ZZ{i}"), json!("line")); + } + hostile.insert("LINE".into(), json!("circle")); + hostile.insert("ZZLONG".into(), json!("x".repeat(5000))); + hostile.insert("ZZNUM".into(), json!(3)); + cadcraft_engine::cmd::file::restore_aliases(&json!({ "aliases": hostile, "file": "mine.pgp" })); + assert_eq!(resolve_alias("line"), "line", "a restored alias never overrides a command name"); + assert_eq!(resolve_alias("zzlong"), "zzlong"); + assert_eq!(resolve_alias("zzn"), "zzn"); + let listing = s.execute("aliasedit", &json!({})).unwrap(); + let restored = listing["aliases"].as_object().map_or(0, serde_json::Map::len); + assert!(restored <= cadcraft_engine::cmd::file::MAX_ALIASES, "the restored set is capped, not {restored}"); + assert!(restored > 9_000, "the valid entries restore, not just {restored}"); + assert_eq!(listing["file"], json!("mine.pgp")); + + // Skipped entries don't use up the cap: invalid ones sorted first leave a full valid set. + let mut first_bad = serde_json::Map::new(); + for i in 0..cadcraft_engine::cmd::file::MAX_ALIASES { + first_bad.insert(format!("A{i:05}"), json!("nosuchcommand")); + first_bad.insert(format!("B{i:05}"), json!("line")); + } + cadcraft_engine::cmd::file::restore_aliases(&json!({ "aliases": first_bad, "file": null })); + let listing = s.execute("aliasedit", &json!({})).unwrap(); + assert_eq!(listing["aliases"].as_object().map_or(0, serde_json::Map::len), cadcraft_engine::cmd::file::MAX_ALIASES); + // A malformed section is skipped without changing what ALIASEDIT holds. + cadcraft_engine::cmd::file::restore_aliases(&json!({ "aliases": { "zzchange": "circle" }, "file": 7 })); + assert_eq!(resolve_alias("zzchange"), "zzchange", "a malformed section restores nothing"); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + assert_eq!(resolve_alias("zz0"), "zz0", "clear still empties the restored set"); +} + #[test] fn hostile_alias_files_never_panic() { let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/engine/tests/it/break_join_locked_layers.rs b/crates/engine/tests/it/break_join_locked_layers.rs index 0a1f6e707..4162ca9ee 100644 --- a/crates/engine/tests/it/break_join_locked_layers.rs +++ b/crates/engine/tests/it/break_join_locked_layers.rs @@ -45,7 +45,8 @@ fn break_and_breakatpoint_refuse_a_locked_line() { let unlocked = snapshot(&s); let r = s.execute("break", &json!({"handle": a, "p1": [3, 0], "p2": [7, 0]})).unwrap(); assert_eq!(r["handles"].as_array().unwrap().len(), 2); - assert!(s.doc().unwrap().entity(cadcraft_engine::doc::Handle::parse_hex(&a).unwrap()).is_none()); + // The line keeps its handle as the piece from its start. + assert_eq!(r["handles"][0].as_str(), Some(a.as_str())); assert!(s.doc().unwrap().entity(cadcraft_engine::doc::Handle::parse_hex(&control).unwrap()).is_some()); let broken = snapshot(&s); s.execute("undo", &json!({})).unwrap(); diff --git a/crates/engine/tests/it/break_trim_keep_handle.rs b/crates/engine/tests/it/break_trim_keep_handle.rs new file mode 100644 index 000000000..0fc5a1fc3 --- /dev/null +++ b/crates/engine/tests/it/break_trim_keep_handle.rs @@ -0,0 +1,444 @@ +//! BREAK, BREAKATPOINT and TRIM change the object itself, as AutoCAD 2024 does: the piece from +//! the object's start, or the only piece left, keeps its handle and its place in the drawing +//! order, and the other pieces are new objects added at the end (`entlast`). Groups keep the +//! object, an associative hatch whose boundary no longer closes keeps its shape and its link +//! ends, and a dimension attached to the object stays on the point it measured, or follows the +//! object's new end where that point was cut off. +//! +//! The two chains, the group, the two hatches and the three dimensions on a line were measured in +//! AutoCAD 2024 (accoreconsole) on the same drawings: the objects in database order (`entnext`) +//! after each chain, a new handle marked `+`, and the dimensions' DIMASSOC references. The other +//! cases follow from those rules, or say what they check. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{AssocSnap, Common, DimAssoc, Dimension, EntityKind, Handle, Hatch, Line, Space}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use serde_json::{Value, json}; + +fn first_handle(v: &Value) -> Handle { + Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap() +} + +/// Adds the object `cmd` makes from `p`, on layer `name`. +fn add(s: &mut Session, name: &str, cmd: &str, p: Value) -> Handle { + let h = first_handle(&s.execute(cmd, &p).unwrap()); + s.execute("properties.set", &json!({ "handles": [h.hex()], "layer": name })).unwrap(); + h +} + +fn line(s: &mut Session, name: &str, a: [f64; 2], b: [f64; 2]) -> Handle { + add(s, name, "line", json!({ "points": [a, b] })) +} + +fn arc(s: &mut Session, name: &str, c: [f64; 2], start: f64, end: f64) -> Handle { + add(s, name, "arc", json!({ "center": c, "radius": 10, "start": start, "end": end })) +} + +fn pline(s: &mut Session, name: &str, vertices: Value, closed: bool) -> Handle { + add(s, name, "pline", json!({ "vertices": vertices, "closed": closed })) +} + +/// The drawing the chains were measured on, each object on a layer named after it, made in this +/// order. +fn drawing() -> Session { + let mut s = Session::new(); + line(&mut s, "LA", [0.0, 50.0], [100.0, 50.0]); + line(&mut s, "LB", [50.0, 0.0], [50.0, 100.0]); + pline(&mut s, "LP", json!([[0, 200], [20, 200], [20, 220]]), false); + line(&mut s, "LE", [200.0, 0.0], [210.0, 0.0]); + line(&mut s, "LF", [210.0, 0.0], [220.0, 0.0]); + line(&mut s, "LC", [0.0, 0.0], [100.0, 100.0]); + line(&mut s, "LD", [0.0, 100.0], [100.0, 0.0]); + arc(&mut s, "LR", [300.0, 0.0], 0.0, 180.0); + add(&mut s, "LO", "circle", json!({ "center": [400, 0], "radius": 10 })); + pline(&mut s, "LK", json!([[500, 0], [520, 0], [520, 20], [500, 20]]), true); + line(&mut s, "LG", [600.0, 0.0], [600.0, 100.0]); + line(&mut s, "LH", [590.0, 40.0], [610.0, 40.0]); + line(&mut s, "LI", [590.0, 60.0], [610.0, 60.0]); + line(&mut s, "LT", [650.0, 0.0], [650.0, 100.0]); + line(&mut s, "LU", [640.0, 40.0], [660.0, 40.0]); + line(&mut s, "LW", [395.0, -20.0], [395.0, 20.0]); + line(&mut s, "LX", [10.0, 190.0], [10.0, 210.0]); + line(&mut s, "LY", [15.0, 190.0], [15.0, 210.0]); + arc(&mut s, "LJ", [700.0, 0.0], 0.0, 90.0); + arc(&mut s, "LL", [700.0, 0.0], 90.0, 360.0); + line(&mut s, "LM", [800.0, 0.0], [810.0, 0.0]); + arc(&mut s, "LN", [810.0, 10.0], 270.0, 360.0); + pline(&mut s, "LQ", json!([[900, 0], [910, 0]]), false); + line(&mut s, "LS", [910.0, 0.0], [910.0, 10.0]); + line(&mut s, "LZ", [1000.0, 0.0], [1010.0, 0.0]); + s +} + +/// `v` to `places` decimals without trailing zeros, as `rtos` printed the measurements. +fn num(v: f64, places: usize) -> String { + let t = format!("{v:.places$}"); + let t = if t.contains('.') { t.trim_end_matches('0').trim_end_matches('.') } else { &t }; + if t == "-0" { "0".into() } else { t.into() } +} + +fn pt(p: Vec2) -> String { + format!("{},{}", num(p.x, 4), num(p.y, 4)) +} + +/// An angle in degrees in [0, 360). +fn deg(a: f64) -> String { + let d = a.to_degrees().rem_euclid(360.0); + num(if d >= 360.0 - 5e-4 { 0.0 } else { d }, 3) +} + +/// The model space objects in order as `layer[+]:TYPE:shape`, `+` marking a handle that wasn't in +/// `original`. +fn table(s: &Session, original: &[Handle]) -> Vec { + s.doc() + .unwrap() + .model + .iter() + .map(|e| { + let shape = match &e.kind { + EntityKind::Line(l) => format!("LINE:{}>{}", pt(l.a.xy()), pt(l.b.xy())), + EntityKind::Arc(a) => format!("ARC:c{}r{}a{}>{}", pt(a.center.xy()), num(a.radius, 4), deg(a.start), deg(a.end)), + EntityKind::Circle(c) => format!("CIRCLE:c{}r{}", pt(c.center.xy()), num(c.radius, 4)), + EntityKind::LwPolyline(p) => { + format!("LWPOLYLINE:f{}{}", u8::from(p.closed), p.vertices.iter().map(|v| format!(";{}", pt(v.p))).collect::()) + } + k => format!("{k:?}"), + }; + let new = if original.contains(&e.handle) { "" } else { "+" }; + format!("{}{new}:{shape}", e.common.layer) + }) + .collect() +} + +fn handles(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.handle).collect() +} + +/// The object on layer `name` that was there first. +fn named(s: &Session, name: &str) -> Handle { + s.doc().unwrap().model.iter().find(|e| e.common.layer == name).unwrap().handle +} + +/// Runs `commands` on the command line one by one, each to its end. +fn run(s: &mut Session, commands: &[&str]) { + for c in commands { + s.script(&format!("{c}\n")).unwrap(); + assert!(s.running.is_none(), "{c}: {}", s.prompt_text()); + } +} + +/// The objects AutoCAD leaves untouched in the middle of both tables. +const UNTOUCHED: [&str; 8] = [ + "LG:LINE:600,0>600,100", + "LH:LINE:590,40>610,40", + "LI:LINE:590,60>610,60", + "LT:LINE:650,0>650,100", + "LU:LINE:640,40>660,40", + "LW:LINE:395,-20>395,20", + "LX:LINE:10,190>10,210", + "LY:LINE:15,190>15,210", +]; + +/// The measured `entnext` table after the chain of breaks below. (LL and LN end at 360°, written +/// 0° here.) +fn after_breaks() -> Vec<&'static str> { + let mut v = vec![ + "LA:LINE:10,50>100,50", + "LB:LINE:50,0>50,20", + "LP:LWPOLYLINE:f0;0,200;10,200", + "LE:LINE:200,0>210,0", + "LF:LINE:210,0>220,0", + "LC:LINE:0,0>100,100", + "LD:LINE:0,100>100,0", + "LR:ARC:c300,0r10a0>45", + "LO:ARC:c400,0r10a90>0", + "LK:LWPOLYLINE:f0;520,10;520,20;500,20;500,0;510,0", + ]; + v.extend(UNTOUCHED); + v.extend([ + "LJ:ARC:c700,0r10a0>45", + "LL:ARC:c700,0r10a90>0", + "LM:LINE:800,0>810,0", + "LN:ARC:c810,10r10a270>0", + "LQ:LWPOLYLINE:f0;900,0;910,0", + "LS:LINE:910,0>910,10", + "LZ:LINE:1000,0>1005,0", + "LB+:LINE:50,30>50,100", + "LR+:ARC:c300,0r10a135>180", + "LP+:LWPOLYLINE:f0;20,210;20,220", + "LZ+:LINE:1005,0>1010,0", + "LJ+:ARC:c700,0r10a45>90", + ]); + v +} + +#[test] +fn a_chain_of_breaks_leaves_the_objects_in_autocads_order() { + let mut s = drawing(); + let original = handles(&s); + run( + &mut s, + &[ + // A line picked nearer its end: the piece from its start still keeps the handle. + "BREAK 50,30 50,20", + // Off the start: one piece, the line itself. + "BREAK 10,50 -10,50", + "BREAK 307.0710678,7.0710678 292.9289322,7.0710678", + // A circle becomes an arc with its handle. + "BREAK 410,0 400,10", + "BREAK 5,200 F 10,200 20,210", + // A closed polyline opens with its handle. + "BREAK 510,0 520,10", + ], + ); + // BREAKATPOINT, picking each object at the point it is broken at. + for (name, at) in [("LZ", [1005.0, 0.0]), ("LJ", [707.0710678, 7.0710678])] { + s.execute("breakatpoint", &json!({ "handle": named(&s, name).hex(), "at": at })).unwrap(); + } + assert_eq!(table(&s, &original), after_breaks()); +} + +#[test] +fn a_chain_of_trims_leaves_the_objects_in_autocads_order() { + let mut s = drawing(); + let original = handles(&s); + // Quick mode: every object cuts. Each pick is between the measured cutting edges. + run(&mut s, &["TRIM 600,50\n", "TRIM 650,80\n", "TRIM 50,10\n", "TRIM 390,0\n", "TRIM 12,200\n"]); + let mut want = vec![ + "LA:LINE:0,50>100,50", + "LB:LINE:50,50>50,100", + "LP:LWPOLYLINE:f0;0,200;10,200", + "LE:LINE:200,0>210,0", + "LF:LINE:210,0>220,0", + "LC:LINE:0,0>100,100", + "LD:LINE:0,100>100,0", + "LR:ARC:c300,0r10a0>180", + "LO:ARC:c400,0r10a240>120", + "LK:LWPOLYLINE:f1;500,0;520,0;520,20;500,20", + "LG:LINE:600,0>600,40", + ]; + want.extend(&UNTOUCHED[1..3]); + want.push("LT:LINE:650,0>650,40"); + want.extend(&UNTOUCHED[4..]); + want.extend([ + "LJ:ARC:c700,0r10a0>90", + "LL:ARC:c700,0r10a90>0", + "LM:LINE:800,0>810,0", + "LN:ARC:c810,10r10a270>0", + "LQ:LWPOLYLINE:f0;900,0;910,0", + "LS:LINE:910,0>910,10", + "LZ:LINE:1000,0>1010,0", + "LG+:LINE:600,60>600,100", + "LP+:LWPOLYLINE:f0;15,200;20,200;20,220", + ]); + assert_eq!(table(&s, &original), want); +} + +#[test] +fn the_json_forms_return_the_kept_object_first() { + let mut s = Session::new(); + let l = first_handle(&s.execute("line", &json!({ "points": [[0, 0], [100, 0]] })).unwrap()); + let r = s.execute("break", &json!({ "handle": l.hex(), "p1": [20, 0], "p2": [30, 0] })).unwrap(); + let hs = r["handles"].as_array().unwrap(); + assert_eq!(hs.len(), 2); + assert_eq!(hs[0], l.hex()); + assert_eq!(handles(&s), vec![l, Handle::parse_hex(hs[1].as_str().unwrap()).unwrap()]); + let r = s.execute("breakatpoint", &json!({ "handle": l.hex(), "at": [10, 0] })).unwrap(); + assert_eq!(r["handles"][0], l.hex()); + // Undo puts the line back, whole, under its own handle. + s.execute("u", &json!({})).unwrap(); + s.execute("u", &json!({})).unwrap(); + assert_eq!(table(&s, &[l]), ["0:LINE:0,0>100,0"]); +} + +#[test] +fn the_new_piece_goes_to_the_space_of_the_object() { + // A paper space line broken through the JSON form while model space is current. + let mut s = Session::new(); + let paper = Space::Paper("Layout1".into()); + let line = EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(100.0, 0.0, 0.0) }); + let l = s.doc_mut().unwrap().add(&paper, Common::default(), line).unwrap(); + s.execute("break", &json!({ "handle": l.hex(), "p1": [20, 0], "p2": [30, 0] })).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(d.model.iter().count(), 0); + let pieces: Vec = d.space(&paper).unwrap().iter().map(|e| e.handle).collect(); + assert_eq!(pieces.len(), 2); + assert_eq!(pieces[0], l); +} + +#[test] +fn a_group_keeps_the_broken_object_and_not_the_new_piece() { + let mut s = Session::new(); + let a = first_handle(&s.execute("line", &json!({ "points": [[0, 50], [100, 50]] })).unwrap()); + let b = first_handle(&s.execute("line", &json!({ "points": [[50, 0], [50, 100]] })).unwrap()); + s.execute("group", &json!({ "name": "G1", "handles": [a.hex(), b.hex()] })).unwrap(); + s.execute("break", &json!({ "handle": b.hex(), "p1": [50, 20], "p2": [50, 30] })).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(d.model.iter().count(), 3); + assert_eq!(d.groups.iter().find(|g| g.name == "G1").unwrap().members, vec![a, b]); +} + +fn hatch(s: &Session, h: Handle) -> Hatch { + match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::Hatch(x) => x.clone(), + k => panic!("not a hatch: {k:?}"), + } +} + +fn loop_points(h: &Hatch) -> Vec> { + h.loops.iter().map(|l| l.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()).collect() +} + +#[test] +fn a_hatch_whose_polyline_is_broken_open_keeps_its_shape_and_loses_its_link() { + let mut s = Session::new(); + let k = first_handle(&s.execute("pline", &json!({ "vertices": [[500, 0], [520, 0], [520, 20], [500, 20]], "closed": true })).unwrap()); + let h = first_handle(&s.execute("hatch", &json!({ "handles": [k.hex()] })).unwrap()); + assert!(hatch(&s, h).associative); + let square = loop_points(&hatch(&s, h)); + s.execute("break", &json!({ "handle": k.hex(), "p1": [510, 0], "p2": [520, 10] })).unwrap(); + assert!(matches!(&s.doc().unwrap().entity(k).unwrap().kind, EntityKind::LwPolyline(p) if !p.closed)); + let after = hatch(&s, h); + assert!(!after.associative); + assert_eq!(loop_points(&after), square); + s.execute("u", &json!({})).unwrap(); + assert!(hatch(&s, h).associative); +} + +#[test] +fn a_hatch_whose_boundary_line_is_trimmed_keeps_its_shape_and_loses_its_link() { + let mut s = Session::new(); + let sides = [ + line(&mut s, "0", [500.0, 0.0], [520.0, 0.0]), + line(&mut s, "0", [520.0, 0.0], [520.0, 20.0]), + line(&mut s, "0", [520.0, 20.0], [500.0, 20.0]), + line(&mut s, "0", [500.0, 20.0], [500.0, 0.0]), + ]; + let h = first_handle(&s.execute("hatch", &json!({ "points": [[510, 10]] })).unwrap()); + assert!(hatch(&s, h).associative); + let square = loop_points(&hatch(&s, h)); + let k1 = line(&mut s, "0", [505.0, -5.0], [505.0, 5.0]); + let k2 = line(&mut s, "0", [515.0, -5.0], [515.0, 5.0]); + let before = handles(&s); + s.execute("trim", &json!({ "handle": sides[0].hex(), "pick": [510, 0], "edges": [k1.hex(), k2.hex()] })).unwrap(); + let after = handles(&s); + assert_eq!(after[..before.len()], before[..]); + assert_eq!(after.len(), before.len() + 1); + let hh = hatch(&s, h); + assert!(!hh.associative); + assert_eq!(loop_points(&hh), square); +} + +fn dim(s: &Session, h: Handle) -> Dimension { + match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::Dimension(d) => d.clone(), + k => panic!("not a dimension: {k:?}"), + } +} + +fn attachments(d: &Dimension) -> Vec<(String, Handle, AssocSnap)> { + let mut v: Vec<(String, Handle, AssocSnap)> = d.assoc.iter().map(|a: &DimAssoc| (a.point.clone(), a.handle, a.snap.clone())).collect(); + v.sort_by(|a, b| a.0.cmp(&b.0)); + v +} + +fn origins(d: &Dimension) -> [(f64, f64); 2] { + [(d.p13.x, d.p13.y), (d.p14.x, d.p14.y)] +} + +/// A vertical line from (x, 0) to (x, 100) with a linear dimension attached to both its ends. +fn dimensioned_line(s: &mut Session, x: f64) -> (Handle, Handle) { + let l = first_handle(&s.execute("line", &json!({ "points": [[x, 0], [x, 100]] })).unwrap()); + let d = first_handle(&s.execute("dimlinear", &json!({ "p1": [x, 0], "p2": [x, 100], "at": [x + 20.0, 50] })).unwrap()); + assert_eq!(attachments(&dim(s, d)), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]); + (l, d) +} + +#[test] +fn a_dimension_across_a_line_broken_in_its_middle_stays_on_both_ends() { + // Measured: the reference to the line's end moves to the new piece, the dimension is unchanged. + let mut s = Session::new(); + let (l, d) = dimensioned_line(&mut s, 50.0); + run(&mut s, &["BREAK 50,20 50,30"]); + let piece = *handles(&s).last().unwrap(); + assert!(piece != l && piece != d); + let dm = dim(&s, d); + assert_eq!(attachments(&dm), [("p13".into(), l, AssocSnap::Start), ("p14".into(), piece, AssocSnap::End)]); + assert_eq!(origins(&dm), [(50.0, 0.0), (50.0, 100.0)]); + s.execute("u", &json!({})).unwrap(); + assert_eq!(attachments(&dim(&s, d)), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]); +} + +#[test] +fn a_dimension_on_a_trimmed_off_end_follows_the_new_end() { + // Measured: the references stay on the line, the dimension measures 40 instead of 100. + let mut s = Session::new(); + let (l, d) = dimensioned_line(&mut s, 650.0); + let edge = first_handle(&s.execute("line", &json!({ "points": [[640, 40], [660, 40]] })).unwrap()); + s.execute("trim", &json!({ "handle": l.hex(), "pick": [650, 80], "edges": [edge.hex()] })).unwrap(); + let dm = dim(&s, d); + assert_eq!(attachments(&dm), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]); + assert_eq!(origins(&dm), [(650.0, 0.0), (650.0, 40.0)]); +} + +#[test] +fn a_dimension_on_a_broken_off_start_follows_the_new_start() { + // Measured: BREAK from the start to (650, 20); the dimension starts at (650, 20). + let mut s = Session::new(); + let (l, d) = dimensioned_line(&mut s, 650.0); + run(&mut s, &["BREAK 650,10 F 650,0 650,20"]); + assert_eq!(handles(&s), [l, d]); + let dm = dim(&s, d); + assert_eq!(attachments(&dm), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]); + assert_eq!(origins(&dm), [(650.0, 20.0), (650.0, 100.0)]); +} + +#[test] +fn a_dimension_follows_a_piece_a_later_pick_of_the_same_trim_shortens() { + // The measured rules pick by pick: the first pick moves the reference to the line's end onto + // the new piece, the second cuts that end off, so the dimension ends at the piece's new end. + let mut s = Session::new(); + let other = first_handle(&s.execute("line", &json!({ "points": [[0, 20], [0, 30]] })).unwrap()); + let l = first_handle(&s.execute("line", &json!({ "points": [[0, 0], [100, 0]] })).unwrap()); + for x in [40, 60, 80] { + s.execute("line", &json!({ "points": [[x, -5], [x, 5]] })).unwrap(); + } + let d = first_handle(&s.execute("dimlinear", &json!({ "p1": [0, 30], "p2": [100, 0], "at": [50, 60] })).unwrap()); + assert_eq!(attachments(&dim(&s, d)), [("p13".into(), other, AssocSnap::End), ("p14".into(), l, AssocSnap::End)]); + s.script("TRIM 50,0 90,0\n\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let piece = *handles(&s).last().unwrap(); + assert_eq!(table(&s, &[l]).last().unwrap(), "0+:LINE:60,0>80,0"); + let dm = dim(&s, d); + assert_eq!(attachments(&dm), [("p13".into(), other, AssocSnap::End), ("p14".into(), piece, AssocSnap::End)]); + assert_eq!(origins(&dm), [(0.0, 30.0), (80.0, 0.0)]); +} + +#[test] +fn a_dimension_on_a_closed_polyline_opened_by_break_keeps_its_vertices() { + // The vertices it measured are still vertices of the polyline, numbered from the break. + let mut s = Session::new(); + let k = first_handle(&s.execute("pline", &json!({ "vertices": [[500, 0], [520, 0], [520, 20], [500, 20]], "closed": true })).unwrap()); + let d = first_handle(&s.execute("dimlinear", &json!({ "p1": [500, 20], "p2": [520, 20], "at": [510, 40] })).unwrap()); + assert_eq!(attachments(&dim(&s, d)), [("p13".into(), k, AssocSnap::Vertex { index: 3 }), ("p14".into(), k, AssocSnap::Vertex { index: 2 })]); + s.execute("break", &json!({ "handle": k.hex(), "p1": [510, 0], "p2": [520, 10] })).unwrap(); + let dm = dim(&s, d); + assert_eq!(attachments(&dm), [("p13".into(), k, AssocSnap::Vertex { index: 2 }), ("p14".into(), k, AssocSnap::Vertex { index: 1 })]); + assert_eq!(origins(&dm), [(500.0, 20.0), (520.0, 20.0)]); + // Still attached: moving the polyline takes the dimension along. + s.execute("move", &json!({ "handles": [k.hex()], "delta": [0, 10] })).unwrap(); + assert_eq!(origins(&dim(&s, d)), [(500.0, 30.0), (520.0, 30.0)]); +} + +#[test] +fn constraints_on_a_broken_object_go_and_leave_the_others_where_they_are() { + let mut s = Session::new(); + let a = first_handle(&s.execute("line", &json!({ "points": [[0, 0], [100, 0]] })).unwrap()); + let b = first_handle(&s.execute("line", &json!({ "points": [[100, 0], [100, 50]] })).unwrap()); + s.execute("geomconstraint", &json!({ "type": "coincident", "h1": a.hex(), "p1": "end", "h2": b.hex(), "p2": "start" })).unwrap(); + s.execute("break", &json!({ "handle": a.hex(), "p1": [40, 0], "p2": [60, 0] })).unwrap(); + let d = s.doc().unwrap(); + assert!(d.constraints.is_empty()); + let original = [a, b]; + assert_eq!(table(&s, &original), ["0:LINE:0,0>40,0", "0:LINE:100,0>100,50", "0+:LINE:60,0>100,0"]); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index a1d948213..2e4df8c15 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -19,6 +19,7 @@ mod blockreplace; mod break_closed_polyline; mod break_join_locked_layers; mod break_keeps_z; +mod break_trim_keep_handle; mod burst; mod change_command; mod chprop_command; @@ -86,6 +87,7 @@ mod minsert; mod mirror_degenerate_line; mod mleader_content; mod mleader_remember; +mod mleader_text_edit; mod mline; mod mocoro; mod modify_curves; @@ -113,6 +115,7 @@ mod polyface_explode; mod post_command_passes; mod prompt_keywords; mod prompt_or_once; +mod properties_set_locked; mod props_bad_lineweight; mod props_insert_scale_attribs; mod purge_mlinestyles; diff --git a/crates/engine/tests/it/mleader_text_edit.rs b/crates/engine/tests/it/mleader_text_edit.rs new file mode 100644 index 000000000..605b3247c --- /dev/null +++ b/crates/engine/tests/it/mleader_text_edit.rs @@ -0,0 +1,124 @@ +//! #1081: a multileader's text can be edited: TEXTEDIT (what a double-click starts) takes it and +//! hands it to the in-place editor, and the Properties palette's Contents field changes it. + +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::{Input, Session}; +use serde_json::json; + +fn text_of(s: &Session) -> String { + s.doc() + .unwrap() + .model + .iter() + .find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| t.contents.clone()) } else { None }) + .unwrap() +} + +#[test] +fn textedit_and_properties_change_a_multileaders_text() { + let mut s = Session::new(); + s.execute("mleader", &json!({"points": [[0, 0], [20, 20]], "text": "example text"})).unwrap(); + let (h, at) = s + .doc() + .unwrap() + .model + .iter() + .find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| (e.handle, t.insert.xy())) } else { None }) + .unwrap(); + + // TEXTEDIT on the text: the current contents are the default, and the in-place editor gets + // the multileader's MTEXT. + s.cmdline("TEXTEDIT").unwrap(); + s.input(Input::Point(at + Vec2::new(1.0, -0.05))).unwrap(); + let p = s.current_prompt().unwrap(); + assert_eq!(p.message, "Enter new text"); + assert_eq!(p.default.as_deref(), Some("example text")); + assert_eq!(s.editing_mtext().map(|m| m.contents), Some("example text".to_string())); + s.input(Input::Text("edited\nsecond line".into())).unwrap(); + assert_eq!(text_of(&s), "edited\\Psecond line"); + s.cancel(); + + // The Properties palette's Contents field. + s.execute("properties.set", &json!({"handles": [h.hex()], "text": "from properties"})).unwrap(); + assert_eq!(text_of(&s), "from properties"); +} + +/// An edited multileader text is undone in one step and is what a DXF save keeps. +#[test] +fn an_edited_multileader_text_undoes_and_survives_a_dxf_save() { + let mut s = Session::new(); + s.execute("mleader", &json!({"points": [[0, 0], [20, 20]], "text": "example text"})).unwrap(); + let at = s + .doc() + .unwrap() + .model + .iter() + .find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| t.insert.xy()) } else { None }) + .unwrap(); + s.cmdline("TEXTEDIT").unwrap(); + s.input(Input::Point(at + Vec2::new(1.0, -0.05))).unwrap(); + s.input(Input::Text("edited\nsecond line".into())).unwrap(); + s.cancel(); + // 2007 DXF: older versions keep a multileader as a LEADER and an MTEXT. + let opts = cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2007), binary: false }; + let reopened = cadcraft_io::read_dxf(&cadcraft_io::write_with(s.doc().unwrap(), "x.dxf", &opts).unwrap()).unwrap(); + let saved = + reopened.model.iter().find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| t.contents.clone()) } else { None }); + assert_eq!(saved.as_deref(), Some("edited\\Psecond line")); + s.undo().unwrap(); + assert_eq!(text_of(&s), "example text"); +} + +/// A multileader on a locked layer is refused when it is picked, before the editor opens, and +/// Properties leaves it alone. +#[test] +fn a_multileader_on_a_locked_layer_is_refused_when_picked() { + let mut s = Session::new(); + s.execute("mleader", &json!({"points": [[0, 0], [20, 20]], "text": "example text"})).unwrap(); + let (h, at) = s + .doc() + .unwrap() + .model + .iter() + .find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| (e.handle, t.insert.xy())) } else { None }) + .unwrap(); + s.execute("layer.set", &json!({"name": "0", "locked": true})).unwrap(); + s.cmdline("TEXTEDIT").unwrap(); + s.input(Input::Point(at + Vec2::new(1.0, -0.05))).unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("The object is on a locked layer.")); + assert!(s.editing_mtext().is_none(), "the editor doesn't open"); + assert_eq!(s.current_prompt().unwrap().message, "Select an annotation object"); + s.cancel(); + let r = s.execute("properties.set", &json!({"handles": [h.hex()], "text": "from properties"})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["locked"].as_u64()), (Some(0), Some(1)), "{r}"); + assert_eq!(text_of(&s), "example text"); +} + +#[test] +fn a_text_too_long_for_the_editor_is_asked_for_at_the_command_line() { + let mut s = Session::new(); + s.execute("mleader", &json!({"points": [[0, 0], [20, 20]], "text": "example text"})).unwrap(); + let (h, at) = s + .doc() + .unwrap() + .model + .iter() + .find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| (e.handle, t.insert.xy())) } else { None }) + .unwrap(); + let long = format!("example text {}", "x".repeat(cadcraft_engine::mtext_edit::MAX_CHARS)); + s.execute("properties.set", &json!({"handles": [h.hex()], "text": long})).unwrap(); + assert_eq!(text_of(&s), long); + s.cmdline("TEXTEDIT").unwrap(); + s.input(Input::Point(at + Vec2::new(1.0, -0.05))).unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("This text is too long for the editor; enter the new text at the command line.")); + assert!(s.editing_mtext().is_none(), "the editor doesn't open"); + assert_eq!(s.current_prompt().unwrap().message, "Enter new text"); + // Enter keeps it whole; a typed answer still replaces it, as for any other text. + s.input(Input::Enter).unwrap(); + assert_eq!(text_of(&s), long, "the text is not shortened"); + s.input(Input::Point(at + Vec2::new(1.0, -0.05))).unwrap(); + s.input(Input::Text("short".into())).unwrap(); + assert_eq!(text_of(&s), "short"); + s.cancel(); +} diff --git a/crates/engine/tests/it/mocoro.rs b/crates/engine/tests/it/mocoro.rs index 88fb8c4ee..8d1ff521c 100644 --- a/crates/engine/tests/it/mocoro.rs +++ b/crates/engine/tests/it/mocoro.rs @@ -233,3 +233,17 @@ fn options_on_objects_that_are_gone_record_nothing() { assert!(lines(&s).is_empty()); assert_eq!(undo_len(&s), undo, "no empty undo step"); } + +#[test] +fn json_form_copies_stay_within_maxarray() { + let mut s = Session::new(); + let l = line(&mut s, [0.0, 0.0], [10.0, 0.0]); + // 5,000 Copy options of 30 objects would be 150,000 copies, over the default MAXARRAY of 100,000. + let others: Vec = (0..29).map(|i| line(&mut s, [0.0, f64::from(i + 1)], [10.0, f64::from(i + 1)])).collect(); + let mut hs = vec![l]; + hs.extend(others); + let ops: Vec = (0..5_000).map(|i| json!({"copy": [0, i]})).collect(); + let e = s.execute("mocoro", &json!({"handles": hs, "base": [0, 0], "ops": ops})).unwrap_err(); + assert!(e.to_string().contains("MAXARRAY"), "{e}"); + assert_eq!(lines(&s).len(), 30, "nothing was copied"); +} diff --git a/crates/engine/tests/it/properties_set_locked.rs b/crates/engine/tests/it/properties_set_locked.rs new file mode 100644 index 000000000..d36ec72e9 --- /dev/null +++ b/crates/engine/tests/it/properties_set_locked.rs @@ -0,0 +1,154 @@ +//! `properties.set`, which the Properties palette, Quick Properties and CHPROP edit through, leaves +//! objects on locked layers alone as CHPROP, MATCHPROP and MOVE do, and says how many it left out. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::color::Color; +use cadcraft_engine::doc::{Common, EntityKind, Handle, Insert, Space}; +use cadcraft_engine::geom::Vec3; +use serde_json::{Value, json}; + +fn handle(v: &Value) -> Handle { + Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap() +} + +fn line(s: &mut Session, y: f64) -> Handle { + handle(&s.execute("line", &json!({ "points": [[0, y], [50, y]] })).unwrap()) +} + +/// Line a on layer 0 and lines b and c on the locked layer L1; their handles. +fn locked_drawing() -> (Session, [Handle; 3]) { + let mut s = Session::new(); + let hs = [line(&mut s, 0.0), line(&mut s, 20.0), line(&mut s, 40.0)]; + s.execute("properties.set", &json!({ "handles": [hs[1].hex(), hs[2].hex()], "layer": "L1" })).unwrap(); + s.execute("layer.set", &json!({ "name": "L1", "locked": true })).unwrap(); + (s, hs) +} + +fn counts(r: &Value) -> (Option, Option) { + (r["changed"].as_u64(), r["locked"].as_u64()) +} + +fn colors(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.common.color).collect() +} + +fn layers(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.common.layer.clone()).collect() +} + +#[test] +fn objects_on_locked_layers_are_left_out() { + let (mut s, [a, b, c]) = locked_drawing(); + let r = s.execute("properties.set", &json!({ "handles": [a.hex()], "color": 2 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(0)), "{r}"); + assert!(r.get("message").is_none(), "{r}"); + let r = s.execute("properties.set", &json!({ "handles": [a.hex(), b.hex()], "color": 3 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was on a locked layer."); + assert_eq!(colors(&s), [Color::Index(3), Color::ByLayer, Color::ByLayer]); + // The selection when no handles are given; a new layer leaves them on theirs. + s.set_selection(vec![a, b, c]); + let r = s.execute("properties.set", &json!({ "layer": "L2" })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(2)), "{r}"); + assert_eq!(r["message"], "2 objects were on a locked layer."); + assert_eq!(layers(&s), ["L2", "L1", "L1"]); + // An object listed twice counts once. + let r = s.execute("properties.set", &json!({ "handles": [a.hex(), a.hex(), b.hex(), b.hex()], "color": 6 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was on a locked layer."); +} + +/// CHPROP says so when it leaves an edit out: an object it moved onto a locked layer keeps its +/// color. +#[test] +fn chprop_says_when_it_leaves_an_object_it_moved_onto_a_locked_layer_alone() { + let (mut s, _) = locked_drawing(); + let d = line(&mut s, 60.0); + s.cmdline("(setq d (entlast))").unwrap(); + s.log.clear(); + s.cmdline("(command \"_.CHPROP\" d \"\" \"_LA\" \"L1\" \"_C\" 3 \"\")").unwrap(); + let e = s.doc().unwrap().entity(d).unwrap().common.clone(); + assert_eq!((e.layer.as_str(), e.color), ("L1", Color::ByLayer)); + assert!(s.log.iter().any(|l| l == "1 object was on a locked layer. Nothing was changed."), "{:?}", s.log); +} + +/// A handle that names no object is refused before anything changes. +#[test] +fn a_missing_object_is_refused_before_any_change() { + let (mut s, [a, b, _]) = locked_drawing(); + let undo = s.state().unwrap().undo.len(); + assert!(s.execute("properties.set", &json!({ "handles": [a.hex(), b.hex(), "FFFFF"], "color": 7 })).is_err()); + assert_eq!(colors(&s), [Color::ByLayer; 3]); + assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step"); +} + +#[test] +fn with_every_object_locked_nothing_changes() { + let (mut s, [_, b, c]) = locked_drawing(); + let undo = s.state().unwrap().undo.len(); + let r = s.execute("properties.set", &json!({ "handles": [b.hex(), c.hex()], "layer": "NEW", "color": 4 })).unwrap(); + assert_eq!(counts(&r), (Some(0), Some(2)), "{r}"); + assert_eq!(r["message"], "2 objects were on a locked layer. Nothing was changed."); + assert_eq!(colors(&s), [Color::ByLayer; 3]); + assert!(s.doc().unwrap().layer("NEW").is_none(), "no layer is made"); + assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step"); + // A bad value is still refused, whichever it is. + for bad in [ + json!({ "color": "nonsense" }), + json!({ "linetype": "NOT_LOADED" }), + json!({ "dimStyle": "Missing" }), + json!({ "textHeight": -1 }), + json!({ "precision": 9 }), + ] { + let mut p = bad.clone(); + p["handles"] = json!([b.hex()]); + assert!(s.execute("properties.set", &p).is_err(), "{bad}"); + } + // CHPROP's JSON form is properties.set. + let r = s.execute("chprop", &json!({ "handles": [b.hex()], "color": 4 })).unwrap(); + assert_eq!(counts(&r), (Some(0), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was on a locked layer. Nothing was changed."); +} + +/// While a reference is edited in place, only its working set changes; before, an edit that +/// reached outside it was refused whole. +#[test] +fn during_refedit_objects_outside_the_working_set_are_left_out() { + let mut s = Session::new(); + let l = line(&mut s, 0.0); + s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [l.hex()], "keep": "delete" })).unwrap(); + let kind = EntityKind::Insert(Insert { + block: "B".into(), + insert: Vec3::new(100.0, 0.0, 0.0), + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + }); + let a = s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap(); + let other = line(&mut s, 20.0); + let r = s.execute("refedit", &json!({ "handle": a.hex() })).unwrap(); + let copy = handle(&json!({ "handle": r["working"][0] })); + let r = s.execute("properties.set", &json!({ "handles": [copy.hex(), other.hex()], "color": 5 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was not in the working set."); + let d = s.doc().unwrap(); + assert_eq!(d.entity(copy).unwrap().common.color, Color::Index(5)); + assert_eq!(d.entity(other).unwrap().common.color, Color::ByLayer); + assert!(d.refedit.is_some(), "the edit goes on"); + // With only objects outside the working set, nothing changes: no layer, no undo step. + let undo = s.state().unwrap().undo.len(); + let r = s.execute("properties.set", &json!({ "handles": [other.hex()], "color": 6, "layer": "NEW" })).unwrap(); + assert_eq!(counts(&r), (Some(0), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was not in the working set. Nothing was changed."); + assert_eq!(s.doc().unwrap().entity(other).unwrap().common.color, Color::ByLayer); + assert!(s.doc().unwrap().layer("NEW").is_none(), "no layer is made"); + assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step"); + // A handle that names no object isn't counted as outside the working set: it's refused. + assert!(s.execute("properties.set", &json!({ "handles": [copy.hex(), "FFFFF"], "color": 6 })).is_err()); + assert_eq!(s.doc().unwrap().entity(copy).unwrap().common.color, Color::Index(5)); +} diff --git a/crates/engine/tests/ole_frame_transform.rs b/crates/engine/tests/ole_frame_transform.rs new file mode 100644 index 000000000..171af556c --- /dev/null +++ b/crates/engine/tests/ole_frame_transform.rs @@ -0,0 +1,285 @@ +//! An OLE2FRAME is window-selectable (it counts in the extents, #2422): MOVE and COPY carry it by +//! the offset, and the transforms that would not keep it axis aligned are refused before anything +//! reports success (review on #2587). + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Common, Drawing, EntityKind, RawTag, Space, Unknown}; +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 h = d.add(&Space::Model, Common::default(), kind).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "ole.dxf", None); + (s, h.hex()) +} + +fn corners(s: &Session) -> Vec<(i32, String)> { + let d = s.doc().unwrap(); + d.model + .iter() + .filter_map(|e| { + if let EntityKind::Unknown(u) = &e.kind { Some(u.tags.iter().map(|t| (t.code, t.value.clone())).collect::>()) } else { None } + }) + .flatten() + .collect() +} + +#[test] +fn move_and_copy_carry_an_ole_frame() { + let (mut s, h) = session(); + s.execute("move", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + let want: Vec<(i32, String)> = [(10, "40"), (20, "-14"), (11, "45"), (21, "-17")].iter().map(|(c, v)| (*c, v.to_string())).collect(); + assert_eq!(corners(&s), want); + s.execute("copy", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + let all = corners(&s); + assert_eq!(all.len(), 8); + assert_eq!(all[4..].iter().map(|(_, v)| v.as_str()).collect::>(), ["50", "-9", "55", "-12"]); +} + +#[test] +fn rotate_and_mirror_refuse_an_ole_frame() { + let (mut s, h) = session(); + let before = corners(&s); + for (cmd, p) in + [("rotate", json!({ "handles": [h], "base": [0, 0], "angle": 30 })), ("mirror", json!({ "handles": [h], "p1": [0, 0], "p2": [1, 0] }))] + { + let e = s.execute(cmd, &p).expect_err(cmd); + assert!(e.to_string().contains("OLE object"), "{cmd}: {e}"); + } + assert_eq!(corners(&s), before); + assert_eq!(s.doc().unwrap().model.len(), 1, "nothing was copied"); +} + +/// The OLE data's marker and four corners (x, y, z doubles each), as hex split into chunks. +fn data_session(chunks: &[usize], hex_override: Option<&str>) -> (Session, String) { + let tag = |code: i32, v: &str| RawTag { code, value: v.into() }; + let mut blob = vec![1u8, 0]; + for (x, y) in [(30.0f64, -19.0f64), (35.0, -19.0), (35.0, -22.0), (30.0, -22.0)] { + for v in [x, y, 7.0] { + blob.extend_from_slice(&v.to_le_bytes()); + } + } + let hex: String = hex_override.map(str::to_string).unwrap_or_else(|| blob.iter().map(|b| format!("{b:02X}")).collect()); + let mut tags = vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")]; + let mut at = 0; + for &n in chunks { + let end = (at + n).min(hex.len()); + tags.push(tag(310, &hex[at..end])); + at = end; + } + if at < hex.len() { + 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 mut s = Session::empty(); + s.open_drawing(d, "ole.dxf", None); + (s, h.hex()) +} + +fn data_tags(s: &Session) -> Vec { + let d = s.doc().unwrap(); + d.model + .iter() + .filter_map(|e| { + if let EntityKind::Unknown(u) = &e.kind { + Some(u.tags.iter().filter(|t| t.code == 310).map(|t| t.value.clone()).collect::>()) + } else { + None + } + }) + .flatten() + .collect() +} + +#[test] +fn move_also_moves_the_corners_in_the_ole_data() { + let (mut s, h) = data_session(&[10, 100, 40], None); + let before = data_tags(&s); + s.execute("move", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + let after = data_tags(&s); + assert_eq!(after.iter().map(String::len).collect::>(), before.iter().map(String::len).collect::>(), "chunk lengths are kept"); + let hex: String = after.concat(); + let bytes: Vec = (0..hex.len() / 2).map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap()).collect(); + let f = |o: usize| f64::from_le_bytes(bytes[o..o + 8].try_into().unwrap()); + let want = [(40.0, -14.0), (45.0, -14.0), (45.0, -17.0), (40.0, -17.0)]; + for (c, (x, y)) in want.iter().enumerate() { + assert_eq!((f(2 + c * 24), f(10 + c * 24), f(18 + c * 24)), (*x, *y, 7.0), "corner {c}"); + } +} + +#[test] +fn move_leaves_malformed_or_short_ole_data_alone() { + for (chunks, hex) in [(vec![4], "0100"), (vec![3, 3], "ABCDE"), (vec![10], "ZZ0100ZZ0100"), (vec![2], "é")] { + let (mut s, h) = data_session(&chunks, Some(hex)); + let before = data_tags(&s); + s.execute("move", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + assert_eq!(data_tags(&s), before, "{hex}"); + assert_eq!(corners(&s)[0].1, "40", "the corner groups still move"); + } +} + +/// OLE data whose bytes are not this frame's corners (an unknown header, so the layout does not +/// apply) is not rewritten by MOVE; the frame's own corner groups still move (review on #2587). +#[test] +fn move_leaves_ole_data_that_is_not_the_frames_corners_alone() { + let mut blob = vec![9u8, 9]; + for (x, y) in [(1.0f64, 2.0f64), (3.0, 2.0), (3.0, 4.0), (1.0, 4.0)] { + for v in [x, y, 7.0] { + blob.extend_from_slice(&v.to_le_bytes()); + } + } + let hex: String = blob.iter().map(|b| format!("{b:02X}")).collect(); + let (mut s, h) = data_session(&[40, 100], Some(&hex)); + let before = data_tags(&s); + s.execute("move", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + assert_eq!(data_tags(&s), before); + assert_eq!(corners(&s)[0].1, "40", "the corner groups still move"); +} + +#[test] +fn mocoro_refuses_before_it_changes_anything() { + let (mut s, h) = session(); + let before = corners(&s); + let undo = s.state().unwrap().undo.len(); + let ops = json!([{ "move": [10, 5] }, { "copy": [20, 0] }, { "rotate": 30 }]); + let e = s.execute("mocoro", &json!({ "handles": [h], "base": [0, 0], "ops": ops })).expect_err("rotate"); + assert!(e.to_string().contains("OLE object"), "{e}"); + assert_eq!(corners(&s), before, "the earlier move and copy were not applied"); + assert_eq!(s.doc().unwrap().model.len(), 1); + assert_eq!(s.state().unwrap().undo.len(), undo); +} + +#[test] +fn a_locked_ole_frame_does_not_block_an_in_place_rotation() { + let tag = |code: i32, v: &str| RawTag { code, value: v.into() }; + 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 ole = d.add(&Space::Model, common, kind).unwrap(); + if let Some(l) = d.layer_mut("L") { + l.locked = true; + } + let mut s = Session::empty(); + s.open_drawing(d, "ole.dxf", None); + let ln = s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + let ln = ln["handle"].as_str().or_else(|| ln["handles"][0].as_str()).unwrap().to_string(); + let before = corners(&s); + s.execute("rotate", &json!({ "handles": [ln.clone(), ole.hex()], "base": [0, 0], "angle": 90 })).unwrap(); + assert_eq!(corners(&s), before, "the locked frame is left alone"); + let d = s.doc().unwrap(); + let e = d.entity(cadcraft_engine::doc::Handle::parse_hex(&ln).unwrap()).unwrap(); + let cadcraft_engine::doc::EntityKind::Line(l) = &e.kind else { panic!("line") }; + assert!((l.b.y - 10.0).abs() < 1e-9 && l.b.x.abs() < 1e-9, "{l:?}"); +} + +/// The four corners (x, y) in the OLE data header, read back from the 310 groups. +fn data_corners(s: &Session) -> Vec<(f64, f64)> { + let hex: String = data_tags(s).concat(); + let bytes: Vec = (0..hex.len() / 2).map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap()).collect(); + let f = |o: usize| f64::from_le_bytes(bytes[o..o + 8].try_into().unwrap()); + (0..4).map(|c| (f(2 + c * 24), f(10 + c * 24))).collect() +} + +fn line_in(s: &mut Session) -> String { + let ln = s.execute("line", &json!({ "points": [[1, 2], [4, 6]] })).unwrap(); + ln["handle"].as_str().or_else(|| ln["handles"][0].as_str()).unwrap().to_string() +} + +fn line_ends(s: &Session, h: &str) -> ((f64, f64), (f64, f64)) { + let e = s.doc().unwrap().entity(cadcraft_engine::doc::Handle::parse_hex(h).unwrap()).unwrap(); + let EntityKind::Line(l) = &e.kind else { panic!("line") }; + ((l.a.x, l.a.y), (l.b.x, l.b.y)) +} + +/// SCALE with a uniform positive factor carries an OLE frame with the rest of the selection: the +/// corner groups and the corners in the OLE data are both mapped (review on #2587). +#[test] +fn scale_carries_an_ole_frame_with_the_rest_of_the_selection() { + let (mut s, h) = data_session(&[10, 100, 40], None); + let ln = line_in(&mut s); + s.execute("scale", &json!({ "handles": [ln.clone(), h], "base": [0, 0], "factor": 2 })).unwrap(); + assert_eq!(line_ends(&s, &ln), ((2.0, 4.0), (8.0, 12.0))); + let want: Vec<(i32, String)> = [(10, "60"), (20, "-38"), (11, "70"), (21, "-44")].iter().map(|(c, v)| (*c, v.to_string())).collect(); + let tags: Vec<(i32, String)> = corners(&s).into_iter().filter(|(c, _)| *c != 310).collect(); + assert_eq!(tags, want); + assert_eq!(data_corners(&s), vec![(60.0, -38.0), (70.0, -38.0), (70.0, -44.0), (60.0, -44.0)]); +} + +/// MOCORO with a scale step carries the frame too, like SCALE. +#[test] +fn mocoro_scales_an_ole_frame() { + let (mut s, h) = data_session(&[10, 100, 40], None); + s.execute("mocoro", &json!({ "handles": [h], "base": [0, 0], "ops": [{ "scale": 3 }] })).unwrap(); + assert_eq!(data_corners(&s)[0], (90.0, -57.0)); + assert_eq!(corners(&s)[0].1, "90"); +} + +/// ARRAYPATH with align rotates each copy, which an OLE frame refuses. The refusal comes before +/// the first copy is added: an error does not roll the drawing back (review on #2587). +#[test] +fn arraypath_refuses_before_adding_any_copy() { + let (mut s, h) = session(); + // Straight for 30 units, then a right-angle bend: the first copies only move, a later one turns. + let path = s.execute("pline", &json!({ "points": [[0, 0], [30, 0], [30, 30]] })).unwrap(); + let path = path["handle"].as_str().or_else(|| path["handles"][0].as_str()).unwrap().to_string(); + let count = s.doc().unwrap().model.len(); + let before = corners(&s); + let e = s.execute("arraypath", &json!({ "handles": [h], "path": path, "count": 7, "align": true })).expect_err("align"); + assert!(e.to_string().contains("OLE object"), "{e}"); + assert_eq!(s.doc().unwrap().model.len(), count, "no copy was added"); + assert_eq!(corners(&s), before); +} + +/// A refused command leaves the drawing and its undo history alone: UNDO afterwards takes back the +/// earlier MOVE, not a phantom step (review on #2587). +#[test] +fn a_refused_rotation_adds_no_undo_step() { + let (mut s, h) = session(); + let original = corners(&s); + s.execute("move", &json!({ "handles": [h.clone()], "delta": [10, 5] })).unwrap(); + let undo = s.state().unwrap().undo.len(); + s.execute("rotate", &json!({ "handles": [h], "base": [0, 0], "angle": 30 })).expect_err("rotate"); + assert_eq!(s.state().unwrap().undo.len(), undo); + s.execute("undo", &json!({})).unwrap(); + assert_eq!(corners(&s), original); +} + +/// The classic -ARRAY makes separate copies: a polar array that turns its items refuses an OLE +/// frame before the first copy, and one that keeps the items upright carries it. +#[test] +fn classic_polar_array_refuses_a_turned_frame_but_not_an_upright_one() { + let (mut s, h) = session(); + let before = corners(&s); + let turned = json!({ "handles": [h.clone()], "type": "polar", "center": [0, 0], "count": 4, "rotate": true }); + let e = s.execute("-array", &turned).expect_err("turned items"); + assert!(e.to_string().contains("OLE object"), "{e}"); + assert_eq!((s.doc().unwrap().model.len(), corners(&s)), (1, before)); + let upright = json!({ "handles": [h], "type": "polar", "center": [0, 0], "count": 4, "rotate": false }); + s.execute("-array", &upright).unwrap(); + assert_eq!(s.doc().unwrap().model.len(), 4); +} + +/// The frame is picked by its outline but is not geometry for other commands: a line across it is +/// not cut at its edges by TRIM, and object snap near its corner offers no frame point (review on +/// #2587). +#[test] +fn ole_frame_is_not_a_trim_edge_or_snap_target() { + use cadcraft_engine::snap::{mode, osnap}; + let (mut s, _frame) = session(); + let ln = s.execute("line", &json!({ "points": [[28, -20.5], [37, -20.5]] })).unwrap(); + let ln = ln["handle"].as_str().or_else(|| ln["handles"][0].as_str()).unwrap().to_string(); + // No cutting edge is named, so every object but the line itself is one. + let _ = s.execute("trim", &json!({ "handle": ln.clone(), "pick": [32, -20.5] })); + assert_eq!(line_ends(&s, &ln), ((28.0, -20.5), (37.0, -20.5)), "the line is not cut at the frame"); + assert_eq!(s.doc().unwrap().model.len(), 2); + let all = mode::END | mode::MID | mode::INT | mode::PER | mode::CEN | mode::QUA | mode::NOD; + let hit = osnap(s.doc().unwrap(), &Space::Model, cadcraft_engine::geom::Vec2::new(30.0, -19.0), 0.5, all, None, false); + assert!(hit.is_none(), "no snap point on the frame: {hit:?}"); +} diff --git a/crates/engine/tests/plot_format.rs b/crates/engine/tests/plot_format.rs new file mode 100644 index 000000000..48a4306bb --- /dev/null +++ b/crates/engine/tests/plot_format.rs @@ -0,0 +1,69 @@ +//! PLOT chooses the output format from the extension of `path` when no device is named (#2556), +//! like EXPORT does; a device that writes another format is refused. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::cmd::plotters::{PlotterStore, set_plotter_store}; +use serde_json::json; + +fn session() -> Session { + set_plotter_store(PlotterStore::memory()); + set_io(IoHooks { + read: |_, _| Err("no reader in this test".into()), + write: |_, _| Err("no writer in this test".into()), + plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), + }); + let mut s = Session::new(); + s.cmdline("line 0,0 100,0").unwrap(); + s.cmdline("").unwrap(); + s +} + +fn magic(path: &std::path::Path) -> Vec { + std::fs::read(path).unwrap().into_iter().take(5).collect() +} + +#[test] +fn the_extension_picks_png_svg_or_pdf() { + let mut s = session(); + let dir = std::env::temp_dir().join(format!("cadcraft-plot-format-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let cases: [(&str, &[u8], &str); 4] = + [("a.png", b"\x89PNG\r", "png"), ("b.svg", b" Result { continue; } let has = |script: &str| scripts.split(',').any(|s| s.trim() == script); - let web_face = (*family == "BIZ UDPGothic" && *style == "Regular") || has("Arab") || (has("Thai") && *style == "Regular"); + let web_face = (*family == "BIZ UDPGothic" && *style == "Regular") || has("Arab") || has("Geor") || (has("Thai") && *style == "Regular"); if wasm && !web_face { continue; } diff --git a/crates/fonts/src/bidi.rs b/crates/fonts/src/bidi.rs index 1ca5a90ae..0cebd6bbc 100644 --- a/crates/fonts/src/bidi.rs +++ b/crates/fonts/src/bidi.rs @@ -33,13 +33,21 @@ pub(crate) fn is_mark(c: char) -> bool { } /// Base direction of a paragraph from its first strong character (rules P2/P3): `Some(true)` -/// right-to-left, `Some(false)` left-to-right, `None` when it has no strong character. +/// right-to-left, `Some(false)` left-to-right, `None` when it has no strong character. As rule +/// P2 requires, characters between an isolate initiator and its matching PDI (or the end of the +/// paragraph, when unmatched) are skipped. pub fn base_rtl(s: &str) -> Option { - s.chars().find_map(|c| match bidi_class(c) { - BidiClass::L => Some(false), - BidiClass::R | BidiClass::AL => Some(true), - _ => None, - }) + let mut isolate_depth: usize = 0; + for c in s.chars() { + match bidi_class(c) { + BidiClass::LRI | BidiClass::RLI | BidiClass::FSI => isolate_depth = isolate_depth.saturating_add(1), + BidiClass::PDI => isolate_depth = isolate_depth.saturating_sub(1), + BidiClass::L if isolate_depth == 0 => return Some(false), + BidiClass::R | BidiClass::AL if isolate_depth == 0 => return Some(true), + _ => {} + } + } + None } fn para_level(base: Option) -> Option { @@ -349,14 +357,24 @@ pub fn presentation_forms(chars: &[char], keep: impl Fn(char) -> bool) -> Vec<(c let mut i = 0; while let Some(&c) = chars.get(i) { let form = forms.get(i).copied().flatten(); + // Combining marks (harakat) between lam and alef are transparent for joining, so they + // don't block the ligature; they stay after it, in logical order. + let alef_at = + if c == '\u{0644}' { chars.get(i + 1..).and_then(|rest| rest.iter().position(|ch| !is_mark(*ch))).map(|p| i + 1 + p) } else { None }; if c == '\u{0644}' && let Some(f) = form - && let Some(&a) = chars.get(i + 1) + && let Some(j) = alef_at + && let Some(&a) = chars.get(j) && let Some(lig) = lam_alef(a, matches!(f, Form::Medial | Form::Final)) && keep(lig) { out.push((lig, i)); - i += 2; + for k in i + 1..j { + if let Some(&m) = chars.get(k) { + out.push((m, k)); + } + } + i = j + 1; continue; } let shaped = form.and_then(|f| presentation_form(c, f)).filter(|p| keep(*p)).unwrap_or(c); @@ -442,6 +460,48 @@ mod tests { assert!(visual_runs(&[], None).is_empty() && char_levels("", None).is_empty()); } + #[test] + fn paragraph_direction_skips_isolate_contents() { + // RLI שלום PDI abc: the Hebrew sits inside the isolate, so the first strong character is "a". + assert_eq!(base_rtl("\u{2067}שלום\u{2069} abc"), Some(false)); + assert_eq!(base_rtl("\u{2066}abc\u{2069} שלום"), Some(true)); + assert_eq!(base_rtl("\u{2068}שלום\u{2069}abc"), Some(false)); + // Nested isolates: only the outermost PDI closes the outer one. + assert_eq!(base_rtl("\u{2066}a\u{2067}ב\u{2069}a\u{2069}ב"), Some(true)); + assert_eq!(base_rtl("\u{2067}\u{2066}a\u{2069}ב\u{2069}a"), Some(false)); + // An unmatched initiator isolates the rest of the paragraph. + assert_eq!(base_rtl("\u{2067}שלום"), None); + assert_eq!(base_rtl("\u{2067}שלום\u{2069}"), None); + // A stray PDI does not close anything and does not underflow. + assert_eq!(base_rtl("\u{2069}\u{2069}שלום"), Some(true)); + // No strong character outside the isolates. + assert_eq!(base_rtl("12 \u{2066}abc\u{2069} 34"), None); + // Without isolates nothing changes. + assert_eq!(base_rtl(" 123 سلام abc"), Some(true)); + } + + #[test] + fn harakat_between_lam_and_alef_keep_the_ligature() { + let run = |s: &str| -> Vec<(char, usize)> { + let chars: Vec = s.chars().collect(); + presentation_forms(&chars, |_| true) + }; + // Lam + fatha + alef: the ligature, then the fatha (logical order kept). + assert_eq!(run("ل\u{064E}ا"), vec![('\u{FEFB}', 0), ('\u{064E}', 1)]); + // Word-medial: س + lam + fatha + shadda + alef gives the final ligature, marks after it. + assert_eq!(run("سل\u{064E}\u{0651}ا"), vec![('\u{FEB3}', 0), ('\u{FEFC}', 1), ('\u{064E}', 2), ('\u{0651}', 3)]); + // Plain lam + alef is unchanged. + assert_eq!(run("لا"), vec![('\u{FEFB}', 0)]); + // Mark after the alef is not between them: unchanged behaviour. + assert_eq!(run("لا\u{064E}"), vec![('\u{FEFB}', 0), ('\u{064E}', 2)]); + // Lam + mark + a non-alef letter: no ligature, the lam joins forward as before. + assert_eq!(run("ل\u{064E}م"), vec![('\u{FEDF}', 0), ('\u{064E}', 1), ('\u{FEE2}', 2)]); + // Lam + mark at the end: no alef, nothing breaks. + assert_eq!(run("ل\u{064E}"), vec![('\u{FEDD}', 0), ('\u{064E}', 1)]); + // A non-mark between lam and alef blocks the ligature. + assert_eq!(run("ل-ا").len(), 3); + } + #[test] fn hostile_input_never_panics() { for s in [ diff --git a/crates/fonts/src/craft_fonts.rs b/crates/fonts/src/craft_fonts.rs index 801b84027..3436d1d5f 100644 --- a/crates/fonts/src/craft_fonts.rs +++ b/crates/fonts/src/craft_fonts.rs @@ -1,8 +1,8 @@ //! Fonts from the optional craft-fonts build input (). //! //! Built with `CRAFT_FONTS_DIR=`, `build.rs` embeds the fonts listed in its -//! `fonts/manifest.txt` (web builds: only BIZ UDPGothic Regular, the Arabic faces and the Thai -//! Regular faces). Without it [`CRAFT_FONTS`] is empty and nothing changes. The font table ([`crate::ttf`]) +//! `fonts/manifest.txt` (web builds: only BIZ UDPGothic Regular, the Arabic and Georgian faces and +//! the Thai Regular faces). Without it [`CRAFT_FONTS`] is empty and nothing changes. The font table ([`crate::ttf`]) //! lists the embedded fonts with the installed ones, under [`CraftFont::stem`]. A text style //! can name one (`BIZ UDPGothic`), and they are fallbacks for characters a text's font lacks. //! They are copied out of the binary only when first used. @@ -85,6 +85,7 @@ mod tests { Some("Arab") => '\u{0628}', Some("Thai") => '\u{0E01}', Some("Hang" | "Kore") => '가', + Some("Geor") => 'ა', _ => 'A', }; assert!(face.is_some_and(|x| x.has_glyph(sample)), "{} lacks {sample}", f.family); diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index e3bc973a5..9fe7aa47e 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -9,6 +9,8 @@ pub(crate) mod para; /// Strip MTEXT formatting codes to plain text with `\n` paragraph breaks. /// Stacked fractions `\S1/2;` become `1/2`; `\~` is a space; braces are dropped. pub fn plain_mtext(s: &str) -> String { + let s = unescape_codes(s); + let s = s.as_ref(); let mut out = String::with_capacity(s.len()); let chars: Vec = s.chars().collect(); let mut i = 0; @@ -63,7 +65,7 @@ pub fn plain_mtext(s: &str) -> String { i += 7; } // Codes with an argument terminated by ';' (\f, \F, \H, \W, \Q, \T, \A, \C, \c, \p). - _ => { + _ if takes_arg(code) => { let mut j = i + 2; while let Some(&ch) = chars.get(j) { if ch == ';' { @@ -73,6 +75,8 @@ pub fn plain_mtext(s: &str) -> String { } i = j + 1; } + // An unknown code has no argument: drop the backslash and the code only. + _ => i += 2, } } '{' | '}' => i += 1, @@ -180,11 +184,96 @@ enum Atom { Para(usize), } -/// Upper bound on parsed atoms (hostile contents). +/// Upper bound on parsed atoms (words, spaces and paragraph breaks) per MTEXT. Hostile contents +/// are cut here: once more than this many atoms are parsed, `parse` stops reading and the rest +/// of the contents is silently dropped from the layout. There is no warning to the caller. const MAX_ATOMS: usize = 200_000; /// Scale of stacked text relative to the surrounding text. const STACK_SCALE: f64 = 0.7; +/// Codes that take an argument terminated by `;` (besides `\S`, which has its own scan). Any +/// other code stands alone, so a missing `;` must not swallow the text after it. +pub(crate) fn takes_arg(code: char) -> bool { + matches!(code, 'f' | 'F' | 'H' | 'W' | 'Q' | 'T' | 'A' | 'C' | 'c' | 'p') +} + +/// The line-spacing factor to lay out with: AutoCAD's 0.25..=4 range, 1 for a missing or +/// non-finite value. +pub(crate) fn sane_line_spacing(v: f64) -> f64 { + if v.is_finite() && v > 0.0 { v.clamp(0.25, 4.0) } else { 1.0 } +} + +/// Four hex digits at `chars[at..at + 4]`. +fn hex4(chars: &[char], at: usize) -> Option { + let digits = chars.get(at..at.checked_add(4)?)?; + digits.iter().try_fold(0u32, |acc, c| Some(acc * 16 + c.to_digit(16)?)) +} + +/// Push a decoded character so that the tokenizers read it as text, never as markup. +fn push_literal(out: &mut String, c: char) { + if matches!(c, '\\' | '{' | '}') { + out.push('\\'); + } + out.push(c); +} + +/// Decode `\U+hhhh` (one UTF-16 unit; a surrogate pair gives one character, a lone surrogate +/// U+FFFD) and `\M+nhhhh` (double-byte East Asian characters) to the characters they stand +/// for. Malformed escapes are left for the tokenizers, which drop the backslash and the code. +/// An escaped backslash (`\\U+0041`) is not an escape. +pub(crate) fn unescape_codes(s: &str) -> std::borrow::Cow<'_, str> { + if !s.contains("\\U+") && !s.contains("\\M+") { + return std::borrow::Cow::Borrowed(s); + } + let chars: Vec = s.chars().collect(); + let mut out = String::with_capacity(s.len()); + let mut i = 0; + while let Some(&c) = chars.get(i) { + if c != '\\' { + out.push(c); + i += 1; + continue; + } + let (n, plus) = (chars.get(i + 1).copied(), chars.get(i + 2).copied()); + if n == Some('U') && plus == Some('+') { + if let Some(unit) = hex4(&chars, i + 3) { + i += 7; + let low = |at: usize| { + (chars.get(at) == Some(&'\\') && chars.get(at + 1) == Some(&'U') && chars.get(at + 2) == Some(&'+')) + .then(|| hex4(&chars, at + 3)) + .flatten() + .filter(|u| (0xDC00..0xE000).contains(u)) + }; + let ch = if (0xD800..0xDC00).contains(&unit) { + match low(i) { + Some(lo) => { + i += 7; + char::from_u32(0x10000 + ((unit - 0xD800) << 10) + (lo - 0xDC00)) + } + None => None, + } + } else { + char::from_u32(unit) + }; + push_literal(&mut out, ch.unwrap_or('\u{fffd}')); + continue; + } + } else if n == Some('M') && plus == Some('+') && chars.get(i + 3).is_some_and(char::is_ascii_digit) && hex4(&chars, i + 4).is_some() { + push_literal(&mut out, cadcraft_dxf::mif_escape_at(&chars, i).unwrap_or('\u{fffd}')); + i += 8; + continue; + } + // Any other backslash pair stays as it is (and an escaped backslash stays one). + out.push('\\'); + i += 1; + if let Some(&next) = chars.get(i) { + out.push(next); + i += 1; + } + } + std::borrow::Cow::Owned(out) +} + fn arg(chars: &[char], from: usize) -> (String, usize) { let mut j = from; let mut a = String::new(); @@ -236,6 +325,8 @@ fn font_switch(a: &str) -> Option { /// Parse MTEXT contents into words, spaces and paragraph breaks with their formats. fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { let chars: Vec = contents.chars().collect(); + let h_min = base.height * 1e-3; + let h_max = if (base.height * 1e3).is_finite() { base.height * 1e3 } else { f64::MAX }; let mut fmts = vec![base]; let mut cur = 0usize; let mut stack: Vec = Vec::new(); @@ -342,14 +433,22 @@ fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { None => (false, num(&a)), }; if let Some(v) = v.filter(|v| *v > 0.0 && *v < 1e6) { - derive(&mut fmts, &mut cur, &|f| f.height = if rel { f.height * v } else { v }); + // Relative heights compound; keep the result within 1e-3..1e3 times the + // MTEXT's own height, never infinite. + derive(&mut fmts, &mut cur, &|f| f.height = if rel { (f.height * v).min(h_max).max(h_min) } else { v }); } } 'W' => { let (a, n) = arg(&chars, i); i = n; - if let Some(v) = num(a.trim_end_matches(['x', 'X'])).filter(|v| *v > 0.01 && *v < 100.0) { - derive(&mut fmts, &mut cur, &|f| f.wf = v); + // `\W2x;` multiplies the current factor (like `\H2x;`); `\W2;` sets it. + let (rel, v) = match a.trim().strip_suffix(['x', 'X']) { + Some(r) => (true, num(r)), + None => (false, num(&a)), + }; + if let Some(v) = v.filter(|v| *v > 0.01 && *v < 100.0) { + // Relative factors compound; keep the result within the absolute range. + derive(&mut fmts, &mut cur, &|f| f.wf = if rel { (f.wf * v).clamp(0.01, 100.0) } else { v }); } } 'Q' => { @@ -381,11 +480,13 @@ fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { derive(&mut fmts, &mut cur, &|f| f.valign = v); } } - _ => { - // \T, \p and unknown codes: argument up to ';'. + _ if takes_arg(code) => { + // \T and \p: argument up to ';'. let (_, n) = arg(&chars, i); i = n; } + // An unknown code has no argument: only the backslash and the code are dropped. + _ => {} } } '{' => { @@ -692,11 +793,14 @@ fn plain_lines(atoms: &[Atom], fmts: &[Fmt], base: &Fmt, width: f64) -> Vec MTextLayout { + let contents = unescape_codes(contents); + let contents = contents.as_ref(); let h = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 }; let wf = if p.width_factor.is_finite() && p.width_factor > 0.0 { p.width_factor } else { 1.0 }; let width = if p.width.is_finite() && p.width > 0.0 { p.width } else { 0.0 }; let rotation = if p.rotation.is_finite() { p.rotation } else { 0.0 }; - let base = Fmt { font: p.font.clone(), height: h, color: None, under: false, over: false, wf, oblique: p.oblique, valign: 1 }; + let oblique = if p.oblique.is_finite() { p.oblique } else { 0.0 }; + let base = Fmt { font: p.font.clone(), height: h, color: None, under: false, over: false, wf, oblique, valign: 1 }; if para::needed(contents, p) { return para::layout(contents, p, &base); } @@ -719,7 +823,7 @@ pub fn layout_mtext_with(contents: &str, p: &MTextParams) -> MTextLayout { for l in &mut lines { l.reorder_bidi(bases.get(l.para).copied().flatten()); } - let ls = if p.line_spacing > 0.0 && p.line_spacing.is_finite() { p.line_spacing } else { 1.0 }; + let ls = sane_line_spacing(p.line_spacing); // Baselines below the top of the first line. let mut baselines = Vec::with_capacity(lines.len()); let mut y = 0.0; @@ -800,7 +904,108 @@ mod tests { assert_eq!(plain_mtext("\\H2.5x;Big"), "Big"); assert_eq!(plain_mtext("unterminated \\H2"), "unterminated "); assert_eq!(plain_mtext("\\U+0041B \\U+00E8"), "AB è"); - assert_eq!(plain_mtext("\\U+12"), "", "a short escape is a code with an argument"); + assert_eq!(plain_mtext("\\U+12"), "+12", "a short escape loses only the backslash and the code"); + } + + #[test] + fn unicode_escapes_are_decoded_in_every_parser() { + // The escape has no `;`, so it must not swallow the rest of the text. + assert_eq!(plain_mtext("A\\U+00B0 B C;D"), "A\u{b0} B C;D"); + assert_eq!(lay("A\\U+00B0 B C;D", 0.0).lines, vec!["A\u{b0} B C;D"]); + // The paragraph path (`\p`) and the plain path agree. + assert_eq!(lay("\\pxql;A\\U+00B0 B C;D", 0.0).lines, vec!["A\u{b0} B C;D"]); + let scanned = para::Paragraphs::scan("\\U+00B0\\pi1;x\\U+0041 y;z"); + assert!(scanned.formatted()); + // A surrogate pair is one character; a lone surrogate is U+FFFD. + assert_eq!(plain_mtext("\\U+D83D\\U+DE00!"), "\u{1f600}!"); + assert_eq!(lay("\\U+D83D\\U+DE00!", 0.0).lines, vec!["\u{1f600}!"]); + assert_eq!(plain_mtext("a\\U+D83Db"), "a\u{fffd}b"); + assert_eq!(plain_mtext("a\\U+DE00b\\U+D83D"), "a\u{fffd}b\u{fffd}"); + // A decoded backslash or brace is text, not markup; an escaped backslash is not an escape. + assert_eq!(plain_mtext("\\U+005CH2;x"), "\\H2;x"); + assert_eq!(plain_mtext("\\\\U+0041"), "\\U+0041"); + // `\M+n` double-byte characters, decoded like the DXF reader does. + assert_eq!(plain_mtext("\\M+5BCFE x;y"), "\u{4ef6} x;y"); + // Malformed escapes lose only the backslash and the code. + assert_eq!(plain_mtext("a\\U+12 b"), "a+12 b"); + assert_eq!(lay("a\\U+12 b", 0.0).lines, vec!["a+12 b"]); + assert_eq!(lay("\\pxql;a\\U+12 b", 0.0).lines, vec!["a+12 b"]); + assert_eq!(plain_mtext("a\\M+ b"), "a+ b"); + } + + #[test] + fn unknown_code_without_semicolon_keeps_the_text() { + assert_eq!(plain_mtext("A\\Zbc d"), "Abc d"); + assert_eq!(lay("A\\Zbc d", 0.0).lines, vec!["Abc d"]); + assert_eq!(lay("\\pxql;A\\Zbc d", 0.0).lines, vec!["Abc d"]); + // A trailing lone backslash is dropped. + assert_eq!(plain_mtext("A\\"), "A"); + // Codes with an argument still take it up to the `;`, or to the end. + assert_eq!(plain_mtext("A\\H2;B"), "AB"); + assert_eq!(plain_mtext("A\\H2 B"), "A"); + } + + #[test] + fn non_finite_oblique_and_line_spacing_are_repaired() { + let run = |oblique: f64, spacing: f64| { + let p = MTextParams { oblique, line_spacing: spacing, ..MTextParams::new(Vec2::ZERO, 1.0) }; + layout_mtext_with("AB\\PCD", &p) + }; + let finite = + |l: &MTextLayout| l.bounds.min.x.is_finite() && l.bounds.max.x.is_finite() && l.bounds.min.y.is_finite() && l.bounds.max.y.is_finite(); + let reference = run(0.0, 1.0); + for o in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let l = run(o, 1.0); + assert!(finite(&l), "oblique {o}"); + assert_eq!(l.bounds, reference.bounds, "oblique {o}"); + } + for s in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, -2.0] { + let l = run(0.0, s); + assert!(finite(&l), "spacing {s}"); + assert_eq!(l.bounds, reference.bounds, "spacing {s}"); + } + // Spacing is clamped to AutoCAD's 0.25..=4 range. + assert_eq!(run(0.0, 1e9).bounds, run(0.0, 4.0).bounds); + assert_eq!(run(0.0, 1e-9).bounds, run(0.0, 0.25).bounds); + assert!(run(0.0, 4.0).bounds.height() > reference.bounds.height()); + // The paragraph layout takes the same path. + let p = MTextParams { oblique: f64::NAN, line_spacing: f64::NAN, ..MTextParams::new(Vec2::ZERO, 1.0) }; + assert!(finite(&layout_mtext_with("\\pxql;AB\\PCD", &p))); + } + + #[test] + fn relative_heights_do_not_run_away() { + let src = format!("{}A", "\\H999999x;".repeat(60)); + let l = lay(&src, 0.0); + assert!(l.bounds.height().is_finite() && l.bounds.width().is_finite()); + assert!(l.bounds.height() <= 1e3 * 1.5, "{}", l.bounds.height()); + assert!(l.bounds.height() > 100.0, "the glyph must not vanish: {}", l.bounds.height()); + // Shrinking is bounded too. + let tiny = lay(&format!("{}A", "\\H0.000001x;".repeat(60)), 0.0); + assert!(tiny.bounds.height() > 0.0); + } + + /// The width factor of the last format `parse` derived. + fn last_wf(contents: &str, base_wf: f64) -> f64 { + let base = Fmt { font: TextFont::Stroke, height: 1.0, color: None, under: false, over: false, wf: base_wf, oblique: 0.0, valign: 1 }; + parse(contents, base).1.last().map_or(f64::NAN, |f| f.wf) + } + + #[test] + fn width_factor_x_is_relative() { + assert_eq!(last_wf("\\W2;a", 1.5), 2.0, "absolute sets the factor"); + assert_eq!(last_wf("\\W2x;a", 1.5), 3.0, "x multiplies the current factor"); + assert_eq!(last_wf("\\W2;\\W2x;a", 1.0), 4.0, "relative builds on the last absolute"); + assert_eq!(last_wf("\\W0.5X;a", 1.0), 0.5, "capital X too"); + // Hostile: a long relative chain stays inside the absolute range. + let chain = "\\W99x;".repeat(50); + assert_eq!(last_wf(&chain, 1.0), 100.0); + let down = "\\W0.02x;".repeat(50); + assert_eq!(last_wf(&down, 1.0), 0.01); + // Out of range or not a number: ignored. + assert_eq!(last_wf("\\W1e999x;a", 1.5), 1.5); + assert_eq!(last_wf("\\WNaNx;a", 1.5), 1.5); + assert_eq!(last_wf("\\Wx;a", 1.5), 1.5); } #[test] diff --git a/crates/fonts/src/mtext/para.rs b/crates/fonts/src/mtext/para.rs index c3b6da3e6..9abb9f32a 100644 --- a/crates/fonts/src/mtext/para.rs +++ b/crates/fonts/src/mtext/para.rs @@ -264,6 +264,7 @@ pub struct Paragraphs { impl Paragraphs { pub fn scan(contents: &str) -> Paragraphs { + let contents = super::unescape_codes(contents); let chars: Vec = contents.chars().collect(); let mut out = Paragraphs { states: vec![ParaProps::default()], ..Default::default() }; let mut cur = 0usize; @@ -303,10 +304,12 @@ impl Paragraphs { cur = out.states.len() - 1; } } - _ => { + _ if super::takes_arg(code) => { let (_, n) = arg(&chars, i); i = n; } + // An unknown code has no argument: only the backslash and the code go. + _ => {} } } '\n' => { @@ -604,7 +607,7 @@ pub(super) fn layout(contents: &str, p: &MTextParams, base: &Fmt) -> MTextLayout let lines = LineBuilder::new(¶s, &fmts, base, width, h).build(&atoms); // Vertical placement: baselines below the top of each line's column. - let ls = if p.line_spacing > 0.0 && p.line_spacing.is_finite() { p.line_spacing } else { 1.0 }; + let ls = super::sane_line_spacing(p.line_spacing); let cols = p.columns.as_ref().filter(|_| width > 0.0); let max_cols = match cols { Some(c) if c.dynamic => MAX_COLUMNS, diff --git a/crates/fonts/src/stroke.rs b/crates/fonts/src/stroke.rs index e6d38b7db..43aa2dd3f 100644 --- a/crates/fonts/src/stroke.rs +++ b/crates/fonts/src/stroke.rs @@ -110,6 +110,61 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> { 'Ø' | 'ø' | '⌀' => (4.0, "1c0d0h1i3i4h4d3c1c 0c4i"), // List bullet: a small crossed diamond at mid x-height. '•' => (2.0, "1d0e1f2e1d 0e2e 1d1f"), + // Original Latin diacritics, composed from our own letter bodies and marks. + '\u{00C0}' => (4.0, concat!("0c2i4c 1f3f", " 1k3j")), + '\u{00C1}' => (4.0, concat!("0c2i4c 1f3f", " 1j3k")), + '\u{00C2}' => (4.0, concat!("0c2i4c 1f3f", " 0j2k4j")), + '\u{00C3}' => (4.0, concat!("0c2i4c 1f3f", " 0j1k3j4k")), + '\u{00C4}' => (4.0, concat!("0c2i4c 1f3f", " 1j1k 3j3k")), + '\u{00C5}' => (4.0, concat!("0c2i4c 1f3f", " 2j1k2l3k2j")), + '\u{00C7}' => (4.0, concat!("4h3i1i0h0d1c3c4d", " 2c3b2a1a")), + '\u{00C8}' => (4.0, concat!("4i0i0c4c 0f3f", " 1k3j")), + '\u{00C9}' => (4.0, concat!("4i0i0c4c 0f3f", " 1j3k")), + '\u{00CA}' => (4.0, concat!("4i0i0c4c 0f3f", " 0j2k4j")), + '\u{00CB}' => (4.0, concat!("4i0i0c4c 0f3f", " 1j1k 3j3k")), + '\u{00CC}' => (2.0, concat!("0i2i 1i1c 0c2c", " 0k2j")), + '\u{00CD}' => (2.0, concat!("0i2i 1i1c 0c2c", " 0j2k")), + '\u{00CE}' => (2.0, concat!("0i2i 1i1c 0c2c", " 0j1k2j")), + '\u{00CF}' => (2.0, concat!("0i2i 1i1c 0c2c", " 0j0k 2j2k")), + '\u{00D1}' => (4.0, concat!("0c0i4c4i", " 0j1k3j4k")), + '\u{00D2}' => (4.0, concat!("1c0d0h1i3i4h4d3c1c", " 1k3j")), + '\u{00D3}' => (4.0, concat!("1c0d0h1i3i4h4d3c1c", " 1j3k")), + '\u{00D4}' => (4.0, concat!("1c0d0h1i3i4h4d3c1c", " 0j2k4j")), + '\u{00D5}' => (4.0, concat!("1c0d0h1i3i4h4d3c1c", " 0j1k3j4k")), + '\u{00D6}' => (4.0, concat!("1c0d0h1i3i4h4d3c1c", " 1j1k 3j3k")), + '\u{00D9}' => (4.0, concat!("0i0d1c3c4d4i", " 1k3j")), + '\u{00DA}' => (4.0, concat!("0i0d1c3c4d4i", " 1j3k")), + '\u{00DB}' => (4.0, concat!("0i0d1c3c4d4i", " 0j2k4j")), + '\u{00DC}' => (4.0, concat!("0i0d1c3c4d4i", " 1j1k 3j3k")), + '\u{00DD}' => (4.0, concat!("0i2f4i 2f2c", " 1j3k")), + '\u{00E0}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 1i3h")), + '\u{00E1}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 1h3i")), + '\u{00E2}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 0h2i4h")), + '\u{00E3}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 0h1i3h4i")), + '\u{00E4}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 1h1i 3h3i")), + '\u{00E5}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 2h1i2j3i2h")), + '\u{00E7}' => (4.0, concat!("4f3g1g0f0d1c3c4d", " 2c3b2a1a")), + '\u{00E8}' => (4.0, concat!("0e4e4f3g1g0f0d1c3c4d", " 1i3h")), + '\u{00E9}' => (4.0, concat!("0e4e4f3g1g0f0d1c3c4d", " 1h3i")), + '\u{00EA}' => (4.0, concat!("0e4e4f3g1g0f0d1c3c4d", " 0h2i4h")), + '\u{00EB}' => (4.0, concat!("0e4e4f3g1g0f0d1c3c4d", " 1h1i 3h3i")), + '\u{00EC}' => (1.0, concat!("0c0g", " 0i1h")), + '\u{00ED}' => (1.0, concat!("0c0g", " 0h1i")), + '\u{00EE}' => (1.0, concat!("0c0g", " 0h0i1h")), + '\u{00EF}' => (1.0, concat!("0c0g", " 0h0i 1h1i")), + '\u{00F1}' => (4.0, concat!("0c0g 0f1g3g4f4c", " 0h1i3h4i")), + '\u{00F2}' => (4.0, concat!("1c0d0f1g3g4f4d3c1c", " 1i3h")), + '\u{00F3}' => (4.0, concat!("1c0d0f1g3g4f4d3c1c", " 1h3i")), + '\u{00F4}' => (4.0, concat!("1c0d0f1g3g4f4d3c1c", " 0h2i4h")), + '\u{00F5}' => (4.0, concat!("1c0d0f1g3g4f4d3c1c", " 0h1i3h4i")), + '\u{00F6}' => (4.0, concat!("1c0d0f1g3g4f4d3c1c", " 1h1i 3h3i")), + '\u{00F9}' => (4.0, concat!("0g0d1c3c4d 4g4c", " 1i3h")), + '\u{00FA}' => (4.0, concat!("0g0d1c3c4d 4g4c", " 1h3i")), + '\u{00FB}' => (4.0, concat!("0g0d1c3c4d 4g4c", " 0h2i4h")), + '\u{00FC}' => (4.0, concat!("0g0d1c3c4d 4g4c", " 1h1i 3h3i")), + '\u{00FD}' => (4.0, concat!("0g2c 4g1a0a", " 1h3i")), + '\u{00FF}' => (4.0, concat!("0g2c 4g1a0a", " 1h1i 3h3i")), + '\u{0178}' => (4.0, concat!("0i2f4i 2f2c", " 1j1k 3j3k")), _ => return None, }; Some(g) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 2f4ffab24..2edefe7b4 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -103,7 +103,11 @@ impl Face { let Some(f) = self.font() else { return Vec::new() }; [skrifa::string::StringId::FAMILY_NAME, skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FULL_NAME] .into_iter() - .flat_map(|id| f.localized_strings(id).map(|s| norm(&s.to_string())).collect::>()) + // A name table can hold many records that point at one big string: at most + // MAX_NAME_RECORDS per name id, each decoded only up to MAX_NAME_CHARS characters. + .flat_map(|id| { + f.localized_strings(id).take(MAX_NAME_RECORDS).map(|s| norm(&s.chars().take(MAX_NAME_CHARS).collect::())).collect::>() + }) .collect() } } @@ -118,6 +122,10 @@ pub fn faces(bytes: &Arc>) -> Vec { } const MAX_FACES_PER_FILE: u32 = 32; +/// Name records read per name id of a face, and characters read of each: real fonts have a few +/// dozen short ones. +const MAX_NAME_RECORDS: usize = 64; +const MAX_NAME_CHARS: usize = 256; /// Bounds of the missing-glyph search: files loaded, bytes loaded, faces checked per character. const MAX_FALLBACK_FILES: usize = 24; const MAX_FALLBACK_BYTES: usize = 160 << 20; diff --git a/crates/fonts/tests/latin_accents.rs b/crates/fonts/tests/latin_accents.rs new file mode 100644 index 000000000..79d4a37c1 --- /dev/null +++ b/crates/fonts/tests/latin_accents.rs @@ -0,0 +1,54 @@ +use cadcraft_fonts::{MTextParams, TextFont, char_advance, layout_mtext_with, line_width, shape_stroke}; +use cadcraft_geom::Vec2; + +#[test] +fn latin_accents_keep_single_strokes_and_the_base_letter_spacing() { + let groups = [ + ('A', "ÀÁÂÃÄÅ"), + ('C', "Ç"), + ('E', "ÈÉÊË"), + ('I', "ÌÍÎÏ"), + ('N', "Ñ"), + ('O', "ÒÓÔÕÖ"), + ('U', "ÙÚÛÜ"), + ('Y', "ÝŸ"), + ('a', "àáâãäå"), + ('c', "ç"), + ('e', "èéêë"), + ('i', "ìíîï"), + ('n', "ñ"), + ('o', "òóôõö"), + ('u', "ùúûü"), + ('y', "ýÿ"), + ]; + for (base, accents) in groups { + for c in accents.chars() { + let shaped = shape_stroke(&c.to_string(), 6.0, 0.8, 0.2); + assert!(shaped.glyphs.is_empty(), "{c} must not become a filled system-font outline"); + assert!(!shaped.strokes.is_empty()); + assert_eq!(char_advance(c), char_advance(base)); + assert!((line_width(&c.to_string(), 6.0, 0.8) - shaped.width).abs() < 1e-9); + assert!(shaped.strokes.iter().flatten().all(|p| p.is_finite())); + let next = shape_stroke(&format!("{c}B"), 6.0, 0.8, 0.2); + let plain = shape_stroke(&format!("{base}B"), 6.0, 0.8, 0.2); + assert_eq!(next.width, plain.width, "accent does not shift the next letter"); + } + } + for (accent, base) in [('Ç', 'C'), ('Ã', 'A'), ('Á', 'A'), ('Ó', 'O')] { + let plain = shape_stroke(&base.to_string(), 6.0, 1.0, 0.0); + let marked = shape_stroke(&accent.to_string(), 6.0, 1.0, 0.0); + assert!(marked.strokes.starts_with(&plain.strokes), "same letter body for {accent}"); + assert!(marked.strokes.len() > plain.strokes.len()); + } +} + +#[test] +fn portuguese_mtext_wraps_with_consistent_stroke_metrics() { + let text = "A CONCEPÇÃO SERÁ APROVADA APÓS O PROCESSAMENTO DA ESTRUTURA"; + let params = MTextParams { width: 32.0, font: TextFont::Stroke, ..MTextParams::new(Vec2::ZERO, 1.0) }; + let layout = layout_mtext_with(text, ¶ms); + assert!(layout.lines.len() >= 2); + assert_eq!(layout.lines.join(" "), text); + assert!(layout.pieces.iter().all(|p| p.shaped.glyphs.is_empty())); + assert!(layout.strokes.iter().flatten().all(|p| p.is_finite())); +} diff --git a/crates/geom/src/curve.rs b/crates/geom/src/curve.rs index 04f665f88..5d0e53f17 100644 --- a/crates/geom/src/curve.rs +++ b/crates/geom/src/curve.rs @@ -484,6 +484,9 @@ pub struct Polyline { pub closed: bool, } +/// Sampled points one [`Polyline::tessellate`] call produces before arcs become chords. +pub const MAX_TESSELLATED_POINTS: usize = 4_000_000; + impl Polyline { pub fn from_points(pts: &[Vec2], closed: bool) -> Self { Polyline { vertices: pts.iter().map(|p| PolyVertex::new(*p)).collect(), closed } @@ -516,10 +519,24 @@ impl Polyline { b } pub fn tessellate(&self, tol: f64) -> Vec { + let mut budget = MAX_TESSELLATED_POINTS; + self.tessellate_within(tol, &mut budget) + } + /// [`Polyline::tessellate`] spending about `budget` sampled points (shared by the caller + /// across many polylines). The budget is checked before each segment, so the last segment + /// started may overshoot it by that one segment's samples. Once it is spent, the remaining arcs are drawn as chords, so the + /// output stays proportional to the input vertices. Each arc can sample thousands of points, + /// so a compact polyline could otherwise expand into gigabytes (CWE-400). + pub fn tessellate_within(&self, tol: f64, budget: &mut usize) -> Vec { let mut out: Vec = Vec::new(); for s in self.segments() { let mut pts = Vec::new(); - s.tessellate(tol, &mut pts); + if *budget > 0 { + s.tessellate(tol, &mut pts); + *budget = budget.saturating_sub(pts.len()); + } else { + pts.extend([s.start(), s.end()]); + } let skip = usize::from(out.last().is_some_and(|l| pts.first().is_some_and(|f| l.near(*f, 1e-9)))); out.extend(pts.into_iter().skip(skip)); } diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index e62f478fb..d482141fd 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -20,7 +20,8 @@ mod vec; pub use bounds::Bounds2; pub use curve::{ - Arc, Circle, Ellipse, Line, PolyVertex, Polyline, Segment, arc_to_bulge, bulge_to_arc, point_in_polygon, polygon_centroid, shoelace, + Arc, Circle, Ellipse, Line, MAX_TESSELLATED_POINTS, PolyVertex, Polyline, Segment, arc_to_bulge, bulge_to_arc, point_in_polygon, + polygon_centroid, shoelace, }; pub use fillet::{CornerFit, TanCurve, tangent_circles}; pub use intersect::{circle_circle, intersect_ext, intersect_segments, line_circle, line_line, line_line_infinite}; diff --git a/crates/geom/src/nurbs.rs b/crates/geom/src/nurbs.rs index e07852340..04cf933cb 100644 --- a/crates/geom/src/nurbs.rs +++ b/crates/geom/src/nurbs.rs @@ -8,7 +8,7 @@ use std::f64::consts::FRAC_PI_2; -use crate::spline::{basis, find_span}; +use crate::spline::{MAX_STACK_DEGREE, basis, find_span}; use crate::{EPS, Ellipse, Spline, TAU, Vec2}; /// Highest degree the editing operations work with. @@ -88,6 +88,34 @@ fn elevate_bezier(p: &[H]) -> Vec { .collect() } +/// Basis functions of degree `p` in `n[..=p]` and of degree `p - 1` in `lower[..p]` for `p >= 1`, +/// in one Cox-de Boor sweep: the degree `p - 1` values are the state just before the last step, +/// so they match [`basis`] exactly. `left` and `right` are scratch of `p + 1` values; the outputs +/// stay untouched when a slice is too short. +#[allow(clippy::too_many_arguments)] +fn basis_pair_into(span: usize, u: f64, p: usize, knots: &[f64], n: &mut [f64], lower: &mut [f64], left: &mut [f64], right: &mut [f64]) { + if p == 0 || n.len() <= p || lower.len() < p || left.len() <= p || right.len() <= p { + return; + } + n[0] = 1.0; + for j in 1..=p { + let k = |i: isize| knots.get(i.max(0) as usize).copied().unwrap_or(0.0); + left[j] = u - k(span as isize + 1 - j as isize); + right[j] = k(span as isize + j as isize) - u; + if j == p { + lower[..p].copy_from_slice(&n[..p]); + } + let mut saved = 0.0; + for r in 0..j { + let den = right[r + 1] + left[j - r]; + let tmp = if den.abs() > 1e-300 { n[r] / den } else { 0.0 }; + n[r] = saved + right[r + 1] * tmp; + saved = left[j - r] * tmp; + } + n[j] = saved; + } +} + impl Spline { fn weight(&self, i: usize) -> f64 { if self.weights.is_empty() { 1.0 } else { self.weights.get(i).copied().unwrap_or(1.0) } @@ -130,6 +158,8 @@ impl Spline { /// First derivative without re-validating the spline. The caller must have confirmed /// [`Spline::is_valid`] already; integration calls this once per sample, and re-running the /// O(knots) validity scan each time would make measuring a valid spline quadratic (CWE-407). + /// Up to degree [`MAX_STACK_DEGREE`] both bases come from one stack-only sweep; higher degrees + /// compute them on the heap. fn derivative_unchecked(&self, t: f64) -> Vec2 { let d = self.velocity(t); if d.is_finite() { d } else { Vec2::ZERO } @@ -142,8 +172,17 @@ impl Spline { let (lo, hi) = self.domain(); let t = if t.is_finite() { t.clamp(lo, hi) } else { lo }; let span = find_span(n, p, t, &self.knots); - let nb = basis(span, t, p, &self.knots); - let nd = basis(span, t, p - 1, &self.knots); + let (mut sb, mut sd, mut sl, mut sr) = + ([0.0; MAX_STACK_DEGREE + 1], [0.0; MAX_STACK_DEGREE + 1], [0.0; MAX_STACK_DEGREE + 1], [0.0; MAX_STACK_DEGREE + 1]); + let (hb, hd); + let (nb, nd): (&[f64], &[f64]) = if (1..=MAX_STACK_DEGREE).contains(&p) { + basis_pair_into(span, t, p, &self.knots, &mut sb, &mut sd, &mut sl, &mut sr); + (&sb, &sd) + } else { + hb = basis(span, t, p, &self.knots); + hd = basis(span, t, p - 1, &self.knots); + (&hb, &hd) + }; let k = |i: usize| self.knots.get(i).copied().unwrap_or(0.0); let ratio = |num: Option<&f64>, den: f64| if den.abs() > 1e-300 { num.copied().unwrap_or(0.0) / den } else { 0.0 }; let (mut a, mut w, mut da, mut dw) = (Vec2::ZERO, 0.0, Vec2::ZERO, 0.0); @@ -624,6 +663,132 @@ mod tests { Spline::from_control(vec![Vec2::new(0.0, 0.0), Vec2::new(3.0, 3.0), Vec2::new(6.0, -3.0), Vec2::new(9.0, 0.0), Vec2::new(12.0, 2.0)], 3) } + /// The previous implementation (two heap-allocated bases), kept as the oracle for the + /// allocation-free `derivative_unchecked`. + impl Spline { + fn derivative_unchecked_old(&self, t: f64) -> Vec2 { + let p = self.degree; + let Some(n) = self.control.len().checked_sub(1) else { return Vec2::ZERO }; + let (lo, hi) = self.domain(); + let t = if t.is_finite() { t.clamp(lo, hi) } else { lo }; + let span = find_span(n, p, t, &self.knots); + let nb = basis(span, t, p, &self.knots); + let nd = basis(span, t, p - 1, &self.knots); + let k = |i: usize| self.knots.get(i).copied().unwrap_or(0.0); + let ratio = |num: Option<&f64>, den: f64| if den.abs() > 1e-300 { num.copied().unwrap_or(0.0) / den } else { 0.0 }; + let (mut a, mut w, mut da, mut dw) = (Vec2::ZERO, 0.0, Vec2::ZERO, 0.0); + for j in 0..=p { + let Some(i) = (span + j).checked_sub(p) else { continue }; + let Some(c) = self.control.get(i) else { continue }; + let wi = self.weight(i); + let n0 = nb.get(j).copied().unwrap_or(0.0); + // N'_{i,p} = p (N_{i,p-1} / (u_{i+p} - u_i) - N_{i+1,p-1} / (u_{i+p+1} - u_{i+1})). + let left = if j >= 1 { ratio(nd.get(j - 1), k(i + p) - k(i)) } else { 0.0 }; + let right = if j < p { ratio(nd.get(j), k(i + p + 1) - k(i + 1)) } else { 0.0 }; + let dn = p as f64 * (left - right); + a += *c * (n0 * wi); + w += n0 * wi; + da += *c * (dn * wi); + dw += dn * wi; + } + if w.abs() < 1e-300 { + return Vec2::ZERO; + } + let d = (da - a / w * dw) / w; + if d.is_finite() { d } else { Vec2::ZERO } + } + } + + struct XorShift(u64); + impl XorShift { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn unit(&mut self) -> f64 { + (self.next() >> 11) as f64 / (1u64 << 53) as f64 + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + } + + /// A valid random spline of degree `p`: clamped or unclamped knots, repeated interior knots, + /// and non-rational, rational or zero/negative weights. + fn random_spline(r: &mut XorShift, p: usize) -> Spline { + let n = p + 1 + r.below(8); + let control = (0..n).map(|_| Vec2::new(r.unit() * 100.0 - 50.0, r.unit() * 100.0 - 50.0)).collect(); + let total = n + p + 1; + let mut knots: Vec = + (0..total).map(|_| (r.unit() * 8.0).floor() * if r.below(3) == 0 { 0.5 } else { 1.0 } + r.unit() * f64::from(r.below(2) == 0)).collect(); + knots.sort_by(f64::total_cmp); + if r.below(2) == 0 { + // Clamp both ends. + let (lo, hi) = (knots[p], knots[n]); + knots[..=p].fill(lo); + knots[n..].fill(hi); + } + let weights = match r.below(4) { + 0 => Vec::new(), + 1 => (0..n).map(|_| 0.2 + r.unit() * 4.0).collect(), + 2 => (0..n).map(|_| if r.below(5) == 0 { 0.0 } else { r.unit() * 2.0 - 0.5 }).collect(), + _ => (0..n).map(|_| 1.0 + r.unit() * 1e-9).collect(), + }; + Spline { degree: p, knots, control, weights, ..Spline::default() } + } + + fn bits(v: Vec2) -> (u64, u64) { + (v.x.to_bits(), v.y.to_bits()) + } + + #[test] + fn derivative_is_bit_identical_to_the_heap_implementation() { + let mut r = XorShift(0x9E37_79B9_7F4A_7C15); + let mut zero_results = 0usize; + for p in 1..=12usize { + let mut compared = 0usize; + for _ in 0..400 { + let s = random_spline(&mut r, p); + if !s.is_valid() { + continue; + } + let (lo, hi) = s.domain(); + let mut ts = vec![lo, hi, 0.5 * (lo + hi), lo - 1.0, hi + 1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY]; + ts.extend(s.knots.iter().copied()); + ts.extend(s.knots.iter().map(|k| k.next_up())); + ts.extend(s.knots.iter().map(|k| k.next_down())); + ts.extend((0..8).map(|_| lo + (hi - lo) * r.unit())); + for t in ts { + let (new, old) = (s.derivative_unchecked(t), s.derivative_unchecked_old(t)); + assert_eq!(bits(new), bits(old), "degree {p}, t = {t}, knots {:?}, weights {:?}", s.knots, s.weights); + compared += 1; + zero_results += usize::from(old == Vec2::ZERO); + } + } + assert!(compared > 1000, "degree {p}: only {compared} comparisons ran"); + } + // The zero-vector exits (vanishing weight sum, non-finite result) are exercised too. + assert!(zero_results > 0); + } + + #[test] + fn derivative_dispatch_around_the_stack_limit_does_not_change_results() { + // The last stack degree and the first heap degree both match the oracle on a clamped + // uniform spline (the heap degree runs the unchanged old path; this checks the dispatch). + for p in [MAX_STACK_DEGREE, MAX_STACK_DEGREE + 1] { + let ctrl: Vec = (0..p + 4).map(|i| Vec2::new(i as f64, (i * i % 7) as f64)).collect(); + let s = Spline::from_control(ctrl, p); + assert_eq!(s.degree, p); + let (lo, hi) = s.domain(); + for i in 0..=50 { + let t = lo + (hi - lo) * f64::from(i) / 50.0; + assert_eq!(bits(s.derivative_unchecked(t)), bits(s.derivative_unchecked_old(t)), "degree {p}, t = {t}"); + } + } + } + #[test] fn derivative_matches_finite_differences() { let mut s = cubic(); diff --git a/crates/geom/src/region.rs b/crates/geom/src/region.rs index c186534c9..a132c699b 100644 --- a/crates/geom/src/region.rs +++ b/crates/geom/src/region.rs @@ -75,7 +75,108 @@ fn split_pair(segs: &[(Vec2, Vec2)], splits: &mut [Vec], i: usize, j: usize } } +/// Upper bound on candidate-pair *visits*. Every visit counts, including repeats of a pair that shares several grid +/// cells, not only the distinct pairs actually tested. A long segment replicated across many +/// cells makes the same pair reappear in each, so a budget on distinct pairs alone leaves the +/// repeated work unbounded (CWE-407). +const MAX_PAIR_VISITS: u64 = 60_000_000; +/// Upper bound on distinct segment pairs tested for a crossing. +const MAX_PAIRS_TESTED: usize = 20_000_000; + +/// Split parameters of every segment (always `0` and `1`, plus every crossing), found with a uniform grid. +fn pair_splits(segs: &[(Vec2, Vec2)], bb: &Bounds2) -> Option>> { + pair_splits_limited(segs, bb, MAX_PAIR_VISITS, MAX_PAIRS_TESTED) +} + +/// `pair_splits` with explicit budgets: `None` once more than `max_visits` candidate pairs were visited +/// or more than `max_pairs` distinct pairs were tested. +fn pair_splits_limited(segs: &[(Vec2, Vec2)], bb: &Bounds2, max_visits: u64, max_pairs: usize) -> Option>> { + let n = segs.len(); + let cells = ((n as f64).sqrt().ceil() as usize).clamp(1, 512); + let cw = (bb.width() / cells as f64).max(1e-12); + let ch = (bb.height() / cells as f64).max(1e-12); + let cell = |p: Vec2| { + ( + ((p.x - bb.min.x) / cw).floor().clamp(0.0, (cells - 1) as f64) as usize, + ((p.y - bb.min.y) / ch).floor().clamp(0.0, (cells - 1) as f64) as usize, + ) + }; + // Cell lists in a flat grid, indexed `gx * cells + gy`; each list is in ascending segment order. + let mut grid: Vec> = vec![Vec::new(); cells * cells]; + // The lowest cell of each segment's cell range; the lowest cell two segments share is the + // componentwise maximum of their two. + let mut low: Vec<(usize, usize)> = vec![(0, 0); n]; + let mut is_long = vec![false; n]; + let mut long: Vec = Vec::new(); + for (i, (a, b)) in segs.iter().enumerate() { + let (x0, y0) = cell(a.min(*b)); + let (x1, y1) = cell(a.max(*b)); + if let Some(l) = low.get_mut(i) { + *l = (x0, y0); + } + if (x1 - x0 + 1) * (y1 - y0 + 1) > 4096 { + // Very long segment: too many cells to register in; it is tested against every segment below. + long.push(i); + if let Some(f) = is_long.get_mut(i) { + *f = true; + } + continue; + } + for gx in x0..=x1 { + for gy in y0..=y1 { + if let Some(list) = grid.get_mut(gx * cells + gy) { + list.push(i); + } + } + } + } + let mut splits: Vec> = vec![vec![0.0, 1.0]; n]; + let mut tested: usize = 0; + let mut visits: u64 = 0; + for (c, list) in grid.iter().enumerate() { + let (gx, gy) = (c / cells, c % cells); + for (k, &i) in list.iter().enumerate() { + let Some(&(ix, iy)) = low.get(i) else { continue }; + for &j in list.iter().skip(k + 1) { + visits += 1; + if visits > max_visits { + return None; + } + let Some(&(jx, jy)) = low.get(j) else { continue }; + // A pair sharing several cells is tested once, in the lowest cell both occupy. + if i == j || gx != ix.max(jx) || gy != iy.max(jy) { + continue; + } + split_pair(segs, &mut splits, i, j); + tested += 1; + if tested > max_pairs { + return None; + } + } + } + } + // A long segment is in no cell list. Two long segments are tested once, from the lower index. + for &i in &long { + for j in 0..n { + if i == j || (j < i && is_long.get(j).copied().unwrap_or(false)) { + continue; + } + split_pair(segs, &mut splits, i, j); + tested += 1; + if tested > max_pairs { + return None; + } + } + } + Some(splits) +} + fn build(polys: &[Vec], tol: f64) -> Option { + build_with(polys, tol, pair_splits) +} + +/// `build` with the crossing search injected, so tests can run the old and the new search on the same input. +fn build_with(polys: &[Vec], tol: f64, find_splits: impl Fn(&[(Vec2, Vec2)], &Bounds2) -> Option>>) -> Option { let mut segs: Vec<(Vec2, Vec2)> = Vec::new(); let mut owner: Vec = Vec::new(); for (k, pl) in polys.iter().enumerate() { @@ -96,70 +197,9 @@ fn build(polys: &[Vec], tol: f64) -> Option { if segs.is_empty() || segs.len() > MAX_SEGMENTS { return None; } - // Split points per segment (parameters), found with a uniform grid. let bb = Bounds2::from_points(segs.iter().flat_map(|(a, b)| [*a, *b])); let n = segs.len(); - let cells = ((n as f64).sqrt().ceil() as usize).clamp(1, 512); - let cw = (bb.width() / cells as f64).max(1e-12); - let ch = (bb.height() / cells as f64).max(1e-12); - let cell = |p: Vec2| { - ( - ((p.x - bb.min.x) / cw).floor().clamp(0.0, (cells - 1) as f64) as usize, - ((p.y - bb.min.y) / ch).floor().clamp(0.0, (cells - 1) as f64) as usize, - ) - }; - let mut grid: HashMap<(usize, usize), Vec> = HashMap::new(); - let mut long: Vec = Vec::new(); - for (i, (a, b)) in segs.iter().enumerate() { - let (x0, y0) = cell(a.min(*b)); - let (x1, y1) = cell(a.max(*b)); - if (x1 - x0 + 1) * (y1 - y0 + 1) > 4096 { - // Very long segment: too many cells to register in; it is tested against every segment below. - long.push(i); - continue; - } - for gx in x0..=x1 { - for gy in y0..=y1 { - grid.entry((gx, gy)).or_default().push(i); - } - } - } - let mut splits: Vec> = vec![vec![0.0, 1.0]; n]; - let mut tested = std::collections::HashSet::new(); - // Count every candidate-pair *visit*, including repeats of a pair that shares several grid - // cells, not only the distinct pairs actually tested. A long segment replicated across many - // cells makes the same pair reappear in each, so a budget on distinct pairs alone leaves the - // repeated hashing unbounded (CWE-407). - let mut visits: u64 = 0; - const MAX_PAIR_VISITS: u64 = 60_000_000; - for list in grid.values() { - for (k, &i) in list.iter().enumerate() { - for &j in list.iter().skip(k + 1) { - visits += 1; - if visits > MAX_PAIR_VISITS { - return None; - } - if i == j || !tested.insert((i.min(j), i.max(j))) { - continue; - } - split_pair(&segs, &mut splits, i, j); - if tested.len() > 20_000_000 { - return None; - } - } - } - } - for &i in &long { - for j in 0..n { - if i == j || !tested.insert((i.min(j), i.max(j))) { - continue; - } - split_pair(&segs, &mut splits, i, j); - if tested.len() > 20_000_000 { - return None; - } - } - } + let splits = find_splits(&segs, &bb)?; let mut g = Graph { pts: Vec::new(), adj: Vec::new(), src: Vec::with_capacity(n), edge_src: HashMap::new() }; let mut index: HashMap<(i64, i64), usize> = HashMap::new(); let mut vid = |p: Vec2, g: &mut Graph| -> usize { @@ -391,10 +431,10 @@ fn outside(core: &Graph, u: usize, steps: usize) -> Option> { } /// Outlines of the groups of curves inside the face `outer` (vertex indices into `g`). -fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Vec { +fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option> { let comp = components(g); let outer_comp: std::collections::HashSet = outer.iter().filter_map(|&i| comp.get(i).copied()).collect(); - let Some(outer_pts) = points(g, outer) else { return Vec::new() }; + let outer_pts = points(g, outer)?; let ob = Bounds2::from_points(outer_pts.iter().copied()); let core = prune(g); // Leftmost (then lowest) vertex still on a cycle, per component. @@ -424,19 +464,32 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Vec { let mut starts: Vec<(usize, usize)> = start.into_iter().collect(); starts.sort_unstable(); let mut out = Vec::new(); + // Each containment test scans a whole polygon, accepted or not: they share one allowance of + // polygon edges, and the search ends when it is spent. + let mut edges_left: usize = 100_000_000; for (c, u) in starts { if out.len() >= MAX_ISLANDS { break; } let Some(&pu) = core.pts.get(u) else { continue }; - if !ob.contains(pu) || !point_in_polygon(&outer_pts, pu) { + if !ob.contains(pu) { + continue; + } + let left = edges_left.checked_sub(outer_pts.len())?; + edges_left = left; + if !point_in_polygon(&outer_pts, pu) { continue; } let steps = edges.get(&c).copied().unwrap_or(0).saturating_add(4); let Some(lp) = outside(&core, u, steps) else { continue }; let area = shoelace(&lp); let ib = Bounds2::from_points(lp.iter().copied()); - if lp.len() < 3 || !area.is_finite() || area <= 0.0 || !ob.contains_box(&ib) || point_in_polygon(&lp, p) { + if lp.len() < 3 || !area.is_finite() || area <= 0.0 || !ob.contains_box(&ib) { + continue; + } + let left = edges_left.checked_sub(lp.len())?; + edges_left = left; + if point_in_polygon(&lp, p) { continue; } let mut src = sources.remove(&c).unwrap_or_default(); @@ -444,7 +497,7 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Vec { src.dedup(); out.push(Island { outline: lp, sources: src }); } - out + Some(out) } /// The point of the nearest other curve within `snap` of the end `e` of curve `i`, as (curve, @@ -457,6 +510,10 @@ fn nearest_curve(polys: &[Vec], i: usize, e: Vec2, snap: f64, tol: f64, bu if j == i { continue; } + // A curve with no segment costs a visit too, so many of them can't multiply the searches. + if other.len() < 2 { + *budget = budget.checked_sub(1).ok_or(())?; + } for (k, w) in other.windows(2).enumerate() { if *budget == 0 { return Err(()); @@ -558,7 +615,7 @@ pub fn boundary_at_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Opti let g = build_gap(polys, tol, gap)?; let ids = outer_face(&g, p)?; let outer = points(&g, &ids)?; - let islands = islands(&g, &ids, p); + let islands = islands(&g, &ids, p)?; let mut outer_sources: Vec = ids.iter().zip(ids.iter().cycle().skip(1)).filter_map(|(&u, &v)| g.edge_src.get(&(u.min(v), u.max(v))).copied()).collect(); outer_sources.sort_unstable(); @@ -630,6 +687,187 @@ mod tests { vec![Vec2::new(x0, y0), Vec2::new(x0 + s, y0), Vec2::new(x0 + s, y0 + s), Vec2::new(x0, y0 + s), Vec2::new(x0, y0)] } + /// The crossing search before the lowest-shared-cell rule: a `HashSet` of tested pairs over a `HashMap` grid. + fn pair_splits_oracle(segs: &[(Vec2, Vec2)], bb: &Bounds2, max_visits: u64, max_pairs: usize) -> Option>> { + let n = segs.len(); + let cells = ((n as f64).sqrt().ceil() as usize).clamp(1, 512); + let cw = (bb.width() / cells as f64).max(1e-12); + let ch = (bb.height() / cells as f64).max(1e-12); + let cell = |p: Vec2| { + ( + ((p.x - bb.min.x) / cw).floor().clamp(0.0, (cells - 1) as f64) as usize, + ((p.y - bb.min.y) / ch).floor().clamp(0.0, (cells - 1) as f64) as usize, + ) + }; + let mut grid: HashMap<(usize, usize), Vec> = HashMap::new(); + let mut long: Vec = Vec::new(); + for (i, (a, b)) in segs.iter().enumerate() { + let (x0, y0) = cell(a.min(*b)); + let (x1, y1) = cell(a.max(*b)); + if (x1 - x0 + 1) * (y1 - y0 + 1) > 4096 { + long.push(i); + continue; + } + for gx in x0..=x1 { + for gy in y0..=y1 { + grid.entry((gx, gy)).or_default().push(i); + } + } + } + let mut splits: Vec> = vec![vec![0.0, 1.0]; n]; + let mut tested = std::collections::HashSet::new(); + let mut visits: u64 = 0; + for list in grid.values() { + for (k, &i) in list.iter().enumerate() { + for &j in list.iter().skip(k + 1) { + visits += 1; + if visits > max_visits { + return None; + } + if i == j || !tested.insert((i.min(j), i.max(j))) { + continue; + } + split_pair(segs, &mut splits, i, j); + if tested.len() > max_pairs { + return None; + } + } + } + } + for &i in &long { + for j in 0..n { + if i == j || !tested.insert((i.min(j), i.max(j))) { + continue; + } + split_pair(segs, &mut splits, i, j); + if tested.len() > max_pairs { + return None; + } + } + } + Some(splits) + } + + struct Rng(u64); + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn unit(&mut self) -> f64 { + (self.next() >> 11) as f64 / (1u64 << 53) as f64 + } + } + + /// Random segments: short ones, some long ones, and some on a coarse lattice (shared ends, overlaps). + fn random_segments(r: &mut Rng, n: usize, size: f64, long_every: u64) -> Vec<(Vec2, Vec2)> { + let mut out = Vec::new(); + for _ in 0..n { + let a = Vec2::new(r.unit() * size, r.unit() * size); + let seg = match r.next() % 4 { + 0 if long_every > 0 && r.next().is_multiple_of(long_every) => ( + Vec2::new(r.unit() * size * 0.02, r.unit() * size * 0.02), + Vec2::new(size * (0.98 + r.unit() * 0.02), size * (0.98 + r.unit() * 0.02)), + ), + 1 => { + let q = |r: &mut Rng| (r.next() % 9) as f64 * size / 8.0; + (Vec2::new(q(r), q(r)), Vec2::new(q(r), q(r))) + } + _ => (a, a + Vec2::new((r.unit() - 0.5) * size * 0.1, (r.unit() - 0.5) * size * 0.1)), + }; + if !seg.0.near(seg.1, 1e-9) { + out.push(seg); + } + } + out + } + + fn sorted_bits(splits: &[Vec]) -> Vec> { + splits + .iter() + .map(|v| { + let mut v = v.clone(); + v.sort_by(f64::total_cmp); + v.iter().map(|x| x.to_bits()).collect() + }) + .collect() + } + + fn bounds_of(segs: &[(Vec2, Vec2)]) -> Bounds2 { + Bounds2::from_points(segs.iter().flat_map(|(a, b)| [*a, *b])) + } + + fn assert_same_search(segs: &[(Vec2, Vec2)], max_visits: u64, max_pairs: usize) { + let bb = bounds_of(segs); + let old = pair_splits_oracle(segs, &bb, max_visits, max_pairs); + let new = pair_splits_limited(segs, &bb, max_visits, max_pairs); + assert_eq!(old.as_deref().map(sorted_bits), new.as_deref().map(sorted_bits), "n={} visits<={max_visits} pairs<={max_pairs}", segs.len()); + } + + #[test] + fn pair_search_matches_oracle_with_budgets() { + // Small inputs in few cells: many pairs share several cells. Sweeping each budget over + // 0..=400 crosses its exhaustion point for most seeds, including the exact boundary. + for seed in 1..=150u64 { + let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + let n = 2 + (r.next() % 28) as usize; + let segs = random_segments(&mut r, n, 100.0, 0); + if segs.is_empty() { + continue; + } + for v in 0..=400u64 { + assert_same_search(&segs, v, usize::MAX); + } + for p in 0..=400usize { + assert_same_search(&segs, u64::MAX, p); + } + assert_same_search(&segs, 60_000_000, 20_000_000); + } + } + + #[test] + fn pair_search_matches_oracle_with_long_segments() { + // Around 5000 segments give a 71x71 grid, so a diagonal covers more than 4096 cells and takes the long path. + for seed in 1..=3u64 { + let mut r = Rng(seed.wrapping_mul(0xD1B5_4A32_D192_ED03) | 1); + let n = 5_000 + (r.next() % 500) as usize; + let segs = random_segments(&mut r, n, 1000.0, 40); + let bb = bounds_of(&segs); + let cells = ((segs.len() as f64).sqrt().ceil() as usize).clamp(1, 512); + assert!(cells >= 64, "grid too coarse to reach the long path"); + assert_same_search(&segs, 60_000_000, 20_000_000); + // Budgets exhausted in the cell phase (visits, then pairs). + assert_same_search(&segs, 3_000, 20_000_000); + assert_same_search(&segs, 60_000_000, 200); + assert!(pair_splits_limited(&segs, &bb, 3_000, 20_000_000).is_none()); + assert!(pair_splits_limited(&segs, &bb, 60_000_000, 200).is_none()); + let (cw, ch) = ((bb.width() / cells as f64).max(1e-12), (bb.height() / cells as f64).max(1e-12)); + let span = |a: f64, b: f64, o: f64, w: f64| { + (((b.max(a) - o) / w).floor().min((cells - 1) as f64) - ((b.min(a) - o) / w).floor().max(0.0) + 1.0) as usize + }; + let long = segs.iter().filter(|(a, b)| span(a.x, b.x, bb.min.x, cw) * span(a.y, b.y, bb.min.y, ch) > 4096).count(); + assert!(long > 0, "seed {seed}: no segment takes the long path"); + } + } + + #[test] + fn build_matches_oracle_on_random_drawings() { + for seed in 1..=60u64 { + let mut r = Rng(seed.wrapping_mul(0xA076_1D64_78BD_642F) | 1); + let n = 5 + (r.next() % 400) as usize; + let polys: Vec> = random_segments(&mut r, n, 100.0, 0).into_iter().map(|(a, b)| vec![a, b]).collect(); + let old = build_with(&polys, 1e-6, |s, bb| pair_splits_oracle(s, bb, MAX_PAIR_VISITS, MAX_PAIRS_TESTED)); + let new = build(&polys, 1e-6); + let (Some(old), Some(new)) = (old, new) else { panic!("seed {seed}: build failed") }; + assert_eq!(old.pts, new.pts, "seed {seed}"); + assert_eq!(old.adj, new.adj, "seed {seed}"); + assert_eq!(old.src, new.src, "seed {seed}"); + assert_eq!(old.edge_src, new.edge_src, "seed {seed}"); + } + } + #[test] fn long_segment_crossing_in_unsampled_cell_is_split() { // A diagonal long enough to skip the grid, and a short segment crossing it in a cell the old coarse sampling missed. diff --git a/crates/geom/src/spline.rs b/crates/geom/src/spline.rs index 1d5922d37..99b63f941 100644 --- a/crates/geom/src/spline.rs +++ b/crates/geom/src/spline.rs @@ -347,21 +347,64 @@ fn basis_into(span: usize, u: f64, p: usize, knots: &[f64], n: &mut [f64], left: } } -/// Gaussian elimination with partial pivoting. +/// Gaussian elimination with partial pivoting. The interpolation and least-squares matrices are +/// banded, so every loop is limited to the band (lower width `kl`, upper width `ku`, measured from +/// the matrix; partial pivoting widens the upper band to at most `kl + ku`). The skipped operations +/// only combine entries that are exactly `+0.0` (they stay `+0.0` through the full sweep), so the +/// result is bit for bit that of the full sweep (for finite input that does not overflow). A matrix with full bandwidth (the cyclic matrix of +/// a closed fit) costs what it did before. +/// +/// A skipped `0 * x` is not zero when `x` is NaN or infinite, so a matrix or right-hand side with +/// NaN, infinity or magnitudes above `1e100` (which could overflow) takes the full sweep, and so +/// does a back-substitution row whose banded sum is zero (skipped zero terms can flip its sign). #[allow(clippy::needless_range_loop)] pub(crate) fn solve(mut a: Vec>, mut b: Vec) -> Option> { + #[cfg(test)] + if tests::DENSE_ORACLE.get() { + return tests::solve_dense(a, b); + } let n = b.len(); + // Per row: how far its non-zero entries reach left and right of the diagonal, and whether one + // is NaN, infinite or large enough to overflow. + let measure = |r: usize, row: &[f64]| { + // Bit test, not `!= 0.0`: a stored `-0.0` is not the `+0.0` the skipped entries rely on. + let row = row.get(..n).unwrap_or(row); + let Some(first) = row.iter().position(|v| v.to_bits() != 0) else { return (0, 0, false) }; + let last = row.iter().rposition(|v| v.to_bits() != 0).unwrap_or(first); + let wild = row.get(first..=last).is_some_and(|band| band.iter().any(|v| v.is_nan() || v.abs() > 1e100)); + (r.saturating_sub(first), last.saturating_sub(r), wild) + }; + let join = |x: (usize, usize, bool), m: (usize, usize, bool)| (x.0.max(m.0), x.1.max(m.1), x.2 | m.2); + // A last row that reaches column 0 (the cyclic matrix of a closed fit) makes every range of the + // sweep full-width whatever the other rows hold, so they need no measuring. + let mut m = (0usize, 0usize, false); + for r in [0, n.saturating_sub(1)] { + if let Some(row) = a.get(r) { + m = join(m, measure(r, row)); + } + } + // (kl = n - 1 widens every range to the full matrix, so the unmeasured rows cannot matter.) + if m.0 + 1 < n { + m = a.iter().enumerate().take(n).fold(m, |x, (r, row)| join(x, measure(r, row))); + } + let (mut kl, mut ku, wild) = m; + if wild || b.iter().any(|v| v.is_nan() || v.abs() > 1e100) { + (kl, ku) = (n, n); + } + let kw = ku + kl; for c in 0..n { - let piv = (c..n).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?; + let end = (c + kl).min(n - 1) + 1; + let piv = (c..end).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?; if a[piv][c].abs() < 1e-14 { return None; } a.swap(c, piv); b.swap(c, piv); - for r in c + 1..n { + let kend = (c + kw).min(n - 1) + 1; + for r in c + 1..end { let f = a[r][c] / a[c][c]; if f != 0.0 { - for k in c..n { + for k in c..kend { a[r][k] -= f * a[c][k]; } b[r] -= f * b[c]; @@ -370,7 +413,12 @@ pub(crate) fn solve(mut a: Vec>, mut b: Vec) -> Option> { } let mut x = vec![0.0; n]; for r in (0..n).rev() { - let s: f64 = (r + 1..n).map(|k| a[r][k] * x[k]).sum(); + let end = (r + kw).min(n - 1) + 1; + let mut s: f64 = (r + 1..end).map(|k| a[r][k] * x[k]).sum(); + if s == 0.0 && end < n { + // The skipped terms are signed zeros; added to a zero they can flip its sign. + s = (r + 1..n).map(|k| a[r][k] * x[k]).sum(); + } x[r] = (b[r] - s) / a[r][r]; } Some(x) diff --git a/crates/geom/src/spline/tests.rs b/crates/geom/src/spline/tests.rs index 820490d89..6a81b141f 100644 --- a/crates/geom/src/spline/tests.rs +++ b/crates/geom/src/spline/tests.rs @@ -380,3 +380,196 @@ fn a_normal_low_degree_spline_is_valid() { assert!(s.is_valid()); assert!(s.tessellate(1e-3).len() > 4); } + +thread_local! { + /// While set, `solve` runs `solve_dense` (this thread only, so parallel tests do not mix). + pub(super) static DENSE_ORACLE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// `solve` before it was limited to the matrix band, kept as the reference. +#[allow(clippy::needless_range_loop)] +pub(super) fn solve_dense(mut a: Vec>, mut b: Vec) -> Option> { + let n = b.len(); + for c in 0..n { + let piv = (c..n).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?; + if a[piv][c].abs() < 1e-14 { + return None; + } + a.swap(c, piv); + b.swap(c, piv); + for r in c + 1..n { + let f = a[r][c] / a[c][c]; + if f != 0.0 { + for k in c..n { + a[r][k] -= f * a[c][k]; + } + b[r] -= f * b[c]; + } + } + } + let mut x = vec![0.0; n]; + for r in (0..n).rev() { + let s: f64 = (r + 1..n).map(|k| a[r][k] * x[k]).sum(); + x[r] = (b[r] - s) / a[r][r]; + } + Some(x) +} + +fn bits(v: &[f64]) -> Vec { + v.iter().map(|x| x.to_bits()).collect() +} + +fn bits2(v: &[Vec2]) -> Vec { + v.iter().flat_map(|p| [p.x.to_bits(), p.y.to_bits()]).collect() +} + +/// Both solvers on one system: `None` together, or the same bits. +fn assert_same_solution(a: &[Vec], b: &[f64], what: &str) { + let old = solve_dense(a.to_vec(), b.to_vec()); + let new = solve(a.to_vec(), b.to_vec()); + assert_eq!(old.as_deref().map(bits), new.as_deref().map(bits), "{what}"); +} + +/// A random matrix with `kl` sub- and `ku` super-diagonals (some entries exactly zero). +fn banded(n: usize, kl: usize, ku: usize, seed: &mut u64) -> Vec> { + let mut a = vec![vec![0.0; n]; n]; + for (r, row) in a.iter_mut().enumerate() { + for (c, v) in row.iter_mut().enumerate() { + if c + kl >= r && c <= r + ku && noise(seed) > 0.15 { + *v = noise(seed) * 4.0 - 2.0; + } + } + } + a +} + +#[test] +fn banded_solve_matches_the_dense_sweep_bit_for_bit() { + let mut seed = 0x5eed_u64; + for n in [1, 2, 3, 4, 5, 8, 17, 40, 120] { + for (kl, ku) in [(0, 0), (1, 0), (0, 2), (1, 1), (3, 3), (2, 5), (n, n)] { + for _ in 0..6 { + let a = banded(n, kl, ku, &mut seed); + // Right-hand sides with zeros of both signs make the zero-sign cases reachable. + let b: Vec = (0..n) + .map(|i| [noise(&mut seed) * 9.0 - 4.0, 0.0, -0.0][(noise(&mut seed) * 3.0) as usize % 3] * (i % 4 != 0) as u8 as f64) + .collect(); + assert_same_solution(&a, &b, &format!("n={n} kl={kl} ku={ku}")); + assert_same_solution(&a, &vec![0.0; n], &format!("zero rhs n={n} kl={kl} ku={ku}")); + assert_same_solution(&a, &vec![-0.0; n], &format!("negative-zero rhs n={n} kl={kl} ku={ku}")); + } + } + } +} + +#[test] +fn solve_handles_negative_zeros_signed_zero_sums_and_hostile_values() { + let mut seed = 77_u64; + for n in [3, 6, 30] { + let mut a = banded(n, 1, 2, &mut seed); + // A stored `-0.0` outside the band is still part of the matrix. + a[0][n - 1] = -0.0; + a[n - 1][0] = -0.0; + let b: Vec = (0..n).map(|i| if i % 2 == 0 { -0.0 } else { 1.0 }).collect(); + assert_same_solution(&a, &b, &format!("negative zeros n={n}")); + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e200, 1e101] { + let mut ab = a.clone(); + ab[n / 2][n / 2] = bad; + assert_same_solution(&ab, &b, &format!("{bad:?} in the matrix, n={n}")); + let mut bb = b.clone(); + bb[n - 1] = bad; + assert_same_solution(&a, &bb, &format!("{bad:?} in the rhs, n={n}")); + } + } + // Bad values in a narrow band with no corner entry, so the guard (not a full-width matrix) decides. + for bad in [f64::NAN, f64::INFINITY, 1e200, 1e101] { + let a = banded(12, 1, 2, &mut seed); + let mut ab = a.clone(); + ab[5][5] = bad; + ab[5][6] = 1.0; + assert_same_solution(&ab, &[1.0; 12], &format!("{bad:?} in a narrow band")); + let mut b = vec![1.0; 12]; + b[3] = bad; + assert_same_solution(&a, &b, &format!("{bad:?} in the rhs of a narrow band")); + } + // Singular and empty systems. + assert_same_solution(&[vec![0.0, 0.0], vec![0.0, 1.0]], &[1.0, 1.0], "singular"); + assert_same_solution(&[], &[], "empty"); + assert_eq!(solve(Vec::new(), Vec::new()), Some(Vec::new())); +} + +/// Fit points: a wavy line with noise; every `zero_every`-th coordinate is exactly zero. +fn fit_points(n: usize, seed: &mut u64, zero_every: usize) -> Vec { + (0..n) + .map(|i| { + let x = i as f64 * 3.0 + noise(seed); + let y = (i as f64 * 0.3).sin() * 50.0 + noise(seed) * 5.0; + if zero_every > 0 && i % zero_every == 0 { Vec2::new(x, 0.0) } else { Vec2::new(x, y) } + }) + .collect() +} + +fn spline_bits(s: &Spline) -> (Vec, Vec, Vec, Vec, usize) { + (bits(&s.knots), bits2(&s.control), bits(&s.weights), bits2(&s.fit), s.degree) +} + +/// Fit with the banded `solve`, then with the dense reference, and compare every bit. +/// Clears `DENSE_ORACLE` when dropped, so a failing assertion cannot leave it set. +struct OracleOff; +impl Drop for OracleOff { + fn drop(&mut self) { + DENSE_ORACLE.set(false); + } +} + +fn assert_fit_unchanged(fit: &[Vec2], closed: bool, opts: FitOptions, what: &str) { + let _off = OracleOff; + let new = Spline::fit_with(fit, closed, opts); + DENSE_ORACLE.set(true); + let old = Spline::fit_with(fit, closed, opts); + DENSE_ORACLE.set(false); + assert_eq!(spline_bits(&old), spline_bits(&new), "{what}"); +} + +#[test] +fn fits_are_bit_identical_to_the_dense_solver() { + let mut seed = 2432_u64; + let tolerant = FitOptions { tolerance: 0.5, ..FitOptions::default() }; + let tangents = FitOptions { start_tangent: Some(Vec2::new(0.0, 1.0)), end_tangent: Some(Vec2::new(1.0, -1.0)), ..FitOptions::default() }; + let chord = FitOptions { knots: crate::KnotParam::Chord, ..FitOptions::default() }; + for n in [3, 4, 5, 7, 12, 30, 100] { + for round in 0..4 { + let zero_every = [0, 2, 3, 1][round]; + let pts = fit_points(n, &mut seed, zero_every); + for closed in [false, true] { + for (name, opts) in [("default", FitOptions::default()), ("tolerance", tolerant), ("tangents", tangents), ("chord", chord)] { + assert_fit_unchanged(&pts, closed, opts, &format!("n={n} closed={closed} {name} zero_every={zero_every}")); + } + } + } + } + // Large point sets: open interpolation (banded) and a closed one (full bandwidth), and a + // tolerance fit at the size the approximation search still accepts. + let big = fit_points(1000, &mut seed, 0); + assert_fit_unchanged(&big, false, FitOptions::default(), "n=1000 open"); + assert_fit_unchanged(&big[..150], true, FitOptions::default(), "n=150 closed"); + assert_fit_unchanged(&big[..300], false, tolerant, "n=300 tolerance"); + // Repeated points are kinks, which fit each piece on its own. + let mut kinked = fit_points(40, &mut seed, 0); + kinked.insert(10, kinked[10]); + kinked.insert(25, kinked[25]); + assert_fit_unchanged(&kinked, false, FitOptions::default(), "kinks"); +} + +#[test] +fn the_cyclic_matrix_of_a_closed_fit_keeps_the_full_sweep() { + // Corner entries give the closed matrix a full bandwidth; it must still agree with the dense sweep. + let mut seed = 9_u64; + for n in [4, 9, 60] { + let mut a = banded(n, 1, 1, &mut seed); + a[0][n - 1] = 0.7; + a[n - 1][0] = -0.3; + let b: Vec = (0..n).map(|_| noise(&mut seed)).collect(); + assert_same_solution(&a, &b, &format!("cyclic n={n}")); + } +} diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 915a1071e..57ffcd663 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -221,6 +221,18 @@ fn segment_offset() { assert!(s.offset(6.0).is_none()); } +/// A polyline of many fine arcs samples at most the point budget, then draws chords. +#[test] +fn polyline_tessellation_is_bounded() { + let vertices: Vec = (0..3000).map(|i| PolyVertex { bulge: 1.0, ..PolyVertex::new(Vec2::new(f64::from(i) * 1e6, 0.0)) }).collect(); + let pl = Polyline { vertices, closed: false }; + let pts = pl.tessellate(1e-9); + assert!(pts.len() <= MAX_TESSELLATED_POINTS + 2 * 3000 + 4096, "{}", pts.len()); + assert!(pts.len() > 3000); + let mut budget = 10; + assert!(pl.tessellate_within(1e-9, &mut budget).len() <= 4096 + 2 * 3000); +} + #[test] fn arc_segments_bounded() { assert_eq!(arc_segments(0.0, 1.0, 0.1), 1); diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 21ba5d5cc..f39a630f1 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -25,8 +25,11 @@ quick-xml = { workspace = true } image = { workspace = true } [dev-dependencies] -# Reads CADCraft's DWG output as written (tests only; the same version as cadcraft-dwg's). -acadrust = "0.6.6" tiny-skia = { workspace = true } # Reads plotted PDFs back. craft-pdf = { workspace = true, features = ["read"] } + +# Inspect DWG output only where cadcraft-dwg builds its native bridge. An unconditional +# dev-dependency also builds acadrust during --all-targets, breaking FreeBSD aarch64 (#2526). +[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies] +acadrust = "0.6.6" diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 0b733f47c..7a3994f55 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -844,15 +844,33 @@ pub(crate) fn apply_anno(d: &mut cadcraft_doc::Drawing, p: AnnoPayload) { std::sync::Arc::make_mut(b).annotative = true; } } + // Which layout holds each paper space object, found once: `modify_entity` searches every + // layout for a handle model space lacks, which a long list of missing handles made quadratic. + let mut in_layout: std::collections::HashMap = Default::default(); + if !p.objects.is_empty() { + // First layout wins, as `modify_entity` did. + for (i, l) in d.layouts.iter().enumerate() { + for h in l.entities.handles() { + in_layout.entry(h).or_insert(i); + } + } + } for o in p.objects { let Some(h) = Handle::parse_hex(&o.handle) else { continue }; + let store = if d.model.contains(h) { + &mut d.model + } else if let Some(l) = in_layout.get(&h).and_then(|&i| d.layouts.get_mut(i)) { + &mut l.entities + } else { + continue; + }; let mut scales: Vec = Vec::new(); for s in o.scales.into_iter().filter(|s| s.is_valid() && !s.name.trim().is_empty()) { if scales.len() < cadcraft_doc::MAX_SCALES && !scales.iter().any(|x| x.name.eq_ignore_ascii_case(&s.name)) { scales.push(s); } } - let _ = d.modify_entity(h, |e| { + store.modify(h, |e| { if cadcraft_doc::can_be_annotative(&e.kind) { e.common.anno_scales = scales; } diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 1a2c8696b..d1e0cd2c6 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -16,7 +16,7 @@ use std::borrow::Cow; use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Arc; -use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject}; +use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number}; use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown}; use cadcraft_dxf::{Section, Tag}; @@ -339,7 +339,8 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { } let root = objects.first().filter(|(k, _, _)| is_dictionary(k)).and_then(|(_, _, t)| head(t).handle); let root_entries = objects.first().filter(|(k, _, _)| is_dictionary(k)).map(|(_, _, t)| entries(t)).unwrap_or_default(); - let root_key = |h: &str| root_entries.iter().find(|(_, eh)| eh == h).map(|(k, _)| k.clone()); + let root_keys = root_key_index(&root_entries); + let root_key = |h: &str| root_keys.get(h).map(|k| (*k).to_string()); // An extension dictionary of an entity or record (not of another object). let is_xdict = |k: usize| { let Some((_, _, t)) = objects.get(k) else { return false }; @@ -417,10 +418,11 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { } } if proxies { + f.complete_class_table = classes.iter().filter(|(k, _, _)| k == "CLASS").count() <= MAX_OBJECTS; f.class_order = class_order; } for (kind, _, t) in &classes { - if kind == "CLASS" && val(t, 1).is_some_and(|n| types.contains(&up(&n))) && f.classes.len() < MAX_OBJECTS { + if kind == "CLASS" && (f.complete_class_table || val(t, 1).is_some_and(|n| types.contains(&up(&n)))) && f.classes.len() < MAX_OBJECTS { f.classes.push(t.iter().map(raw).collect()); } } @@ -452,10 +454,21 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { f.data_store = ds.tags.iter().take(MAX_DATA_STORE_GROUPS).map(raw).collect(); } if !f.is_empty() { + f.version = file_version(secs); d.foreign = Arc::new(f); } } +/// The `$ACADVER` the file's own HEADER section declares, if it does. Not the drawing's: a new +/// drawing starts as AC1032, and a file without the variable would leave that default there. +fn file_version(secs: &[Section]) -> Option { + let header = secs.iter().find(|s| s.name.eq_ignore_ascii_case("HEADER"))?; + let at = header.tags.iter().position(|t| t.code == 9 && t.str().trim().eq_ignore_ascii_case("$ACADVER"))?; + let value = header.tags.get(at + 1).filter(|t| t.code != 9)?.str(); + let value = value.trim(); + (!value.is_empty()).then(|| value.to_string()) +} + fn entity_types(drawing: &Drawing) -> HashMap { let mut types = HashMap::new(); for entity in all_entities(drawing) { @@ -482,6 +495,16 @@ fn extension_dictionaries( dictionaries } +/// The root dictionary's key for each entry handle (the first key when several name one handle), +/// built once: a lookup per object scanning the entries made a large dictionary quadratic. +fn root_key_index(root_entries: &[(String, String)]) -> HashMap<&str, &str> { + let mut index = HashMap::with_capacity(root_entries.len()); + for (key, handle) in root_entries { + index.entry(handle.as_str()).or_insert(key.as_str()); + } + index +} + /// Determine which objects belong to unmodelled dictionary entries or owners. fn retained_objects( objects: &[(String, usize, &[Tag])], @@ -492,7 +515,8 @@ fn retained_objects( root_entries: &[(String, String)], xdict_of: &HashMap, ) -> HashMap { - let root_key = |handle: &str| root_entries.iter().find(|(_, entry_handle)| entry_handle == handle).map(|(key, _)| key); + let root_keys = root_key_index(root_entries); + let root_key = |handle: &str| root_keys.get(handle).copied(); let is_xdict = |index: usize| { let Some((_, _, tags)) = objects.get(index) else { return false }; let header = head(tags); @@ -506,44 +530,108 @@ fn retained_objects( // hundreds of thousands of groups) would be read once per child (#862). let mut xdict_memo: HashMap = HashMap::new(); let mut is_xdict = |index: usize| *xdict_memo.entry(index).or_insert_with(|| is_xdict(index)); - let mut retained = HashMap::new(); - for index in 0..objects.len() { - let mut path = Vec::new(); - let mut current = index; - let keep = loop { - if let Some(&known) = retained.get(¤t) { - break known; - } - if path.contains(¤t) || path.len() >= MAX_DEPTH { - break false; - } - path.push(current); - let Some((_, _, tags)) = objects.get(current) else { break false }; - let header = head(tags); - let (Some(handle), Some(owner)) = (header.handle, header.owner) else { break false }; - if by_handle.get(&handle) != Some(¤t) { - break false; - } - if root == Some(owner.as_str()) { - break root_key(&handle).is_some_and(|key| !modelled_key(key)); - } - if let Some(&parent) = by_handle.get(&owner) { - if is_xdict(parent) && objects.get(parent).is_some_and(|object| modelled_entry(object.2, &handle)) { + let hard = hard_owners(objects.iter().filter_map(|(_, _, t)| Some((head(t).handle?, held(t))))); + // One pass with `kept` the objects an earlier pass kept: a null-owner object goes with the + // first of its hard owners that is kept. + let mut pass = |kept: &HashMap| { + // Previously live objects already have a proved path to a retained owner. Seed that + // proof before traversal, so mutual hard owners cannot hide it from their children. + let mut retained: HashMap = kept.iter().filter(|(_, live)| **live).map(|(&i, &live)| (i, live)).collect(); + let kept = |h: &str| by_handle.get(h).and_then(|i| kept.get(i)) == Some(&true); + for index in 0..objects.len() { + let mut path = Vec::new(); + let mut current = index; + let keep = loop { + if let Some(&known) = retained.get(¤t) { + break known; + } + if path.contains(¤t) || path.len() >= MAX_DEPTH { break false; } - current = parent; - continue; + path.push(current); + let Some((_, _, tags)) = objects.get(current) else { break false }; + let header = head(tags); + let Some(handle) = header.handle else { break false }; + let Some(owner) = owner_of(header.owner, &handle, &hard, kept) else { break false }; + if by_handle.get(&handle) != Some(¤t) { + break false; + } + if root == Some(owner.as_str()) { + break root_key(&handle).is_some_and(|key| !modelled_key(key)); + } + if let Some(&parent) = by_handle.get(&owner) { + if is_xdict(parent) && objects.get(parent).is_some_and(|object| modelled_entry(object.2, &handle)) { + break false; + } + current = parent; + continue; + } + if is_xdict(current) { + break entries(tags).iter().any(|(key, _)| !MODELLED_XDICT_KEYS.contains(&up(key).as_str())); + } + break entities.get(&owner) == Some(&true); + }; + for visited in path { + retained.insert(visited, keep); } - if is_xdict(current) { - break entries(tags).iter().any(|(key, _)| !MODELLED_XDICT_KEYS.contains(&up(key).as_str())); + } + retained + }; + settle(&hard, |kept| pass(kept)) +} + +/// Run `pass` until what it keeps settles. The first pass sees nothing kept, so a null-owner +/// object goes with its first hard owner; while one of its other hard owners is kept and that +/// one is not, the next pass moves it there. A file where no object has two hard owners takes +/// one pass; otherwise it stops when a pass changes nothing, after at most [`MAX_DEPTH`] more. +fn settle( + hard: &HashMap>, + mut pass: impl FnMut(&HashMap) -> HashMap, +) -> HashMap { + let mut kept = pass(&HashMap::new()); + if hard.values().all(|owners| owners.len() < 2) { + return kept; + } + for _ in 0..MAX_DEPTH { + let next = pass(&kept); + if next == kept { + break; + } + kept = next; + } + kept +} + +/// The handles an object names by a hard owner reference (group 360). +fn held(tags: &[Tag]) -> impl Iterator + '_ { + tags.iter().take_while(|g| g.code < 1000).filter(|g| g.code == 360).map(|g| g.str()) +} + +/// The objects that own each object by a hard owner reference (group 360), in file order: +/// `child handle → owner handles`. +fn hard_owners>(objects: impl Iterator)>) -> HashMap> { + // Membership is hashed, while the vector keeps file order. A long list of distinct + // holders for one child must not scan all earlier holders once per reference. + let mut out: HashMap, HashSet)> = HashMap::new(); + for (h, children) in objects { + for c in children { + let (owners, seen) = out.entry(norm(c.as_ref())).or_default(); + if seen.insert(h.clone()) { + owners.push(h.clone()); } - break entities.get(&owner) == Some(&true); - }; - for visited in path { - retained.insert(visited, keep); } } - retained + out.into_iter().map(|(child, (owners, _))| (child, owners)).collect() +} + +/// An object's owner: its group 330, or for one whose owner is null (another application's +/// proxy that another proxy holds) the object that hard-owns it ([`hard_owners`]): the first +/// one that is `kept`, or else the first one. +fn owner_of(owner: Option, handle: &str, hard: &HashMap>, kept: impl Fn(&str) -> bool) -> Option { + owner.filter(|o| o != "0").or_else(|| { + let owners = hard.get(handle)?; + owners.iter().find(|o| kept(o)).or_else(|| owners.first()).cloned() + }) } /// Proxy records (DXF Reference, ACAD_PROXY_OBJECT and ACAD_PROXY_ENTITY): another application's @@ -552,32 +640,6 @@ fn is_proxy(kind: &str) -> bool { matches!(up(kind).as_str(), "ACAD_PROXY_OBJECT" | "ACAD_PROXY_ENTITY") } -/// Where a proxy's class number is: its first group 91 outside the `102 {NAME` … `102 }` groups -/// (an application's can hold a 91 of its own) and before any xdata. -fn class_group>(groups: impl IntoIterator) -> Option { - let mut in_group = false; - for (i, (code, value)) in groups.into_iter().enumerate() { - match code { - 1000.. => return None, - 102 => in_group = value.as_ref().trim().starts_with('{'), - 91 if !in_group => return Some(i), - _ => {} - } - } - None -} - -/// A proxy's class number (see [`class_group`]). -fn class_number>(groups: impl IntoIterator + Clone) -> Option { - let i = class_group(groups.clone())?; - groups.into_iter().nth(i).and_then(|(_, v)| v.as_ref().trim().parse().ok()) -} - -/// The place in CLASSES a class number names (500 is the first class). -fn class_index(number: Option) -> Option { - usize::try_from(number?.checked_sub(500)?).ok() -} - /// Set a proxy's class number (see [`class_group`]). fn set_class_number(tags: &mut [Tag], n: i64) { if let Some(t) = class_group(tags.iter().map(|t| (t.code, t.str()))).and_then(|i| tags.get_mut(i)) { @@ -656,6 +718,8 @@ pub(crate) fn unknown_entity(u: &Unknown, e: &Entity, owner: &str, paper: bool) } _ if in_group => continue, 5 | 67 => continue, + // After a subclass marker, 330 can be proxy data even without a source owner. + 100 => owner_seen = true, 330 if !owner_seen => { owner_seen = true; continue; @@ -873,7 +937,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap| class_index(old).and_then(|i| f.class_order.get(i)).and_then(|n| numbers.get(n).copied()); + let renumber = |old| proxy_class_number(f, &numbers, old); // Entities of types CADCraft doesn't model, placed among the written ones. let mut planned = plan_unknown(d, &recs, tags, &roles, modern); for list in planned.values_mut() { @@ -916,43 +980,56 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap = f.objects.iter().map(|o| (o.handle.hex(), o)).collect(); let dict_entries: HashMap = f.dictionary.iter().map(|(k, h)| (h.hex(), k.as_str())).collect(); let nod = f.targets.iter().filter(|(_, k)| k.0 == "NOD" && k.1.is_empty()).map(|(h, _)| h.hex()).collect::>(); - let owners: HashMap = f + let hard = hard_owners( + f.objects.iter().map(|o| (o.handle.hex(), o.tags.iter().take_while(|t| t.code < 1000).filter(|t| t.code == 360).map(|t| t.value.trim()))), + ); + // Each kept object's own owner (group 330), read one record at a time. + let own: HashMap> = f .objects .iter() - .filter_map(|o| Some((o.handle.hex(), head(&o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect::>()).owner?))) + .map(|o| { + let t: Vec = o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect(); + (o.handle.hex(), head(&t).owner) + }) .collect(); - let mut alive_memo: HashMap = HashMap::new(); - 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()) { - alive_memo.insert(o.handle.hex(), false); - } - for o in &f.objects { - let mut path: Vec = Vec::new(); - let mut cur = o.handle.hex(); - let verdict = loop { - if let Some(&v) = alive_memo.get(&cur) { - break v; - } - if path.contains(&cur) || path.len() >= MAX_DEPTH { - break false; - } - path.push(cur.clone()); - let Some(owner) = owners.get(&cur).cloned() else { break false }; - if objs.contains_key(&owner) { - cur = owner; - continue; - } - if nod.contains(&owner) { - break dict_entries.get(&cur).is_some_and(|k| !root_keys.contains(&up(k))) && root.is_some(); - } - if attached.contains(&cur) { - break true; - } - break unknown.contains(&owner) && written.contains(&owner); - }; - for p in path { - alive_memo.insert(p, verdict); + let alive_memo = settle(&hard, |kept: &HashMap| { + // Keep established live paths available to descendants during this pass as well. + let mut alive_memo: HashMap = 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()) + { + alive_memo.insert(o.handle.hex(), false); } - } + for o in &f.objects { + let mut path: Vec = Vec::new(); + let mut cur = o.handle.hex(); + let verdict = loop { + if let Some(&v) = alive_memo.get(&cur) { + break v; + } + if path.contains(&cur) || path.len() >= MAX_DEPTH { + break false; + } + path.push(cur.clone()); + let Some(owner) = owner_of(own.get(&cur).cloned().flatten(), &cur, &hard, kept) else { break false }; + if objs.contains_key(&owner) { + cur = owner; + continue; + } + if nod.contains(&owner) { + break dict_entries.get(&cur).is_some_and(|k| !root_keys.contains(&up(k))) && root.is_some(); + } + if attached.contains(&cur) { + break true; + } + break unknown.contains(&owner) && written.contains(&owner); + }; + for p in path { + alive_memo.insert(p, verdict); + } + } + alive_memo + }); // New handles for the written kept objects, above every written handle and the seed. let mut next = seed(tags).max(max_handle(tags).saturating_add(1)); let mut alive: HashMap = HashMap::new(); @@ -969,11 +1046,8 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap, d: &Drawing, reactors: &HashMap, old: Option) -> Option { + if f.complete_class_table { + class_index(old).filter(|&i| i < f.classes.len()).and(old) + } else { + class_index(old).and_then(|i| f.class_order.get(i)).and_then(|n| numbers.get(n).copied()) + } +} + +/// Source classes precede decoder-owned classes so proxy positions stay stable. +fn source_class_record(f: &Foreign, record: &Rec, recs: &[Rec], tags: &[Tag], class_names: &HashSet, out: &mut Vec) -> bool { + if record.sec != "CLASSES" { + return false; + } + if !f.complete_class_table { + if record.kind == "ENDSEC" { + for class in f.classes.iter().filter(|c| c.iter().find(|t| t.code == 1).is_some_and(|n| !class_names.contains(&up(&n.value)))) { + out.push(Tag::s(0, "CLASS")); + out.extend(class.iter().map(tag)); + } + } + return false; + } + if record.kind == "CLASS" { + return true; + } + if record.kind != "ENDSEC" { + return false; + } + for class in &f.classes { + out.push(Tag::s(0, "CLASS")); + out.extend(class.iter().map(tag)); + } + let source_names: HashSet<_> = f.classes.iter().filter_map(|c| c.iter().find(|t| t.code == 1)).map(|t| up(&t.value)).collect(); + for class in recs.iter().filter(|r| r.sec == "CLASSES" && r.kind == "CLASS") { + let body = tags.get(class.start + 1..class.end).unwrap_or_default(); + if val(body, 1).is_some_and(|n| !source_names.contains(&up(&n))) { + out.push(Tag::s(0, "CLASS")); + out.extend_from_slice(body); + } + } + false +} + /// Where the entities of types CADCraft doesn't model go: each before the next written entity of /// its space or block (else at the end of it), as `(section, record)` lists by the index of the /// record they precede. Owners come from the written block records. @@ -1275,3 +1393,28 @@ fn seed(tags: &[Tag]) -> u64 { fn max_handle(tags: &[Tag]) -> u64 { tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(&t.str())).map(|h| h.0).max().unwrap_or(0) } + +#[cfg(test)] +mod hard_owner_tests { + use super::hard_owners; + + #[test] + fn holders_are_unique_in_first_seen_order() { + let objects = + [("10".to_string(), ["00a", "A"].into_iter()), ("20".to_string(), ["A", "00A"].into_iter()), ("10".to_string(), ["A", "A"].into_iter())]; + let owners = hard_owners(objects.into_iter()); + assert_eq!(owners.get("A").unwrap(), &["10", "20"]); + assert_eq!(owners.len(), 1); + } + + #[test] + fn many_distinct_holders_keep_file_order() { + let count = 10_000; + let owners = hard_owners((0..count).map(|i| (format!("{i:X}"), ["FFFF", "FFFF"].into_iter()))); + let holders = owners.get("FFFF").unwrap(); + assert_eq!(holders.len(), count); + for (i, holder) in holders.iter().enumerate() { + assert_eq!(holder, &format!("{i:X}")); + } + } +} diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 40366a7c7..61d1f7eb3 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -24,7 +24,8 @@ mod tables; mod text; use document::{ - apply_sortents, count_skipped, outside_sections, parse_entities, place_blocks, place_entities, read_blocks, read_objects, setup_layouts, + 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; @@ -61,6 +62,11 @@ struct Rx { block_arrays: HashMap, /// LAYER record handle (upper case) → layer name (VIEWPORT group 331/341 frozen layers). layers: HashMap, + /// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport + /// (PAPERVIEW) the reader dropped. + paper_views_dropped: Vec<(Option, bool, Option)>, + /// Upper-case name of the BLOCK whose entities are being read, if any. + block: Option, } /// Read a DXF file into a drawing. @@ -126,6 +132,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { let (paper_block_for, first_layout) = setup_layouts(&mut d, &mut layout_objs, &rx); place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout); place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout); + 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); @@ -144,6 +151,35 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { Ok(d) } +/// Viewport ids another program left unknown (ZWCAD writes 69 = -1, read as 0). A layout whose +/// viewports all lack an id gets them numbered in file order, as DWG readers do; when only +/// some lack one and none is 1, the first viewport is the sheet and gets id 1. Either way the +/// sheet keeps id 1, so saving does not add a second sheet viewport ahead of it (#1463). A layout +/// whose generated sheet (PAPERVIEW) the reader just dropped is left alone: none of its viewports +/// is the sheet, and numbering one as 1 would lose the generated sheet on the next save. +fn number_unknown_viewport_ids(d: &mut Drawing, sheet_dropped: &std::collections::HashSet) { + for l in d.layouts.iter_mut().filter(|l| !sheet_dropped.contains(&l.name)) { + let mut vps: Vec = l.entities.iter().filter(|e| matches!(&e.kind, EntityKind::Viewport(_))).map(|e| (**e).clone()).collect(); + let id = |e: &Entity| if let EntityKind::Viewport(v) = &e.kind { v.id } else { 0 }; + if vps.iter().all(|e| id(e) == 0) { + for (i, e) in vps.iter_mut().enumerate() { + if let EntityKind::Viewport(v) = &mut e.kind { + v.id = i as u32 + 1; + } + } + } else if vps.iter().all(|e| id(e) != 1) && vps.first().is_some_and(|e| id(e) == 0) { + if let Some(EntityKind::Viewport(v)) = vps.first_mut().map(|e| &mut e.kind) { + v.id = 1; + } + } else { + continue; + } + for e in vps { + l.entities.replace(e); + } + } +} + /// 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. diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index 907427718..59dcf7107 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -1,4 +1,4 @@ -use super::{Color, Common, Lineweight, Rgb, Tag, Transparency, Vec2, Vec3}; +use super::{Color, Common, Lineweight, PolyVertex, Rgb, Tag, Transparency, Vec2, Vec3}; /// Value lookup helpers over an entity's tags. pub(super) struct T<'a>(pub(super) &'a [Tag]); @@ -112,3 +112,95 @@ pub(super) fn ocs(c: &Common, p: Vec3) -> Vec3 { pub(super) fn ocs_n(n: Vec3, p: Vec3) -> Vec3 { if (n.z - 1.0).abs() < 1e-12 && n.x.abs() < 1e-12 && n.y.abs() < 1e-12 { p } else { cadcraft_geom::Mat4::ocs(n).apply(p) } } + +/// Whether an object with OCS points `pts` (x, y and elevation) lies in a plane tilted off the +/// XY plane: drawing its points as plan coordinates (x flipped for a mirrored plane, as the +/// readers do) would put some of them off their place seen from above by more than a +/// billionth of the object's size and distance from the origin. A normal that is the Z axis +/// or the Z axis turned over moves nothing, and noise in one moves points by a negligible +/// amount, so those objects keep their arcs; however small the tilt, an object far enough from +/// the origin to be moved visibly is projected. +pub(super) fn tilted(n: Vec3, pts: impl IntoIterator) -> bool { + if !n.is_finite() || n.len() < 1e-12 { + return false; + } + let m = cadcraft_geom::Mat4::ocs(n); + let flip = if n.z < 0.0 { -1.0 } else { 1.0 }; + let (mut moved, mut reach) = (0.0f64, 1.0f64); + for p in pts.into_iter().filter(|p| p.is_finite()) { + let shown = Vec2::new(flip * p.x, p.y); + moved = moved.max((m.apply(p).xy() - shown).len()); + reach = reach.max(p.x.abs()).max(p.y.abs()).max(p.z.abs()); + } + moved > 1e-9 * reach +} + +/// Points along a run of OCS vertices at `elevation`, for [`tilted`]: its vertices and, on its +/// arcs, points between them (an arc can bulge where its ends don't move). +pub(super) fn run_points(vertices: &[PolyVertex], elevation: f64, closed: bool) -> Vec { + let mut pts = Vec::with_capacity(vertices.len()); + for (i, v) in vertices.iter().enumerate() { + pts.push(v.p); + let next = if i + 1 < vertices.len() { + vertices.get(i + 1) + } else if closed { + vertices.first() + } else { + None + }; + if let Some(w) = next.filter(|_| v.bulge != 0.0) { + // Each arc sampled from its own size, so a small one next to a long edge counts too. + let arc = cadcraft_geom::Polyline { vertices: vec![*v, PolyVertex::new(w.p)], closed: false }; + let b = arc.bounds(); + let size = (b.max - b.min).len(); + pts.extend(arc.tessellate(if size.is_finite() && size > 0.0 { size * 0.05 } else { 1e-6 })); + } + } + pts.into_iter().map(|p| p.to3(elevation)).collect() +} + +/// The most vertices one tilted run is flattened to: past it, bulged edges are kept as their +/// chords, so a file full of arcs can't ask for gigabytes (one arc adds at most 4,096 more). +const MAX_TILTED_VERTICES: usize = 1_000_000; + +/// A run of OCS vertices at `elevation` in the plane of `n` as seen from above in the WCS. A +/// tilted arc is an elliptical arc there, so each bulged edge is flattened (within a thousandth +/// of the edge's own size, up to [`MAX_TILTED_VERTICES`] in all), its width spread evenly along +/// it; vertices that start straight edges keep their widths. Also gives the mean WCS Z, the +/// elevation the flattened run takes. +pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], closed: bool) -> (Vec, f64) { + let m = cadcraft_geom::Mat4::ocs(n); + let mut local: Vec = Vec::with_capacity(vertices.len()); + for (i, v) in vertices.iter().enumerate() { + let next = if i + 1 < vertices.len() { + vertices.get(i + 1) + } else if closed { + vertices.first() + } else { + None + }; + match next { + Some(w) if v.bulge != 0.0 && local.len() < MAX_TILTED_VERTICES => { + let arc = cadcraft_geom::Polyline { vertices: vec![*v, PolyVertex::new(w.p)], closed: false }; + // From the edge's own size, so a long edge elsewhere can't flatten a small arc away. + let b = arc.bounds(); + let size = (b.max - b.min).len(); + let edge = arc.tessellate(if size.is_finite() && size > 0.0 { size * 1e-3 } else { 1e-6 }); + // The edge runs from this vertex to the next one in equal turns of its arc; its + // width changes evenly along it, as a tapered segment's does. + let steps = edge.len().saturating_sub(1).max(1); + let width = |k: usize| v.start_width + (v.end_width - v.start_width) * k as f64 / steps as f64; + local.extend(edge.iter().take(steps).enumerate().map(|(k, p)| PolyVertex { + p: *p, + bulge: 0.0, + start_width: width(k), + end_width: width(k + 1), + })); + } + _ => local.push(PolyVertex { bulge: 0.0, ..*v }), + } + } + let to_plan = |p: Vec2| m.apply(Vec3::new(p.x, p.y, elevation)); + let z = if local.is_empty() { elevation } else { local.iter().map(|v| to_plan(v.p).z).sum::() / local.len() as f64 }; + (local.into_iter().map(|v| PolyVertex { p: to_plan(v.p).xy(), ..v }).collect(), z) +} diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index 7d22e95d1..610881e38 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -17,6 +17,9 @@ pub(super) fn parse_entities( let owner = crate::dxf_ext::owner(tags); let paper = t.i(67) == Some(1); let handle = t.s(5).and_then(|h| Handle::parse_hex(&h)); + if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) { + rx.paper_views_dropped.push((owner.clone(), paper, rx.block.clone())); + } let mut kindent = entity_with_table_budget(kind, tags, table_cells_left); if let Some((c, _)) = kindent.as_mut() && let Some(n) = entity_plot_style(tags, rx) @@ -111,7 +114,9 @@ pub(super) fn read_blocks( j += 1; } 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); + rx.block = None; blocks.push((name, base, description, ents, xref)); i = j + 1; } else { @@ -251,6 +256,14 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec, rx: &mut Rx, } } +/// The layout an entity record belongs to: paper space when flagged (67=1) or owned by a +/// `*PAPER_SPACE` block, else `None` for model space. +fn paper_layout(owner: Option, paper: bool, rx: &Rx, paper_block_for: &HashMap, first_layout: &str) -> Option { + let owner_name = owner.and_then(|o| rx.brs.get(&o.trim().to_ascii_uppercase()).cloned()).map(|n| n.to_ascii_uppercase()); + let to_paper = paper || owner_name.as_deref().is_some_and(|n| n.starts_with("*PAPER_SPACE")); + to_paper.then(|| owner_name.and_then(|n| paper_block_for.get(&n).cloned()).unwrap_or_else(|| first_layout.to_string())) +} + /// Place the ENTITIES section: model space, or paper space when flagged (67=1). pub(super) fn place_entities( d: &mut Drawing, @@ -262,19 +275,32 @@ pub(super) fn place_entities( let mut layers = LayerSet::new(d); for (owner, paper, e) in entities { layers.ensure(d, &e.common.layer); - let owner_name = owner.and_then(|o| rx.brs.get(&o.trim().to_ascii_uppercase()).cloned()).map(|n| n.to_ascii_uppercase()); - let to_paper = paper || owner_name.as_deref().is_some_and(|n| n.starts_with("*PAPER_SPACE")); - if to_paper { - let lname = owner_name.and_then(|n| paper_block_for.get(&n).cloned()).unwrap_or_else(|| first_layout.to_string()); - if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) { - l.entities.push(e); + match paper_layout(owner, paper, rx, paper_block_for, first_layout) { + Some(lname) => { + if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) { + l.entities.push(e); + } } - } else { - d.model.push(e); + None => d.model.push(e), } } } +/// Layouts whose generated sheet viewport (PAPERVIEW) the reader dropped: their viewports keep +/// their ids, so the next save generates the sheet again instead of promoting one of them. +pub(super) fn dropped_paper_views(rx: &Rx, paper_block_for: &HashMap, first_layout: &str) -> std::collections::HashSet { + rx.paper_views_dropped + .iter() + .filter_map(|(owner, paper, block)| match block { + // In a paper-space block the sheet is that block's layout, where `place_blocks` puts + // the block's other entities, whatever its owner group says. + Some(b) if b.starts_with("*PAPER_SPACE") => Some(paper_block_for.get(b).cloned().unwrap_or_else(|| first_layout.to_string())), + Some(_) => None, + None => paper_layout(owner.clone(), *paper, rx, paper_block_for, first_layout), + }) + .collect() +} + pub(super) fn count_skipped(skipped: &mut std::collections::BTreeMap, section: &str, n: usize) { if n > 0 { let c = skipped.entry(section.to_string()).or_insert(0); diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index c28dfd7bb..b2818f01a 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -1,4 +1,4 @@ -use super::common::{T, common, ocs}; +use super::common::{T, common, ocs, plan_of_tilted, run_points, tilted}; use super::hatch::hatch; use super::mtext_dxf; use super::text::{attdef, attrib_modes, attrib_props, mtext_from, multiline_attrib, split_embedded, text_from}; @@ -47,7 +47,7 @@ fn ellipse(c: &Common, t: &T) -> Ellipse { } /// A LWPOLYLINE, or the region CADCraft wrote as one. -fn lwpolyline(tags: &[Tag], c: &Common, t: &T) -> Option { +fn lwpolyline(tags: &[Tag], c: &mut Common, t: &T) -> Option { let mut verts = Vec::new(); let mut cur: Option = None; for tg in tags { @@ -83,13 +83,19 @@ fn lwpolyline(tags: &[Tag], c: &Common, t: &T) -> Option { } verts.extend(cur); let flags = t.i(70).unwrap_or(0); - if c.extrusion.z < 0.0 { + let mut elevation = t.fd(38, 0.0); + if tilted(c.extrusion, run_points(&verts, elevation, flags & 1 != 0)) { + // 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); + c.extrusion = Vec3::Z; + } else if c.extrusion.z < 0.0 { for v in &mut verts { v.p.x = -v.p.x; v.bulge = -v.bulge; } } - let pl = LwPolyline { vertices: verts, closed: flags & 1 != 0, const_width: t.fd(43, 0.0), elevation: t.fd(38, 0.0), plinegen: flags & 128 != 0 }; + let pl = LwPolyline { vertices: verts, closed: flags & 1 != 0, const_width: t.fd(43, 0.0), elevation, plinegen: flags & 128 != 0 }; // A region CADCraft wrote as polylines (`dxf_region`). crate::dxf_region::from_polyline(tags, pl) } @@ -123,14 +129,14 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef return None; } let t = T(tags); - let c = common(&t); + let mut c = common(&t); let k = match kind { "LINE" => EntityKind::Line(Line { a: t.p(10), b: t.p(11) }), "POINT" => EntityKind::Point(Point { p: t.p(10), angle: t.fd(50, 0.0).to_radians() }), "CIRCLE" => EntityKind::Circle(Circle { center: ocs(&c, t.p(10)), radius: t.fd(40, 1.0).abs() }), "ARC" => EntityKind::Arc(arc(&c, &t)), "ELLIPSE" => EntityKind::Ellipse(ellipse(&c, &t)), - "LWPOLYLINE" => lwpolyline(tags, &c, &t)?, + "LWPOLYLINE" => lwpolyline(tags, &mut c, &t)?, "SPLINE" => EntityKind::Spline(spline(&t)), "HELIX" => EntityKind::Helix(helix(tags)), "RAY" => EntityKind::Ray(RayLine { base: t.p(10), dir: t.p(11) }), @@ -231,7 +237,35 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef "3DFACE" => EntityKind::Face3d(Face3d { corners: [t.p(10), t.p(11), t.p(12), t.p(13)], hidden_edges: t.i(70).unwrap_or(0) as u8 }), "HATCH" => { let mut k = hatch(tags, &t)?; - if c.extrusion.z < 0.0 + if let EntityKind::Hatch(h) = &mut k + && tilted(c.extrusion, h.loops.iter().flat_map(|l| run_points(&l.vertices, h.elevation, true))) + { + // In a tilted plane (a terrain face, a slope): the boundary as seen from above, + // at its mean height, and the pattern direction and origin projected the same way. + let n = c.extrusion; + let m = cadcraft_geom::Mat4::ocs(n); + let (mut sum, mut count) = (0.0, 0usize); + for l in &mut h.loops { + let (v, z) = plan_of_tilted(n, h.elevation, &l.vertices, true); + sum += z * v.len() as f64; + count += v.len(); + l.vertices = v; + } + // The pattern keeps the spacing and dashes of its plane: only its direction turns. + let plan_angle = |a: f64| { + let dir = m.apply(Vec3::new(a.cos(), a.sin(), 0.0)).xy(); + if dir.len() > 1e-9 { cadcraft_geom::norm_angle(dir.y.atan2(dir.x)) } else { a } + }; + h.angle = plan_angle(h.angle); + if let Some(g) = h.gradient.as_mut() { + g.angle = plan_angle(g.angle); + } + h.origin = m.apply(Vec3::new(h.origin.x, h.origin.y, h.elevation)).xy(); + if count > 0 { + h.elevation = sum / count as f64; + } + c.extrusion = Vec3::Z; + } else if c.extrusion.z < 0.0 && let EntityKind::Hatch(h) = &mut k { // Boundary in the mirrored OCS, like LWPOLYLINE; the pattern direction mirrors too. @@ -254,7 +288,9 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef // 12/22 is in display coordinates, whose origin is the view target 17/27/37. view_center: t.view_center(12, 17, twist), view_height: t.fd(45, 1.0), - id: t.i(69).unwrap_or(0) as u32, + // ZWCAD writes -1 (unknown): 0 here, numbered in order by the reader (#1463). + // Group 69 is 16-bit: other out-of-range values are unknown too, never truncated. + id: t.i(69).filter(|i| (1..=32767).contains(i)).unwrap_or(0) as u32, locked: t.i(90).unwrap_or(0) & 16384 != 0, frozen_layers: crate::dxf_ext::read_frozen(tags), layer_colors: crate::dxf_ext::read_layer_colors(tags), diff --git a/crates/io/src/dxf_read/objects.rs b/crates/io/src/dxf_read/objects.rs index 374313d48..98cdf7d52 100644 --- a/crates/io/src/dxf_read/objects.rs +++ b/crates/io/src/dxf_read/objects.rs @@ -252,6 +252,9 @@ pub(super) fn page_setup(t: &T) -> PageSetup { let rotated = matches!(t.i(73), Some(1 | 3)); if w > 0.0 && h > 0.0 { p.landscape = rotated != (w > h); + // Kept to be written back, so only a rotation the DXF Reference defines (0-3): any other + // value reads as not rotated and is written so. + p.file_paper = Some((w, h, t.i(73).filter(|r| (0..=3).contains(r)).unwrap_or(0))); } else if t.i(73).is_some() { p.landscape = rotated; } diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 518df8d3f..f18c44412 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -199,7 +199,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { // The first *ACTIVE viewport holds the current snap/grid settings. "VPORT" if !active_vport && t.s(2).is_some_and(|n| n.trim().eq_ignore_ascii_case("*ACTIVE")) => { active_vport = true; - vport_record(d, &t); + vport_record(d, &t, true); for (name, code) in [("SNAPUNIT", 14), ("GRIDUNIT", 15)] { if let (Some(x), Some(y)) = (t.f(code), t.f(code + 10)) { let p = Vec2::new(x, y); @@ -282,12 +282,13 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { None => d.dim_styles.push(st), } } - "VPORT" => vport_record(d, &t), + "VPORT" => vport_record(d, &t, false), _ => {} } } - // One *Active viewport is no tiling: the view is the editor's (it zooms to the extents), - // kept only for its view twist (see `cadcraft_engine::DocState`). + // One *Active viewport is no tiling: its single tile is not a configuration to switch to. Its + // view was kept in the HEADER pair as it was read (see `vport_record`), and the record stays + // only for its view twist (see `cadcraft_engine::DocState`). d.vports.retain(|c| c.tiles.len() > usize::from(c.is_active()) || c.tiles.first().is_some_and(|t| t.twist != 0.0)); } @@ -322,22 +323,38 @@ fn index_table_handles(recs: &[(String, Vec)], rx: &mut Rx) { const MAX_VPORT_TILES: usize = 64; /// A VPORT record: one tile of the configuration it names (`*ACTIVE` the one shown). Corners -/// are fractions of the drawing area; unusable tiles are skipped. -fn vport_record(d: &mut Drawing, t: &T) { +/// are fractions of the drawing area; unusable tiles are skipped. `first_active`: this is the +/// file's first `*ACTIVE` record, the one whose view is the drawing's saved view. +fn vport_record(d: &mut Drawing, t: &T, first_active: bool) { let name = t.s(2).map(|n| n.trim().to_string()).unwrap_or_default(); // View twist (group 51, degrees). let twist = t.f(51).map_or(0.0, |a| cadcraft_geom::norm_angle(a.to_radians())); // The view centre 12/22 is in display coordinates, whose origin is the view target 17/27/37. let (min, max, center) = (t.p(10).xy(), t.p(11).xy(), t.view_center(12, 17, twist)); + // A modern file keeps the view it was saved at in the first `*ACTIVE` record (12/22 centre, + // 40 height) as well as in the HEADER pair, and as with the snap and grid spacing the record + // is the newer of the two and wins (#1602). A record that leaves the centre out has no view + // to give -- `p` reads a missing coordinate as zero -- so the header pair stays. + // From the caller, which knows the record's place: whether a tile was kept for an earlier + // `*ACTIVE` record says nothing when that record's tile was unusable. + let first_active = first_active && name.eq_ignore_ascii_case(VportConfig::ACTIVE); + let centred = t.f(12).is_some() && t.f(22).is_some(); let height = t.fd(40, 0.0); let unit = |v: f64| v.is_finite() && (-1e-9..=1.0 + 1e-9).contains(&v); - let ok = [min.x, min.y, max.x, max.y].into_iter().all(unit) - && max.x > min.x + 1e-6 - && max.y > min.y + 1e-6 - && center.is_finite() - && height.is_finite() - && height > 0.0; - if name.is_empty() || !ok { + // One record carries two separate things: where the tile sits on the screen (10/11) and the + // view it shows (12/22, 40). They are judged apart, because a record can hold a usable view + // with a tile rectangle that is not usable -- a first `*ACTIVE` like that used to return + // before the view was read, so a file whose header has no view opened on the extent fit + // instead of where it was saved (noted in review). + let view_ok = center.is_finite() && height.is_finite() && height > 0.0; + let tile_ok = [min.x, min.y, max.x, max.y].into_iter().all(unit) && max.x > min.x + 1e-6 && max.y > min.y + 1e-6; + if name.is_empty() { + return; + } + if first_active && centred && view_ok { + d.header.set_saved_view(center, height); + } + if !view_ok || !tile_ok { return; } let aspect = t.f(41).filter(|a| a.is_finite() && *a > 0.0).unwrap_or(0.0); diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 411f1c4b2..3ce6393d8 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -127,11 +127,17 @@ pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> String { cadcraft_dxf::write_ascii(&tags) } -/// Subclass markers the DWG bridge knows by another spelling (it matches them exactly): -/// AutoCAD writes a dynamic block lookup parameter's as `AcDbBlockLookUpParameter`, the bridge -/// reads `AcDbBlockLookupParameter`; otherwise the parameter loses its name and its lookup -/// action in the DWG, and AutoCAD's lookups stop working. +/// Proxy type names and lookup-parameter subclass names must match the bridge reader's spelling. +/// Ordinary DXF output retains source spellings. fn bridge_markers(tags: &mut [Tag]) { + for tag in tags.iter_mut().filter(|tag| tag.code == 0) { + for name in ["ACAD_PROXY_ENTITY", "ACAD_PROXY_OBJECT"] { + if tag.str().trim().eq_ignore_ascii_case(name) { + *tag = Tag::s(0, name); + break; + } + } + } for t in tags.iter_mut().filter(|t| t.code == 100) { if t.str().trim().eq_ignore_ascii_case("AcDbBlockLookupParameter") { *t = Tag::s(100, "AcDbBlockLookupParameter"); diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index 9b8c1f800..14dbfee73 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -46,6 +46,10 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("INSUNITS", 70), ("MEASUREMENT", 70), ("PSLTSCALE", 70), + // The model view the drawing is saved at, as DXF keeps it in HEADER (the `*ACTIVE` VPORT + // record below repeats it). Written so a drawing opened on its saved view saves it back. + ("VIEWCTR", -2), + ("VIEWSIZE", 40), ]; /// The current dimension style's variables as header variables (`$DIMTXT`, `$DIMDEC`…), after diff --git a/crates/io/src/dxf_write/layout.rs b/crates/io/src/dxf_write/layout.rs index 1341f8ec2..fdd3bfff6 100644 --- a/crates/io/src/dxf_write/layout.rs +++ b/crates/io/src/dxf_write/layout.rs @@ -72,6 +72,11 @@ pub(super) fn paper_view(w: &mut W, d: &Drawing, e: &Entity, owner: &str, cx: &C /// The VPORT table: the `*Active` model space tiles (one viewport on the extents when there is no /// tiled configuration) and the saved configurations, each tile a record, the current one first. pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { + // The view the drawing is saved at, so that reading a drawing and writing it back keeps it; + // a drawing that stores none is written on its extents. The fallback fits the width as well, + // through the aspect the record is written with: a drawing 100 wide and 10 tall otherwise got + // a view 11 tall, which shows a sliver of it, and a horizontal line got 1e-6 (#1602). + const ASPECT: f64 = 1.6; // An untiled view's twist: the lone `*Active` tile the editor keeps for it. let twist = d .vports @@ -79,21 +84,37 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { .find(|c| c.is_active() && c.tiles.len() == 1) .and_then(|c| c.tiles.first()) .map_or(0.0, |t| cadcraft_geom::norm_angle(t.twist)); - // The extents fitted as the turned view sees them. - let (center, height) = if ext.is_empty() { - (Vec2::new(6.0, 4.5), 9.0) - } else if twist == 0.0 { - (ext.center(), (ext.height() * 1.1).max(1e-6)) - } else { - let r = Bounds2::from_points(ext.corners().map(|p| p.rotate(twist))); - let height = r.height() * 1.1; - (r.center().rotate(-twist), if height.is_finite() { height.max(1e-6) } else { 9.0 }) + let (center, height) = match d.header.saved_view() { + Some(v) => v, + None if ext.is_empty() => (Vec2::new(6.0, 4.5), 9.0), + None if twist == 0.0 => (ext.center(), (ext.height().max(ext.width() / ASPECT) * 1.1).max(1e-6)), + // The extents fitted as the turned view sees them. + None => { + let r = Bounds2::from_points(ext.corners().map(|p| p.rotate(twist))); + let height = r.height().max(r.width() / ASPECT) * 1.1; + (r.center().rotate(-twist), if height.is_finite() { height.max(1e-6) } else { 9.0 }) + } }; - let single = VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center, height, aspect: 1.6, twist }; + let single = VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center, height, aspect: ASPECT, twist }; let tiled = d.vports.iter().find(|c| c.is_active() && c.tiles.len() > 1); - let mut records: Vec<(&str, &VportTile)> = match tiled { - Some(c) => c.tiles.iter().map(|t| (VportConfig::ACTIVE, t)).collect(), - None => vec![(VportConfig::ACTIVE, &single)], + // The first `*ACTIVE` record is the one a reader takes the view from, so it carries the saved + // view while keeping its own place on the screen and the tiles after it unchanged. Writing + // the stored tiles as they stand put the new view in HEADER and the old one here, and the + // read takes this one, so updating the view of a tiled drawing did not survive a round trip + // (noted in review). + // + // Only where there is a saved view to carry. `center` and `height` are the extents fallback + // when the header holds none, and a tiled drawing can hold none -- `-VPORTS` splits the + // current view into tiles without setting one -- so overriding regardless replaced a tile's + // own good view with that fallback, and the drawing opened on the extents instead of where + // its tile was (noted in review). + let saved = d.header.saved_view().is_some(); + let first = tiled.and_then(|c| c.tiles.first()).map(|t| if saved { VportTile { center, height, ..*t } } else { *t }); + let mut records: Vec<(&str, &VportTile)> = match (tiled, first.as_ref()) { + (Some(c), Some(first)) => { + std::iter::once((VportConfig::ACTIVE, first)).chain(c.tiles.iter().skip(1).map(|t| (VportConfig::ACTIVE, t))).collect() + } + _ => vec![(VportConfig::ACTIVE, &single)], }; records.extend(d.vports.iter().filter(|c| !c.is_active() && !c.name.is_empty()).flat_map(|c| c.tiles.iter().map(|t| (c.name.as_str(), t)))); let th = table_head(w, "VPORT", records.len()); diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 99d6a25e1..24c877b72 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -425,13 +425,14 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData< w.s(2, if device.is_empty() || device.eq_ignore_ascii_case("None") { "none_device" } else { device }); w.s(4, page.paper.replace(' ', "_")); w.s(6, ""); + let (paper_w, paper_h, rotation) = plot_paper(page); for (c, v) in [ (40, page.margins_mm[0]), (41, page.margins_mm[1]), (42, page.margins_mm[2]), (43, page.margins_mm[3]), - (44, page.width_mm), - (45, page.height_mm), + (44, paper_w), + (45, paper_h), (46, 0.0), (47, 0.0), (48, page.plot_window[0]), @@ -446,7 +447,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData< w.i(70, plot_flags); // Plot paper units: 1 millimetres, 0 inches (#1058). w.i(72, i64::from(cadcraft_render::paper::page_unit_mm(d, page) == 1.0)); - w.i(73, i64::from(page.landscape)); + w.i(73, rotation); w.i(74, plot_type); w.s(7, &page.plot_style_table); w.i(75, if page.scale_to_fit { 0 } else { 16 }); @@ -1150,6 +1151,42 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34 w.t } +/// Paper size (groups 44, 45) and plot rotation (group 73) for a LAYOUT object. Page setups +/// keep a portrait size and a landscape flag. The values read from the file are written back +/// as they were while they still describe that size and orientation, whatever convention the +/// program that wrote them follows. Otherwise a media whose name makes it wider than tall, +/// such as `ISO_full_bleed_A3_(420.00_x_297.00_MM)`, gets its size in that order and the +/// rotation relative to it, so readers that take the media's size from its name agree with +/// groups 44 and 45 (#1463). Other media are written as before. +fn plot_paper(page: &PageSetup) -> (f64, f64, i64) { + if let Some((w, h, rotation)) = page.file_paper { + let same = |a: f64, b: f64| (a - b).abs() < 1e-6; + let landscape = matches!(rotation, 1 | 3) != (w > h); + if same(w.min(h), page.width_mm) && same(w.max(h), page.height_mm) && landscape == page.landscape { + return (w, h, rotation); + } + } + if media_is_landscape(&page.paper) { + let (short, long) = (page.width_mm.min(page.height_mm), page.width_mm.max(page.height_mm)); + (long, short, i64::from(!page.landscape)) + } else { + (page.width_mm, page.height_mm, i64::from(page.landscape)) + } +} + +/// Whether a media name ends in a size wider than tall, like `… (420.00 x 297.00 MM)`. +fn media_is_landscape(paper: &str) -> bool { + let name = paper.replace('_', " "); + let Some(open) = name.rfind('(') else { return false }; + let mut sides = name[open + 1..].splitn(2, ['x', 'X', '×']); + let num = |s: Option<&str>| { + let s = s?.trim_start(); + let end = s.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(s.len()); + s[..end].parse::().ok() + }; + matches!((num(sides.next()), num(sides.next())), (Some(w), Some(h)) if w > h) +} + /// DXF Reference group 91 of CLASS records, the instance count, which came with the 2004 format. /// From 2004 every CLASS record gets its actual count, counted after `dxf_raw::finish` restores /// foreign classes and objects (AutoCAD rejects a 2004+ file without it, #635). An R2000 file has @@ -1167,33 +1204,56 @@ fn add_class_instance_counts(tags: &mut Vec, target: Version) { return; } let mut counts: HashMap = HashMap::new(); + let mut classes = 0; for t in tags.iter().filter(|t| t.code == 0) { let kind = t.str(); if kind != "CLASS" { *counts.entry(kind.to_ascii_uppercase()).or_default() += 1; + } else { + classes += 1; } } - let mut start = 0; - while start < tags.len() { - if tags.get(start).is_none_or(|t| t.code != 0 || t.str() != "CLASS") { - start += 1; + // One pass into a new list: inserting each missing count in place shifted every later tag, + // quadratic in the number of CLASS records. + // Tags move by value (no clone); the old and new buffers coexist while it runs. At most one + // group 91 is added per CLASS record, so that is all the room the new list needs beyond the old one. + let old = std::mem::take(tags); + tags.reserve(old.len() + classes); + let mut it = old.into_iter(); + let mut pending = it.next(); + while let Some(t) = pending.take() { + if t.code != 0 || t.str() != "CLASS" { + tags.push(t); + pending = it.next(); continue; } - let end = tags[start + 1..].iter().position(|t| t.code == 0).map_or(tags.len(), |i| start + 1 + i); - let name = tags[start + 1..end].iter().find(|t| t.code == 1).map(Tag::str).unwrap_or_default().to_ascii_uppercase(); + let mut record = vec![t]; + for n in it.by_ref() { + if n.code == 0 { + pending = Some(n); + break; + } + record.push(n); + } + let name = record.iter().skip(1).find(|t| t.code == 1).map(Tag::str).unwrap_or_default().to_ascii_uppercase(); let count = counts.get(&name).copied().unwrap_or(0); - let inserted = if let Some(i) = tags[start + 1..end].iter().position(|t| t.code == 91) { - tags[start + 1 + i] = Tag::i(91, count); - false - } else if let Some(i) = tags[start + 1..end].iter().position(|t| t.code == 90) { - tags.insert(start + 2 + i, Tag::i(91, count)); - true - } else { - false - }; - // Inserting the group shifts the next record's start by one. - start = end + usize::from(inserted); + // The first 91 gets the count; without one, a 91 goes in after the first 90. + let mut added = record.iter().skip(1).any(|t| t.code == 91); + let mut replaced = false; + for (i, t) in record.into_iter().enumerate() { + let code = t.code; + if i > 0 && code == 91 && !replaced { + tags.push(Tag::i(91, count)); + replaced = true; + continue; + } + tags.push(t); + if i > 0 && code == 90 && !added { + tags.push(Tag::i(91, count)); + added = true; + } + } } } @@ -1221,3 +1281,31 @@ fn mark_xrefs(tags: &mut [Tag], d: &Drawing) { } } } + +#[cfg(test)] +mod class_count_tests { + use super::*; + + fn record(kind: &str, name: &str, extra: &[Tag]) -> Vec { + let mut r = vec![Tag::s(0, kind), Tag::s(1, name), Tag::i(90, 0)]; + r.extend_from_slice(extra); + r + } + + /// The first 91 gets the count, a CLASS without one gets it after its 90, in one pass over many records. + #[test] + fn counts_are_set_and_added_in_one_pass() { + let mut tags = record("CLASS", "FOO", &[]); + tags.extend(record("CLASS", "BAR", &[Tag::i(91, 7), Tag::i(91, 8)])); + for i in 0..50_000 { + tags.extend(record("CLASS", &format!("X{i}"), &[])); + } + tags.push(Tag::s(0, "FOO")); + let started = std::time::Instant::now(); + add_class_instance_counts(&mut tags, Version::R2018); + assert!(started.elapsed() < std::time::Duration::from_secs(5)); + assert_eq!(&tags[..4], &[Tag::s(0, "CLASS"), Tag::s(1, "FOO"), Tag::i(90, 0), Tag::i(91, 1)]); + assert_eq!(&tags[4..9], &[Tag::s(0, "CLASS"), Tag::s(1, "BAR"), Tag::i(90, 0), Tag::i(91, 0), Tag::i(91, 8)]); + assert_eq!(tags.iter().filter(|t| t.code == 91).count(), 50_003); + } +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index e82c3e35d..0d0615e8a 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -141,9 +141,12 @@ pub fn write_noted(d: &Drawing, name: impl AsRef, opts: &SaveOptions) -> R } /// The DWG bridge reads our R2000 DXF and writes the DWG at `version`, in the DWG worker when -/// there is one. +/// there is one. The objects CADCraft keeps without modelling them are still in the groups of the +/// file they came from (`Foreign::version`, not `$ACADVER`, which SAVEAS changes), and the bridge +/// reads them as that version. fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec, cadcraft_dwg::Unwritten)> { - cadcraft_dwg::encode_noted(dxf_write::dwg_bridge(d, version).as_bytes(), version.code()).map_err(IoError::Format) + let bridge = dxf_write::dwg_bridge(d, version); + cadcraft_dwg::encode_kept_noted(bridge.as_bytes(), version.code(), d.foreign.version.as_deref()).map_err(IoError::Format) } /// Like [`write`], but image formats (PNG, SVG, PDF) show `window` (a model-space rectangle in diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 6d9a69bf1..c27a7b5dc 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -50,6 +50,8 @@ const MAX_LAYER_NAME: usize = 1000; /// Most link annotations in one file, and the longest link target (bytes). const MAX_LINKS: usize = 10_000; const MAX_URL: usize = 2048; +/// The most link annotations in one PDF, over all pages (a page holds at most [`MAX_LINKS`]). +const MAX_FILE_ANNOTATIONS: usize = 100_000; /// Longest title and page label written (characters). const MAX_TEXT: usize = 1000; @@ -357,7 +359,10 @@ fn sheet_name(space: &Space) -> String { /// Write a vector PDF with one page per space (at most [`MAX_PAGES`]), each labelled with its /// layout name. The options apply to every sheet; layouts use their own page setups. pub fn pdf_sheets(d: &Drawing, spaces: &[Space], o: &PdfOptions) -> Result> { - let items: Vec<(Space, PdfOptions)> = spaces.iter().take(MAX_PAGES + 1).map(|s| (s.clone(), o.clone())).collect(); + // Links are file-wide (`pdf_items` reads them from `o`), so a sheet's own options carry none: + // a copy of the list per sheet multiplied it by the sheet count. + let sheet = PdfOptions { links: Vec::new(), ..o.clone() }; + let items: Vec<(Space, PdfOptions)> = spaces.iter().take(MAX_PAGES + 1).map(|s| (s.clone(), sheet.clone())).collect(); pdf_items(d, &items, o) } @@ -453,8 +458,16 @@ fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as let mut writer = Writer::new(settings, metadata); let mut fonts = fonts::Fonts::new(!text_as_geometry); let mut groups = Groups::default(); + // Link annotations of the whole file: each page keeps its own copy of the targets, so the + // pages times the links must not multiply without a bound. + let mut annotations_left = MAX_FILE_ANNOTATIONS; for (s, po) in items { - let page = sheet(drawn, s, po, &links)?; + // Once the budget is spent no link is built (scanned and cloned) for later pages. + let mut page = sheet(drawn, s, po, if annotations_left == 0 { &links[..0] } else { &links })?; + // Only targets `write_page` accepts count against the budget. + page.links.retain(|(_, url)| uri(url).is_some()); + page.links.truncate(annotations_left); + annotations_left -= page.links.len(); let doc = writer.document_mut(); // Groups are added to the document, so they must exist before the page starts. groups.add(doc, d, &page.layers); @@ -625,7 +638,8 @@ pub(crate) fn placement(space: &Space, bounds: &Bounds2, fit: bool, sheet: &Shee /// The hyperlinks to plot: the options' own, then (with [`PdfOptions::hyperlinks`]) those the /// drawing file gave its entities as `PE_URL` extended data, at most [`MAX_LINKS`] in all. fn all_links(d: &Drawing, o: &PdfOptions) -> Vec<(Handle, String)> { - let mut out: Vec<(Handle, String)> = o.links.iter().take(MAX_LINKS).cloned().collect(); + // A target past MAX_URL is refused at the annotation anyway; it is left out before it is copied. + let mut out: Vec<(Handle, String)> = o.links.iter().filter(|(_, u)| u.len() <= MAX_URL).take(MAX_LINKS).cloned().collect(); if !o.hyperlinks { return out; } diff --git a/crates/io/src/svg_read.rs b/crates/io/src/svg_read.rs index 54ef9d846..d94a7e60b 100644 --- a/crates/io/src/svg_read.rs +++ b/crates/io/src/svg_read.rs @@ -590,7 +590,10 @@ fn hidden(e: &BytesStart) -> bool { } fn attr(e: &BytesStart, name: &[u8]) -> Option { - for a in e.attributes().flatten() { + // Stop at the first malformed attribute: skipping errors resumed the parser's duplicate check, + // which rescans the attributes before it each time, so many duplicates were quadratic. + for a in e.attributes() { + let Ok(a) = a else { return None }; if a.key.into_inner().as_bytes() == name { return a.normalized_value(XmlVersion::Explicit1_0).ok().map(|v| v.into_owned()); } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index f9f055675..1d21467e5 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -396,6 +396,16 @@ fn many_distinct_symbol_names_read_quickly() { assert_eq!(d.text_style("ST0").map(|s| s.height), Some(2.0)); } +/// Elements with many duplicate attributes are read in bounded time. +#[test] +fn svg_duplicate_attributes_are_not_rescanned() { + let dup = " x=\"1\"".repeat(20_000); + let svg = format!("{}", format!("").repeat(20)); + let started = std::time::Instant::now(); + let _ = read(svg.as_bytes(), "dup.svg"); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed()); +} + #[test] fn hostile_dxf_does_not_panic() { for t in [ @@ -579,6 +589,164 @@ fn pdf_hostile_options_and_empty() { } } +/// The view a drawing was saved at is the `*ACTIVE` VPORT record's centre and height, repeated in +/// the `$VIEWCTR`/`$VIEWSIZE` header pair. It used to be dropped on read and replaced on write by +/// a fit of the geometry extents, so a drawing with far-off geometry opened hundreds of times too +/// far out, and a conversion replaced wherever the drawing had been left (#1602). +#[test] +fn dxf_keeps_the_view_the_drawing_was_saved_at() { + const SAVED: &str = "\ +0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1027\n9\n$VIEWCTR\n10\n50.0\n20\n50.0\n30\n0.0\n9\n$VIEWSIZE\n40\n20.0\n0\nENDSEC\n\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n1.0\n21\n1.0\n\ +12\n50.0\n22\n50.0\n40\n20.0\n41\n1.5\n0\nENDTAB\n0\nENDSEC\n\ +0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n100.0\n21\n60.0\n31\n0.0\n\ +0\nLINE\n8\n0\n10\n5000000.0\n20\n5000000.0\n30\n0.0\n11\n5000100.0\n21\n5000060.0\n31\n0.0\n0\nENDSEC\n0\nEOF\n"; + + // The stored view survives the read, far-away geometry and all: the extents here are + // 5 000 100 x 5 000 060, a fit of which is 275 000 times the height the drawing was saved at. + let d = read_dxf(SAVED.as_bytes()).unwrap(); + assert_eq!(d.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0))); + assert!(d.extents(&Space::Model).max.x > 5e6, "the far-off line is read too"); + + // And writing the drawing back keeps it, in both places a reader looks. + let text = write_dxf(&d); + let back = read_dxf(text.as_bytes()).unwrap(); + assert_eq!(back.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0))); + let active = text.replace("\r\n", "\n"); + let active = active.split("*Active").nth(1).unwrap_or_default(); + for group in ["\n 12\n50", "\n 22\n50", "\n 40\n20"] { + assert!(active.contains(group), "the *ACTIVE record keeps {group:?}: {}", &active[..active.len().min(400)]); + } + + // A drawing that stores no view is still written on its extents. + let mut plain = d.clone(); + plain.header.vars.remove("VIEWCTR"); + plain.header.vars.remove("VIEWSIZE"); + assert_eq!(plain.header.saved_view(), None); + let fitted = read_dxf(write_dxf(&plain).as_bytes()).unwrap(); + let (center, height) = fitted.header.saved_view().unwrap(); + assert!(center.x > 2.4e6 && height > 5e6, "the extents fit: {center:?} {height}"); + + // That fit covers the width as well: a wide, flat drawing opened on its height alone would + // show a sliver of it, and a drawing with no height at all would have no view. + let mut wide = cadcraft_doc::Drawing::new_metric(); + for (a, b) in [([0.0, 0.0], [100.0, 10.0]), ([0.0, 10.0], [100.0, 10.0])] { + let line = cadcraft_doc::Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) }; + wide.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap(); + } + let back = read_dxf(write_dxf(&wide).as_bytes()).unwrap(); + let (_, height) = back.header.saved_view().unwrap(); + assert!(height > 60.0, "a 100 x 10 drawing needs more than its height: {height}"); + + let mut flat = cadcraft_doc::Drawing::new_metric(); + let line = cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(100.0, 0.0, 0.0) }; + flat.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap(); + let back = read_dxf(write_dxf(&flat).as_bytes()).unwrap(); + let (_, height) = back.header.saved_view().unwrap(); + assert!(height > 60.0, "a horizontal line needs a view with width in it: {height}"); +} + +/// A `*ACTIVE` record that leaves its view centre out (no 12/22) is not a view: `$VIEWCTR` and +/// `$VIEWSIZE` stay, rather than being replaced by the zero the missing groups read as. +#[test] +fn a_viewport_record_without_a_centre_keeps_the_header_view() { + const NO_CENTRE: &str = "\ +0\nSECTION\n2\nHEADER\n9\n$VIEWCTR\n10\n50.0\n20\n50.0\n9\n$VIEWSIZE\n40\n20.0\n0\nENDSEC\n\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n1.0\n21\n1.0\n\ +40\n99.0\n0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n11\n9.0\n21\n9.0\n0\nENDSEC\n0\nEOF\n"; + let d = read_dxf(NO_CENTRE.as_bytes()).unwrap(); + assert_eq!(d.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0)), "the header pair is kept"); +} + +/// The saved view is the first `*ACTIVE` record's even when that record's tile rectangle is +/// unusable: the next `*ACTIVE` record is a second tile, not the first again (#2837 review). +#[test] +fn the_first_active_record_gives_the_view_even_with_an_unusable_tile() { + const TWO: &str = "\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n\ +0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n0.0\n21\n0.0\n12\n50.0\n22\n50.0\n40\n20.0\n\ +0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n1.0\n21\n1.0\n12\n900.0\n22\n900.0\n40\n5.0\n\ +0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n11\n9.0\n21\n9.0\n0\nENDSEC\n0\nEOF\n"; + let d = read_dxf(TWO.as_bytes()).unwrap(); + assert_eq!(d.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0)), "the first record's view"); +} + +/// A tiled drawing need not hold a saved view: `-VPORTS` splits the current view into tiles and +/// sets none. The first tile's own view is then the only one there is, and must not be replaced +/// by the extents fallback `vport_table` computes for a drawing with no view (noted in review). +#[test] +fn a_tiled_drawing_with_no_saved_view_keeps_its_first_tiles_view() { + let mut d = sample(); + let tile = |min: Vec2, max: Vec2, center: Vec2| VportTile { min, max, center, height: 10.0, aspect: 1.0, twist: 0.0 }; + d.vports.push(VportConfig { + name: VportConfig::ACTIVE.to_string(), + tiles: vec![tile(Vec2::ZERO, Vec2::new(0.5, 1.0), Vec2::new(1.0, 1.0)), tile(Vec2::new(0.5, 0.0), Vec2::new(1.0, 1.0), Vec2::new(2.0, 2.0))], + }); + assert_eq!(d.header.saved_view(), None, "the drawing holds no saved view"); + + let back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + let active = back.vports.iter().find(|c| c.is_active()).expect("the tiled configuration is kept"); + assert_eq!(active.tiles.len(), 2, "both tiles are written: {:?}", active.tiles); + assert_eq!(active.tiles[0].center, Vec2::new(1.0, 1.0), "the first tile keeps its own view"); + assert_eq!(active.tiles[0].height, 10.0, "and its own height"); + assert_eq!(active.tiles[1].center, Vec2::new(2.0, 2.0), "the second tile keeps its own view"); + // The read takes the header's view from that first record, so it is the tile's view and not + // the extents fit the writer would otherwise have put there. + assert_eq!(back.header.saved_view(), Some((Vec2::new(1.0, 1.0), 10.0)), "read from the first tile"); +} + +/// Updating the saved view of a drawing that has several model-space tiles survives a round +/// trip. The write put the new view in HEADER but emitted the stored tiles unchanged, and the +/// read takes its view from the first `*ACTIVE` record, so the update was read back as the old +/// view (noted in review of #1602). +#[test] +fn a_saved_view_set_on_a_tiled_drawing_survives_a_round_trip() { + let mut d = sample(); + // Two tiles side by side, the first the current one, each with its own old view. + let tile = |min: Vec2, max: Vec2, center: Vec2| VportTile { min, max, center, height: 10.0, aspect: 1.0, twist: 0.0 }; + d.vports.push(VportConfig { + name: VportConfig::ACTIVE.to_string(), + tiles: vec![tile(Vec2::ZERO, Vec2::new(0.5, 1.0), Vec2::new(1.0, 1.0)), tile(Vec2::new(0.5, 0.0), Vec2::new(1.0, 1.0), Vec2::new(2.0, 2.0))], + }); + d.header.set_saved_view(Vec2::new(70.0, 80.0), 30.0); + + let back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(back.header.saved_view(), Some((Vec2::new(70.0, 80.0), 30.0)), "the view that was set is the one read back"); + // The tiled configuration is still there, and the first tile keeps its own half of the screen. + let active = back.vports.iter().find(|c| c.is_active()).expect("the tiled configuration is kept"); + assert_eq!(active.tiles.len(), 2, "both tiles are written: {:?}", active.tiles); + assert_eq!(active.tiles[0].max, Vec2::new(0.5, 1.0), "the first tile keeps its rectangle"); + assert_eq!(active.tiles[1].center, Vec2::new(2.0, 2.0), "and the second tile keeps its own view"); +} + +/// A first `*ACTIVE` record can hold a usable view (12/22 centre, 40 height) with a tile +/// rectangle that is not usable. The record used to be dropped whole before the view was read, +/// so a file whose header carries no view opened on the extent fit rather than where it was +/// saved (noted in review of #1602). +#[test] +fn a_viewport_record_with_a_bad_tile_still_gives_its_view() { + // No `$VIEWCTR`/`$VIEWSIZE`, and a tile whose corners are equal (10/11 both 0,0), so the + // rectangle is unusable while the view is not: centre 50,50 and height 20. + const BAD_TILE: &str = "\ +0\nSECTION\n2\nHEADER\n0\nENDSEC\n\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n0.0\n21\n0.0\n\ +12\n50.0\n22\n50.0\n40\n20.0\n0\nENDTAB\n0\nENDSEC\n\ +0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n11\n9.0\n21\n9.0\n0\nENDSEC\n0\nEOF\n"; + let d = read_dxf(BAD_TILE.as_bytes()).unwrap(); + assert_eq!(d.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0)), "the view the record holds is read"); + // The unusable rectangle is still refused, so the split did not make the tile permissive. + assert!(d.vports.iter().all(|c| c.tiles.is_empty()), "the tile itself is not kept: {:?}", d.vports); + + // And a record with no usable view either leaves the header alone, as before. + const NEITHER: &str = "\ +0\nSECTION\n2\nHEADER\n0\nENDSEC\n\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n0.0\n21\n0.0\n\ +12\n50.0\n22\n50.0\n40\n0.0\n0\nENDTAB\n0\nENDSEC\n\ +0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n11\n9.0\n21\n9.0\n0\nENDSEC\n0\nEOF\n"; + let neither = read_dxf(NEITHER.as_bytes()).unwrap(); + assert_eq!(neither.header.saved_view(), None, "a zero height is not a view, so the header keeps none"); +} + #[test] fn dxf_roundtrips_page_setup() { let mut d = sample(); @@ -598,6 +766,114 @@ fn dxf_roundtrips_page_setup() { assert_eq!(p.paper, a3.name); } +/// Groups 44, 45 and 73 of a layout's AcDbPlotSettings in DXF text. +fn plot_paper_groups(dxf: &str, layout: &str) -> (f64, f64, i64) { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let pairs: Vec<(&str, &str)> = lines.chunks(2).filter(|c| c.len() == 2).map(|c| (c[0], c[1])).collect(); + let name = pairs.windows(2).position(|w| w[0] == ("100", "AcDbLayout") && w[1] == ("1", layout)).unwrap_or_else(|| panic!("no LAYOUT {layout}")); + let start = pairs[..name].iter().rposition(|p| *p == ("100", "AcDbPlotSettings")).unwrap(); + let get = |code: &str| pairs[start..name].iter().find(|p| p.0 == code).map(|p| p.1).unwrap(); + (get("44").parse().unwrap(), get("45").parse().unwrap(), get("73").parse().unwrap()) +} + +#[test] +fn landscape_media_keeps_its_size_order_and_rotation() { + // A media defined wider than tall, as ZWCAD and AutoCAD name it (#1463). + let media = "ISO full bleed A3 (420.00 x 297.00 MM)"; + for (landscape, rotation) in [(true, 0), (false, 1)] { + let mut d = sample(); + { + let p = &mut d.layouts[0].page; + p.paper = media.into(); + p.width_mm = 297.0; + p.height_mm = 420.0; + p.landscape = landscape; + } + let dxf = write_dxf(&d); + assert_eq!(plot_paper_groups(&dxf, "Layout1"), (420.0, 297.0, rotation), "DXF, landscape {landscape}"); + let r = read_dxf(dxf.as_bytes()).unwrap(); + let p = &r.layout("Layout1").unwrap().page; + assert_eq!((p.width_mm, p.height_mm, p.landscape), (297.0, 420.0, landscape), "DXF read back"); + assert_eq!(p.paper, media); + + let dwg = write(&d, "t.dwg").unwrap(); + let back = String::from_utf8_lossy(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned(); + assert_eq!(plot_paper_groups(&back, "Layout1"), (420.0, 297.0, rotation), "DWG, landscape {landscape}"); + let r = read(&dwg, "t.dwg").unwrap(); + let p = &r.layout("Layout1").unwrap().page; + assert_eq!((p.width_mm, p.height_mm, p.landscape), (297.0, 420.0, landscape), "DWG read back"); + } +} + +/// A file's own groups 44, 45 and 73 are written back unchanged, in DXF and DWG, whether they +/// follow ZWCAD's convention (the media's size, no turn) or AutoCAD's (a portrait size and a +/// quarter turn) for a media named wider than tall. Once the page setup changes, they no +/// longer describe it and the size and rotation are derived again. +#[test] +fn a_files_own_paper_groups_are_written_back() { + let set = |dxf: &str, (w, h, r): (f64, f64, i64)| -> String { + let mut lines: Vec = dxf.lines().map(String::from).collect(); + let name = (0..lines.len() - 3) + .find(|&i| { + lines[i].trim() == "100" && lines[i + 1].trim() == "AcDbLayout" && lines[i + 2].trim() == "1" && lines[i + 3].trim() == "Layout1" + }) + .unwrap(); + let start = (0..name).rev().find(|&i| lines[i].trim() == "100" && lines[i + 1].trim() == "AcDbPlotSettings").unwrap(); + for i in (start..name).step_by(2) { + match lines[i].trim() { + "44" => lines[i + 1] = w.to_string(), + "45" => lines[i + 1] = h.to_string(), + "73" => lines[i + 1] = r.to_string(), + _ => {} + } + } + lines.join("\n") + }; + // (media, groups as the program wrote them, portrait size and landscape CADCraft reads) + let cases = [ + ("ISO full bleed A3 (420.00 x 297.00 MM)", (420.0, 297.0, 0), (297.0, 420.0, true)), + ("ISO A4 (297.00 x 210.00 MM)", (210.0, 297.0, 1), (210.0, 297.0, true)), + ("ISO A4 (297.00 x 210.00 MM)", (210.0, 297.0, 0), (210.0, 297.0, false)), + ]; + for (media, groups, (pw, ph, landscape)) in cases { + let mut d = sample(); + d.layouts[0].page.paper = media.into(); + let file = set(&write_dxf(&d), groups); + let r = read_dxf(file.as_bytes()).unwrap(); + let p = &r.layout("Layout1").unwrap().page; + assert_eq!((p.width_mm, p.height_mm, p.landscape), (pw, ph, landscape), "{media} {groups:?} read"); + assert_eq!(plot_paper_groups(&write_dxf(&r), "Layout1"), groups, "{media} {groups:?} DXF"); + let dwg = write(&r, "t.dwg").unwrap(); + let back = String::from_utf8_lossy(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned(); + assert_eq!(plot_paper_groups(&back, "Layout1"), groups, "{media} {groups:?} DWG"); + let r = read(&dwg, "t.dwg").unwrap(); + assert_eq!(plot_paper_groups(&write_dxf(&r), "Layout1"), groups, "{media} {groups:?} DWG read and saved again"); + } + // Turned in CADCraft after reading: the stored groups no longer apply. + let mut d = sample(); + d.layouts[0].page.paper = "ISO full bleed A3 (420.00 x 297.00 MM)".into(); + let mut r = read_dxf(set(&write_dxf(&d), (420.0, 297.0, 0)).as_bytes()).unwrap(); + r.layouts.iter_mut().find(|l| l.name == "Layout1").unwrap().page.landscape = false; + assert_eq!(plot_paper_groups(&write_dxf(&r), "Layout1"), (420.0, 297.0, 1), "portrait after the change"); + // A plot rotation the DXF Reference doesn't define (0-3) reads as not rotated and is written + // back as 0, not as read (#2028 review). + let r = read_dxf(set(&write_dxf(&d), (210.0, 297.0, 99)).as_bytes()).unwrap(); + assert_eq!(plot_paper_groups(&write_dxf(&r), "Layout1").2, 0, "an undefined rotation is not written back"); +} + +#[test] +fn portrait_media_is_written_as_before() { + let mut d = sample(); + { + let p = &mut d.layouts[0].page; + p.paper = "ISO A3 (297.00 x 420.00 MM)".into(); + p.width_mm = 297.0; + p.height_mm = 420.0; + p.landscape = true; + } + assert_eq!(plot_paper_groups(&write_dxf(&d), "Layout1"), (297.0, 420.0, 1)); +} + // --------------------------------------------------------------------------------------------- // Round trips of styles, overrides, associativity, constraints and tables. @@ -667,6 +943,151 @@ fn viewport_frozen_layers_roundtrip() { assert!(frozen.contains(&(3, Vec::new())), "{frozen:?}"); } +/// `Layout1` with viewports 1 (the sheet), 2 and 3, written to DXF and read back with the id (69) +/// of every viewport `blank` names replaced by -1 (ZWCAD's "unknown"): the ids and widths read. +fn viewport_ids_read_back(blank: impl Fn(&str) -> bool) -> (Drawing, Vec<(u32, f64)>) { + viewport_ids_read_back_as(blank, "-1") +} + +/// [`viewport_ids_read_back`], with `value` in place of the id of every viewport `blank` names. +fn viewport_ids_read_back_as(blank: impl Fn(&str) -> bool, value: &str) -> (Drawing, Vec<(u32, f64)>) { + let mut d = sample(); + let paper = Space::Paper("Layout1".into()); + for (id, w) in [(1, 420.0), (2, 8.0), (3, 4.0)] { + let vp = Viewport { + center: Vec3::new(5.0, 4.0, 0.0), + width: w, + height: 6.0, + view_center: Vec2::new(5.0, 4.0), + view_height: 6.0, + id, + ..Viewport::default() + }; + d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap(); + } + let text = write_dxf(&d); + let mut lines: Vec = text.lines().map(String::from).collect(); + for i in (0..lines.len() - 1).step_by(2) { + if lines[i].trim() == "69" && blank(lines[i + 1].trim()) { + lines[i + 1] = value.into(); + } + } + let back = read_dxf(lines.join("\n").as_bytes()).unwrap(); + let ids = + back.layouts[0].entities.iter().filter_map(|e| if let EntityKind::Viewport(v) = &e.kind { Some((v.id, v.width)) } else { None }).collect(); + (back, ids) +} + +/// ZWCAD writes every VIEWPORT with id (69) -1: they are numbered in file order, the first being +/// the paper-space viewport, so saving adds no second sheet viewport (#1463). +#[test] +fn viewport_ids_unknown_are_numbered_in_order() { + let (back, ids) = viewport_ids_read_back(|_| true); + assert_eq!(ids, [(1, 420.0), (2, 8.0), (3, 4.0)]); + assert!(!write_dxf(&back).contains("PAPERVIEW"), "the layout already has its paper-space viewport"); +} + +/// A layout that mixes known ids with -1 is left alone: the known ids stay, the unknown one reads +/// as 0 (not numbered), as before #1463. +#[test] +fn viewport_ids_mixed_are_kept() { + let (back, ids) = viewport_ids_read_back(|v| v == "2"); + assert_eq!(ids, [(1, 420.0), (0, 8.0), (3, 4.0)]); + assert!(!write_dxf(&back).contains("PAPERVIEW"), "viewport 1 is still the sheet"); +} + +/// Only the sheet's id is unknown: no viewport has id 1, so the first one, the sheet, gets it +/// and saving adds no second sheet (#1463). +#[test] +fn viewport_ids_unknown_sheet_becomes_one() { + let (back, ids) = viewport_ids_read_back(|v| v == "1"); + assert_eq!(ids, [(1, 420.0), (2, 8.0), (3, 4.0)]); + assert!(!write_dxf(&back).contains("PAPERVIEW"), "the first viewport is the sheet"); +} + +/// Group 69 is a 16-bit code: an id outside 1..=32767 reads as unknown (0), and is never truncated +/// into a real id (4294967297 would become a second id 1, a second paper-space viewport). +#[test] +fn viewport_ids_out_of_range_read_as_unknown() { + for bad in ["4294967297", "65537", "32768"] { + let (_, ids) = viewport_ids_read_back_as(|v| v == "2", bad); + assert_eq!(ids, [(1, 420.0), (0, 8.0), (3, 4.0)], "69 = {bad}"); + } + let (_, ids) = viewport_ids_read_back_as(|v| v == "2", "32767"); + assert_eq!(ids, [(1, 420.0), (32767, 8.0), (3, 4.0)]); +} + +/// A layout whose only viewport has id 0 (entmake, MCP): the writer adds the PAPERVIEW sheet ahead +/// of it and the reader drops that sheet again. The id-0 viewport must not be numbered 1, or the +/// next save takes it as the sheet and the generated sheet is lost (#2107). +#[test] +fn viewport_id_zero_keeps_implicit_sheet_across_saves() { + let mut d = sample(); + let vp = Viewport { + center: Vec3::new(5.0, 4.0, 0.0), + width: 8.0, + height: 6.0, + view_center: Vec2::new(5.0, 4.0), + view_height: 6.0, + id: 0, + ..Viewport::default() + }; + d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); + let first = write_dxf(&d); + assert!(first.contains("PAPERVIEW"), "the writer adds the sheet"); + let back = read_dxf(first.as_bytes()).unwrap(); + let ids: Vec = + back.layouts[0].entities.iter().filter_map(|e| if let EntityKind::Viewport(v) = &e.kind { Some(v.id) } else { None }).collect(); + assert_eq!(ids, [0], "the dropped sheet is not replaced by numbering the id-0 viewport"); + let second = write_dxf(&back); + let lines: Vec<&str> = second.lines().map(str::trim).collect(); + let sheet = lines.iter().position(|l| *l == "PAPERVIEW").expect("the second save still generates the sheet"); + let vp0 = (0..lines.len() - 1).find(|i| lines[*i] == "69" && lines[i + 1] == "0").expect("the id-0 viewport is written"); + assert!(sheet < vp0, "the generated sheet comes first"); +} + +/// The same for a layout written as a `*Paper_SpaceN` block (not the active one) whose PAPERVIEW +/// sheet lost its owner group (330): the sheet still belongs to the block's layout, as +/// `place_blocks` puts the block's other entities there, so that layout is left alone too. +#[test] +fn viewport_id_zero_in_paper_block_keeps_implicit_sheet_without_owner() { + let mut d = sample(); + d.layouts.push(Layout::new("Layout2", 2)); + let vp = Viewport { + center: Vec3::new(5.0, 4.0, 0.0), + width: 8.0, + height: 6.0, + view_center: Vec2::new(5.0, 4.0), + view_height: 6.0, + id: 0, + ..Viewport::default() + }; + d.add(&Space::Paper("Layout2".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); + let first = write_dxf(&d); + let lines: Vec<&str> = first.lines().collect(); + let sheet = lines.iter().position(|l| l.trim() == "PAPERVIEW").expect("the writer adds the sheet"); + let start = (0..sheet).rev().find(|i| lines[*i].trim() == "0" && lines[i + 1].trim() == "VIEWPORT").unwrap(); + let owner = (start..sheet).find(|i| lines[*i].trim() == "330").expect("the sheet has an owner"); + assert!(lines[start..sheet].iter().any(|l| l.trim().eq_ignore_ascii_case("*Paper_Space0") || l.trim() == "AcDbViewport"), "sheet record found"); + let stripped: String = lines + .iter() + .enumerate() + .filter(|(i, _)| *i != owner && *i != owner + 1) + .map(|(_, l)| { + format!( + "{l} +" + ) + }) + .collect(); + assert!(stripped.contains("*Paper_Space0"), "the second layout is a paper-space block"); + let back = read_dxf(stripped.as_bytes()).unwrap(); + let l2 = back.layouts.iter().find(|l| l.name == "Layout2").expect("Layout2"); + let ids: Vec = l2.entities.iter().filter_map(|e| if let EntityKind::Viewport(v) = &e.kind { Some(v.id) } else { None }).collect(); + assert_eq!(ids, [0], "the dropped sheet of Layout2 is not replaced by numbering its id-0 viewport"); + assert!(write_dxf(&back).contains("PAPERVIEW"), "the second save still generates the sheet"); +} + /// `d` as an R2018 DXF (frozen viewport layers in group 331). fn dxf_2018(d: &Drawing) -> String { let opts = SaveOptions { version: Some(Version::R2018), binary: false }; @@ -2200,6 +2621,152 @@ fn mirrored_hatch_extrusion_flips_boundary() { } } +/// Issue #1886: a HATCH in a tilted plane (a terrain face) is drawn as seen from above, not turned +/// about the origin. With extrusion (0, 0.5, -√3/2) the OCS axes are x = (-1,0,0) and +/// y = (0, √3/2, 1/2): the square (1,0)..(3,2) lies over (-3,0)..(-1,√3), from z 0 up to z 1. +/// Before, the negative Z counted as a plain mirror and only x was flipped. +#[test] +fn tilted_hatch_is_drawn_as_seen_from_above() { + let text = "0\nSECTION\n2\nENTITIES\n0\nHATCH\n8\n0\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n2\nSOLID\n70\n1\n71\n0\n91\n1\n\ + 92\n2\n72\n0\n73\n1\n93\n4\n10\n1\n20\n0\n10\n3\n20\n0\n10\n3\n20\n2\n10\n1\n20\n2\n97\n0\n75\n0\n76\n1\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "h.dxf").unwrap(); + let b = d.extents(&Space::Model); + for (got, want) in [(b.min.x, -3.0), (b.min.y, 0.0), (b.max.x, -1.0), (b.max.y, 3f64.sqrt())] { + assert!((got - want).abs() < 1e-9, "extents {b:?}"); + } + let e = d.model.iter().next().unwrap(); + assert_eq!(e.common.extrusion, Vec3::Z, "its points are plan coordinates now"); + let EntityKind::Hatch(h) = &e.kind else { panic!("not a hatch") }; + assert!((h.elevation - 0.5).abs() < 1e-9, "the mean height of its corners: {}", h.elevation); +} + +/// A tilted gradient hatch turns its gradient's direction with its boundary: in that plane OCS +X +/// is plan -X, so a gradient at 0 runs at 180°. +#[test] +fn tilted_hatch_turns_its_gradient() { + let text = "0\nSECTION\n2\nENTITIES\n0\nHATCH\n8\n0\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n2\nSOLID\n70\n1\n71\n0\n91\n1\n\ + 92\n2\n72\n0\n73\n1\n93\n4\n10\n1\n20\n0\n10\n3\n20\n0\n10\n3\n20\n2\n10\n1\n20\n2\n97\n0\n75\n0\n76\n1\n\ + 450\n1\n451\n0\n452\n0\n453\n2\n460\n0\n461\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "h.dxf").unwrap(); + let h = first(&d, |k| if let EntityKind::Hatch(h) = k { Some(h.clone()) } else { None }); + let g = h.gradient.expect("a gradient"); + assert!((g.angle - std::f64::consts::PI).abs() < 1e-9, "gradient angle {}", g.angle); +} + +/// A straight tilted LWPOLYLINE keeps its vertex widths (groups 40/41) on the projected vertices. +#[test] +fn tilted_straight_lwpolyline_keeps_its_widths() { + let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\ + 10\n1\n20\n0\n40\n0.5\n41\n1\n10\n3\n20\n2\n40\n1\n41\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + let got: Vec<(f64, f64)> = p.vertices.iter().map(|v| (v.start_width, v.end_width)).collect(); + assert_eq!(got, vec![(0.5, 1.0), (1.0, 0.0)]); + assert!((p.vertices[1].p.x + 3.0).abs() < 1e-9 && (p.vertices[1].p.y - 3f64.sqrt()).abs() < 1e-9, "{:?}", p.vertices[1].p); +} + +/// A tilted LWPOLYLINE mixing straight and bulged edges keeps the widths of its straight edges; +/// only the points of the flattened arc have none. +#[test] +fn tilted_mixed_lwpolyline_keeps_its_straight_widths() { + let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n3\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\ + 10\n0\n20\n0\n40\n0.5\n41\n1\n10\n2\n20\n0\n42\n1\n10\n4\n20\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + let v = &p.vertices; + assert!(v.len() > 4 && v.iter().all(|v| v.bulge == 0.0), "{} vertices", v.len()); + assert_eq!((v[0].start_width, v[0].end_width), (0.5, 1.0), "the straight edge keeps its widths"); + assert!(v[1..].iter().all(|v| v.start_width == 0.0 && v.end_width == 0.0), "the flattened arc has none"); + assert!((v[1].p.x + 2.0).abs() < 1e-9 && (v[v.len() - 1].p.x + 4.0).abs() < 1e-9, "{:?} {:?}", v[1].p, v[v.len() - 1].p); +} + +/// A small arc next to a long straight edge stays an arc: its flattening tolerance comes from +/// its own size. The half circle of radius 1 bulges a whole unit off its chord. +#[test] +fn tilted_small_arc_beside_a_long_edge_stays_curved() { + let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n3\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\ + 10\n0\n20\n0\n10\n10000\n20\n0\n42\n1\n10\n10002\n20\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + assert!(p.vertices.len() > 8, "{} vertices", p.vertices.len()); + // OCS y maps to plan y times √3/2: the arc's far point is about 0.866 off the chord. + let off = p.vertices.iter().map(|v| v.p.y.abs()).fold(0.0, f64::max); + assert!((off - 3f64.sqrt() / 2.0).abs() < 1e-2, "the arc reaches {off} off its chord"); +} + +/// A tilted tapered arc spreads its width evenly over its flattened segments: from 1 at its +/// start to 3 at its end, each segment starting where the last one ended. +#[test] +fn tilted_tapered_arc_spreads_its_width() { + let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\ + 10\n0\n20\n0\n40\n1\n41\n3\n42\n1\n10\n2\n20\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + let v = &p.vertices; + assert!(v.len() > 4, "{} vertices", v.len()); + let arc = &v[..v.len() - 1]; + assert_eq!(arc.first().map(|v| v.start_width), Some(1.0)); + assert!(arc.last().is_some_and(|v| (v.end_width - 3.0).abs() < 1e-9), "{:?}", arc.last()); + assert!(arc.windows(2).all(|w| (w[0].end_width - w[1].start_width).abs() < 1e-9 && w[0].start_width < w[1].start_width)); +} + +/// A tilted polyline made of a great many arcs is flattened within a budget: past a million +/// vertices its arcs stay chords, so a hostile file can't ask for gigabytes (#2584 review). +#[test] +fn a_tilted_polyline_of_many_arcs_is_flattened_within_a_budget() { + let n = 50_000; + let mut text = format!("0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n{n}\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n"); + for i in 0..n { + text.push_str(&format!("10\n{i}\n20\n0\n42\n1\n")); + } + text.push_str("0\nENDSEC\n0\nEOF\n"); + let d = read(text.as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + // Every arc flattened would be millions; the budget, one last arc past it and the chords. + assert!(p.vertices.len() <= 1_000_000 + 4_096 + n, "{} vertices", p.vertices.len()); + assert!(p.vertices.len() > n, "the arcs before the budget are still curved"); +} + +/// Far from the origin even a tilt under a thousandth moves an object visibly, so it is +/// projected: with normal (0, 0.0009, 1) a polyline at elevation 1,000,000 lies about 900 units +/// up from its OCS y. Noise in a plan normal moves nothing visible and keeps the arcs. +#[test] +fn a_slight_tilt_far_away_is_projected_and_noise_is_not() { + let poly = |n: &str, more: &str| { + format!("0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n38\n1000000\n{n}10\n0\n20\n0\n{more}10\n1\n20\n0\n0\nENDSEC\n0\nEOF\n") + }; + let d = read(poly("210\n0\n220\n0.0009\n230\n1\n", "").as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + let ny = 0.0009 / (1.0f64 + 0.0009 * 0.0009).sqrt(); + assert!((p.vertices[0].p.y - ny * 1.0e6).abs() < 1e-6, "{:?}", p.vertices[0].p); + assert_eq!(d.model.iter().next().unwrap().common.extrusion, Vec3::Z); + let d = read(poly("210\n0\n220\n1e-15\n230\n1\n", "42\n1\n").as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + assert_eq!(p.vertices.iter().map(|v| v.bulge).collect::>(), vec![1.0, 0.0], "a plan polyline keeps its arc"); +} + +/// Issue #1886: a LWPOLYLINE circle (two half-circle bulges) in the same tilted plane is the +/// ellipse it looks like from above, flattened; a plain one keeps its bulges. +#[test] +fn tilted_lwpolyline_is_drawn_as_seen_from_above() { + let circle = |n: &str| { + format!("0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n1\n{n}10\n1\n20\n0\n42\n1\n10\n-1\n20\n0\n42\n1\n0\nENDSEC\n0\nEOF\n") + }; + let d = read(circle("210\n0\n220\n0.5\n230\n-0.8660254037844386\n").as_bytes(), "p.dxf").unwrap(); + let b = d.extents(&Space::Model); + let ry = 3f64.sqrt() / 2.0; + for (got, want) in [(b.min.x, -1.0), (b.min.y, -ry), (b.max.x, 1.0), (b.max.y, ry)] { + assert!((got - want).abs() < 5e-3, "extents {b:?}"); + } + let e = d.model.iter().next().unwrap(); + assert_eq!(e.common.extrusion, Vec3::Z); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + assert!(p.vertices.len() > 8 && p.vertices.iter().all(|v| v.bulge == 0.0), "{} vertices", p.vertices.len()); + let plain = read(circle("").as_bytes(), "p.dxf").unwrap(); + let p = first(&plain, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + assert_eq!(p.vertices.iter().map(|v| v.bulge).collect::>(), vec![1.0, 1.0]); +} + /// The model extents of a one-loop solid HATCH whose edge boundary is `edges` (group 72 onwards). fn hatch_edge_extents(edges: &str) -> Bounds2 { let n = edges.matches("72\n").count(); @@ -2948,6 +3515,119 @@ fn proxies_keep_their_class_when_classes_are_rewritten() { assert_eq!(names, ["VISUALSTYLE", "WIDGETX"]); } +/// The proxies of [`proxy_file`] keep their classes in a DWG too. A proxy names its class by +/// number, 500 plus the class's place in the CLASSES the file lists; acadrust numbers the classes +/// it writes in its own order (its default classes first), so the DXF's numbers named other +/// classes there: a 2018 drawing's piping proxies came out as LARGE_RADIAL_DIMENSION and +/// SECTIONOBJECT, and the ODA File Converter refused the file ("AcDbProxyObject can't be cast to +/// AcDbBlockTableRecord"). A DWG before 2013 leaves them out (acadrust writes no class for them). +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn proxies_keep_their_class_in_dwg() { + use acadrust::entities::{EntityType, ExtendedEntityData}; + use acadrust::objects::ObjectType; + let d = read(&proxy_file(), "p.dxf").unwrap(); + for version in [Version::R2018, Version::R2013, Version::R2010, Version::R2004] { + let dwg = write_with(&d, "p.dwg", &SaveOptions { version: Some(version), binary: false }).unwrap(); + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let class_of = |id: i32| doc.classes.iter().find(|c| i32::from(c.class_number) == id).map(|c| c.dxf_name.clone()); + let mut objects: Vec> = doc + .objects + .values() + .filter_map(|o| match o { + ObjectType::ProxyObject(p) => Some(class_of(p.class_id)), + _ => None, + }) + .collect(); + objects.sort(); + // Before 2013 acadrust writes no class for a proxy, so the DWG leaves the proxies out. + let legacy = version < Version::R2013; + let expected = if legacy { vec![] } else { vec![Some("VISUALSTYLE".to_string()), Some("WIDGETX".to_string())] }; + assert_eq!(objects, expected, "{version:?}: proxy objects"); + let entities: Vec> = doc + .entities() + .filter_map(|e| match e { + EntityType::Extended(x) => match &x.data { + ExtendedEntityData::Proxy(p) => Some(class_of(p.class_id)), + _ => None, + }, + _ => None, + }) + .collect(); + let expected = if legacy { vec![] } else { vec![Some("WIDGETX".to_string())] }; + assert_eq!(entities, expected, "{version:?}: proxy entity"); + } +} + +/// An ASCII DXF given to the DWG conversion directly, with a proxy whose number names no class of +/// its CLASSES ([`proxy_file`]'s "Stray", 537): kept with that number it would name some other +/// class of the DWG, so the DWG leaves it out, as CADCraft's own save does, and keeps the proxies +/// whose classes it can name. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn a_proxy_whose_class_is_unknown_is_left_out_of_the_dwg() { + use acadrust::entities::{EntityType, ExtendedEntityData}; + use acadrust::objects::ObjectType; + let dwg = cadcraft_dwg::dxf_to_dwg_as(&proxy_file(), "AC1032").unwrap(); + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let class_of = |id: i32| doc.classes.iter().find(|c| i32::from(c.class_number) == id).map(|c| c.dxf_name.clone()); + let mut objects: Vec> = doc + .objects + .values() + .filter_map(|o| match o { + ObjectType::ProxyObject(p) => Some(class_of(p.class_id)), + _ => None, + }) + .collect(); + objects.sort(); + assert_eq!(objects, [Some("VISUALSTYLE".to_string()), Some("WIDGETX".to_string())]); + let entities: Vec> = doc + .entities() + .filter_map(|e| match e { + EntityType::Extended(x) => match &x.data { + ExtendedEntityData::Proxy(p) => Some(class_of(p.class_id)), + _ => None, + }, + _ => None, + }) + .collect(); + assert_eq!(entities, [Some("WIDGETX".to_string())]); +} + +/// What the DWG writer reports it left out counts the proxy it can't name, so a save's loss +/// report has it with the other records the DWG doesn't keep. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_proxy_left_out_of_the_dwg_is_counted_as_unwritten() { + let (_, unwritten) = cadcraft_dwg::dxf_to_dwg_noted(&proxy_file(), "AC1032").unwrap(); + assert_eq!(unwritten, [("ACAD_PROXY_OBJECT".to_string(), 1)].into_iter().collect()); + let d = read(&proxy_file(), "p.dxf").unwrap(); + let binary = write_with(&d, "p.dxf", &SaveOptions { version: Some(Version::R2018), binary: true }).unwrap(); + let (_, unwritten) = cadcraft_dwg::dxf_to_dwg_noted(&binary, "AC1032").unwrap(); + // CADCraft's own save already left the stray proxy out; the binary DXF's other three go. + assert_eq!(unwritten, [("ACAD_PROXY_ENTITY".to_string(), 1), ("ACAD_PROXY_OBJECT".to_string(), 2)].into_iter().collect()); +} + +/// A binary DXF given to the DWG conversion directly: its CLASSES aren't read, so the proxies' +/// numbers can't be mapped to the DWG's classes. Kept as they were, they named other classes +/// (the ODA refuses such a file), so the DWG leaves them out, as a pre-2013 DWG does, and the +/// rest of the drawing is written. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn a_binary_dxf_leaves_its_proxies_out_of_the_dwg() { + use acadrust::entities::{EntityType, ExtendedEntityData}; + use acadrust::objects::ObjectType; + let d = read(&proxy_file(), "p.dxf").unwrap(); + let binary = write_with(&d, "p.dxf", &SaveOptions { version: Some(Version::R2018), binary: true }).unwrap(); + assert!(binary.starts_with(b"AutoCAD Binary DXF")); + let dwg = cadcraft_dwg::dxf_to_dwg_as(&binary, "AC1032").unwrap(); + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let proxies = doc.objects.values().filter(|o| matches!(o, ObjectType::ProxyObject(_))).count() + + doc.entities().filter(|e| matches!(e, EntityType::Extended(x) if matches!(x.data, ExtendedEntityData::Proxy(_)))).count(); + assert_eq!(proxies, 0, "no proxy with an unmapped class number"); + assert!(doc.layers.get("0").is_some(), "the drawing itself is written"); +} + /// A name that isn't valid Unicode still picks its format by extension. #[cfg(unix)] #[test] diff --git a/crates/io/tests/dwg_active_layout.rs b/crates/io/tests/dwg_active_layout.rs index 5093b2f5f..f2da61dcc 100644 --- a/crates/io/tests/dwg_active_layout.rs +++ b/crates/io/tests/dwg_active_layout.rs @@ -2,11 +2,15 @@ //! the one written as `*Paper_Space` (the DWG header's paper space block), the others //! `*Paper_SpaceN`. Saving used to make the first tab the active one again. +// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DXF still works. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use std::io::Cursor; use cadcraft_doc::{Common, Drawing, EntityKind, Layout, Line, Space}; use cadcraft_geom::Vec3; -use cadcraft_io::{SaveOptions, Version, read, write_with}; +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +use cadcraft_io::Version; +use cadcraft_io::{SaveOptions, read, write_with}; fn three_sheets() -> Drawing { let mut d = Drawing::new_metric(); @@ -19,6 +23,7 @@ fn three_sheets() -> Drawing { } /// The layout the DWG marks active: the one whose block the header names as paper space. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] fn dwg_active_layout(dwg: &[u8]) -> String { let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.to_vec())).read().unwrap(); let ps = doc.header.paper_space_block_handle; @@ -31,11 +36,13 @@ fn dwg_active_layout(dwg: &[u8]) -> String { .unwrap() } +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] fn dwg(d: &Drawing) -> Vec { write_with(d, "case.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap() } #[test] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] fn the_active_layout_stays_active_through_dwg_saves() { let mut d = three_sheets(); d.active_layout = Some("S2".into()); @@ -68,6 +75,7 @@ fn the_active_layout_survives_dxf_too() { } #[test] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] fn without_an_active_layout_the_first_tab_is_active() { let mut d = three_sheets(); d.active_layout = Some("gone".into()); @@ -75,6 +83,7 @@ fn without_an_active_layout_the_first_tab_is_active() { } #[test] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] fn the_active_layout_name_is_matched_ignoring_case() { let mut d = three_sheets(); d.active_layout = Some("s2".into()); diff --git a/crates/io/tests/dwg_kept_object_versions.rs b/crates/io/tests/dwg_kept_object_versions.rs new file mode 100644 index 000000000..5cb39919f --- /dev/null +++ b/crates/io/tests/dwg_kept_object_versions.rs @@ -0,0 +1,301 @@ +//! Objects CADCraft keeps without modelling them reach the DWG as the file they came from holds +//! them. The DWG bridge is an R2000 DXF, and acadrust reads some objects differently by version: +//! read as R2000, a 2013 or later file's mental ray render settings came out a class version too +//! high (the ODA File Converter then refuses the whole DWG: "Object improperly read: +//! AcDbMentalRayRenderSettings"), RapidRT render settings from a 2013 file a version too low, and +//! a field lost its flags and cached value. The bridge now reads the kept groups as the version +//! they were read from (`$ACADVER`). +//! +//! The drawing is synthetic: render settings and a field in the named object dictionary, with +//! values chosen to be told apart. The reference is acadrust's own conversion of the same DXF to +//! the same DWG version (an older DWG can't hold everything: a 2004 field has no value flags or +//! format), read back; CADCraft's DWG must hold the same objects. When the DWG is the DXF's own +//! version, that reference is also checked against the DXF as read. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + +use std::fmt::Write as _; +use std::io::Cursor; + +use acadrust::objects::{ClassObjectData, Field, ObjectType}; +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +/// A minimal DXF of `version` ("AC1032"): a model space MTEXT, and in the named object dictionary +/// mental ray and RapidRT render settings and a field with a non-ASCII cached value. +fn synthetic(version: &str) -> String { + let mut g: Vec<(i32, String)> = Vec::new(); + let mut put = |code: i32, value: &str| g.push((code, value.to_string())); + for (c, v) in [(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, version), (9, "$HANDSEED"), (5, "FFF"), (0, "ENDSEC")] { + put(c, v); + } + put(0, "SECTION"); + put(2, "CLASSES"); + for (name, cpp, app) in [ + ("MENTALRAYRENDERSETTINGS", "AcDbMentalRayRenderSettings", "SCENEOE"), + ("RAPIDRTRENDERSETTINGS", "AcDbRapidRTRenderSettings", "ObjectDBX Classes"), + ("FIELD", "AcDbField", "ObjectDBX Classes"), + ] { + for (c, v) in [(0, "CLASS"), (1, name), (2, cpp), (3, app), (90, "1024"), (91, "1"), (280, "0"), (281, "0")] { + put(c, v); + } + } + put(0, "ENDSEC"); + let mtext = [(0, "MTEXT"), (5, "200"), (100, "AcDbEntity"), (8, "0"), (100, "AcDbMText"), (10, "0"), (20, "0"), (30, "0")]; + for (c, v) in [(0, "SECTION"), (2, "ENTITIES")].into_iter().chain(mtext) { + put(c, v); + } + for (c, v) in [(40, "2.5"), (41, "0"), (71, "1"), (72, "5"), (1, "synthetic"), (0, "ENDSEC")] { + put(c, v); + } + for (c, v) in [(0, "SECTION"), (2, "OBJECTS"), (0, "DICTIONARY"), (5, "C"), (330, "0"), (100, "AcDbDictionary"), (281, "1")] { + put(c, v); + } + for (c, v) in [(3, "ACAD_RENDER_ACTIVE_SETTINGS"), (350, "300"), (3, "ACAD_RENDER_ACTIVE_RAPIDRT_SETTINGS"), (350, "301")] { + put(c, v); + } + put(3, "SYNTHETIC_FIELD"); + put(350, "302"); + // The common AcDbRenderSettings groups; 90 is the class version as a 2013+ DXF stores it. + let base = |name: &str| { + let base: Vec<(i32, String)> = [ + (100, "AcDbRenderSettings"), + (90, "2"), + (1, name), + (290, "1"), + (290, "0"), + (290, "1"), + (290, "0"), + (1, ""), + (1, "synthetic preset"), + (90, "7"), + ] + .into_iter() + .map(|(c, v)| (c, v.to_string())) + .collect(); + base + }; + g.extend([(0, "MENTALRAYRENDERSETTINGS"), (5, "300"), (330, "C")].map(|(c, v)| (c, v.to_string()))); + g.extend(base("SyntheticMR")); + g.push((100, "AcDbMentalRayRenderSettings".into())); + let mental_ray = [ + (90, "2"), + (90, "-1"), + (90, "2"), + (70, "1"), + (40, "2.0"), + (40, "2.0"), + (40, "0.125"), + (40, "0.25"), + (40, "0.375"), + (40, "0.5"), + (70, "1"), + (290, "1"), + (290, "1"), + (90, "3"), + (90, "4"), + (90, "6"), + (290, "1"), + (90, "250"), + (290, "1"), + (40, "2.5"), + (90, "5000"), + (90, "3"), + (90, "4"), + (90, "6"), + (290, "1"), + (90, "100"), + (290, "1"), + (290, "0"), + (290, "1"), + (40, "1.5"), + (40, "0.5"), + (40, "1200.0"), + (70, "1"), + (70, "2"), + (40, "5.0"), + (70, "1"), + (70, "1"), + (290, "0"), + (1, "mr note"), + (90, "16"), + (70, "2"), + (90, "2048"), + (290, "1"), + (40, "1.25"), + ]; + g.extend(mental_ray.map(|(c, v)| (c, v.to_string()))); + g.extend([(0, "RAPIDRTRENDERSETTINGS"), (5, "301"), (330, "C")].map(|(c, v)| (c, v.to_string()))); + g.extend(base("SyntheticRT")); + g.push((100, "AcDbRapidRTRenderSettings".into())); + let rapid_rt = [(90, "3"), (70, "1"), (90, "4"), (90, "5"), (70, "1"), (70, "2"), (40, "2.5"), (40, "1.5"), (290, "1")]; + g.extend(rapid_rt.map(|(c, v)| (c, v.to_string()))); + let field = [ + (0, "FIELD"), + (5, "302"), + (330, "C"), + (100, "AcDbField"), + (1, "AcVar"), + (2, "\\AcVar Filename \\f \"%fn2\""), + (90, "0"), + (97, "0"), + (91, "63"), + (92, "0"), + (94, "59"), + (95, "2"), + (96, "0"), + (300, ""), + (93, "1"), + (6, "Variable"), + (93, "0"), + (90, "4"), + (1, "Filename"), + (94, "0"), + (300, ""), + (302, ""), + (304, "ACVALUE_END"), + (7, "ACFD_FIELD_VALUE"), + (93, "4"), + (90, "4"), + (1, "C:\\synthetic\\Ação-01.dwg"), + (94, "0"), + (300, "%fn2"), + (302, "Ação-01"), + (304, "ACVALUE_END"), + (301, "Ação-01"), + (98, "7"), + (0, "ENDSEC"), + (0, "EOF"), + ]; + g.extend(field.map(|(c, v)| (c, v.to_string()))); + g.iter().fold(String::new(), |mut s, (c, v)| { + let _ = write!(s, "{c:>3}\r\n{v}\r\n"); + s + }) +} + +/// The render settings and the field a document holds (the drawing has one of each). +struct Kept { + mental_ray: Option, + rapid_rt: Option, + field: Option, +} + +fn kept(doc: &acadrust::CadDocument) -> Kept { + let mut k = Kept { mental_ray: None, rapid_rt: None, field: None }; + for o in doc.objects.values() { + match o { + ObjectType::ClassObject(c) if matches!(c.data, ClassObjectData::MentalRayRenderSettings(_)) => k.mental_ray = Some(c.data.clone()), + ObjectType::ClassObject(c) if matches!(c.data, ClassObjectData::RapidRtRenderSettings(_)) => k.rapid_rt = Some(c.data.clone()), + ObjectType::Field(f) => k.field = Some(f.clone()), + _ => {} + } + } + k +} + +/// acadrust's version for a CADCraft one. +fn acad(v: Version) -> acadrust::DxfVersion { + acadrust::DxfVersion::from_version_string(v.code()) +} + +/// The DXF of `version` saved as a `target` DWG holds the render settings and the field that +/// acadrust's own DXF → DWG conversion keeps. +fn kept_objects_survive(version: &str, target: Version) { + let dxf = synthetic(version); + let mut source = acadrust::DxfReader::from_reader(Cursor::new(dxf.clone().into_bytes())).unwrap().read().unwrap(); + let as_read = kept(&source); + assert!(as_read.mental_ray.is_some() && as_read.rapid_rt.is_some() && as_read.field.is_some(), "the synthetic DXF reads"); + source.version = acad(target); + let direct = acadrust::DwgWriter::write_to_vec(&source).unwrap(); + let reference = kept(&acadrust::DwgReader::from_stream(Cursor::new(direct)).read().unwrap()); + if target.code() == version { + assert_eq!(reference.mental_ray, as_read.mental_ray, "the reference DWG keeps the mental ray settings"); + assert_eq!(reference.rapid_rt, as_read.rapid_rt, "the reference DWG keeps the RapidRT settings"); + assert_eq!(reference.field.as_ref().map(|f| &f.value), as_read.field.as_ref().map(|f| &f.value), "the reference DWG keeps the field"); + } + + let d = read(dxf.as_bytes(), "kept.dxf").unwrap(); + let dwg = write_with(&d, "kept.dwg", &SaveOptions { version: Some(target), binary: false }).unwrap(); + let written = acadrust::DwgReader::from_stream(Cursor::new(dwg)).read().unwrap(); + let written = kept(&written); + + // Every difference is listed, so a failure names all the objects that came out wrong. + let mut wrong = Vec::new(); + if written.mental_ray != reference.mental_ray { + wrong.push(format!("mental ray render settings: {:?}\n expected {:?}", written.mental_ray, reference.mental_ray)); + } + if written.rapid_rt != reference.rapid_rt { + wrong.push(format!("RapidRT render settings: {:?}\n expected {:?}", written.rapid_rt, reference.rapid_rt)); + } + let field = |f: &Option| { + f.as_ref().map(|f| (f.evaluator_id.clone(), f.code.clone(), f.value.clone(), f.value_string.clone(), f.child_values.clone())) + }; + if field(&written.field) != field(&reference.field) { + wrong.push(format!("field: {:?}\n expected {:?}", field(&written.field), field(&reference.field))); + } + assert!(wrong.is_empty(), "{version} → {target:?}:\n{}", wrong.join("\n")); +} + +/// A drawing saved once as an older DWG has that version as its `$ACADVER` (SAVEAS sets it, so a +/// later QSAVE writes it again), but its kept objects are still in the 2018 file's groups. The +/// next save must still read them as 2018: read as the saved version, the mental ray settings +/// came out a class version too high (the ODA refuses the DWG) and a 2004 field lost its cached +/// value. +#[test] +fn kept_groups_keep_their_version_across_saves() { + let dxf = synthetic("AC1032"); + for (first, second) in [(Version::R2004, Version::R2004), (Version::R2010, Version::R2018), (Version::R2018, Version::R2018)] { + let mut source = acadrust::DxfReader::from_reader(Cursor::new(dxf.clone().into_bytes())).unwrap().read().unwrap(); + source.version = acad(second); + let reference = kept(&acadrust::DwgReader::from_stream(Cursor::new(acadrust::DwgWriter::write_to_vec(&source).unwrap())).read().unwrap()); + + let mut d = read(dxf.as_bytes(), "kept.dxf").unwrap(); + write_with(&d, "kept.dwg", &SaveOptions { version: Some(first), binary: false }).unwrap(); + // What SAVEAS does to the drawing after writing it. + d.header.set_str("ACADVER", first.code()); + let dwg = write_with(&d, "kept.dwg", &SaveOptions { version: Some(second), binary: false }).unwrap(); + let written = kept(&acadrust::DwgReader::from_stream(Cursor::new(dwg)).read().unwrap()); + let field = |k: &Kept| k.field.as_ref().map(|f| (f.value.clone(), f.value_string.clone())); + assert_eq!(written.mental_ray, reference.mental_ray, "{first:?} then {second:?}: mental ray render settings"); + assert_eq!(field(&written), field(&reference), "{first:?} then {second:?}: field"); + } +} + +/// A DXF without `$ACADVER` has no version for its kept groups: the drawing's own `$ACADVER` +/// is then the default a new drawing starts with (AC1032), which says nothing about the file, so +/// the kept groups are read as the bridge's R2000, as before. +#[test] +fn a_file_without_acadver_records_no_version() { + let dxf = synthetic("AC1032").replacen(" 9\r\n$ACADVER\r\n 1\r\nAC1032\r\n", "", 1); + assert!(!dxf.contains("$ACADVER")); + let d = read(dxf.as_bytes(), "kept.dxf").unwrap(); + assert!(!d.foreign.objects.is_empty(), "the render settings and the field are kept"); + assert_eq!(d.foreign.version, None); + let with = read(synthetic("AC1032").as_bytes(), "kept.dxf").unwrap(); + assert_eq!(with.foreign.version.as_deref(), Some("AC1032")); +} + +#[test] +fn a_2018_files_kept_objects_reach_a_2018_dwg() { + kept_objects_survive("AC1032", Version::R2018); +} + +/// RapidRT render settings are the case whose class version acadrust adjusts only in 2013 files. +#[test] +fn a_2013_files_kept_objects_reach_a_2013_dwg() { + kept_objects_survive("AC1027", Version::R2013); +} + +#[test] +fn a_2018_files_kept_objects_reach_a_2004_dwg() { + kept_objects_survive("AC1032", Version::R2004); +} + +/// A drawing from an R2000 DXF (no newer groups to read differently) saves as before. +#[test] +fn an_r2000_files_drawing_still_saves_as_dwg() { + let dxf = " 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nLINE\r\n 8\r\n0\r\n 10\r\n0\r\n 20\r\n0\r\n 30\r\n0\r\n 11\r\n10\r\n 21\r\n5\r\n 31\r\n0\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + let d = read(dxf.as_bytes(), "line.dxf").unwrap(); + let dwg = write_with(&d, "line.dwg", &SaveOptions::default()).unwrap(); + let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg)).read().unwrap(); + assert_eq!(doc.entities().count(), 1); +} diff --git a/crates/io/tests/dwg_polyline_vertex_order.rs b/crates/io/tests/dwg_polyline_vertex_order.rs index 5cb63d2f6..b9606ded5 100644 --- a/crates/io/tests/dwg_polyline_vertex_order.rs +++ b/crates/io/tests/dwg_polyline_vertex_order.rs @@ -4,7 +4,7 @@ //! //! The DWG is written here with acadrust, giving the second 3D-polyline vertex the highest //! handle: exactly what an editing program produces when it inserts a vertex. -#![cfg(not(target_arch = "wasm32"))] +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use acadrust::entities::{EntityType, Polyline3D, Vertex3DPolyline}; use acadrust::types::{DxfVersion, Handle, Vector3}; diff --git a/crates/io/tests/dwg_required_dictionaries.rs b/crates/io/tests/dwg_required_dictionaries.rs index 3feb0d7dd..f28be9618 100644 --- a/crates/io/tests/dwg_required_dictionaries.rs +++ b/crates/io/tests/dwg_required_dictionaries.rs @@ -3,7 +3,7 @@ //! it as empty ("No data was imported..."), though it reads the same drawing as DXF (and as an //! AC1032 DWG) fine. The DWG bridge adds the dictionary AutoCAD writes, with its usual variables, //! when the DXF has none. -#![cfg(not(target_arch = "wasm32"))] +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use std::io::Cursor; diff --git a/crates/io/tests/dwg_table_cell_height.rs b/crates/io/tests/dwg_table_cell_height.rs index 11ee98c9d..e7f7ca79a 100644 --- a/crates/io/tests/dwg_table_cell_height.rs +++ b/crates/io/tests/dwg_table_cell_height.rs @@ -1,6 +1,8 @@ //! TABLE heights inherit from the table style unless the file records a cell override. #![cfg(not(target_arch = "wasm32"))] +// FreeBSD ARM64 has no native DWG bridge (#2526), but the DXF regression still applies. + use cadcraft_doc::{Common, Drawing, EntityKind, Space, Table, TableCell, TableStyle}; fn drawing() -> Drawing { @@ -42,6 +44,7 @@ fn check(d: &Drawing) { } #[test] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] fn table_cell_heights_keep_inheritance_through_dwg() { let bytes = cadcraft_io::write(&drawing(), "height.dwg").unwrap(); // A style record can be present for metadata without overriding its text height. @@ -68,11 +71,13 @@ fn table_cell_heights_keep_inheritance_through_dxf() { // ---- cells with their own style record (review on #2588) ---- +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] use acadrust::entities::table::{CellContent, CellStyle, CellStylePropertyFlags}; /// Write the drawing as a DWG, edit its first cell through acadrust (`edit`), write it again as a /// DWG (or, with `as_dxf`, as a DXF by acadrust's writer) and read it with CADCraft. Returns the first cell's /// text height override. +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] fn first_cell_height(as_dxf: bool, edit: impl FnOnce(&mut acadrust::entities::table::TableCell)) -> Option { let bytes = cadcraft_io::write(&drawing(), "height.dwg").unwrap(); let mut doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(bytes)).read().unwrap(); @@ -100,6 +105,7 @@ fn first_cell_height(as_dxf: bool, edit: impl FnOnce(&mut acadrust::entities::ta .unwrap() } +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] fn styled(height: f64, flags: CellStylePropertyFlags) -> CellStyle { let mut s = CellStyle::new(); s.text_height = height; @@ -108,12 +114,14 @@ fn styled(height: f64, flags: CellStylePropertyFlags) -> CellStyle { } #[test] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] fn a_cell_style_with_the_text_height_flag_keeps_its_height() { let h = first_cell_height(false, |c| c.style = Some(styled(0.5, CellStylePropertyFlags::TEXT_HEIGHT))); assert_eq!(h, Some(0.5)); } #[test] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] fn content_with_format_override_bit_128_keeps_its_own_height() { // acadrust writes the content's height as group 144 and the style's as 140; they differ here // so the result shows which one CADCraft honoured. @@ -131,6 +139,7 @@ fn content_with_format_override_bit_128_keeps_its_own_height() { /// Only the first content's override stands for the cell: a later content's height must not /// replace the first content's inherited one (review on #2588). #[test] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] fn a_later_contents_height_does_not_replace_the_first_contents() { let h = first_cell_height(false, |c| { c.style = Some(styled(0.18, CellStylePropertyFlags::NONE)); @@ -147,6 +156,7 @@ fn a_later_contents_height_does_not_replace_the_first_contents() { /// Bit 128 with an unusable content height copies nothing, so the writer's default style height /// is still cleared (review on #2588). #[test] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] fn bit_128_with_an_invalid_height_still_clears_the_default() { for bad in [0.0, -1.0, f64::NAN] { let h = first_cell_height(false, |c| { @@ -162,12 +172,14 @@ fn bit_128_with_an_invalid_height_still_clears_the_default() { } #[test] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] fn a_cell_with_no_style_record_inherits_the_table_style() { assert_eq!(first_cell_height(false, |c| c.style = None), None); } /// A style record with a height and neither override is not an override, through DWG. #[test] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] fn a_style_height_without_an_override_is_cleared() { assert_eq!(first_cell_height(false, |c| c.style = Some(styled(0.18, CellStylePropertyFlags::NONE))), None); } diff --git a/crates/io/tests/dwg_unavailable.rs b/crates/io/tests/dwg_unavailable.rs new file mode 100644 index 000000000..421aded7c --- /dev/null +++ b/crates/io/tests/dwg_unavailable.rs @@ -0,0 +1,21 @@ +//! The targets without the native DWG bridge still handle DXF and report an actionable error +//! for DWG instead of pretending that opening or saving succeeded. + +#![cfg(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))] + +use cadcraft_doc::Drawing; +use cadcraft_io::{read, write}; + +#[test] +fn no_dwg_bridge_preserves_dxf_and_reports_dwg_unavailable() { + let drawing = Drawing::new_metric(); + let dxf = write(&drawing, "drawing.dxf").expect("DXF remains available"); + assert!(read(&dxf, "drawing.dxf").is_ok()); + + let read_error = read(b"AC1032unavailable", "drawing.dwg").unwrap_err().to_string(); + let write_error = write(&drawing, "drawing.dwg").unwrap_err().to_string(); + for error in [read_error, write_error] { + assert!(error.contains("DWG"), "{error}"); + assert!(error.contains("DXF"), "{error}"); + } +} diff --git a/crates/io/tests/hard_owned_objects_kept.rs b/crates/io/tests/hard_owned_objects_kept.rs new file mode 100644 index 000000000..93aba5cc4 --- /dev/null +++ b/crates/io/tests/hard_owned_objects_kept.rs @@ -0,0 +1,204 @@ +//! An object of another application whose owner is null, but which another kept object holds by a +//! hard owner reference (360), is kept with it, as one application's proxy object held by another. +//! In DXF and in DWG, save after save. + +use cadcraft_io::{read, read_dxf, write, write_dxf}; + +/// A named object dictionary entry `OTHER_APP` (a dictionary) with an XRECORD that holds a second +/// XRECORD by a 360 reference; the second one's owner is null. An object nothing keeps names the +/// second XRECORD by a 360 first. +fn source() -> String { + let groups: &[(i32, &str)] = &[ + (0, "SECTION"), + (2, "ENTITIES"), + (0, "LINE"), + (5, "30"), + (8, "0"), + (10, "0"), + (20, "0"), + (11, "10"), + (21, "0"), + (0, "ENDSEC"), + (0, "SECTION"), + (2, "OBJECTS"), + (0, "DICTIONARY"), + (5, "C"), + (330, "0"), + (100, "AcDbDictionary"), + (3, "OTHER_APP"), + (350, "50"), + // An object nothing keeps (null owner, no holder) that also names the held record by a + // 360, before the holder does: it is dropped, and the held record stays with the holder. + (0, "XRECORD"), + (5, "60"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "stray"), + (360, "52"), + (0, "DICTIONARY"), + (5, "50"), + (330, "C"), + (100, "AcDbDictionary"), + (281, "1"), + (3, "HOLDER"), + (360, "51"), + (0, "XRECORD"), + (5, "51"), + (102, "{ACAD_REACTORS"), + (330, "50"), + (102, "}"), + (330, "50"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "holder"), + (360, "52"), + (0, "XRECORD"), + (5, "52"), + (102, "{ACAD_REACTORS"), + (330, "51"), + (102, "}"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "held"), + (0, "ENDSEC"), + (0, "EOF"), + ]; + groups.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect() +} + +fn check(text: &str, label: &str) { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let pairs: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect(); + // Each record from its `0` group on, as (code, value) pairs. + let records: Vec<&[(&str, &str)]> = pairs + .iter() + .enumerate() + .filter(|(_, (c, _))| *c == "0") + .map(|(i, _)| { + let n = pairs[i + 1..].iter().position(|(c, _)| *c == "0").map_or(pairs.len(), |n| i + 1 + n); + &pairs[i..n] + }) + .collect(); + let with = |text: &str| records.iter().find(|r| r.contains(&("1", text))).copied().unwrap_or_else(|| panic!("{label}: no record {text}")); + let holder = with("holder"); + let Some((_, held_handle)) = holder.iter().find(|(c, _)| *c == "360") else { panic!("{label}: the holder holds nothing: {holder:?}") }; + let held = with("held"); + assert!(held.contains(&("5", *held_handle)), "{label}: the holder's 360 names the held record: {holder:?} {held:?}"); + assert!(!records.iter().any(|r| r.contains(&("1", "stray"))), "{label}: the object nothing keeps is dropped"); +} + +#[test] +fn an_object_held_by_a_kept_one_is_kept() { + let mut d = read_dxf(source().as_bytes()).expect("read"); + for generation in 1..=2 { + let text = write_dxf(&d); + check(&text, &format!("DXF {generation}")); + d = read_dxf(text.as_bytes()).expect("reread"); + } + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + for generation in 1..=2 { + let dwg = write(&d, "held.dwg").expect("DWG"); + d = read(&dwg, "held.dwg").expect("DWG read"); + check(&write_dxf(&d), &format!("DWG {generation}")); + } +} + +/// Mutual hard owners must not erase the live path through a retained dictionary entry. +#[test] +fn cyclic_hard_owners_with_a_live_holder_stay_kept() { + let groups = [ + (0, "SECTION"), + (2, "OBJECTS"), + (0, "DICTIONARY"), + (5, "C"), + (330, "0"), + (100, "AcDbDictionary"), + (3, "OTHER_APP"), + (350, "50"), + (0, "XRECORD"), + (5, "60"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "stray"), + (360, "54"), + (0, "XRECORD"), + (5, "52"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "first"), + (360, "53"), + (360, "54"), + (0, "XRECORD"), + (5, "53"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "second"), + (360, "52"), + (0, "XRECORD"), + (5, "54"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "child"), + (0, "DICTIONARY"), + (5, "50"), + (330, "C"), + (100, "AcDbDictionary"), + (281, "1"), + (3, "HOLDER"), + (360, "51"), + (0, "XRECORD"), + (5, "51"), + (330, "50"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "holder"), + (360, "52"), + (360, "53"), + (0, "ENDSEC"), + (0, "EOF"), + ]; + let text = groups.iter().map(|(code, value)| format!("{code}\n{value}\n")).collect::(); + let mut drawing = read_dxf(text.as_bytes()).unwrap(); + let mut names = vec!["copy.dxf", "again.dxf"]; + if cfg!(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))) { + names.extend(["copy.dwg", "again.dwg"]); + } + for name in names { + let bytes = write(&drawing, name).unwrap(); + drawing = read(&bytes, name).unwrap(); + let text = write_dxf(&drawing); + let tags = cadcraft_dxf::parse(text.as_bytes()).unwrap(); + let objects = cadcraft_dxf::sections(&tags).into_iter().find(|s| s.name == "OBJECTS").unwrap(); + let records = cadcraft_dxf::records(&objects.tags); + let record = |label: &str| records.iter().find(|(_, tags)| tags.iter().any(|t| t.code == 1 && t.str() == label)).unwrap().1.clone(); + let first = record("first"); + let second = record("second"); + let holder = record("holder"); + let child = record("child"); + assert!(!records.iter().any(|(_, tags)| tags.iter().any(|t| t.code == 1 && t.str() == "stray")), "{name}"); + let handle = |tags: &[cadcraft_dxf::Tag]| tags.iter().find(|t| t.code == 5).unwrap().str(); + assert!(first.iter().any(|t| t.code == 360 && t.str() == handle(&second)), "{name}"); + assert!(second.iter().any(|t| t.code == 360 && t.str() == handle(&first)), "{name}"); + assert!(first.iter().any(|t| t.code == 360 && t.str() == handle(&child)), "{name}"); + for object in [&first, &second] { + assert!(holder.iter().any(|t| t.code == 360 && t.str() == handle(object)), "{name}"); + } + } +} + +/// A real 330 owner takes precedence, even when a retained object also names the record by 360. +#[test] +fn a_real_owner_is_not_replaced_by_a_hard_owner() { + let text = source().replace("330\n0\n100\nAcDbXrecord\n280\n1\n1\nheld", "330\nDEAD\n100\nAcDbXrecord\n280\n1\n1\nheld"); + assert!(text.contains("330\nDEAD")); + let drawing = read_dxf(text.as_bytes()).unwrap(); + let output = write_dxf(&drawing); + assert!(output.lines().any(|line| line.trim() == "holder")); + assert!(!output.lines().any(|line| line.trim() == "held")); +} diff --git a/crates/io/tests/it/codepages.rs b/crates/io/tests/it/codepages.rs index 56f9af80f..3179b7054 100644 --- a/crates/io/tests/it/codepages.rs +++ b/crates/io/tests/it/codepages.rs @@ -205,7 +205,8 @@ fn binary_dxf_honours_the_code_page() { let read = |b: &[u8]| text_of(&cadcraft_io::read_dxf(b).unwrap()); assert_eq!(read(&bin("AC1015", "ANSI_1251", b"\xCF\xF0\xE8\xE2\xE5\xF2")), "Привет"); assert_eq!(read(&bin("AC1018", "ANSI_932", b"\x95\x5C\\U+00E9")), "表é"); - // A short Cyrillic string that is also valid UTF-8 (D1 B2) is still read in the code page. + // A short Cyrillic string that is also valid UTF-8 (D1 B2) is still read in the code page: + // a pre-R2007 binary file has no way to escape to UTF-8, so its strings are never read as it. assert_eq!(read(&bin("AC1015", "ANSI_1251", b"\xD1\xB2")), "СІ"); assert_eq!(read(&bin("AC1021", "ANSI_1251", "Привет".as_bytes())), "Привет"); assert_eq!(read(&bin("AC1015", "ANSI_1361", b"Caf\xE9")), "Café"); diff --git a/crates/io/tests/it/dim_block_text.rs b/crates/io/tests/it/dim_block_text.rs index 244e9401c..8a6225a93 100644 --- a/crates/io/tests/it/dim_block_text.rs +++ b/crates/io/tests/it/dim_block_text.rs @@ -103,7 +103,7 @@ fn dxf_angular_block_text_keeps_the_decimal_separator() { } } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn dwg_angular_block_text_keeps_the_decimal_separator() { use std::io::Cursor; diff --git a/crates/io/tests/it/dwg_layout_owner.rs b/crates/io/tests/it/dwg_layout_owner.rs index 45de12cb8..20dfa72c3 100644 --- a/crates/io/tests/it/dwg_layout_owner.rs +++ b/crates/io/tests/it/dwg_layout_owner.rs @@ -2,6 +2,8 @@ //! by their own block (entity mode 0 and its handle). Written as "paper space" (mode 1), AutoCAD //! put them on the first layout and left theirs empty. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + use std::io::Cursor; use cadcraft_doc::{Circle, Common, Drawing, EntityKind, Layout, Line, Space}; diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index 9c4943350..fbcc74e35 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -87,6 +87,7 @@ fn a_saved_drawing_keeps_the_dynamic_block_as_read() { } /// The Door fixture with a scale action on the Width parameter: graph node 6, object 68. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] fn with_scale_action() -> String { let node = "91 6\n93 32\n95 7\n360 68\n92 -1\n92 -1\n92 -1\n92 -1\n"; let action = "0 BLOCKSCALEACTION\n5 68\n330 61\n100 AcDbEvalExpr\n90 7\n98 33\n99 232\n\ @@ -105,6 +106,7 @@ fn with_scale_action() -> String { /// the DWG holds it with its connections, and it reads back as the same action. AutoCAD refused /// such DWGs while acadrust left out the byte after its connections (cadcraft-dwg's /// `scale_actions_keep_the_byte_autocad_reads_after_their_connections` covers the byte). +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn a_scale_action_survives_a_dwg_save() { use acadrust::objects::{DynamicBlockData, DynamicBlockObject, ObjectType}; @@ -585,11 +587,12 @@ fn a_point_past_the_end_of_a_frame_edge_is_outside_it() { #[test] fn a_tilted_polyline_keeps_the_stored_vertex_list() { - // Polyline 34 lies in a plane tilted about the y axis (extrusion (1,0,0)): its vertices are in - // that plane's coordinates, not the block's, so the frame isn't tested against them and the - // stored list (vertex 0) is used, as before; so is polyline 36's, tilted by only 5e-10 (at an - // elevation of 2e9 that moves it about a unit). Polyline 35 is mirrored (extrusion (0,0,-1)): it - // is read flipped into the block's plane, (-20, 1) as (20, 1), so the frame is tested. + // Polyline 34 lies in a plane tilted about the y axis (extrusion (1,0,0)): it is read as seen + // from above (#1886), (20, 1) as (0, 20), so the frame is tested against those points; none is + // inside, so it moves whole. Polyline 36 is tilted by only 5e-10 (at an elevation of 2e9 that + // moves it about a unit, below what reading projects): its vertices stay in its own plane and + // the stored list (vertex 0) is used, as before. Polyline 35 is mirrored (extrusion (0,0,-1)): + // it is read flipped into the block's plane, (-20, 1) as (20, 1), so the frame is tested. let polyline = |h: &str, [x0, x1]: [i32; 2], [ex, ey, ez]: [f64; 3], elevation: f64| { format!( "0 LWPOLYLINE\n5 {h}\n330 1D\n100 AcDbEntity\n8 0\n100 AcDbPolyline\n90 2\n70 0\n38 {elevation}\n10 {x0}\n20 1\n10 {x1}\n20 1\n210 {ex}\n220 {ey}\n230 {ez}\n" @@ -610,7 +613,7 @@ fn a_tilted_polyline_keeps_the_stored_vertex_list() { let (mut d, r) = door_reference(&src); cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); let s = shapes(&d, r); - assert_eq!(s[3], [(14.0, 1.0), (36.0, 1.0)]); + assert_eq!(s[3], [(-6.0, 20.0), (-6.0, 36.0)]); assert_eq!(s[4], [(20.0, 1.0), (30.0, 1.0)]); assert_eq!(s[5], [(14.0, 1.0), (36.0, 1.0)]); } diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 2e6c894a9..57081f97a 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -49,6 +49,8 @@ mod mtext_line_spacing; mod multiline_attributes; #[cfg(not(target_arch = "wasm32"))] mod ole2frame_roundtrip; +#[cfg(not(target_arch = "wasm32"))] +mod ole_frame; mod paperview_marker; mod passthrough_image_roundtrip; mod pdf_followups; diff --git a/crates/io/tests/it/mtext_caret_spaces.rs b/crates/io/tests/it/mtext_caret_spaces.rs index 8bb1ed071..92b6ffd9a 100644 --- a/crates/io/tests/it/mtext_caret_spaces.rs +++ b/crates/io/tests/it/mtext_caret_spaces.rs @@ -74,7 +74,7 @@ fn dxf_mtext_caret_spaces_round_trip() -> TestResult { Ok(()) } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn dwg_mtext_caret_spaces_round_trip() -> TestResult { let (original, expected) = drawing()?; @@ -103,7 +103,7 @@ fn dwg_mtext_caret_spaces_round_trip() -> TestResult { Ok(()) } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn bridge_caret_space_is_escaped_once_in_each_direction() -> TestResult { let (d, _) = drawing()?; diff --git a/crates/io/tests/it/ole_frame.rs b/crates/io/tests/it/ole_frame.rs new file mode 100644 index 000000000..188987db5 --- /dev/null +++ b/crates/io/tests/it/ole_frame.rs @@ -0,0 +1,96 @@ +//! An OLE2FRAME is kept as an unknown entity; a DWG save carries it with its data and frame +//! position (#2422). A DWG's OLE2FRAME object has no corner fields: the position travels in the +//! start of the OLE data (a 2-byte marker, then the frame's four corners as three little-endian +//! doubles each: upper left, upper right, lower right, lower left), which is how the DXF's +//! groups 10 and 11 come back. That layout is read from the acadrust dependency's decoder. + +use cadcraft_doc::EntityKind; +use cadcraft_io::{SaveOptions, Version, read, read_dxf, write_with}; + +const UL: (f64, f64) = (30.14, -18.99); +const LR: (f64, f64) = (35.27, -22.39); + +/// The OLE data: the envelope with the frame's corners. +fn blob() -> Vec { + let mut b = vec![1u8, 0]; + for (x, y) in [UL, (LR.0, UL.1), LR, (UL.0, LR.1)] { + for v in [x, y, 0.0] { + b.extend_from_slice(&v.to_le_bytes()); + } + } + b +} + +/// A 2000 DXF with one OLE2FRAME: corners, the binary data and the end marker (DXF Reference). +fn dxf() -> String { + let data = blob(); + let hex: String = data.iter().map(|b| format!("{b:02X}")).collect(); + format!( + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n\ + 0\nOLE2FRAME\n5\n2B\n100\nAcDbEntity\n8\n0\n100\nAcDbOle2Frame\n70\n2\n3\nOLE Object\n\ + 10\n{}\n20\n{}\n30\n0\n11\n{}\n21\n{}\n31\n0\n71\n2\n72\n0\n90\n{}\n310\n{hex}\n1\nOLE\n\ + 0\nENDSEC\n0\nEOF\n", + UL.0, + UL.1, + LR.0, + LR.1, + data.len() + ) +} + +fn ole(d: &cadcraft_doc::Drawing) -> Option { + d.model.iter().find_map(|e| match &e.kind { + EntityKind::Unknown(u) if u.dxf_type == "OLE2FRAME" => Some(u.clone()), + _ => None, + }) +} + +#[test] +fn a_dwg_keeps_an_ole_frame_with_its_data_and_position() { + let d = read_dxf(dxf().as_bytes()).unwrap(); + assert!(ole(&d).is_some()); + let want: String = blob().iter().map(|b| format!("{b:02X}")).collect(); + for v in [Version::R2000, Version::R2010, Version::R2018] { + let dwg = write_with(&d, "x.dwg", &SaveOptions { version: Some(v), binary: false }).unwrap(); + let back = read(&dwg, "x.dwg").unwrap(); + let u = ole(&back).unwrap_or_else(|| panic!("{v:?}: the OLE2FRAME is gone")); + let data: String = u.tags.iter().filter(|t| t.code == 310).map(|t| t.value.to_ascii_uppercase()).collect(); + let corner = |code: i32| u.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()); + assert_eq!(data, want, "{v:?}: data"); + assert_eq!((corner(10), corner(20), corner(11), corner(21)), (Some(UL.0), Some(UL.1), Some(LR.0), Some(LR.1)), "{v:?}: frame corners"); + } +} + +/// A frame moved through its corner tags (what MOVE does) keeps the new position in a DWG save +/// and read-back (review on #2587). +#[test] +fn a_moved_ole_frame_keeps_its_position_in_a_dwg() { + let mut d = read_dxf(dxf().as_bytes()).unwrap(); + for h in d.model.handles() { + d.model.modify(h, |e| e.kind.transform(&cadcraft_geom::Mat3::translate(cadcraft_geom::Vec2::new(100.0, -50.0)))); + } + let dwg = write_with(&d, "x.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap(); + let u = ole(&read(&dwg, "x.dwg").unwrap()).unwrap(); + let c = |code: i32| u.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).unwrap(); + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + assert!(near(c(10), UL.0 + 100.0) && near(c(20), UL.1 - 50.0) && near(c(11), LR.0 + 100.0) && near(c(21), LR.1 - 50.0), "{:?}", u.tags); +} + +/// After a move, a DXF save and read-back carries the moved corners both in groups 10/11 and in +/// the OLE data header (review on #2587). +#[test] +fn a_moved_ole_frame_keeps_its_data_header_in_a_dxf() { + let mut d = read_dxf(dxf().as_bytes()).unwrap(); + for h in d.model.handles() { + d.model.modify(h, |e| e.kind.transform(&cadcraft_geom::Mat3::translate(cadcraft_geom::Vec2::new(100.0, -50.0)))); + } + let bytes = write_with(&d, "x.dxf", &SaveOptions { version: None, binary: false }).unwrap(); + let u = ole(&read_dxf(&bytes).unwrap()).unwrap(); + let hex: String = u.tags.iter().filter(|t| t.code == 310).map(|t| t.value.clone()).collect(); + let b: Vec = (0..hex.len() / 2).map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap()).collect(); + let f = |o: usize| f64::from_le_bytes(b[o..o + 8].try_into().unwrap()); + let near = |a: f64, c: f64| (a - c).abs() < 1e-9; + assert!(near(f(2), UL.0 + 100.0) && near(f(10), UL.1 - 50.0) && near(f(2 + 48), LR.0 + 100.0) && near(f(10 + 48), LR.1 - 50.0)); + let g = |code: i32| u.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).unwrap(); + assert!(near(g(10), UL.0 + 100.0) && near(g(21), LR.1 - 50.0)); +} diff --git a/crates/io/tests/it/roundtrip/collections.rs b/crates/io/tests/it/roundtrip/collections.rs index 81ed33641..e83e1d876 100644 --- a/crates/io/tests/it/roundtrip/collections.rs +++ b/crates/io/tests/it/roundtrip/collections.rs @@ -256,7 +256,9 @@ pub(super) fn assert_layouts(a: &Drawing, b: &Drawing, context: &str) { for layout in &a.layouts { let back = b.layouts.iter().find(|l| l.name == layout.name).expect("layout must survive"); assert_eq!(back.tab_order, layout.tab_order, "{context}.{}.tab_order", layout.name); - assert_eq!(back.page, layout.page, "{context}.{}.page", layout.name); + // The groups 44, 45 and 73 the file stored are provenance, not a setting. + let setting = |p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, ..p.clone() }; + assert_eq!(setting(&back.page), setting(&layout.page), "{context}.{}.page", layout.name); assert_eq!(back.view, layout.view, "{context}.{}.view", layout.name); compare::entities(a, b, &layout.entities, &back.entities, &format!("{context}.layout[{}]", layout.name)); } diff --git a/crates/io/tests/it/roundtrip/mod.rs b/crates/io/tests/it/roundtrip/mod.rs index d38f84eb1..02a35c808 100644 --- a/crates/io/tests/it/roundtrip/mod.rs +++ b/crates/io/tests/it/roundtrip/mod.rs @@ -4,7 +4,7 @@ mod cases; mod collections; mod compare; -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] mod dwg; mod dxf; mod handle_limits; diff --git a/crates/io/tests/it/tables_objects_roundtrip.rs b/crates/io/tests/it/tables_objects_roundtrip.rs index ec2fe7726..09086b4d1 100644 --- a/crates/io/tests/it/tables_objects_roundtrip.rs +++ b/crates/io/tests/it/tables_objects_roundtrip.rs @@ -111,7 +111,9 @@ fn layout_page_setup_and_paper_view_round_trip() { let r = round_trip(&d); for (a, b) in d.layouts.iter().zip(&r.layouts) { assert_eq!(a.name, b.name); - assert_eq!(a.page, b.page, "{}", a.name); + // The groups 44, 45 and 73 the file stored are provenance, not a setting. + let read = cadcraft_doc::PageSetup { file_paper: None, ..b.page.clone() }; + assert_eq!(a.page, read, "{}", a.name); assert_eq!(a.view, b.view, "{}", a.name); } assert_eq!(r.layouts.len(), d.layouts.len()); diff --git a/crates/io/tests/registered_proxy.rs b/crates/io/tests/registered_proxy.rs new file mode 100644 index 000000000..20ccffea1 --- /dev/null +++ b/crates/io/tests/registered_proxy.rs @@ -0,0 +1,296 @@ +//! Synthetic application data must keep its identity as well as its bytes. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +use acadrust::classes::DxfClass; +use acadrust::entities::{EntityCommon, EntityType, ExtendedEntity, ExtendedEntityData, Line, RegisteredClassEntityData}; +use acadrust::objects::{ProxyObjectReference, ProxyPayload, ProxyReferenceKind}; +use acadrust::types::{DxfVersion, Vector3}; +use cadcraft_doc::EntityKind; +use cadcraft_io::{SaveOptions, Version}; +use std::io::Cursor; + +fn source(version: DxfVersion) -> Vec { + source_payload(version, ProxyPayload::from_bits(&[0xA5, 0x80], 9)) +} + +fn source_payload(version: DxfVersion, payload: ProxyPayload) -> Vec { + let mut document = acadrust::CadDocument::new(); + document.version = version; + document.classes.add_or_update(DxfClass::new_entity("SPDSNOTEPOSITION", "mcsDbObjectNotePosition")); + let target = document.add_entity(EntityType::Line(Line::from_points(Vector3::ZERO, Vector3::new(10.0, 0.0, 0.0)))).unwrap(); + document + .add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon { graphic_data: Some(vec![0x12, 0x34, 0x56]), ..Default::default() }, + data: ExtendedEntityData::RegisteredClass(RegisteredClassEntityData { + dxf_name: "SPDSNOTEPOSITION".into(), + cpp_class_name: "mcsDbObjectNotePosition".into(), + properties: vec![], + payload, + object_ids: vec![ProxyObjectReference { kind: ProxyReferenceKind::HardPointer, handle: target }], + }), + }))) + .unwrap(); + acadrust::DwgWriter::write_to_vec(&document).unwrap() +} + +fn check(bytes: &[u8], name: &str) -> cadcraft_doc::Drawing { + let drawing = cadcraft_io::read(bytes, name).unwrap(); + assert_eq!(drawing.entity_count(), 2); + let line = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Line(_))).unwrap().handle; + let unknown = drawing + .model + .iter() + .find_map(|e| match &e.kind { + EntityKind::Unknown(u) => Some(u), + _ => None, + }) + .unwrap(); + assert!(unknown.tags.iter().any(|t| t.code == 340 && t.value == line.hex())); + let dxf = if name.ends_with(".dwg") { cadcraft_dwg::dwg_to_dxf(bytes).unwrap() } else { bytes.to_vec() }; + let tags = cadcraft_dxf::parse(&dxf).unwrap(); + let sections = cadcraft_dxf::sections(&tags); + let classes = sections.iter().find(|s| s.name == "CLASSES").unwrap(); + let classes = cadcraft_dxf::records(&classes.tags); + let decoded = acadrust::DxfReader::from_reader(Cursor::new(dxf)).unwrap().read().unwrap(); + let proxy = decoded + .entities() + .find_map(|e| match e { + EntityType::Extended(e) => match &e.data { + ExtendedEntityData::Proxy(p) => Some(p), + _ => None, + }, + _ => None, + }) + .unwrap(); + assert_eq!(proxy.payload.bit_count, 9); + assert_eq!(proxy.payload.data(), [0xA5, 0x80]); + assert_eq!(proxy.graphics.data(), [0x12, 0x34, 0x56]); + let class = classes.get(usize::try_from(proxy.class_id - 500).unwrap()).unwrap(); + assert!(class.1.iter().any(|t| t.code == 1 && t.str() == "SPDSNOTEPOSITION")); + assert!(class.1.iter().any(|t| t.code == 2 && t.str() == "mcsDbObjectNotePosition")); + drawing +} + +#[test] +fn opaque_registered_entities_survive_repeated_saves_with_their_original_class() { + for source_version in [DxfVersion::AC1015, DxfVersion::AC1027, DxfVersion::AC1032] { + let input = source(source_version); + let initial = check(&input, "source.dwg"); + for target in [Version::R2013, Version::R2018] { + for name in ["copy.dxf", "copy.dwg"] { + let mut drawing = initial.clone(); + for _ in 0..3 { + let bytes = cadcraft_io::write_with(&drawing, name, &SaveOptions { version: Some(target), ..Default::default() }).unwrap(); + drawing = check(&bytes, name); + } + } + } + } +} + +#[test] +fn legacy_dwg_leaves_proxies_out_while_legacy_dxf_retains_the_data() { + let drawing = check(&source(DxfVersion::AC1032), "source.dwg"); + for target in [Version::R2000, Version::R2004, Version::R2007, Version::R2010] { + let options = SaveOptions { version: Some(target), ..Default::default() }; + // A DWG before 2013 can't name the proxy's class: it is left out, and the rest is saved. + let bytes = cadcraft_io::write_with(&drawing, "old.dwg", &options).unwrap(); + let reread = cadcraft_io::read(&bytes, "old.dwg").unwrap(); + assert_eq!(reread.entity_count(), 1, "{target:?}"); + assert!(reread.model.iter().all(|e| matches!(e.kind, EntityKind::Line(_))), "{target:?}"); + let bytes = cadcraft_io::write_with(&drawing, "old.dxf", &options).unwrap(); + check(&bytes, "old.dxf"); + } +} + +fn duplicate_class_dxf() -> Vec { + let mut text = String::from("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n0\nENDSEC\n0\nSECTION\n2\nCLASSES\n"); + for (cpp, entity, flags) in [("First", 1, 1025), ("Second", 1, 128), ("Object", 0, 17)] { + text.push_str(&format!("0\nCLASS\n1\nCUSTOM\n2\n{cpp}\n3\nSynthetic\n90\n{flags}\n91\n1\n280\n1\n281\n{entity}\n")); + } + text.push_str("0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n10\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n11\n10\n21\n0\n"); + for (handle, class) in [("20", 500), ("21", 501)] { + text.push_str(&format!("0\nACAD_PROXY_ENTITY\n5\n{handle}\n100\nAcDbEntity\n8\n0\n100\nAcDbProxyEntity\n90\n498\n91\n{class}\n92\n0\n93\n9\n310\nA580\n330\n10\n340\n10\n350\n10\n360\n10\n94\n0\n95\n33\n70\n0\n")); + } + text.push_str("0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n3\nCUSTOM_OBJECT\n350\n30\n0\nACAD_PROXY_OBJECT\n5\n30\n330\nC\n100\nAcDbProxyObject\n90\n499\n91\n502\n93\n9\n310\nA580\n340\n10\n94\n0\n95\n33\n70\n0\n0\nENDSEC\n0\nEOF\n"); + text.into_bytes() +} + +#[test] +fn duplicate_names_keep_distinct_classes_for_entities_and_dictionary_objects() { + let source = duplicate_class_dxf(); + for binary in [false, true] { + let input = if binary { cadcraft_dxf::write_binary(&cadcraft_dxf::parse(&source).unwrap(), true) } else { source.clone() }; + let mut drawing = cadcraft_io::read(&input, "source.dxf").unwrap(); + for _ in 0..3 { + for name in ["copy.dxf", "copy.dwg"] { + let bytes = cadcraft_io::write_with(&drawing, name, &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + let dxf = if name.ends_with(".dwg") { cadcraft_dwg::dwg_to_dxf(&bytes).unwrap() } else { bytes.clone() }; + let tags = cadcraft_dxf::parse(&dxf).unwrap(); + let sections = cadcraft_dxf::sections(&tags); + let classes = cadcraft_dxf::records(§ions.iter().find(|s| s.name == "CLASSES").unwrap().tags); + let custom: Vec<_> = classes.iter().filter(|(_, t)| t.iter().any(|t| t.code == 1 && t.str() == "CUSTOM")).collect(); + assert_eq!(custom.len(), 3); + for (class, (cpp, flags)) in custom.iter().zip([("First", 1025), ("Second", 128), ("Object", 17)]) { + assert!(class.1.iter().any(|t| t.code == 2 && t.str() == cpp)); + assert!(class.1.iter().any(|t| t.code == 90 && t.i64() == flags)); + assert!(class.1.iter().any(|t| t.code == 3 && t.str() == "Synthetic")); + assert!(class.1.iter().any(|t| t.code == 280 && t.i64() == 1)); + } + let records: Vec<_> = + sections.iter().flat_map(|s| cadcraft_dxf::records(&s.tags)).filter(|(kind, _)| kind.starts_with("ACAD_PROXY_")).collect(); + assert_eq!(records.len(), 3); + let mut identities = Vec::new(); + for (_, tags) in &records { + let id = tags.iter().find(|t| t.code == 91).unwrap().i64(); + identities.push(classes[usize::try_from(id - 500).unwrap()].1.iter().find(|t| t.code == 2).unwrap().str()); + assert!(tags.iter().any(|t| matches!(t.code, 93 | 161) && t.i64() == 9), "{name}: {tags:?}"); + assert!(tags.iter().any(|t| t.code == 310 && t.str() == "A580")); + } + identities.sort(); + assert_eq!(identities, ["First", "Object", "Second"]); + drawing = cadcraft_io::read(&bytes, name).unwrap(); + assert_eq!(drawing.entity_count(), 3); + let line = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Line(_))).unwrap().handle.hex(); + for entity in drawing.model.iter().filter_map(|e| if let EntityKind::Unknown(u) = &e.kind { Some(u) } else { None }) { + for code in [330, 340, 350, 360] { + assert!(entity.tags.iter().any(|t| t.code == code && t.value == line), "missing reference {code}"); + } + } + } + } + } +} + +#[test] +fn zero_bit_opaque_entities_are_still_retained() { + let source = source_payload(DxfVersion::AC1032, ProxyPayload::default()); + let mut drawing = cadcraft_io::read(&source, "source.dwg").unwrap(); + for name in ["copy.dxf", "copy.dwg", "again.dwg"] { + let bytes = cadcraft_io::write_with(&drawing, name, &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + drawing = cadcraft_io::read(&bytes, name).unwrap(); + assert_eq!(drawing.entity_count(), 2); + assert!(drawing.model.iter().any(|e| matches!(e.kind, EntityKind::Unknown(_)))); + } +} + +#[test] +fn proxies_inside_block_definitions_survive_repeated_saves() { + use cadcraft_doc::{Block, Common, Entity}; + let mut drawing = check(&source(DxfVersion::AC1032), "source.dwg"); + let kind = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Unknown(_))).unwrap().kind.clone(); + let handle = drawing.new_handle(); + let mut block = Block::new("CUSTOM_BLOCK"); + block.entities.push(Entity { handle, common: Common::default(), kind }); + drawing.blocks.insert("CUSTOM_BLOCK".into(), std::sync::Arc::new(block)); + for name in ["copy.dxf", "copy.dwg", "again.dwg"] { + let bytes = cadcraft_io::write_with(&drawing, name, &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + drawing = check(&bytes, name); + let block = drawing.blocks.get("CUSTOM_BLOCK").unwrap(); + assert_eq!(block.entities.len(), 1); + assert!(block.entities.iter().any(|e| matches!(e.kind, EntityKind::Unknown(_)))); + } +} + +#[test] +fn unused_malformed_classes_do_not_block_plain_geometry() { + for (name, cpp, flags, count) in [("", "Unused", 0, 0), ("UNUSED", "", 0, 0), ("UNUSED", "Unused", 65536, 0), ("UNUSED", "Unused", 0, i64::MAX)] { + let dxf = format!( + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n0\nENDSEC\n0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\n{name}\n2\n{cpp}\n3\nSynthetic\n90\n{flags}\n91\n{count}\n281\n1\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n10\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n2\n20\n3\n11\n12\n21\n13\n0\nENDSEC\n0\nEOF\n" + ); + let bytes = cadcraft_dwg::dxf_to_dwg_as(dxf.as_bytes(), "AC1032").unwrap(); + let drawing = cadcraft_io::read(&bytes, "plain.dwg").unwrap(); + let lines: Vec<_> = drawing.model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l) } else { None }).collect(); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0].a.x, 2.0); + assert_eq!(lines[0].a.y, 3.0); + assert_eq!(lines[0].b.x, 12.0); + assert_eq!(lines[0].b.y, 13.0); + } +} + +#[test] +fn proxy_spelling_is_preserved_in_dxf_and_normalized_only_for_dwg() { + let source = String::from_utf8(duplicate_class_dxf()).unwrap(); + for (entity, object) in [("acad_proxy_entity", "acad_proxy_object"), ("AcAd_PrOxY_EnTiTy", "AcAd_PrOxY_ObJeCt")] { + let dxf = source.replace("ACAD_PROXY_ENTITY", entity).replace("ACAD_PROXY_OBJECT", object); + let drawing = cadcraft_io::read(dxf.as_bytes(), "source.dxf").unwrap(); + assert_eq!(drawing.entity_count(), 3); + let out = cadcraft_io::write_with(&drawing, "copy.dxf", &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + let tags = cadcraft_dxf::parse(&out).unwrap(); + assert!(tags.iter().any(|t| t.code == 0 && t.str() == entity)); + let bytes = cadcraft_io::write_with(&drawing, "copy.dwg", &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + let decoded = cadcraft_dwg::dwg_to_dxf(&bytes).unwrap(); + let tags = cadcraft_dxf::parse(&decoded).unwrap(); + let proxies: Vec<_> = cadcraft_dxf::sections(&tags) + .iter() + .flat_map(|s| cadcraft_dxf::records(&s.tags)) + .filter(|(kind, _)| kind.starts_with("ACAD_PROXY_")) + .collect(); + assert_eq!(proxies.len(), 3); + for (_, tags) in proxies { + assert!(tags.iter().any(|t| t.code == 310 && t.str() == "A580")); + assert!(tags.iter().any(|t| matches!(t.code, 93 | 161) && t.i64() == 9)); + } + let recovered = cadcraft_io::read(&bytes, "copy.dwg").unwrap(); + assert_eq!(recovered.entity_count(), 3); + } +} + +/// Exercise the actual ASCII bridge, which writes Unicode as CIF escapes. +#[test] +fn unicode_class_identity_survives_the_ascii_bridge() { + let mut tags = cadcraft_dxf::parse(&duplicate_class_dxf()).unwrap(); + for tag in &mut tags { + let text = tag.str(); + let replacement = match (tag.code, text.as_str()) { + (1, "CUSTOM") => Some("Объект"), + (2, "First") => Some("Первый"), + (2, "Second") => Some("Второй"), + (2, "Object") => Some("ОбъектКласс"), + (3, "Synthetic") => Some("Café🙂"), + _ => None, + }; + if let Some(text) = replacement { + *tag = cadcraft_dxf::Tag::s(tag.code, text); + } + } + let text = cadcraft_dxf::write_ascii(&tags); + assert!(text.contains("\\U+")); + let mut drawing = cadcraft_io::read(text.as_bytes(), "unicode.dxf").unwrap(); + for _ in 0..2 { + let bytes = cadcraft_io::write_with(&drawing, "copy.dwg", &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + let decoded = acadrust::DwgReader::from_stream(std::io::Cursor::new(&bytes)).read().unwrap(); + let classes: Vec<_> = decoded.classes.iter().filter(|c| c.dxf_name == "Объект").collect(); + assert_eq!(classes.len(), 3); + for (class, cpp) in classes.iter().zip(["Первый", "Второй", "ОбъектКласс"]) { + assert_eq!(class.cpp_class_name, cpp); + assert_eq!(class.application_name, "Café🙂"); + } + drawing = cadcraft_io::read(&bytes, "copy.dwg").unwrap(); + assert_eq!(drawing.entity_count(), 3); + } +} + +/// A malformed unused class must not silently collapse two otherwise valid class identities. +#[test] +fn ambiguous_fallback_classes_are_reported_without_losing_plain_geometry() { + for escaped in [false, true] { + let mut source = String::from_utf8(duplicate_class_dxf()).unwrap().replacen( + "0\nENDSEC\n0\nSECTION\n2\nENTITIES", + "0\nCLASS\n1\nUNUSED\n2\nUnused\n90\n65536\n0\nENDSEC\n0\nSECTION\n2\nENTITIES", + 1, + ); + if escaped { + // Different DXF spellings decode to the same name. The unrelated object class + // remains unambiguous and must still be written. + source = source.replace("1\nCUSTOM\n2\nSecond", "1\n\\U+0043USTOM\n2\nSecond"); + source = source.replace("1\nCUSTOM\n2\nObject", "1\nOTHER\n2\nObject"); + } + let (bytes, unwritten) = cadcraft_dwg::dxf_to_dwg_noted(source.as_bytes(), "AC1032").unwrap(); + assert_eq!(unwritten.get("ACAD_PROXY_ENTITY"), Some(&2)); + assert_eq!(unwritten.get("ACAD_PROXY_OBJECT"), if escaped { None } else { Some(&1) }); + let drawing = cadcraft_io::read(&bytes, "copy.dwg").unwrap(); + assert_eq!(drawing.entity_count(), 1); + assert!(drawing.model.iter().all(|e| matches!(e.kind, EntityKind::Line(_)))); + } +} diff --git a/crates/io/tests/shx_text.rs b/crates/io/tests/shx_text.rs new file mode 100644 index 000000000..bd04a031b --- /dev/null +++ b/crates/io/tests/shx_text.rs @@ -0,0 +1,35 @@ +//! Synthetic DXF STYLE -> TEXT/MTEXT -> display list, without external font fixtures. + +use cadcraft_doc::Space; + +fn font() -> Vec { + let mut bytes = b"AutoCAD-86 unifont 1.0\r\n\x1a".to_vec(); + bytes.extend_from_slice(&[4, 0, 0, 0, 8, 0]); + bytes.extend_from_slice(&[b's', 0, 6, 2, 2, 0, 0, 0]); + for (id, program) in + [(32u16, vec![2, 8, 3, 0, 0]), (65, vec![8, 0, 6, 8, 4, 250, 2, 8, 3, 0, 0]), (193, vec![7, 0, 65, 5, 2, 8, 252, 7, 1, 8, 2, 1, 6, 0])] + { + bytes.extend_from_slice(&id.to_le_bytes()); + bytes.extend_from_slice(&(program.len() as u16 + 1).to_le_bytes()); + bytes.push(0); + bytes.extend(program); + } + bytes +} + +#[test] +fn shx_style_and_unicode_escapes_render_as_native_strokes_and_roundtrip() { + cadcraft_fonts::shx::register("cadcraft-io-synthetic.shx", &font()).unwrap(); + let dxf = "0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nSTYLE\n0\nSTYLE\n2\nR80\n3\ncadcraft-io-synthetic.shx\n0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nTEXT\n7\nR80\n10\n0\n20\n0\n40\n6\n1\nA\\U+00C1\n0\nMTEXT\n7\nR80\n10\n0\n20\n-20\n40\n6\n41\n18\n1\nA\\U+00C1 A\\U+00C1\n0\nENDSEC\n0\nEOF\n"; + let drawing = cadcraft_io::read(dxf.as_bytes(), "synthetic.dxf").unwrap(); + let display = cadcraft_render::build(&drawing, &Space::Model, &cadcraft_render::Options::default()); + assert!(display.tris.is_empty(), "SHX letters and accents are strokes, not filled TrueType outlines"); + assert!(display.verts.iter().any(|p| (p.x - 11.0).abs() < 1e-9), "native advance of 7, not the built-in advance"); + assert!(display.verts.iter().any(|p| p.y > 6.0), "accent above the cap height"); + assert!(display.verts.iter().any(|p| p.y < -27.0), "MTEXT wraps its second word"); + let saved = cadcraft_io::write_dxf(&drawing); + let reopened = cadcraft_io::read(saved.as_bytes(), "synthetic.dxf").unwrap(); + let again = cadcraft_render::build(&reopened, &Space::Model, &cadcraft_render::Options::default()); + assert_eq!(display.verts, again.verts); + assert!(again.tris.is_empty()); +} diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 1359fbdda..cb597504f 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -17,3 +17,10 @@ serde_json = { workspace = true } log = { workspace = true } # Secure randomness for the per-session control token (MIT OR Apache-2.0). getrandom = "0.4" + +[dev-dependencies] +# Reads the pixels of rendered PNGs in the tests. +tiny-skia = { workspace = true } +[target.'cfg(unix)'.dependencies] +# O_NOFOLLOW when reading the token file (MIT OR Apache-2.0). +libc = "0.2" diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 913569e82..efdb9c9ea 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -1,7 +1,7 @@ //! Where MCP tool calls end up: a control-channel method call. use std::io::{BufRead, BufReader, Read, Write}; -use std::net::{TcpStream, ToSocketAddrs}; +use std::net::{Ipv4Addr, SocketAddr, TcpStream, ToSocketAddrs}; use std::time::Duration; use cadcraft_engine::Session; @@ -76,9 +76,17 @@ impl Remote { /// The per-session token for this port, read (and cached) from the owner-only token file. A /// missing file is not fatal here: the request is sent without a token and the server replies /// with an authentication error the user can act on. + /// + /// The desktop app listens only on `127.0.0.1:PORT`, so the token goes only to that exact + /// peer: a name that also resolves elsewhere (`localhost` → `::1`, where another local account + /// may listen on the same port) must not be handed the desktop's credential (CWE-522). fn token(&mut self) -> Option<&str> { + let port = port_of(&self.addr)?; + let peer = self.conn.as_ref().and_then(|(_, s)| s.peer_addr().ok()); + if peer != Some(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) { + return None; + } if self.token.is_none() - && let Some(port) = port_of(&self.addr) && let Ok(t) = crate::control_token::read(port) { self.token = Some(t); @@ -207,6 +215,14 @@ fn is_read_only(method: &str) -> bool { impl Remote { /// Put the current token (if any) on `req`, replacing the one it carries. + /// Connect if needed, put the token for the peer actually connected to on `req`, and send it. + fn sign_and_send(&mut self, req: &mut Value) -> Result { + if self.conn.is_none() { + self.reach().map_err(|e| (e, false))?; + } + self.set_token(req); + self.roundtrip(&req.to_string()) + } fn set_token(&mut self, req: &mut Value) { let token = self.token().map(str::to_string); if let Some(obj) = req.as_object_mut() { @@ -219,7 +235,7 @@ impl Remote { /// Send `req` and parse the reply, refreshing the token before a safe retry after a transport /// error. A mutation that may have reached the server is never resent automatically. fn exchange(&mut self, method: &str, req: &mut Value) -> Result { - let reply = match self.roundtrip(&req.to_string()) { + let reply = match self.sign_and_send(req) { Ok(r) => r, Err((e, sent)) => { self.token = None; @@ -232,8 +248,7 @@ impl Remote { )); } // A restarted server may have rotated its token before dropping the old socket. - self.set_token(req); - self.roundtrip(&req.to_string()).map_err(|(e, _)| { + self.sign_and_send(req).map_err(|(e, _)| { self.token = None; self.conn = None; format!("CADCraft at {}: {e}", self.addr) @@ -256,14 +271,12 @@ impl Backend for Remote { let id = self.next_id; self.next_id += 1; let mut req = json!({"id": id, "method": method, "params": params}); - self.set_token(&mut req); let mut v = self.exchange(method, &mut req)?; // The token is read before `--launch` opens the app, which then writes a new one (#2087); the // file can also be left over from an earlier session. Once, so a wrong token can't loop. if unauthorized(&v) && v.get("state").and_then(Value::as_str) == Some("not-run") { self.token = None; self.conn = None; - self.set_token(&mut req); v = self.exchange(method, &mut req)?; } if v.get("ok").and_then(Value::as_bool) == Some(true) { @@ -300,7 +313,7 @@ const HEADLESS_METHODS: &[(&str, &str, &str)] = &[ ("engine.execute", "{command, params}", "Run any command with JSON parameters. Never opens a dialog."), ("engine.commands", "", "Every command: id, label, menu path, shortcut, aliases, params doc, enabled."), ("drawing.inspect", "{entities?, limit?}", "Drawing summary and entities with handles and geometry."), - ("ui.render", "{path?, width?, height?, fit?}", "Render the drawing; replies pngBase64."), + ("ui.render", "{path?, width?, height?, fit?, window?, background?, plot_style?}", "Render the drawing; replies pngBase64."), ("app.open", "{path}", "Open a drawing."), ("app.save", "{path?}", "Save the drawing (Save As with a path)."), ("control.methods", "", "This list."), @@ -400,7 +413,14 @@ impl Backend for Headless { let h = p.get("height").and_then(Value::as_f64).unwrap_or(1000.0).clamp(16.0, 8192.0) as u32; let st = s.state().map_err(|e| e.to_string())?; let window = render_window(&p); - let opts = cadcraft_render::Options { view: window, transparency: s.settings.transparency_display, ..Default::default() }; + // `background` and `plot_style` (#803), read as the app reads them. + let look = cadcraft_engine::render_look::RenderLook::from_params(&st.doc, &p)?; + let opts = cadcraft_render::Options { + view: window, + transparency: s.settings.transparency_display, + plot_style_table: look.plot_style_table.clone(), + ..Default::default() + }; let list = cadcraft_render::build(&st.doc, &st.space, &opts); let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(true); let side = |k: &str| p.get(k).and_then(Value::as_f64).map(|x| x as u32); @@ -413,8 +433,7 @@ impl Backend for Headless { cadcraft_render::raster::View { center: v.center, scale: f64::from(h) / v.height.max(1e-12), width: w, height: h } }; let (w, h) = (view.width, view.height); - let png = - cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default()).ok_or("render failed")?; + let png = cadcraft_render::raster::render_png(&list, &view, &look.raster()).ok_or("render failed")?; let mut r = json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "truncated": list.truncated}); if let Some(path) = str_p("path") { @@ -589,6 +608,24 @@ mod tests { }) } + /// A listener on another loopback address with the desktop's port (here `::1`) never receives + /// the desktop's token. + #[test] + fn token_is_not_sent_to_another_loopback_listener() { + let Ok(listener) = TcpListener::bind("[::1]:0") else { return }; + let addr = listener.local_addr().unwrap(); + crate::control_token::issue(addr.port()).unwrap(); + let server = fake_app(listener, move |req, _| { + assert!(req.get("token").is_none(), "token leaked to {addr}"); + json!({"ok": true, "result": "x"}) + }); + let mut remote = Remote::lazy(&addr.to_string(), false); + let got = remote.call("ping", json!({})); + crate::control_token::revoke(addr.port()); + assert_eq!(got, Ok(json!("x"))); + assert_eq!(server.join().unwrap(), 1); + } + /// `--launch` reads the token before it opens the app, so the first request carries the token /// of an earlier session (or none); the app refuses it without running it, and the call is /// resent once with the token the app has just written (#2087). diff --git a/crates/mcp/src/control_token.rs b/crates/mcp/src/control_token.rs index 084f8b455..97052be60 100644 --- a/crates/mcp/src/control_token.rs +++ b/crates/mcp/src/control_token.rs @@ -32,7 +32,9 @@ fn private_dir() -> io::Result { if let Some(h) = std::env::var_os("HOME").filter(|v| !v.is_empty()) { return Ok(PathBuf::from(h).join(".cache")); } - Ok(std::env::temp_dir()) + // The shared temporary directory would put the credential at a path any local account can + // predict and plant a link at: refuse instead. + Err(io::Error::new(io::ErrorKind::NotFound, "XDG_RUNTIME_DIR or HOME is required for a private control token")) } /// Require the Windows per-user local app-data directory for session token storage. @@ -75,7 +77,31 @@ fn issue_at(path: &std::path::Path, bytes: &[u8]) -> io::Result<()> { /// Read the token for `port`, trimming trailing whitespace. Used by clients (the MCP bridge). pub fn read(port: u16) -> io::Result { - let raw = std::fs::read_to_string(token_path(port)?)?; + read_at(&token_path(port)?) +} + +/// Read a token file the issuer wrote: not through a link, a plain file, and (Unix) readable by +/// its owner only, so a file another account planted or left open is not taken as the credential. +fn read_at(path: &std::path::Path) -> io::Result { + use std::io::Read; + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + let file = options.open(path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(io::Error::new(io::ErrorKind::InvalidData, "the control token is not a plain file")); + } + #[cfg(unix)] + if std::os::unix::fs::PermissionsExt::mode(&meta.permissions()) & 0o077 != 0 { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "the control token file is readable by other users")); + } + let mut raw = String::new(); + file.take(1024).read_to_string(&mut raw)?; let token = raw.trim().to_string(); if token.is_empty() { return Err(io::Error::new(io::ErrorKind::InvalidData, "empty control token")); @@ -181,6 +207,24 @@ mod tests { assert_eq!(windows_private_dir(Some("private-app-data".into())).unwrap(), PathBuf::from("private-app-data")); } + /// A link, or a file other users can read, is not accepted as the token. + #[cfg(unix)] + #[test] + fn read_refuses_links_and_shared_files() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("cadcraft-token-read-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let secret = dir.join("secret"); + issue_at(&secret, b"abc").unwrap(); + assert_eq!(read_at(&secret).unwrap(), "abc"); + let link = dir.join("link"); + std::os::unix::fs::symlink(&secret, &link).unwrap(); + assert!(read_at(&link).is_err()); + std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!(read_at(&secret).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + /// Token issuance creates its missing directory hierarchy before writing the credential. #[test] fn issuance_creates_missing_parent() { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 9a437b076..b7eee854e 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -259,3 +259,135 @@ fn a_lazy_bridge_starts_without_the_app_and_says_how_to_open_it() { assert_ne!(r["result"]["isError"], json!(true), "{r}"); app.join().unwrap(); } + +/// The pixels of a `render` tool result. +fn render_pixels(s: &mut Server, args: Value) -> tiny_skia::Pixmap { + let img = tool(s, "render", args); + assert_eq!(img["type"], "image", "{img}"); + let png = cadcraft_engine::cmd::file::base64_decode(img["data"].as_str().unwrap()).unwrap(); + tiny_skia::Pixmap::decode_png(&png).unwrap() +} + +/// The RGB of pixel (x, y). +fn rgb(pm: &tiny_skia::Pixmap, x: u32, y: u32) -> (u8, u8, u8) { + let c = pm.pixel(x, y).unwrap(); + (c.red(), c.green(), c.blue()) +} + +/// The pixel of the middle column that differs most from the corner: what the line along the +/// middle of the image is drawn with. +fn ink(pm: &tiny_skia::Pixmap) -> (u8, u8, u8) { + let bg = rgb(pm, 0, 0); + let far = |c: &(u8, u8, u8)| bg.0.abs_diff(c.0) as u32 + bg.1.abs_diff(c.1) as u32 + bg.2.abs_diff(c.2) as u32; + (0..pm.height()).map(|y| rgb(pm, pm.width() / 2, y)).max_by_key(far).unwrap() +} + +/// A drawing with one line along y = 0: colour 7 (layer 0's colour), or red on a red layer. +fn line_drawing(red: bool) -> Server { + let mut s = Server::new(Box::new(Headless::default())); + if red { + tool(&mut s, "execute", json!({"command": "layer.new", "params": {"name": "Red", "color": "red", "current": true}})); + } + tool(&mut s, "execute", json!({"command": "line", "params": {"points": [[0, 0], [10, 0]]}})); + s +} + +/// Around the line, which runs along the middle of pixel row 20 of a 120 x 40 image (not on a +/// pixel edge, so it isn't blended across two rows). +const WINDOW: [[f64; 2]; 2] = [[-1.0, -1.95], [11.0, 2.05]]; + +/// Guards #803: `render` draws on the background asked for (`white`, `paper`, `#rrggbb`) and a +/// colour-7 line follows it, as on a plot: dark on white, light on the dark canvas, which stays +/// the default. +#[test] +fn render_draws_on_the_background_asked_for() { + let mut s = line_drawing(false); + let dark = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40})); + assert_eq!(rgb(&dark, 0, 0), (33, 40, 48), "the default stays the dark canvas"); + let (r, g, b) = ink(&dark); + assert!(r > 200 && g > 200 && b > 200, "colour 7 is light on the dark canvas: {:?}", (r, g, b)); + for bg in ["white", "paper", "WHITE"] { + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": bg})); + let (w, h) = (pm.width(), pm.height()); + for (x, y) in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)] { + assert_eq!(rgb(&pm, x, y), (255, 255, 255), "{bg}: corner ({x}, {y})"); + } + let (r, g, b) = ink(&pm); + assert!(r < 128 && g < 128 && b < 128, "{bg}: colour 7 is drawn dark on white: {:?}", (r, g, b)); + } + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": "#336699"})); + assert_eq!(rgb(&pm, 0, 0), (0x33, 0x66, 0x99)); + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": "dark"})); + assert_eq!(rgb(&pm, 0, 0), (33, 40, 48)); +} + +/// Guards #803: `plot_style` draws with a built-in plot style table: `monochrome.ctb` turns a red +/// line black, which without one stays red. +#[test] +fn render_draws_with_the_plot_style_asked_for() { + let mut s = line_drawing(true); + let plain = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": "white"})); + let (r, g, b) = ink(&plain); + assert!(r > 200 && g < 100 && b < 100, "red without a plot style: {:?}", (r, g, b)); + for table in ["monochrome.ctb", "Monochrome", "monochrome.CTB"] { + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": "white", "plot_style": table})); + let (r, g, b) = ink(&pm); + assert!(r < 100 && r == g && g == b, "{table}: red plots black: {:?}", (r, g, b)); + } + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": "white", "plot_style": "grayscale.ctb"})); + let (r, g, b) = ink(&pm); + assert!(r == g && g == b, "grayscale.ctb draws red grey: {:?}", (r, g, b)); +} + +/// Guards #803: a plot style alone plots on white, as on paper, so `monochrome.ctb` doesn't draw +/// black on the dark canvas; `background` still wins, and `plot_style: "none"` keeps the canvas +/// and the objects' colours. +#[test] +fn render_with_a_plot_style_plots_on_white() { + for red in [false, true] { + let mut s = line_drawing(red); + for table in ["monochrome.ctb", "grayscale.ctb"] { + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "plot_style": table})); + assert_eq!(rgb(&pm, 0, 0), (255, 255, 255), "{table} without a background plots on white"); + let (r, g, b) = ink(&pm); + assert!(r == g && g == b && r < 128, "{table}, red {red}: drawn dark grey or black on white: {:?}", (r, g, b)); + } + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "plot_style": "monochrome.ctb", "background": "dark"})); + assert_eq!(rgb(&pm, 0, 0), (33, 40, 48), "an explicit background wins"); + for none in ["none", ""] { + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "plot_style": none})); + assert_eq!(rgb(&pm, 0, 0), (33, 40, 48), "{none:?} keeps the dark canvas"); + let (r, g, b) = ink(&pm); + let light = r > 200 && g > 200 && b > 200; + assert!(if red { r > 200 && g < 100 && b < 100 } else { light }, "{none:?}, red {red}: own colour {:?}", (r, g, b)); + } + } +} + +/// Guards #803: an unknown `background` or `plot_style` is refused with what is accepted, not +/// drawn some other way; a value of the wrong type is invalid params. +#[test] +fn render_refuses_unknown_backgrounds_and_plot_styles() { + let mut s = line_drawing(false); + for (args, wants) in [ + (json!({"background": "purple"}), "#rrggbb"), + (json!({"background": "#12345"}), "#rrggbb"), + (json!({"background": "336699"}), "#rrggbb"), + (json!({"background": ""}), "#rrggbb"), + (json!({"plot_style": "nope.ctb"}), "monochrome.ctb"), + (json!({"plot_style": "default.ctx"}), "monochrome.ctb"), + ] { + let r = call(&mut s, 1, "tools/call", json!({"name": "render", "arguments": args.clone()})); + assert_eq!(r["result"]["isError"], json!(true), "{args} must be refused, not drawn"); + let msg = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(msg.contains(wants), "{args}: {msg}"); + } + for args in [json!({"background": 7}), json!({"plot_style": ["monochrome.ctb"]})] { + let r = call(&mut s, 2, "tools/call", json!({"name": "render", "arguments": args.clone()})); + assert_eq!(r["error"]["code"], -32602, "{args} must be invalid params"); + } + // The headless control method refuses them too. + let mut h = Headless::default(); + assert!(crate::Backend::call(&mut h, "ui.render", json!({"background": "purple"})).is_err()); + assert!(crate::Backend::call(&mut h, "ui.render", json!({"plot_style": 3})).is_err()); +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 2c432d608..8518a9aff 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -22,9 +22,11 @@ pub fn tool_definitions(has_ui: bool) -> Value { "inputSchema": {"type": "object", "properties": {"type": {"type": "string"}, "layer": {"type": "string"}, "selected": {"type": "boolean"}, "window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2}, "crossing": {"type": "boolean"}, "limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}), - json!({"name": "render", "description": "Render the active drawing to a PNG and return it as an image: fitted to the extents by default, or just the area `window` [[x0,y0],[x1,y1]] (drawing units), e.g. one sheet or one room of a large drawing. With a window and no size the image is 1600 px wide with the window's shape.", + json!({"name": "render", "description": "Render the active drawing to a PNG and return it as an image content block (content[0].type is \"image\", not text): fitted to the extents by default, or just the area `window` [[x0,y0],[x1,y1]] (drawing units), e.g. one sheet or one room of a large drawing. With a window and no size the image is 1600 px wide with the window's shape. `background`: \"dark\" (the canvas; the default without a plot style), \"white\" (the default with one, as a plot prints on paper), \"paper\" or \"#rrggbb\"; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. \"monochrome.ctb\" (every colour black, as most plots) or \"grayscale.ctb\", which make light colours readable on white; \"none\" (or \"\") draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown background or plot style is refused.", "inputSchema": {"type": "object", "properties": {"width": {"type": "integer", "minimum": 16}, "height": {"type": "integer", "minimum": 16}, "fit": {"type": "boolean"}, "window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2}, + "background": {"type": "string", "description": "\"dark\" (default without plot_style), \"white\" (default with one), \"paper\" or \"#rrggbb\""}, + "plot_style": {"type": "string", "description": "a plot style table: monochrome.ctb, grayscale.ctb, default.ctb, default.stb, monochrome.stb, or one the drawing holds; \"none\" or \"\" for the objects' own properties"}, "path": {"type": "string"}}}}), json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.", "inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "layer": {"type": "string"}, diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index f779bff5b..5e362e5fc 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -227,6 +227,12 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { b.polyline(ctx, rgb, lw, l); } } + // An OLE object's content is not drawn; its frame, from its two corner points, is. + EntityKind::Unknown(u) if u.is_ole_frame() => { + if let Some(q) = cadcraft_doc::ole_frame(&u.tags) { + b.polyline(ctx, rgb, lw, &q); + } + } kind => { for prim in kind.prims() { match prim { diff --git a/crates/render/src/hatch.rs b/crates/render/src/hatch.rs index 1bfeb1b6c..d178cd5b9 100644 --- a/crates/render/src/hatch.rs +++ b/crates/render/src/hatch.rs @@ -12,7 +12,7 @@ use super::{Builder, Ctx, Ink, fill, ink, max_scale}; use cadcraft_color::{Color, Rgb}; use cadcraft_doc::library::{PatternLine, pattern_for}; use cadcraft_doc::{Drawing, Entity, Gradient, Hatch}; -use cadcraft_geom::{Bounds2, Polyline, Vec2, point_in_polygon}; +use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon}; use std::sync::atomic::{AtomicBool, Ordering}; /// Draw a hatch entity: `rgb` is its resolved colour, `tol` the chord tolerance. @@ -128,7 +128,17 @@ const MAX_DEDUP_COMPARISONS: u64 = 50_000_000; /// within islands alternate), 1 outer keeps the outermost loops and their first islands, 2 /// ignore keeps only the outermost loops. Nesting depth = how many other loops enclose a loop. pub fn fill_loops(h: &Hatch, tol: f64) -> Vec> { - let mut loops: Vec> = h.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(tol)).collect(); + // One point budget for all the loops: many short arcs across loops must not add up unbounded. + let mut budget = cadcraft_geom::MAX_TESSELLATED_POINTS; + // Source loops that are the same boundary up to start vertex and winding are tessellated once, so a + // duplicate cannot be sampled coarser than its twin by the shared budget and then escape `dedup_polygons`. + let mut seen = std::collections::HashSet::new(); + let mut loops: Vec> = h + .loops + .iter() + .filter(|l| seen.insert(canonical_key(&l.vertices))) + .map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.tessellate_within(tol, &mut budget)) + .collect(); dedup_polygons(&mut loops); let max_depth = match h.style { 1 => 1, @@ -146,6 +156,50 @@ pub fn fill_loops(h: &Hatch, tol: f64) -> Vec> { loops.iter().enumerate().filter(|(i, l)| depth(*i, l) <= max_depth).map(|(_, l)| l.clone()).collect() } +/// Start index of the least rotation of `s` (two-pointer scan, O(n)). +fn least_rotation(s: &[[u64; 3]]) -> usize { + let n = s.len(); + let (mut i, mut j, mut k) = (0, 1, 0); + while i < n && j < n && k < n { + let (a, b) = (s.get((i + k) % n), s.get((j + k) % n)); + if a == b { + k += 1; + continue; + } + if a > b { + i += k + 1; + } else { + j += k + 1; + } + if i == j { + j += 1; + } + k = 0; + } + i.min(j) +} + +/// A key equal for loops that are the same boundary starting at another vertex or wound the other way +/// (reversing moves each bulge to the other end of its edge and negates it). Exact bits only; the +/// tolerance-based `dedup_polygons` still catches near matches. +fn canonical_key(v: &[PolyVertex]) -> Vec<[u64; 3]> { + let bits = |x: f64| (x + 0.0).to_bits(); // -0.0 and 0.0 match + let n = v.len(); + let fwd: Vec<[u64; 3]> = v.iter().map(|q| [bits(q.p.x), bits(q.p.y), bits(q.bulge)]).collect(); + let rev: Vec<[u64; 3]> = (0..n) + .map(|j| { + let i = n - 1 - j; + let edge = v.get((i + n - 1) % n).map_or(0.0, |q| -q.bulge); + v.get(i).map_or([0; 3], |q| [bits(q.p.x), bits(q.p.y), bits(edge)]) + }) + .collect(); + let rotated = |s: &[[u64; 3]]| { + let k = least_rotation(s); + s.iter().cycle().skip(k).take(s.len()).copied().collect::>() + }; + rotated(&fwd).min(rotated(&rev)) +} + /// A point of a loop to test its nesting with: the middle of its first non-degenerate edge /// (vertices may touch an enclosing loop; edge midpoints rarely do). fn probe(l: &[Vec2]) -> Option { @@ -367,6 +421,7 @@ pub fn reads_solid(d: &Drawing, h: &Hatch, px: f64) -> bool { /// `px`: a pixel in the hatch's units for the level of detail (a dash or dot repeat under two /// pixels is one continuous run); 0 = full detail, as plots, exports and picks use. `view`: only /// the part of the hatch inside it is generated; `None` = all of it. +#[cfg(test)] pub fn pattern_lines(d: &Drawing, h: &Hatch, loops: &[Vec], px: f64, view: Option<&Bounds2>) -> Vec> { pattern_lines_until(d, h, loops, px, view, None) } @@ -380,6 +435,21 @@ pub(crate) fn pattern_lines_until( px: f64, view: Option<&Bounds2>, cancel: Option<&AtomicBool>, +) -> Vec> { + pattern_lines_within(d, h, loops, px, view, cancel, MAX_RUNS, MAX_HATCH_WORK) +} + +/// [`pattern_lines_until`] with the most runs and the dash-work allowance given. +#[allow(clippy::too_many_arguments)] +fn pattern_lines_within( + d: &Drawing, + h: &Hatch, + loops: &[Vec], + px: f64, + view: Option<&Bounds2>, + cancel: Option<&AtomicBool>, + max_runs: usize, + work_limit: u64, ) -> Vec> { let lines = lines_of(d, h); let scale = scale_of(h); @@ -388,7 +458,7 @@ pub(crate) fn pattern_lines_until( // Shared work budget across all families and spans, counting dash-processing steps even when // they emit no geometry: gap-only families produce no runs, so `out.len()` alone cannot bound // their cost (CWE-400). - let mut work: u64 = MAX_HATCH_WORK; + let mut work: u64 = work_limit; for fam in &lines { // A family with dashes but no positive (ink) element can never draw: skip it so its gaps // are not swept at all. @@ -403,8 +473,8 @@ pub(crate) fn pattern_lines_until( continue; } let dashes: Vec = fam.dashes.iter().map(|d| d * scale).collect(); - Family { origin, ang, delta, spacing, dashes: &dashes }.sweep(loops, px, view, cancel, &mut out, &mut work); - if out.len() >= MAX_RUNS || work == 0 || is_set(cancel) { + Family { max_runs, origin, ang, delta, spacing, dashes: &dashes }.sweep(loops, px, view, cancel, &mut out, &mut work); + if out.len() >= max_runs || work == 0 || is_set(cancel) { break; } } @@ -415,6 +485,8 @@ pub(crate) fn pattern_lines_until( const SWATCH_REPEATS: f64 = 6.0; /// Most runs a swatch holds. const MAX_SWATCH_RUNS: usize = 4000; +/// The dash-work allowance of a swatch (a hatch's is [`MAX_HATCH_WORK`]). +const MAX_SWATCH_WORK: u64 = 2_000_000; /// A preview of a pattern for a pattern picker: the runs of its line families `lines` inside the /// `side` × `side` square with a corner at the origin, at a scale that shows a few repeats of the @@ -441,14 +513,19 @@ pub fn pattern_swatch(lines: &[PatternLine], side: f64) -> Vec> { pattern_lines: lines.to_vec(), }; let square = vec![Vec2::new(0.0, 0.0), Vec2::new(side, 0.0), Vec2::new(side, side), Vec2::new(0.0, side)]; - let mut runs = pattern_lines(&Drawing::default(), &h, &[square], 0.0, None); + // The generator stops at the swatch's own limits, so a compact pattern is never made in full + // (about a million runs) to keep a few thousand. + let mut runs = pattern_lines_within(&Drawing::default(), &h, &[square], 0.0, None, None, MAX_SWATCH_RUNS, MAX_SWATCH_WORK); runs.truncate(MAX_SWATCH_RUNS); + runs.shrink_to_fit(); runs } /// One pattern line family, scaled and placed: parallel lines `spacing` apart through `origin` /// at angle `ang`, each shifted along itself by `delta`'s along-line part from the last. struct Family<'a> { + /// Most runs the hatch may hold in all ([`MAX_RUNS`], less for a swatch). + max_runs: usize, origin: Vec2, ang: f64, delta: Vec2, @@ -487,6 +564,13 @@ impl Family<'_> { /// Intersect a pattern family with boundary loops, respecting view, output, cancellation, and shared dash-work limits. fn sweep(&self, loops: &[Vec], px: f64, view: Option<&Bounds2>, cancel: Option<&AtomicBool>, out: &mut Vec>, work: &mut u64) { + // Transforming the boundary is charged before it is done, at the scanline rate (one unit per 8 vertices). + let verts: u64 = loops.iter().map(|l| l.len() as u64).sum(); + let transform_charge = verts / 8 + 1; + if transform_charge > *work { + return; + } + *work -= transform_charge; let local: Vec> = loops.iter().map(|l| l.iter().map(|p| self.to_local(*p)).collect()).collect(); let bb = Bounds2::from_points(local.iter().flatten().copied()); if bb.is_empty() { @@ -505,10 +589,17 @@ impl Family<'_> { // family draws anything at all). let draws = self.dashes.iter().any(|d| *d >= 0.0); let solid_line = self.dashes.is_empty() || pat_len < 1e-12 || (px > 0.0 && pat_len < 2.0 * px && draws); + // Each scanline visits every boundary edge and sorts the intersections. Charge both the + // traversal and an n*ceil(log2(n)) upper bound for sorting, scaled to one unit per eight + // operations, whether or not any dash is made. + let edges: u64 = local.iter().map(|l| l.len() as u64).sum(); + let sort_levels = if edges > 1 { (u64::BITS - (edges - 1).leading_zeros()) as u64 } else { 0 }; + let crossings_charge = edges.saturating_add(edges.saturating_mul(sort_levels)) / 8 + 1; for k in k0..=k1 { - if out.len() >= MAX_RUNS || *work == 0 || is_set(cancel) { + if out.len() >= self.max_runs || crossings_charge > *work || is_set(cancel) { return; } + *work -= crossings_charge; let y = k as f64 * self.spacing; let xs = crossings(&local, y); let offset = shift_per_line * k as f64; @@ -538,10 +629,10 @@ impl Family<'_> { 'outer: while x < x1 { for d in self.dashes { guard += 1; - *work = work.saturating_sub(1); - if guard > 100_000 || out.len() >= MAX_RUNS || *work == 0 { + if guard > 100_000 || out.len() >= self.max_runs || *work == 0 { break 'outer; } + *work -= 1; let len = d.abs(); if *d > 0.0 { let a = x.max(x0); diff --git a/crates/render/src/linetype_text.rs b/crates/render/src/linetype_text.rs index 9f753ed11..ddf8b4f84 100644 --- a/crates/render/src/linetype_text.rs +++ b/crates/render/src/linetype_text.rs @@ -29,11 +29,17 @@ const MAX_TEXTS: usize = 10_000; /// repeated many times). const MAX_POINTS: usize = 2_000_000; +/// Upper bound on the points of all the texts of one run: each placement keeps its own copy of the +/// label's outline, so a long label times [`MAX_TEXTS`] would otherwise be too much to hold. +const MAX_TEXT_POINTS: usize = 4_000_000; + /// One text or shape element of the pattern, shaped once at the origin. struct Element { /// Distance from the start of a pattern repeat to the anchor (where the element ends). at: f64, local: Shaped, + /// Points in `local`, each placement's cost against [`MAX_TEXT_POINTS`]. + points: usize, rotation: f64, absolute: bool, offset: Vec2, @@ -58,6 +64,7 @@ pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: return out; } let mut walk = Walk { pts, i: 0, start: 0.0 }; + let mut points_left = MAX_TEXT_POINTS; let mut base = 0.0; let mut points = 0usize; 'repeats: while base <= len { @@ -67,6 +74,8 @@ pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: if s > len + 1e-9 || out.len() >= MAX_TEXTS || points > MAX_POINTS { break 'repeats; } + let Some(left) = points_left.checked_sub(el.points) else { break 'repeats }; + points_left = left; let Some((p, dir)) = walk.at(s) else { break 'repeats }; let origin = p + dir * el.offset.x + dir.perp() * el.offset.y; let rot = if el.absolute { el.rotation } else { dir.angle() + el.rotation }; @@ -111,6 +120,7 @@ fn elements(d: &Drawing, lt: &Linetype, scale: f64) -> Vec { { out.push(Element { at, + points: point_count(&local), local, rotation: finite(el.rotation), absolute: el.absolute, @@ -135,8 +145,16 @@ fn elements(d: &Drawing, lt: &Linetype, scale: f64) -> Vec { ..TextParams::new(Vec2::ZERO, height) }; let (local, _) = cadcraft_fonts::place(&font, text, ¶ms); + // Points plus one per stroke and glyph slot, and one for the label itself, so a label of empty + // glyphs still has a cost proportional to its size. + let points = local.strokes.iter().map(Vec::len).sum::() + + local.glyphs.iter().flatten().map(Vec::len).sum::() + + local.strokes.len() + + local.glyphs.len() + + 1; out.push(Element { at, + points, local, rotation: finite(el.rotation), absolute: el.absolute, @@ -217,6 +235,20 @@ mod tests { assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &plain, 1.0, 0.0).is_empty()); } + /// A long label repeated along a long run stops at the point allowance, well before MAX_TEXTS. + #[test] + fn placed_labels_stop_at_the_point_allowance() { + let d = Drawing::new_imperial(); + let mut lt = gas(); + lt.pattern[1].text = Some("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM".into()); + // 0.95 per repeat over 9,000: about 9,500 repeats, under the 50,000 the run is drawn for. + let t = texts(&d, &[Vec2::ZERO, Vec2::new(9_000.0, 0.0)], <, 1.0, 0.0); + let points: usize = + t.iter().map(|s| s.strokes.iter().map(Vec::len).sum::() + s.glyphs.iter().flatten().map(Vec::len).sum::()).sum(); + assert!(!t.is_empty() && t.len() < MAX_TEXTS, "{}", t.len()); + assert!(points <= MAX_TEXT_POINTS, "{points}"); + } + /// A shape file written for this test: shape 130 a 2 x 2 box with its pen ending at x = 2. fn register_shapes() { let src = "*130,7,BOX\n1,020,024,028,02C,2,020,0\n"; diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index d802d2c1d..8c9205a14 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -64,9 +64,14 @@ pub struct RasterOptions { pub antialias: bool, } +impl RasterOptions { + /// The dark canvas a render draws on by default. + pub const DARK_BACKGROUND: Rgb = Rgb(33, 40, 48); +} + impl Default for RasterOptions { fn default() -> Self { - RasterOptions { background: Rgb(33, 40, 48), hairline: 1.0, px_per_mm: 0.0, antialias: true } + RasterOptions { background: Self::DARK_BACKGROUND, hairline: 1.0, px_per_mm: 0.0, antialias: true } } } diff --git a/crates/render/src/table.rs b/crates/render/src/table.rs index 741ffd410..146918d04 100644 --- a/crates/render/src/table.rs +++ b/crates/render/src/table.rs @@ -133,6 +133,20 @@ pub fn table_geometry(d: &Drawing, t: &Table) -> TableGeom { if parts.len() <= 1 { return layout(d, t); } + // Every part is laid out and kept, so the cells of all of them count together (a header repeated + // on each part adds to each); past the limit only the table's outline is drawn. + let cols = t.col_widths.len().min(10_000); + let total: usize = parts.iter().map(|p| p.rows.len().min(10_000).saturating_mul(cols)).fold(0, usize::saturating_add); + if total > MAX_LAYOUT_CELLS { + // One outline per part, at the part's origin and as tall as its displayed rows. + let w = edges(&t.col_widths, cols).last().copied().unwrap_or(0.0); + let mut g = TableGeom::default(); + for p in parts { + let h: f64 = p.rows.iter().take(10_000).map(|r| t.row_heights.get(*r).copied().filter(|v| v.is_finite()).unwrap_or(0.0)).sum(); + outline_box(&mut g, p.origin, w, h); + } + return g; + } let mut g = TableGeom::default(); for p in parts { let mut pg = layout(d, &part_table(t, &p.rows, p.origin)); @@ -156,16 +170,20 @@ fn part_table(t: &Table, rows: &[usize], origin: Vec2) -> Table { // Otherwise `layout` renders an outline, so materialising millions of empty cells here would be // wasted work an attacker can trigger with a compact dimension array (CWE-789). if rows.len().min(10_000).saturating_mul(cols) <= MAX_LAYOUT_CELLS { + // `run[i]`: how many rows from part row `i` follow one another in the table, found once so a + // merge is cut by a lookup, not by walking the rows it spans. + let mut run = vec![1u32; rows.len()]; + for i in (0..rows.len().saturating_sub(1)).rev() { + if rows.get(i + 1).zip(rows.get(i)).is_some_and(|(next, this)| *next == this + 1) { + run[i] = run.get(i + 1).copied().unwrap_or(0).saturating_add(1); + } + } for (i, row) in cells.iter_mut().enumerate() { row.resize_with(cols, Default::default); for cell in row.iter_mut() { if let Some((rs, cs)) = cell.merged { // Rows of the merge that follow in this part. - let start = rows.get(i).copied().unwrap_or(0); - let mut n = 1u32; - while n < rs && rows.get(i + n as usize).is_some_and(|r| *r == start + n as usize) { - n += 1; - } + let n = rs.max(1).min(run.get(i).copied().unwrap_or(1)); cell.merged = (n > 1 || cs > 1).then_some((n, cs)); } } @@ -186,6 +204,27 @@ fn part_table(t: &Table, rows: &[usize], origin: Vec2) -> Table { } } +/// The table's outline alone, for a table too large to lay out. +fn outline(t: &Table) -> TableGeom { + let rows = t.row_heights.len().min(10_000); + let cols = t.col_widths.len().min(10_000); + let (w, h) = (edges(&t.col_widths, cols).last().copied().unwrap_or(0.0), edges(&t.row_heights, rows).last().copied().unwrap_or(0.0)); + let mut g = TableGeom::default(); + outline_box(&mut g, t.insert.xy(), w, h); + g +} + +/// The four sides of a `w` by `h` box hanging down from `o`. +fn outline_box(g: &mut TableGeom, o: Vec2, w: f64, h: f64) { + let p = |x: f64, y: f64| o + Vec2::new(x, -y); + let corners = [p(0.0, 0.0), p(w, 0.0), p(w, h), p(0.0, h), p(0.0, 0.0)]; + for s in corners.windows(2) { + if let [a, b] = s { + g.lines.push(TableLine { a: *a, b: *b, color: Color::ByBlock, lineweight: Lineweight::ByBlock }); + } + } +} + /// Lay out one part. fn layout(d: &Drawing, t: &Table) -> TableGeom { let st = table_style_of(d, t); @@ -203,14 +242,7 @@ fn layout(d: &Drawing, t: &Table) -> TableGeom { } let cov = coverage(t); if rows.saturating_mul(cols) > MAX_LAYOUT_CELLS || cov.is_err() { - let (w, h) = (x_at(cols), y_at(rows)); - let corners = [p(0.0, 0.0), p(w, 0.0), p(w, h), p(0.0, h), p(0.0, 0.0)]; - for s in corners.windows(2) { - if let [a, b] = s { - g.lines.push(TableLine { a: *a, b: *b, color: Color::ByBlock, lineweight: Lineweight::ByBlock }); - } - } - return g; + return outline(t); } let k = style_scale(&st, t); // Cell styles by name, scaled to the table. diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 757259583..dd98aadd8 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1127,6 +1127,20 @@ fn raster_hatch_pattern_matches_one_by_one() { } } +/// An OLE2FRAME draws its frame, the rectangle from its two corner points (#2422), and nothing +/// when a corner is missing. +#[test] +fn ole_frame_draws_its_outline() { + let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() }; + let frame = |tags: Vec| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags }); + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap(); + d.add(&Space::Model, Common::default(), frame(vec![tag(10, "1"), tag(20, "2")])).unwrap(); + let l = build(&d, &Space::Model, &Options { tolerance: 0.01, ..Default::default() }); + assert_eq!(l.prims.len(), 1, "only the frame with both corners is drawn"); + assert_eq!(l.prims[0].len, 5, "a closed rectangle: five points"); +} + /// `Options::linetypes` off draws a dashed line, a dashed wide polyline and a linetype on a layer /// as the same whole line a Continuous one draws: what hit tests look at. #[test] @@ -1151,3 +1165,55 @@ fn without_linetypes_every_line_is_drawn_whole() { let drawn = build(&drawing("DASHED"), &Space::Model, &Options::default()); assert!(drawn.prims.len() > 2 * continuous.prims.len(), "drawn with its linetype: {} primitives", drawn.prims.len()); } + +/// A broken table whose parts, with their repeated labels, together hold more cells than a table may +/// lay out is drawn as its outline, though the table's own cells are within the limit. +#[test] +fn broken_table_cells_count_across_its_parts() { + let d = Drawing::new_imperial(); + let t = cadcraft_doc::Table { + col_widths: vec![1.0; 600], + row_heights: vec![1.0; 1000], + title: true, + header: true, + breaks: Some(cadcraft_doc::TableBreak { enabled: true, height: 3.0, ..Default::default() }), + ..Default::default() + }; + assert!(t.parts().len() > 500 && 1000 * 600 <= crate::MAX_LAYOUT_CELLS); + let g = crate::table_geometry(&d, &t); + let parts = t.parts(); + assert_eq!((g.lines.len(), g.texts.len(), g.fills.len()), (4 * parts.len(), 0, 0)); + // Each part's box starts at its own origin. + let top = |i: usize| g.lines[4 * i].a; + assert!((0..parts.len()).all(|i| top(i) == parts[i].origin)); +} + +#[test] +fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() { + let ring = |rot: usize, rev: bool| { + let mut v: Vec = [(0.0, 0.0, 0.5), (4.0, 0.0, -0.25), (4.0, 3.0, 0.0), (0.0, 3.0, 0.1)] + .map(|(x, y, bulge)| PolyVertex { bulge, ..PolyVertex::new(Vec2::new(x, y)) }) + .to_vec(); + if rev { + // The same boundary wound the other way: bulges move to the other end of their edge and flip. + let b: Vec = v.iter().map(|q| q.bulge).collect(); + v.reverse(); + let n = v.len(); + for (j, q) in v.iter_mut().enumerate() { + q.bulge = -b[(n - 1 - j + n - 1) % n]; + } + } + v.rotate_left(rot); + HatchLoop { vertices: v, outer: true, sources: Vec::new() } + }; + let mut h = pattern_hatch("SOLID", 1.0, (0.0, 0.0, 1.0, 1.0)); + h.loops = vec![ring(0, false), ring(2, false), ring(1, true), ring(3, true)]; + assert_eq!(loops_of(&h).len(), 1); + // A different boundary is kept. + h.loops.push(HatchLoop { + vertices: ring(0, false).vertices.into_iter().map(|q| PolyVertex { bulge: 0.0, ..q }).collect(), + outer: true, + sources: Vec::new(), + }); + assert_eq!(loops_of(&h).len(), 2); +} diff --git a/crates/render/tests/it/hatch_fill.rs b/crates/render/tests/it/hatch_fill.rs index ff6195355..894eb720b 100644 --- a/crates/render/tests/it/hatch_fill.rs +++ b/crates/render/tests/it/hatch_fill.rs @@ -211,3 +211,14 @@ fn brick_joints_are_drawn_once_half_a_brick_apart_course_to_course() { assert!(next.iter().all(|nx| (nx - x[0]).rem_euclid(500) == 250), "courses {course}/{}: {x:?} {next:?}", course + 1); } } + +/// A pattern with a huge number of tiny dashes makes a swatch of a few thousand runs, stopping +/// there; and many scanlines over a many-edged boundary are charged to the hatch's work allowance. +#[test] +fn compact_patterns_stop_at_the_swatch_limits() { + let lines = vec![PatternLine { angle: 0.0, origin: (0.0, 0.0), delta: (0.0, 1.0), dashes: vec![1e-6, -1e-6] }]; + let started = std::time::Instant::now(); + let runs = cadcraft_render::pattern_swatch(&lines, 1.0); + assert!(!runs.is_empty() && runs.len() <= 4000, "{}", runs.len()); + assert!(started.elapsed() < std::time::Duration::from_secs(20)); +} diff --git a/crates/ui-egui/src/aliasdlg.rs b/crates/ui-egui/src/aliasdlg.rs index 6caded5f8..16e46e8dc 100644 --- a/crates/ui-egui/src/aliasdlg.rs +++ b/crates/ui-egui/src/aliasdlg.rs @@ -33,8 +33,18 @@ pub struct AliasDlgState { pub filter: String, pub form: Option
, pub error: Option, + /// The warnings the last imported file reported (skipped lines, external commands, unknown + /// commands); the first few are shown in the dialog and all of them on the command line. + pub warnings: Vec, /// ALIASEDIT typed again while open: bring the window to the front on the next frame. pub raise: bool, + /// Import… was clicked over aliases of the user's own: the dialog asks before a file replaces them. + pub confirm_import: bool, +} + +/// Whether Import… asks first: the file would replace the user's aliases or the edits not applied yet. +pub fn import_replaces_something(st: &AliasDlgState) -> bool { + !st.user.is_empty() || !st.applied.is_empty() } /// The user aliases and alias file ALIASEDIT holds now. @@ -143,6 +153,81 @@ pub fn apply(app: &mut CadApp) -> bool { } } +/// Whether `path` names a `.pgp` file, whatever its case. +fn is_pgp(path: &str) -> bool { + std::path::Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("pgp")) +} + +/// Report a failed import in the dialog (when it is open) and on the command line; returns it so +/// the caller can too. +fn refused(app: &mut CadApp, msg: String) -> String { + app.session.echo(msg.clone()); + if let Some(st) = app.alias_dlg.as_mut() { + st.error = Some(msg.clone()); + st.warnings.clear(); + } + msg +} + +/// Load the `.pgp` alias file at `path` through ALIASEDIT, replacing the user aliases as typing +/// `ALIASEDIT {file}` does. The dialog refreshes to what ALIASEDIT holds now, so OK and Apply see +/// no pending difference; the file's warnings are kept for display. Non-`.pgp` and unreadable +/// files are ordinary errors, never a panic. +pub fn import(app: &mut CadApp, path: &str) -> Result<(), String> { + if !is_pgp(path) { + return Err(refused(app, format!("Import: {path} is not a .pgp alias file"))); + } + match app.run("aliasedit", json!({ "file": path })) { + Ok(v) => { + let aliases: BTreeMap = v + .get("aliases") + .and_then(Value::as_object) + .map(|m| m.iter().filter_map(|(a, c)| Some((a.clone(), c.as_str()?.to_string()))).collect()) + .unwrap_or_default(); + let file = v.get("file").and_then(Value::as_str).unwrap_or(path).to_string(); + let loaded = v.get("loaded").and_then(Value::as_u64).unwrap_or(0); + let warnings: Vec = v + .get("warnings") + .and_then(Value::as_array) + .map(|w| w.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_default(); + if let Some(dir) = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()) { + app.ui.last_pgp_dir = Some(dir.to_string_lossy().to_string()); + } + app.session.echo(format!("{loaded} command alias(es) imported from {path}.")); + for w in &warnings { + app.session.echo(format!("Import {path}: {w}")); + } + if let Some(st) = app.alias_dlg.as_mut() { + st.user = aliases.clone(); + st.applied = aliases; + st.file = Some(file); + st.form = None; + st.selected = None; + st.error = None; + st.warnings = warnings; + } + Ok(()) + } + Err(e) => Err(refused(app, e)), + } +} + +/// Import…: ask the host for a `.pgp` file (starting in the folder the last import came from), +/// then load it. A cancelled picker is a no-op; without a native picker (the web) the error names +/// the ALIASEDIT `text` form, since the web has no file system to read a path from. +pub fn pick_and_import(app: &mut CadApp) -> Result<(), String> { + let dir = app.ui.last_pgp_dir.clone().unwrap_or_default(); + // Through `pick_for`, so macOS shows it as a sheet (#1527); aliases belong to no drawing. + match app.pick_for(crate::Pick::Pgp(dir), false, Box::new(|app, path| import(app, &path).map(|()| serde_json::Value::Null))) { + None => Err(refused( + app, + crate::tl!("Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter.").to_string(), + )), + Some(r) => r.map(|_| ()), + } +} + /// Command Aliases window that edits the in-memory alias set in `app.alias_dlg`; OK/Apply send the differences to ALIASEDIT, read the resulting aliases and source file back, and show any error. pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { if app.alias_dlg.is_none() { @@ -150,7 +235,9 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } let built = built_in(); let warn = Tokens::get().warn; - let (mut ok, mut cancel, mut apply_clicked) = (false, false, false); + let (mut ok, mut cancel, mut apply_clicked, mut import_clicked) = (false, false, false, false); + // Without a native file picker (the web) Import… can't open one; ALIASEDIT's `text` form loads a file there. + let can_pick = app.services.pick_pgp.is_some(); let Some(st) = app.alias_dlg.as_mut() else { return }; let id = egui::Id::unique("aliasedit_dialog"); if std::mem::take(&mut st.raise) { @@ -161,6 +248,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { Some(f) => ui.label(crate::tf!("Alias file: {file}", file = f)), None => ui.label(crate::tl!("No alias file loaded. REINIT replaces these aliases with a file's.")), }; + ui.label(RichText::new(crate::tl!("Aliases are saved in your CADCraft profile and survive restarts.")).small()); ui.horizontal(|ui| { let label = ui.label(crate::tl!("Filter")); ui.text_edit_singleline(&mut st.filter).labelled_by(label.id); @@ -221,7 +309,31 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { { st.user.remove(s); } + let import = ui + .add_enabled(can_pick, egui::Button::new(crate::tl!("Import…"))) + .on_disabled_hover_text(crate::tl!("Run ALIASEDIT with the file's contents using its text parameter.")); + if import.clicked() { + if import_replaces_something(st) { + st.confirm_import = true; + } else { + import_clicked = true; + } + } }); + if st.confirm_import { + ui.group(|ui| { + ui.label(crate::tf!("Importing a file replaces your {n} aliases, and any changes not applied yet.", n = st.user.len())); + ui.horizontal(|ui| { + if ui.button(crate::tl!("Import and replace")).clicked() { + st.confirm_import = false; + import_clicked = true; + } + if ui.button(crate::tl!("Keep my aliases")).clicked() { + st.confirm_import = false; + } + }); + }); + } let mut save = false; let mut discard = false; if let Some(form) = st.form.as_mut() { @@ -261,6 +373,15 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { if let Some(e) = &st.error { ui.colored_label(warn, e.as_str()); } + if !st.warnings.is_empty() { + for w in st.warnings.iter().take(3) { + ui.colored_label(warn, w.as_str()); + } + let more = st.warnings.len().saturating_sub(3); + if more > 0 { + ui.label(crate::tf!("{n} more warnings; see the command line.", n = more)); + } + } ui.separator(); ui.horizontal(|ui| { ok = ui.button(crate::tl!("OK")).clicked(); @@ -268,6 +389,9 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { apply_clicked = ui.button(crate::tl!("Apply")).clicked(); }); }); + if import_clicked { + let _ = pick_and_import(app); + } if (ok && apply(app)) || cancel { *open = false; } else if apply_clicked { @@ -277,3 +401,218 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { app.alias_dlg = None; } } + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + use std::path::PathBuf; + use std::rc::Rc; + use std::sync::atomic::{AtomicU32, Ordering}; + use std::sync::{Mutex, MutexGuard, PoisonError}; + + use cadcraft_engine::Session; + use serde_json::json; + + use crate::{CadApp, Services}; + + use super::{open, pick_and_import}; + + /// The alias store is process-wide, so the tests that load files take turns and clear it. + fn alone() -> MutexGuard<'static, ()> { + static LOCK: Mutex<()> = Mutex::new(()); + LOCK.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn temp_dir(name: &str) -> PathBuf { + static N: AtomicU32 = AtomicU32::new(0); + let dir = std::env::temp_dir().join(format!("cadcraft-alias-{}-{}-{name}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::create_dir_all(&dir); + dir + } + + /// An app whose Import picker answers `answer` and records the folder it was asked to start in. + fn app_with_pick(answer: Option) -> (CadApp, Rc>>>) { + let asked = Rc::new(RefCell::new(Vec::new())); + let log = Rc::clone(&asked); + let answer = Rc::new(RefCell::new(answer)); + let services = Services { + pick_pgp: Some(Box::new(move |dir: Option<&str>| { + log.borrow_mut().push(dir.map(str::to_string)); + answer.borrow().clone() + })), + ..Services::default() + }; + (CadApp::new(Session::new(), services), asked) + } + + fn clear(app: &mut CadApp) { + let _ = app.run("aliasedit", json!({ "clear": true })); + } + + /// Where the host shows dialogs without waiting (macOS sheets, #1527), Import… does not run + /// the blocking picker; the file loads once the sheet answers. + #[test] + fn import_waits_for_a_sheet_instead_of_blocking() { + type Done = Box) + Send>; + let _guard = alone(); + let dir = temp_dir("sheet"); + let path = dir.join("aliases.pgp"); + std::fs::write(&path, "XXS, *LINE\n").unwrap_or_default(); + let asked = Rc::new(RefCell::new(Vec::new())); + let answer: Rc>> = Rc::default(); + let (log, slot) = (Rc::clone(&asked), Rc::clone(&answer)); + let services = Services { + pick_pgp: Some(Box::new(|_: Option<&str>| panic!("the blocking picker ran"))), + start_pick: Some(Box::new(move |pick, done| { + log.borrow_mut().push(pick); + *slot.borrow_mut() = Some(done); + })), + ..Services::default() + }; + let mut app = CadApp::new(Session::new(), services); + open(&mut app); + + pick_and_import(&mut app).expect("the sheet starts"); + assert!(matches!(asked.borrow().as_slice(), [crate::Pick::Pgp(_)])); + answer.borrow_mut().take().expect("a sheet was started")(Some(path.to_string_lossy().to_string())); + app.finish_pick(&egui::Context::default()); + + let st = app.alias_dlg.as_ref().expect("the dialog stays open"); + assert_eq!(st.user.get("xxs").map(String::as_str), Some("line")); + clear(&mut app); + } + + #[test] + fn import_loads_the_aliases_shows_the_path_and_warnings() { + let _guard = alone(); + let dir = temp_dir("good"); + let path = dir.join("aliases.pgp"); + std::fs::write(&path, "; our own aliases\nXXL, *LINE\nXXC, *CIRCLE\nNOPE, *NOTACOMMAND\nEXT, notepad.exe\n").unwrap_or_default(); + let picked = path.to_string_lossy().to_string(); + let (mut app, asked) = app_with_pick(Some(picked.clone())); + open(&mut app); + + pick_and_import(&mut app).expect("the file loads"); + + let st = app.alias_dlg.as_ref().expect("the dialog stays open"); + assert_eq!(st.user.get("xxl").map(String::as_str), Some("line")); + assert_eq!(st.user.get("xxc").map(String::as_str), Some("circle")); + assert_eq!(st.file.as_deref(), Some(picked.as_str()), "the imported path is shown"); + assert_eq!(st.applied, st.user, "an import leaves nothing for Apply to resend"); + assert!(st.error.is_none()); + assert!(st.warnings.iter().any(|w| w.contains("unknown command")), "unknown commands are reported: {:?}", st.warnings); + assert!(st.warnings.iter().any(|w| w.contains("external command")), "external commands are reported: {:?}", st.warnings); + assert!(app.session.log.iter().any(|l| l.contains("unknown command")), "the command line shows the full warnings"); + assert_eq!(app.ui.last_pgp_dir.as_deref(), Some(dir.to_string_lossy().as_ref()), "the import folder is remembered"); + assert_eq!(asked.borrow().as_slice(), [None], "the first import has no folder yet"); + + // The next import starts where the last file was. + open(&mut app); + let _ = pick_and_import(&mut app); + assert_eq!(asked.borrow().as_slice(), [None, Some(dir.to_string_lossy().to_string())]); + + clear(&mut app); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Import… asks first when a file would replace aliases of the user's own or unapplied edits; + /// with neither it opens the picker at once. + #[test] + fn import_asks_before_replacing_the_users_aliases() { + let mut st = super::AliasDlgState::default(); + assert!(!super::import_replaces_something(&st)); + st.user.insert("xxl".into(), "line".into()); + assert!(super::import_replaces_something(&st), "an edit not applied yet"); + st.applied = st.user.clone(); + assert!(super::import_replaces_something(&st), "an applied user alias"); + st.user.clear(); + assert!(super::import_replaces_something(&st), "a removal not applied yet"); + } + + #[test] + fn a_cancelled_picker_changes_nothing() { + let _guard = alone(); + let (mut app, asked) = app_with_pick(None); + open(&mut app); + let before = app.alias_dlg.clone(); + + pick_and_import(&mut app).expect("cancelling is not an error"); + + assert_eq!(asked.borrow().len(), 1, "the picker was offered"); + assert_eq!(app.alias_dlg, before, "a cancelled picker leaves the aliases, file and errors alone"); + clear(&mut app); + } + + #[test] + fn non_pgp_and_malformed_files_are_ordinary_errors() { + let _guard = alone(); + let dir = temp_dir("bad"); + let text = dir.join("aliases.txt"); + std::fs::write(&text, "XXL, *LINE\n").unwrap_or_default(); + let (mut app, _) = app_with_pick(Some(text.to_string_lossy().to_string())); + open(&mut app); + let before = app.alias_dlg.clone().unwrap_or_default(); + + let e = pick_and_import(&mut app).expect_err("a .txt file is not an alias file"); + + assert!(e.contains(".pgp"), "{e}"); + let st = app.alias_dlg.as_ref().expect("the dialog stays open"); + assert_eq!(st.user, before.user, "the refused file changes no alias"); + assert_eq!(st.file, before.file); + assert!(st.error.as_deref().is_some_and(|e| e.contains(".pgp")), "{:?}", st.error); + + // Malformed lines are warnings with the aliases that did parse, never a panic. + let broken = dir.join("broken.pgp"); + std::fs::write(&broken, "not an alias line\nNOSUCH, *NOTACOMMAND\n; comment\nXXL, *LINE\n").unwrap_or_default(); + let (mut app, _) = app_with_pick(Some(broken.to_string_lossy().to_string())); + open(&mut app); + pick_and_import(&mut app).expect("malformed lines are warnings"); + let st = app.alias_dlg.as_ref().expect("the dialog stays open"); + assert_eq!(st.user.get("xxl").map(String::as_str), Some("line")); + assert!(st.warnings.len() >= 2, "{:?}", st.warnings); + assert!(st.error.is_none(), "{:?}", st.error); + + // A file that cannot be read is an error, reported in the dialog. + let missing = dir.join("missing.pgp"); + let (mut app, _) = app_with_pick(Some(missing.to_string_lossy().to_string())); + open(&mut app); + let e = pick_and_import(&mut app).expect_err("a missing file is an ordinary error"); + assert!(e.contains("missing.pgp"), "{e}"); + assert!(app.alias_dlg.as_ref().is_some_and(|st| st.error.is_some())); + + clear(&mut app); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn the_last_import_folder_round_trips_through_prefs() { + let mut app = CadApp::new(Session::new(), Services::default()); + app.ui.last_pgp_dir = Some("/tmp/our-aliases".into()); + let saved = app.prefs_json(); + assert!(saved.contains("lastPgpDir"), "{saved}"); + + let mut restored = CadApp::new(Session::new(), Services::default()); + restored.load_prefs(&saved); + assert_eq!(restored.ui.last_pgp_dir.as_deref(), Some("/tmp/our-aliases")); + + restored.load_prefs(r#"{"lastPgpDir": 3}"#); + assert_eq!(restored.ui.last_pgp_dir.as_deref(), Some("/tmp/our-aliases"), "malformed values are ignored"); + restored.load_prefs(r#"{"lastPgpDir": ""}"#); + assert_eq!(restored.ui.last_pgp_dir.as_deref(), Some("/tmp/our-aliases"), "an empty value is ignored"); + } + + #[test] + fn no_picker_points_at_aliasedit_text_without_changing_aliases() { + let mut app = CadApp::new(Session::new(), Services::default()); + open(&mut app); + let before = app.alias_dlg.clone(); + let e = pick_and_import(&mut app).expect_err("the web has no native picker"); + assert!(e.contains("ALIASEDIT"), "{e}"); + assert!(e.contains("contents"), "the web is told to give the file's contents: {e}"); + assert!(e.contains("text"), "the web is told which parameter carries the contents: {e}"); + assert!(!e.contains("path"), "the web has no file system, so a path is not the supported form: {e}"); + let st = app.alias_dlg.as_ref().expect("the dialog stays open"); + assert_eq!(st.user, before.as_ref().map(|b| b.user.clone()).unwrap_or_default()); + assert!(st.error.as_deref().is_some_and(|e| e.contains("ALIASEDIT"))); + } +} diff --git a/crates/ui-egui/src/canvas/pick.rs b/crates/ui-egui/src/canvas/pick.rs index 3bd28b017..96e510df9 100644 --- a/crates/ui-egui/src/canvas/pick.rs +++ b/crates/ui-egui/src/canvas/pick.rs @@ -26,12 +26,16 @@ pub(super) fn wheel_zoom_points(events: &[egui::Event], opts: &egui::InputOption } /// The model space tiles on screen (none without tiling): each tile's rectangle in `full`. -/// Start TEXTEDIT on the text, mtext or attribute definition at `p` (the objects its shortcut menu -/// offers Edit Text for); false when there is none. +/// Start TEXTEDIT on the text, mtext, attribute definition or multileader text at `p` (the objects +/// its shortcut menu offers Edit Text for, and multileaders, #1081); false when there is none. pub(super) fn edit_text_at(app: &mut CadApp, p: Vec2) -> bool { use cadcraft_engine::doc::EntityKind; let is_text = cadcraft_engine::cmd::curves::pick_at(&app.session, p).and_then(|h| { - app.session.doc().ok()?.entity(h).map(|e| matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_))) + app.session.doc().ok()?.entity(h).map(|e| match &e.kind { + EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) => true, + EntityKind::MLeader(m) => m.text.is_some(), + _ => false, + }) }); if is_text != Some(true) { return false; diff --git a/crates/ui-egui/src/closing.rs b/crates/ui-egui/src/closing.rs index 04d526fa2..435917642 100644 --- a/crates/ui-egui/src/closing.rs +++ b/crates/ui-egui/src/closing.rs @@ -88,6 +88,11 @@ impl CadApp { /// Answer the open close prompt (no-op without one). pub fn answer_close(&mut self, choice: Choice) { let Some(uid) = self.closing.as_ref().and_then(|c| c.asking) else { return }; + // Its Save dialog is open (macOS): Save again or Don't Save would race it. + if choice != Choice::Cancel && self.pending_pick.as_ref().is_some_and(|p| p.for_close) { + self.set_status("Answer the Save dialog first."); + return; + } let i = match (choice, self.doc_index(uid)) { (Choice::Cancel, _) => { self.closing = None; @@ -114,26 +119,53 @@ impl CadApp { // The Block Editor's unsaved changes go into the block first (BSAVE), then the // drawing is saved with them. let r = if self.session.state().is_ok_and(|st| st.block_unsaved()) { self.run("bsave", json!({})) } else { Ok(Value::Null) }; + let waiting = self.pending_pick.is_some(); let r = r.and_then(|_| self.run("qsave", Value::Null)); - let saved = r.is_ok() && self.doc_index(uid).and_then(|i| self.session.docs.get(i)).is_some_and(|d| !d.is_dirty()); - match (saved, self.doc_index(uid)) { - (true, Some(i)) => { - self.close_front(i); - self.advance_close(); - } - _ => { - // Not saved (picker cancelled, save failed or unavailable): keep the - // drawing and its edits, and stop closing. - self.closing = None; - let title = self.doc_index(uid).and_then(|i| self.session.docs.get(i)).map(|d| d.title.clone()).unwrap_or_default(); - let msg = match r { - Err(e) => format!("{title} was not saved ({e}); it stays open."), - Ok(_) => format!("{title} was not saved; it stays open."), - }; - self.session.echo(msg.clone()); - self.set_status(msg); - } + // The Save dialog opened without waiting (macOS): closing goes on once it has + // saved; cancelling it leaves the prompt up. + // The dialog is bound to this drawing: if it is closed meanwhile, nothing is + // saved and the prompt goes on with the next drawing. + if !waiting && let Some(mut pending) = self.pending_pick.take() { + let then = pending.then; + pending.for_close = true; + pending.then = Box::new(move |app: &mut CadApp, path| { + let r = then(app, path); + // Unless the prompt was answered otherwise meanwhile. + if app.closing.as_ref().and_then(|c| c.asking) == Some(uid) { + // It reports the outcome itself; an error returned here would + // replace its message in the status bar. + app.close_after_save(uid, r); + return Ok(Value::Null); + } + r + }); + self.pending_pick = Some(pending); + return; } + self.close_after_save(uid, r); + } + } + } + + /// Go on closing after the drawing `uid` was asked to save with result `r`. + fn close_after_save(&mut self, uid: u64, r: Result) { + let saved = r.is_ok() && self.doc_index(uid).and_then(|i| self.session.docs.get(i)).is_some_and(|d| !d.is_dirty()); + match (saved, self.doc_index(uid)) { + (true, Some(i)) => { + self.close_front(i); + self.advance_close(); + } + _ => { + // Not saved (picker cancelled, save failed or unavailable): keep the + // drawing and its edits, and stop closing. + self.closing = None; + let title = self.doc_index(uid).and_then(|i| self.session.docs.get(i)).map(|d| d.title.clone()).unwrap_or_default(); + let msg = match r { + Err(e) => format!("{title} was not saved ({e}); it stays open."), + Ok(_) => format!("{title} was not saved; it stays open."), + }; + self.session.echo(msg.clone()); + self.set_status(msg); } } } @@ -264,6 +296,44 @@ mod tests { app.session.docs.iter().map(|d| d.title.clone()).collect() } + type Done = Box) + Send>; + + /// The host shows its Save dialog without waiting (macOS): the callback that answers it. + fn deferred_save(app: &mut CadApp) -> std::rc::Rc>> { + let slot: std::rc::Rc>> = std::rc::Rc::default(); + let s = slot.clone(); + app.services = Services { + pick_save: Some(Box::new(|_: &str| None)), + start_pick: Some(Box::new(move |_, done| *s.borrow_mut() = Some(done))), + ..Services::default() + }; + slot + } + + /// While the prompt's Save dialog is open, Don't Save (or Save again) does not race it; when + /// the save then fails, the prompt's own "was not saved" message is what the status bar shows. + #[test] + fn the_close_prompt_waits_for_its_save_dialog() { + let mut app = app_with(&["A", "B"]); + let answer = deferred_save(&mut app); + dirty(&mut app, 0); + app.request_close(Some(0)); + app.answer_close(Choice::Save); + assert!(answer.borrow().is_some(), "the Save dialog is open"); + app.answer_close(Choice::Discard); + app.answer_close(Choice::Save); + assert_eq!(titles(&app), ["A", "B"], "Don't Save waits for the Save dialog"); + assert_eq!(app.close_prompt(), Some("A")); + + let nowhere = std::env::temp_dir().join(format!("cadcraft-no-such-dir-{}", std::process::id())).join("A.dxf"); + answer.borrow_mut().take().unwrap()(Some(nowhere.to_string_lossy().to_string())); + app.finish_pick(&egui::Context::default()); + assert_eq!(titles(&app), ["A", "B"], "not saved, so not closed"); + assert!(app.session.docs[0].is_dirty()); + let status = app.status.as_ref().map(|(s, _)| s.as_str()).unwrap_or_default(); + assert!(status.starts_with("A was not saved") && status.ends_with("it stays open."), "{status}"); + } + #[test] fn clean_drawing_closes_without_prompt() { let mut app = app_with(&["A", "B"]); diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index bbaf48df3..d9af319c2 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -6,8 +6,12 @@ //! Pan/Zoom, Quick Select, Find, Properties and Options. //! - **While a command runs** ([`command_entries`]): a quick right-click is Enter; holding the //! button for [`HOLD_SECS`] opens Enter, Cancel, Recent Input, the prompt's options, Snap -//! Overrides and Pan/Zoom instead (AutoCAD's time-sensitive right-click). With that turned off -//! in OPTIONS (`timeSensitiveRightClick`), every right-click opens the menu. +//! Overrides and Pan/Zoom instead (AutoCAD's time-sensitive right-click; Options ▸ User +//! Preferences ▸ Right-Click Customization sets how long, `rightClickDuration`). With that turned +//! off (`timeSensitiveRightClick`), Command mode says what a right-click does +//! (`rightClickCommand`: the menu, Enter, or the menu only when the prompt has options). +//! `rightClickDefault` and `rightClickEdit` can make a right-click with no command running +//! repeat the last command instead of opening the menu. //! - **Shift/Ctrl+right-click** ([`snap_entries`]): the object snap menu. Its items type the point //! modifiers and snap overrides (`_from`, `_endp`, `_non`…) at the current point prompt. //! @@ -41,7 +45,8 @@ const SETTINGS: &[&str] = &["options"]; /// How many recent commands and inputs the menus list. pub const RECENT: usize = 8; /// How long the right button must be held while a command runs to open the command menu instead -/// of acting as Enter (AutoCAD's time-sensitive right-click; 250 ms there by default). +/// of acting as Enter, by default (AutoCAD's time-sensitive right-click; 250 ms there by +/// default). OPTIONS `rightClickDuration` changes it. pub const HOLD_SECS: f64 = 0.25; /// Item ids that are not commands: keys, typed text and snap menu items. @@ -153,9 +158,29 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> { } } -/// [`object_commands`] that are registered, as menu items. +/// [`object_commands`] that are registered, as menu items. The Edit Text entry of a single +/// selected text, mtext or attribute definition opens the Edit Text window instead of the +/// TEXTEDIT command line; the double-click keeps its in-place editing (#842), and several +/// selected texts still take the command line. pub fn object_entries(app: &CadApp) -> Vec { - object_commands(app).into_iter().filter_map(|(id, label)| item(app, id, label)).collect() + object_commands(app) + .into_iter() + .filter_map(|(id, label)| if id == "textedit" { edit_text_window_entry(app).or_else(|| item(app, id, label)) } else { item(app, id, label) }) + .collect() +} + +/// The Edit Text entry as the `textedit:` dialog id, for a single selected text, mtext +/// or attribute definition; `None` otherwise, so the command line entry stands in. +fn edit_text_window_entry(app: &CadApp) -> Option { + use cadcraft_engine::doc::EntityKind; + let sel = app.session.selection(); + if sel.len() != 1 { + return None; + } + let h = *sel.first()?; + let d = app.session.doc().ok()?; + d.entity(h).filter(|e| matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_)))?; + Some(Entry::Item { label: "Edit Text".into(), id: format!("textedit:{}", h.hex()), shortcut: None, enabled: true }) } /// The command menu while a command runs (`None` when none does): Enter and Cancel, Recent Input, @@ -213,6 +238,9 @@ pub fn choose(app: &mut CadApp, id: &str) { } } else if let Some(s) = id.strip_prefix(SNAP) { choose_snap(app, s); + } else if id.starts_with("textedit:") { + // The Edit Text window of the single selected text object; the id carries the handle. + app.ui.dialog = Some(id.to_string()); } else { activate(app, id); } @@ -290,6 +318,21 @@ pub fn groups_ui(ui: &mut egui::Ui, groups: &[Vec], clicked: &mut Option< pub fn show(app: &mut CadApp, resp: &egui::Response) { let mut clicked = None; let snap = app.canvas.snap_menu; + // Right-Click Customization: with nothing selected (Default mode) or a selection (Edit mode), + // a right-click may repeat the last command instead of opening the menu. With no last command + // yet, it opens the menu. + let o = &app.options; + let mode = + if o.right_click_default == o.right_click_edit || app.session.selection().is_empty() { o.right_click_default } else { o.right_click_edit }; + if !snap + && mode == crate::options::IdleClick::Repeat + && let Some(last) = app.session.last_command.clone() + { + if resp.secondary_clicked() { + app.start(&last); + } + return; + } resp.context_menu(|ui| { let groups = if snap { snap_entries(app) } else { entries(app) }; groups_ui(ui, &groups, &mut clicked); @@ -307,8 +350,9 @@ struct Press(f64, egui::Pos2); /// The canvas's right button while a command runs (Shift/Ctrl+right-click is the snap menu's): a /// quick click is Enter — returns `true` when the caller should send it — and a click held for -/// [`HOLD_SECS`] opens the command menu ([`command_entries`]) at the pointer (any click does with -/// the time-sensitive right-click turned off). Call it every frame +/// OPTIONS `rightClickDuration` opens the command menu ([`command_entries`]) at the pointer. With +/// the time-sensitive right-click turned off, `rightClickCommand` says whether a click opens the +/// menu or is Enter. Call it every frame /// with whether the pointer is on the canvas and whether a right-click ended there; it also shows /// the menu while it is open. pub fn in_command(app: &mut CadApp, ui: &egui::Ui, inside: bool, right_clicked: bool) -> bool { @@ -325,14 +369,23 @@ pub fn in_command(app: &mut CadApp, ui: &egui::Ui, inside: bool, right_clicked: ctx.data_mut(|d| d.insert_temp(press_id, Press(now, p))); } let running = app.session.prompting() && !app.canvas.snap_menu; + let o = &app.options; + let timed = o.time_sensitive_right_click; + // Without the time-sensitive right-click, Command mode says whether a click opens the menu. + let menu = match o.right_click_command { + crate::options::CommandClick::Menu => true, + crate::options::CommandClick::Enter => false, + crate::options::CommandClick::MenuWithOptions => app.session.current_prompt().is_some_and(|p| !p.keywords.is_empty()), + }; + let hold = f64::from(o.right_click_hold_ms) / 1000.0; let mut open = false; if released && let Some(Press(t0, p0)) = ctx.data_mut(|d| d.remove_temp::(press_id)) { // A drag isn't a click; a click held long enough asks for the menu. let still = pos.is_some_and(|p| p.distance(p0) <= 6.0); - let held = now - t0 >= HOLD_SECS || !app.options.time_sensitive_right_click; + let held = if timed { now - t0 >= hold } else { menu }; open = running && still && held; } - let enter = running && inside && right_clicked && !open && app.options.time_sensitive_right_click; + let enter = running && inside && right_clicked && !open && (timed || !menu); if !running { return false; } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 9c806a96f..55e2da3f6 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -15,14 +15,17 @@ //! - `ui.click {x, y, shift?, ctrl?}`, `ui.move {x, y}`: real egui pointer input in screen points //! - `ui.key {key, cmd?, shift?, alt?}`, `ui.text {text}`: synthetic keyboard input //! - `ui.set {...UiState fields}`, `ui.resize {width, height}` -//! - `ui.screenshot {path?}`: PNG of the window; `ui.render {path?, width?, height?, fit?}`: headless -//! render of the drawing (no window needed; fits the drawing unless `fit` is false; replies `pngBase64`) +//! - `ui.screenshot {path?}`: PNG of the window; `ui.render {path?, width?, height?, fit?, window?, +//! background?, plot_style?}`: headless render of the drawing (no window needed; fits the drawing +//! unless `fit` is false or a `window` is given; on the dark canvas unless `background` is +//! `white`, `paper` or `#rrggbb`; `plot_style` names a plot style table, which plots on white +//! unless `background` is given, or is `none`; replies `pngBase64`) //! - `app.open {path}`, `app.save {path?}`, `app.quit` //! - `control.methods`: this list, with params and a description; `ping`: replies `"pong"` use std::sync::Arc; use std::sync::atomic::{AtomicU8, Ordering}; -use std::sync::mpsc::{Receiver, Sender}; +use std::sync::mpsc::{Receiver, Sender, TryRecvError}; use std::time::Duration; use cadcraft_engine::Input; @@ -84,6 +87,25 @@ impl PendingReply { // Started: a reply that arrived just now still counts. self.rx.try_recv().unwrap_or_else(|_| json!({"ok": false, "error": "timeout", "state": "may-have-run"})) } + + /// The reply if the app has answered, without waiting: a transport that cannot block (the web + /// shell) polls this once a frame. A request the app dropped without answering reports that. + pub fn try_reply(&self) -> Option { + match self.rx.try_recv() { + Ok(reply) => Some(reply), + Err(TryRecvError::Empty) => None, + Err(TryRecvError::Disconnected) => Some(json!({"ok": false, "error": "the app dropped the request"})), + } + } +} + +impl Drop for PendingReply { + /// A reply nobody waits for any more cancels a request the app has not started, as a timed-out + /// [`PendingReply::wait`] does: the client was told it failed, so the app must not run it late. + /// A request the app already started, or answered, is unaffected. + fn drop(&mut self) { + let _ = self.state.compare_exchange(QUEUED, CANCELLED, Ordering::AcqRel, Ordering::Acquire); + } } pub enum Outcome { @@ -211,7 +233,7 @@ const METHODS: &[(&str, &str, &str)] = &[ ("ui.resize", "{width, height}", "Resize the window."), ("ui.focus", "", "Activate the native window."), ("ui.screenshot", "{path?}", "PNG of the window (needs a presented frame)."), - ("ui.render", "{path?, width?, height?, fit?}", "Headless render of the drawing; replies pngBase64."), + ("ui.render", "{path?, width?, height?, fit?, window?, background?, plot_style?}", "Headless render of the drawing; replies pngBase64."), ("app.open", "{path}", "Open a drawing."), ("app.save", "{path?}", "Save the drawing (Save As with a path)."), ("app.quit", "", "Quit without the unsaved-changes prompt."), @@ -453,7 +475,9 @@ pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Ou } } match serde_json::from_value::(cur) { - Ok(u) => { + Ok(mut u) => { + // Shortcuts are checked as the preferences check them. + u.shortcuts = crate::keys::from_prefs(&json!(u.shortcuts)); if let Err(error) = crate::docking::validate(&u.docking) { return err(error); } @@ -475,7 +499,17 @@ pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Ou let Ok(st) = app.session.state() else { return err("no drawing") }; // `window`: just that area, at the size given or matching its shape. let window = render_window(p); - let opts = cadcraft_render::Options { view: window, transparency: app.session.settings.transparency_display, ..Default::default() }; + // `background` and `plot_style` (#803), read as the headless MCP backend reads them. + let look = match cadcraft_engine::render_look::RenderLook::from_params(&st.doc, p) { + Ok(look) => look, + Err(e) => return err(e), + }; + let opts = cadcraft_render::Options { + view: window, + transparency: app.session.settings.transparency_display, + plot_style_table: look.plot_style_table.clone(), + ..Default::default() + }; let list = cadcraft_render::build(&st.doc, &st.space, &opts); let v = st.view(); let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(true); @@ -484,7 +518,7 @@ pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Ou None => render_view(&list.bounds, v.center, v.height, fit, w, h), }; let (w, h) = (view.width, view.height); - let Some(png) = cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default()) else { + let Some(png) = cadcraft_render::raster::render_png(&list, &view, &look.raster()) else { return err("render failed"); }; #[cfg(not(target_arch = "wasm32"))] @@ -713,6 +747,10 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64) let Some(img) = image::RgbaImage::from_raw(w as u32, h as u32, buf) else { return json!({"ok": false, "error": "bad image", "request": token}); }; + // No file system to write to (the web build): the PNG comes back inline, as `ui.render`'s does. + if cfg!(target_arch = "wasm32") { + return inline_screenshot(&img, token); + } let saved = match path { Some(path) => img.save(path).map(|()| path.to_string()).map_err(std::io::Error::other), None => save_pathless_screenshot(&img, token).map(|path| path.to_string_lossy().into_owned()), @@ -723,10 +761,60 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64) } } +/// A screenshot as an inline PNG reply (`pngBase64`, `width`, `height`, `bytes`, like `ui.render`), for a +/// build that has no file system to write it to: the web build, where `std::env::temp_dir` panics. +fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value { + let (w, h) = img.dimensions(); + let mut png = Vec::new(); + if let Err(e) = img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) { + return json!({"ok": false, "error": e.to_string(), "request": token}); + } + json!({"ok": true, "request": token, "result": {"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "bytes": png.len()}}) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn an_inline_screenshot_carries_the_png_and_its_size() { + let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 255])); + let reply = inline_screenshot(&img, 7); + assert_eq!(reply["ok"], true); + assert_eq!(reply["request"], 7); + assert_eq!((reply["result"]["width"].as_u64(), reply["result"]["height"].as_u64()), (Some(3), Some(2))); + let b64 = reply["result"]["pngBase64"].as_str().unwrap_or_default(); + assert!(b64.starts_with("iVBORw0KGgo"), "a PNG signature in base64: {b64:.20}"); + assert!(reply["result"]["bytes"].as_u64().is_some_and(|n| n > 30), "the PNG byte count is reported"); + } + + #[test] + fn dropping_a_pending_reply_cancels_a_request_the_app_has_not_started() { + let (request, pending) = ControlRequest::new("ui.inspect", json!({})); + drop(pending); + assert!(!request.begin(), "the app must skip a request nobody waits for"); + } + + #[test] + fn dropping_a_pending_reply_leaves_a_started_request_alone() { + let (request, pending) = ControlRequest::new("ui.inspect", json!({})); + assert!(request.begin()); + drop(pending); + assert_eq!(request.state.load(Ordering::Acquire), STARTED, "a started request is not cancelled"); + } + + #[test] + fn try_reply_polls_without_blocking() { + let (request, pending) = ControlRequest::new("ui.inspect", json!({})); + assert_eq!(pending.try_reply(), None, "no answer yet"); + assert!(request.begin()); + request.reply.send(json!({"ok": true, "result": 1})).unwrap_or_default(); + assert_eq!(pending.try_reply(), Some(json!({"ok": true, "result": 1}))); + let (request, pending) = ControlRequest::new("ui.inspect", json!({})); + drop(request); + assert_eq!(pending.try_reply().and_then(|r| r["ok"].as_bool()), Some(false), "the app went away"); + } + #[test] fn render_view_fit_finds_offscreen_drawing() { let far = cadcraft_geom::Bounds2::new(Vec2::new(9000.0, 9000.0), Vec2::new(9100.0, 9050.0)); @@ -834,4 +922,67 @@ mod tests { assert!(render_reply(b"abc", 7, 5, None, true).get("path").is_none()); assert_eq!(render_reply(b"abc", 7, 5, None, true)["truncated"], true); } + + /// The reply to a `ui.render` request in an app showing one line along y = 0: colour 7, or + /// red on a red layer. + fn render_line(red: bool, params: Value) -> Value { + let mut app = CadApp::new(cadcraft_engine::Session::empty(), crate::Services::default()); + app.session.new_drawing(false); + if red { + app.session.execute("layer.new", &json!({"name": "Red", "color": "red", "current": true})).unwrap(); + } + app.session.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let (req, _rx) = ControlRequest::new("ui.render", params); + match handle(&mut app, &egui::Context::default(), &req) { + Outcome::Done(v) => v, + Outcome::Screenshot { .. } => panic!("ui.render must not take a screenshot"), + } + } + + /// The RGB of a reply's corner pixel and of its middle column's darkest pixel. + fn corner_and_darkest(reply: &Value) -> ([u8; 3], [u8; 3]) { + let png = cadcraft_engine::cmd::file::base64_decode(reply["result"]["pngBase64"].as_str().unwrap_or_default()).unwrap(); + let img = image::load_from_memory(&png).unwrap().to_rgb8(); + let corner = img.get_pixel(0, 0).0; + let darkest = (0..img.height()).map(|y| img.get_pixel(img.width() / 2, y).0).min_by_key(|p| p.iter().map(|&c| u32::from(c)).sum::()); + (corner, darkest.unwrap_or_default()) + } + + /// Guards #803 in the app: `ui.render` takes `background` and `plot_style` as the headless MCP + /// backend does (colour 7 drawn dark on white, a red line black with `monochrome.ctb`, white + /// by default with a plot style), keeps the dark canvas by default and refuses unknown values. + #[test] + fn render_takes_a_background_and_a_plot_style() { + // The line runs along the middle of pixel row 20 of the 120 x 40 image. + let window = json!([[-1.0, -1.95], [11.0, 2.05]]); + let render = |red: bool, mut p: Value| { + p["window"] = window.clone(); + p["width"] = json!(120); + p["height"] = json!(40); + let r = render_line(red, p.clone()); + assert_eq!(r["ok"], true, "{p}: {}", r["error"]); + corner_and_darkest(&r) + }; + assert_eq!(render(false, json!({})).0, [33, 40, 48], "the default stays the dark canvas"); + let (corner, ink) = render(false, json!({"background": "white"})); + assert_eq!(corner, [255, 255, 255]); + assert!(ink.iter().all(|&c| c < 128), "colour 7 is drawn dark on white: {ink:?}"); + // A red line stays red without a plot style and plots black with monochrome.ctb, on white + // unless `background` says otherwise. + let (_, [r, g, b]) = render(true, json!({"background": "paper"})); + assert!(r > 200 && g < 100 && b < 100, "red without a plot style: {:?}", [r, g, b]); + for (p, bg) in [ + (json!({"plot_style": "monochrome.ctb"}), [255, 255, 255]), + (json!({"plot_style": "monochrome.ctb", "background": "#336699"}), [0x33, 0x66, 0x99]), + ] { + let (corner, [r, g, b]) = render(true, p.clone()); + assert_eq!(corner, bg, "{p}"); + assert!(r < 100 && r == g && g == b, "{p}: red plots black: {:?}", [r, g, b]); + } + for p in [json!({"background": "purple"}), json!({"background": 7}), json!({"plot_style": "nope.ctb"})] { + let r = render_line(false, p.clone()); + assert_eq!(r["ok"], false, "{p} must be refused"); + assert!(r.get("result").is_none(), "{p}"); + } + } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0132ea219..fcd8713a3 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -24,6 +24,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "hatch" => crate::hatchdlg::dialog(app, ctx, &mut open), "aliasedit" => crate::aliasdlg::dialog(app, ctx, &mut open), "find" => crate::finddlg::dialog(app, ctx, &mut open), + crate::keys::DIALOG => crate::keys::dialog(app, ctx, &mut open), "about" => about(ctx, &mut open), "preview" => crate::exchange::dialog(app, ctx, &mut open), "commands" => commands(app, ctx, &mut open), @@ -32,6 +33,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), "stylesmanager" => crate::plotstyles::dialog(app, ctx, &mut open), o if o == "options" || o.starts_with("options:") => crate::options::dialog(app, ctx, o, &mut open), + o if o.starts_with("textedit:") => crate::textdlg::dialog(app, ctx, o, &mut open), other => crate::managers::dialog(app, ctx, other, &mut open), } // A dialog that closed by opening another (Plot Preview back to Plot) keeps the new one. diff --git a/crates/ui-egui/src/exchange.rs b/crates/ui-egui/src/exchange.rs index 48a615003..b7a0246c6 100644 --- a/crates/ui-egui/src/exchange.rs +++ b/crates/ui-egui/src/exchange.rs @@ -7,7 +7,7 @@ use std::sync::atomic::{AtomicU32, Ordering}; use egui::TextureHandle; use serde_json::{Value, json}; -use crate::CadApp; +use crate::{CadApp, Pick}; /// Bumped each time PREVIEW is started, so the window renders the drawing as it is now. static PREVIEW_GEN: AtomicU32 = AtomicU32::new(0); @@ -23,27 +23,15 @@ pub fn route(app: &mut CadApp, id: &str) -> Result { app.ui.dialog = Some("preview".into()); Ok(Value::Null) } - "import" | "imp" => { - let Some(pick) = app.services.pick_open.as_ref() else { return no_picker(app, "IMPORT", r#"import {"path": "parts.dxf"}"#) }; - match pick() { - Some(path) => app.run("import", json!({ "path": path })), - None => Ok(Value::Null), - } - } - "publish" => { - let Some(pick) = app.services.pick_save.as_ref() else { return no_picker(app, "PUBLISH", "publish {}") }; - match pick(&format!("{stem}.pdf")) { - Some(path) => app.run("publish", json!({ "path": path })), - None => Ok(Value::Null), - } - } - _ => { - let Some(pick) = app.services.pick_save.as_ref() else { return no_picker(app, "EXPORT", r#"export {"format": "svg"}"#) }; - match pick(&format!("{stem}.svg")) { - Some(path) => app.run("export", json!({ "path": path })), - None => Ok(Value::Null), - } - } + "import" | "imp" => app + .pick_then(Pick::Open, |app, path| app.run("import", json!({ "path": path }))) + .unwrap_or_else(|| no_picker(app, "IMPORT", r#"import {"path": "parts.dxf"}"#)), + "publish" => app + .pick_then(Pick::Save(format!("{stem}.pdf")), |app, path| app.run("publish", json!({ "path": path }))) + .unwrap_or_else(|| no_picker(app, "PUBLISH", "publish {}")), + _ => app + .pick_then(Pick::Save(format!("{stem}.svg")), |app, path| app.run("export", json!({ "path": path }))) + .unwrap_or_else(|| no_picker(app, "EXPORT", r#"export {"format": "svg"}"#)), } } @@ -161,7 +149,7 @@ mod tests { use cadcraft_engine::Session; use serde_json::json; - use crate::{CadApp, Services}; + use crate::{CadApp, Pick, Services}; /// An app whose file dialogs record what they were asked and cancel. fn app() -> (CadApp, Rc>>) { @@ -207,4 +195,169 @@ mod tests { let e = app.run("share", json!({})).unwrap_err(); assert!(e.contains("not available yet"), "{e}"); } + + type Done = Box) + Send>; + + /// An app whose host shows its dialogs without waiting (macOS, #1527): the dialogs asked + /// for, and the callback that answers the open one. + fn deferred_app() -> (CadApp, Rc>>, Rc>>) { + let asked = Rc::new(RefCell::new(Vec::new())); + let answer: Rc>> = Rc::default(); + let (log, slot) = (asked.clone(), answer.clone()); + let services = Services { + pick_open: Some(Box::new(|| None)), + pick_save: Some(Box::new(|_: &str| None)), + pick_lisp: Some(Box::new(|_: &str| None)), + start_pick: Some(Box::new(move |pick, done| { + log.borrow_mut().push(pick); + *slot.borrow_mut() = Some(done); + })), + ..Services::default() + }; + (CadApp::new(Session::new(), services), asked, answer) + } + + fn status(app: &CadApp) -> &str { + app.status.as_ref().map(|(s, _)| s.as_str()).unwrap_or_default() + } + + fn uid(app: &CadApp) -> u64 { + app.session.state().unwrap().uid + } + + /// Where the host shows its dialogs without waiting (macOS, #1527), the command acts on the + /// path in a later frame, and no second dialog opens while one is up. + #[test] + fn a_deferred_dialog_acts_when_its_answer_arrives() { + let (mut app, asked, answer) = deferred_app(); + let ctx = egui::Context::default(); + + // Cancelled: nothing happens, and the next command may ask again. + app.start("export"); + assert_eq!(*asked.borrow(), [Pick::Save("Drawing1.svg".into())]); + answer.borrow_mut().take().unwrap()(None); + app.finish_pick(&ctx); + assert!(app.pending_pick.is_none()); + + app.start("imp"); + app.finish_pick(&ctx); + assert!(app.pending_pick.is_some() && app.status.is_none(), "nothing runs before the answer"); + // A second dialog is refused, and says so: in the status bar for a typed or menu + // command, and as an error for a programmatic call. + app.start("publish"); + assert!(status(&app).contains("already open"), "{:?}", app.status); + let e = app.run("ui.open", json!(null)).unwrap_err(); + assert!(e.contains("already open"), "{e}"); + assert_eq!(asked.borrow().len(), 2, "no second dialog while one is open"); + app.status = None; + let missing = std::env::temp_dir().join(format!("cadcraft-missing-{}.dxf", std::process::id())); + answer.borrow_mut().take().unwrap()(Some(missing.to_string_lossy().to_string())); + app.finish_pick(&ctx); + assert!(app.pending_pick.is_none()); + assert!(app.status.is_some(), "IMPORT ran with the picked file and reported its error"); + } + + /// A dialog's answer acts on the drawing that asked for it, even when another drawing was + /// made active before it arrived (a control-channel `document.switch` runs before the answer + /// in the same frame): Save As must not write the other drawing to the chosen file. + #[test] + fn a_deferred_dialog_acts_on_the_drawing_that_asked() { + let (mut app, _, answer) = deferred_app(); + let ctx = egui::Context::default(); + app.run("new", json!({})).unwrap(); + app.run("document.switch", json!({ "index": 0 })).unwrap(); + let first = uid(&app); + let acted_on = Rc::new(RefCell::new(None)); + let seen = acted_on.clone(); + let r = app.pick_then(Pick::Save("Drawing1.dxf".into()), move |app, path| { + *seen.borrow_mut() = Some((uid(app), path)); + Ok(json!(null)) + }); + assert_eq!(r, Some(Ok(json!(null)))); + + app.run("document.switch", json!({ "index": 1 })).unwrap(); + assert_ne!(uid(&app), first); + answer.borrow_mut().take().unwrap()(Some("a.dxf".into())); + app.finish_pick(&ctx); + assert_eq!(*acted_on.borrow(), Some((first, "a.dxf".to_string()))); + assert_eq!(app.session.active, 0, "the drawing that asked is shown again"); + } + + /// The drawing that asked was closed before the answer: nothing is done, and the status bar + /// says so. A dialog that opens a drawing (OPEN, NEW from a template) still acts. + #[test] + fn a_deferred_dialog_for_a_closed_drawing_does_nothing() { + let (mut app, _, answer) = deferred_app(); + let ctx = egui::Context::default(); + app.run("new", json!({})).unwrap(); + let ran = Rc::new(RefCell::new(0)); + let r1 = ran.clone(); + let _ = app.pick_then(Pick::Save("Drawing2.svg".into()), move |_, _| { + *r1.borrow_mut() += 1; + Ok(json!(null)) + }); + app.run("close", json!({ "index": 1 })).unwrap(); + answer.borrow_mut().take().unwrap()(Some("b.svg".into())); + app.finish_pick(&ctx); + assert_eq!(*ran.borrow(), 0, "the closed drawing's export did not run on another drawing"); + assert!(app.pending_pick.is_none()); + assert!(app.status.as_ref().is_some_and(|(s, _)| s.contains("closed") && s.contains("b.svg")), "{:?}", app.status); + + app.run("new", json!({})).unwrap(); + let r2 = ran.clone(); + let _ = app.pick_then_open(Pick::Open, move |_, _| { + *r2.borrow_mut() += 1; + Ok(json!(null)) + }); + app.run("close", json!({ "index": 1 })).unwrap(); + answer.borrow_mut().take().unwrap()(Some("c.dxf".into())); + app.finish_pick(&ctx); + assert_eq!(*ran.borrow(), 1, "OPEN goes on whichever drawing closed meanwhile"); + } + + /// The host dropped the answer (its dialog thread could not start): the status bar says + /// the dialog could not be shown, unlike a cancelled dialog, and the next one may open. + #[test] + fn a_dialog_that_never_answers_is_reported() { + let services = + Services { pick_save: Some(Box::new(|_: &str| None)), start_pick: Some(Box::new(|_, done| drop(done))), ..Services::default() }; + let mut app = CadApp::new(Session::new(), services); + app.start("export"); + app.finish_pick(&egui::Context::default()); + assert!(app.pending_pick.is_none()); + assert!(status(&app).contains("could not be shown"), "{:?}", app.status); + } + + /// With no drawing open, a dialog bound to the active drawing is not shown: its answer could + /// otherwise save or export a drawing opened while it was up. + #[test] + fn a_bound_dialog_needs_an_open_drawing() { + let (mut app, asked, _) = deferred_app(); + app.run("close", json!({ "index": 0 })).unwrap(); + assert!(app.session.state().is_err()); + app.start("ui.saveas"); + let r = app.run("ui.saveas", json!(null)); + assert!(asked.borrow().is_empty(), "no dialog"); + assert!(app.pending_pick.is_none()); + assert!(r.is_err() && app.status.is_some(), "{r:?} {:?}", app.status); + // OPEN needs no drawing. + app.start("ui.open"); + assert_eq!(*asked.borrow(), [Pick::Open]); + } + + /// A command started while APPLOAD's dialog was open (a control request, say) keeps + /// running; APPLOAD is refused and says to run it again. + #[test] + fn appload_does_not_cancel_a_command_started_meanwhile() { + let (mut app, asked, answer) = deferred_app(); + let ctx = egui::Context::default(); + app.start("appload"); + assert!(matches!(asked.borrow().as_slice(), [Pick::Lisp(_)])); + app.start("line"); + assert!(app.session.prompting()); + answer.borrow_mut().take().unwrap()(Some("routine.lsp".into())); + app.finish_pick(&ctx); + assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("line"), "LINE was not cancelled"); + assert!(status(&app).starts_with("APPLOAD: another command started"), "{:?}", app.status); + } } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index af289ff56..546ac773a 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -45,6 +45,8 @@ pub enum Preference { Hungarian, #[serde(rename = "tr")] Turkish, + #[serde(rename = "ka")] + Georgian, #[serde(rename = "bs")] Bosnian, #[serde(rename = "vi")] @@ -52,7 +54,7 @@ pub enum Preference { } impl Preference { - pub const ALL: [Self; 19] = [ + pub const ALL: [Self; 20] = [ Self::Auto, Self::English, Self::Greek, @@ -70,6 +72,7 @@ impl Preference { Self::Arabic, Self::Hungarian, Self::Turkish, + Self::Georgian, Self::Bosnian, Self::Vietnamese, ]; @@ -119,6 +122,7 @@ impl Preference { Self::Arabic => "ar", Self::Hungarian => "hu", Self::Turkish => "tr", + Self::Georgian => "ka", Self::Bosnian => "bs", Self::Vietnamese => "vi", } @@ -149,6 +153,15 @@ impl Preference { Self::Arabic => "العربية", Self::Hungarian => "Magyar", Self::Turkish => "Türkçe", + // Georgian letters come from the craft-fonts Georgian face; a build without it shows + // the English name (as Korean does) and keeps the interface in English. + Self::Georgian => { + if crate::theme::can_show("ka") { + "ქართული" + } else { + "Georgian" + } + } Self::Bosnian => "Bosanski", // Its letters need a font egui doesn't bundle ([`crate::theme::vietnamese_font`]). Self::Vietnamese => { @@ -188,6 +201,7 @@ impl Preference { Self::Arabic => "ar", Self::Hungarian => "hu", Self::Turkish => "tr", + Self::Georgian => "ka", Self::Bosnian => "bs", Self::Vietnamese => "vi", Self::Auto => locales.iter().find_map(|s| locale_language(s)).unwrap_or("en"), @@ -206,7 +220,7 @@ pub struct Language { catalog: OnceLock>, } -pub static LANGUAGES: [Language; 18] = [ +pub static LANGUAGES: [Language; 19] = [ Language { code: "en", name: "English", source: "", plural: plural_en, plural_forms: 2, catalog: OnceLock::new() }, // Greek: one for exactly 1; other for zero and all other integer counts. Language { @@ -253,6 +267,11 @@ pub static LANGUAGES: [Language; 18] = [ Language { code: "hu", name: "Magyar", source: include_str!("i18n/hu.tsv"), plural: plural_ko, plural_forms: 1, catalog: OnceLock::new() }, // Turkish keeps a noun singular after a number ("3 commit"), so like Korean it has one form. Language { code: "tr", name: "Türkçe", source: include_str!("i18n/tr.tsv"), plural: plural_ko, plural_forms: 1, catalog: OnceLock::new() }, + // Georgian keeps a noun singular after a numeral ("5 კომიტი"), so one form, the Korean rule. + // Its letters come from the craft-fonts `Geor` face (`theme::can_show`). + Language { + code: "ka", name: "ქართული", source: include_str!("i18n/ka.tsv"), plural: plural_ko, plural_forms: 1, catalog: OnceLock::new() + }, // Bosnian (Latin script, Ijekavian): one (1, 21), few (2–4, 22–24, not 12–14), other — the // Ukrainian rule for integer counts. Language { code: "bs", name: "Bosanski", source: include_str!("i18n/bs.tsv"), plural: plural_uk, plural_forms: 3, catalog: OnceLock::new() }, diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index cf5741cdd..3d3921b28 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -1380,3 +1380,6 @@ menu View عرض Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. تغيّر الرسم. أغلق النافذة وافتحها مرة أخرى. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 957c48993..7803b744d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1456,3 +1456,6 @@ menu Modify Izmijeni Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. Crtež se promijenio. Zatvorite prozor i otvorite ga ponovo. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 67a6e90f6..ee587f284 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1236,3 +1236,6 @@ menu Modify Modifikace Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. Výkres se změnil. Zavřete okno a otevřete jej znovu. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0925cb6af..d2ffa5620 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1053,3 +1053,6 @@ Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. Die Zeichnung hat sich geändert. Schließen Sie das Fenster und öffnen Sie es erneut. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index c157df39a..042e6a672 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1393,3 +1393,6 @@ menu View Προβολή Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. Το σχέδιο άλλαξε. Κλείστε το παράθυρο και ανοίξτε το ξανά. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0e6471ee..229156b79 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1267,3 +1267,6 @@ Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. El dibujo cambió. Cierre la ventana y ábrala de nuevo. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2f391809e..477407a5a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1026,3 +1026,13 @@ Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. Le dessin a changé. Fermez la fenêtre et rouvrez-la. + Keyboard Shortcuts... Raccourcis clavier... + Keyboard Shortcuts Raccourcis clavier + Replaces the shortcut of {commands} Remplace le raccourci de : {commands} + Needs Ctrl, Alt or a function key Il faut Ctrl, Alt ou une touche de fonction + Press the keys Appuyez sur les touches + Back to CADCraft's shortcut Revenir au raccourci de CADCraft + A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. Un raccourci que vous définissez l'emporte sur celui de CADCraft. Les modifications s'appliquent tout de suite et sont conservées. diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index b87edd3c3..0665055de 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1358,3 +1358,6 @@ menu View Nézet Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. A rajz megváltozott. Zárja be az ablakot, és nyissa meg újra. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b298e1c98..8920337bd 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1378,3 +1378,23 @@ menu Modify Edita Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. Il disegno è cambiato. Chiudere la finestra e riaprirla. + Right-Click Customization... Personalizzazione pulsante destro... + Right-Click Customization Personalizzazione pulsante destro + Turn on time-sensitive right-click Attiva clic destro sensibile al tempo + Longer click duration: Durata clic lungo: + milliseconds millisecondi + While a command runs, a quick click is Enter and a longer click opens the shortcut menu. Durante un comando un clic rapido equivale a Invio, un clic più lungo apre il menu di scelta rapida. + Default Mode Modalità predefinita + No objects selected and no command running: Nessun oggetto selezionato e nessun comando in corso: + Edit Mode Modalità modifica + Objects selected and no command running: Oggetti selezionati e nessun comando in corso: + Repeat last command Ripeti ultimo comando + Shortcut Menu Menu di scelta rapida + Command Mode Modalità comando + While a command runs: Durante un comando: + ENTER INVIO + Shortcut Menu: always enabled Menu di scelta rapida: sempre attivo + Shortcut Menu: enabled when command options are present Menu di scelta rapida: attivo se il comando ha opzioni diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv new file mode 100644 index 000000000..e40f492c7 --- /dev/null +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -0,0 +1,1474 @@ +# CADCraft Georgian (ქართული) interface catalog — original translations by the CADCraft contributors. +# License: MIT OR Apache-2.0 (the repository LICENSE-MIT and LICENSE-APACHE). +# Written from CADCraft's English strings; no proprietary translations were copied. +# Clean room: every entry is written from the plain meaning of the English label in ordinary +# Georgian computing and technical-drawing (ხაზვა) vocabulary (შრე, ზომა, დაშტრიხვა, მომრგვალება, +# ფასკა, წანაცვლება, მოკვეთა, ობიექტზე მიბმა, ხედვის არე, განლაგება). No other product's Georgian +# interface, string table or terminology database was consulted, and no other catalog is used as a source. +# UTF-8: contextEnglish sourceGeorgian translation. +# Empty context = ordinary label; @plural = one form with {n} (a Georgian noun stays singular after +# a numeral: "5 კომიტი"); menu = a menu heading where it differs from the label. +# Commands are verbal nouns (შენახვა, შემობრუნება); prompts read "მიუთითეთ …" for Specify, +# "შეიყვანეთ …" for Enter and "მონიშნეთ …" for Select. Georgian has no letter case: nothing is +# capitalised and Mtavruli is never used. +# Keep command IDs, keywords (Top, Zero, Bottom, _tan to, nX/nXP, Multiple, PICKADD, QPMODE), +# technology/product names and user data unchanged. + + Apply გამოყენება + Attach DWG... DWG-ის მიმაგრება... + Bind მიბმა + Detach მოხსნა + Loaded ჩატვირთულია + Make it a block of this drawing, keeping its layer names ამ ნახაზის ბლოკად ქცევა, შრეების სახელების შენარჩუნებით + Make it a block of this drawing; its layers become NAME$0$LAYER ამ ნახაზის ბლოკად ქცევა; შრეების სახელები გახდება NAME$0$LAYER + No external references are attached. გარე მიმართვები მიმაგრებული არ არის. + Not Found ვერ მოიძებნა + Not loaded არ არის ჩატვირთული + Open გახსნა + Overlay ზედდება + Reference Manager მიმართვების მენეჯერი + Reference Name მიმართვის სახელი + References: {n} მიმართვა: {n} + Reload ხელახლა ჩატვირთვა + Reload All ყველას ხელახლა ჩატვირთვა + Saved Path შენახული გზა + Unload განტვირთვა + Unloaded განტვირთულია + Unreferenced მიმართვის გარეშე + Unresolved გადაუჭრელი + Cancel გაუქმება + OK OK + or [ ან [ + % of all commits ყველა კომიტის % + * Wildcard Match * შაბლონით დამთხვევა + *VARIES* *სხვადასხვა* + + | Top | 2D Wireframe + | ზედა | 2D კარკასი + +Bin +Bin + +LOC +LOC + 1 Viewport 1 ხედვის არე + 2 Points 2 წერტილი + 2 Viewports 2 ხედვის არე + 2D Solid 2D შევსებული არე + 3 Points 3 წერტილი + 3 Viewports 3 ხედვის არე + 3D Face 3D წახნაგი + 3D Operations 3D ოპერაციები + 3D Polyline 3D ტეხილი + 4 Viewports 4 ხედვის არე + < Less than < ნაკლებია + <> Not Equal <> არ უდრის + = Equals = უდრის + > Greater than > მეტია + A variable name starts with a letter and has only letters, digits and _ ცვლადის სახელი ასოთი იწყება და მხოლოდ ასოებს, ციფრებსა და _-ს შეიცავს + About პროგრამის შესახებ + About CADCraft CADCraft-ის შესახებ + Absolute აბსოლუტური + Add Leader მიმთითებლის დამატება + Additional angles დამატებითი კუთხეები + Align სწორება + Align Text ტექსტის სწორება + Aligned გასწორებული + All ყველა + All Annotation Objects ყველა ანოტაციური ობიექტი + All Used Layers ყველა გამოყენებული შრე + All files ყველა ფაილი + Angle კუთხე + Angular კუთხური + Annotation Visibility ანოტაციის ხილვადობა + Annotation scale ანოტაციის მასშტაბი + Apparent Intersection ხილული გადაკვეთა + Append to current selection set მიმდინარე მონიშნულზე დამატება + Apply to: გამოყენება: + Apply true color ნამდვილი ფერის გამოყენება + Arc რკალი + Arc Length რკალის სიგრძე + Area ფართობი + Arrange Panel პანელის დალაგება + Array მასივი + Attach მიმაგრება + Attribute ატრიბუტი + Attribute Definition ატრიბუტის განსაზღვრა + Attribute Display ატრიბუტების ჩვენება + Audit აუდიტი + Auto (system language) ავტომატური (სისტემის ენა) + Auto Constrain ავტომატური შეზღუდვა + AutoConstrain ავტოშეზღუდვა + Axis, End ღერძი, ბოლო + Base ბაზა + Baseline საბაზისო ხაზი + Batch Publish პაკეტური გამოქვეყნება + Binary assets added დამატებული ბინარული ფაილები + Binary assets removed წაშლილი ბინარული ფაილები + Bind... მიბმა... + Blend გადასვლა + Block ბლოკი + Block Attribute Manager... ბლოკის ატრიბუტების მენეჯერი... + Block Description... ბლოკის აღწერა... + Block Editor ბლოკის რედაქტორი + Block Reference ბლოკის ჩასმა + Block... ბლოკი... + Blocks ბლოკები + Blue ლურჯი + Bold მუქი + Boolean ლოგიკური + Boundary საზღვარი + Boundary... საზღვარი... + Box პარალელეპიპედი + Break გაწყვეტა + Break At Point წერტილში გაწყვეტა + Break-line Symbol წყვეტის ხაზის სიმბოლო + Bring Above Objects ობიექტებზე ზემოთ გადატანა + Bring Annotations to Front ანოტაციების წინა პლანზე გადმოტანა + Bring to Front წინა პლანზე გადმოტანა + Bulleted list ბურთულებიანი სია + ByBlock ბლოკის მიხედვით + ByColor ფერის მიხედვით + ByLayer შრის მიხედვით + CADCraft Help CADCraft-ის დახმარება + Cancel გაუქმება + Cartesian (x, y) დეკარტული (x, y) + Center ცენტრი + Center Line ღერძული ხაზი + Center Mark ცენტრის ნიშანი + Center X ცენტრი X + Center Y ცენტრი Y + Center Z ცენტრი Z + Center, Diameter ცენტრი, დიამეტრი + Center, Radius ცენტრი, რადიუსი + Center, Start, Angle ცენტრი, დასაწყისი, კუთხე + Center, Start, End ცენტრი, დასაწყისი, ბოლო + Center, Start, Length ცენტრი, დასაწყისი, სიგრძე + Chamfer ფასკა + Change Space სივრცის შეცვლა + Change to Current Layer მიმდინარე შრეზე გადატანა + Changed: {n} შეცვლილი: {n} + Circle წრე + Circumference წრეწირის სიგრძე + Clear History ისტორიის გასუფთავება + Clear გასუფთავება + Clip მოჭრა + Clip Viewport ხედვის არის მოჭრა + Clipboard გაცვლის ბუფერი + Close დახურვა + Close All ყველას დახურვა + Close All Other Drawings ყველა სხვა ნახაზის დახურვა + Closed შეკრული + Close Comparison შედარების დახურვა + Export Comparison შედარების ექსპორტი + Coincident დამთხვევა + Collapse Palettes პალიტრების ჩაკეცვა + Collapse Tool Sets ხელსაწყოთა ნაკრებების ჩაკეცვა + Collinear კოლინეარობა + Color ფერი + Color 8 ფერი 8 + Color 9 ფერი 9 + Color Index ფერის ინდექსი + Color... ფერი... + Command Aliases ბრძანებების ფსევდონიმები + Command History ბრძანებების ისტორია + Clear Command History ბრძანებების ისტორიის გასუფთავება + Command Line ბრძანების სტრიქონი + Command Line History Lines ბრძანების სტრიქონის ისტორიის სტრიქონები + Command Reference ბრძანებების ცნობარი + Commits კომიტები + Company კომპანია + Compare Drawings... ნახაზების შედარება... + Computer-aided design and drafting: an open-source, clean-room CAD application written in pure Rust. კომპიუტერული დაპროექტება და ხაზვა: ღია კოდის CAD აპლიკაცია, შექმნილი „სუფთა ოთახის“ მეთოდით და დაწერილი სუფთა Rust-ზე. + Concentric კონცენტრულობა + Cone კონუსი + Constraint Bars შეზღუდვების ზოლები + Constraint Settings შეზღუდვების პარამეტრები + Construction Line დამხმარე ხაზი + Contents შიგთავსი + Continue გაგრძელება + Contributors მონაწილეები + Control Vertices მართვის წვეროები + Convert გარდაქმნა + Convert Text to Mtext ტექსტის Mtext-ად გარდაქმნა + Copy კოპირება + Copy Full File Path ფაილის სრული გზის კოპირება + Copy History ისტორიის კოპირება + Copy Layout განლაგების კოპირება + Copy Nested Objects ჩადგმული ობიექტების კოპირება + Copy Selection მონიშნულის კოპირება + Copy with Base Point კოპირება საბაზო წერტილით + Count დათვლა + Count List დათვლის სია + Count Table დათვლის ცხრილი + Create Block ბლოკის შექმნა + Creates a user parameter ქმნის მომხმარებლის პარამეტრს + Ctrl+Enter to finish დასასრულებლად: Ctrl+Enter + Current layer მიმდინარე შრე + Current selection მიმდინარე მონიშნული + Current: {color} მიმდინარე: {color} + Cut ამოჭრა + Cut with Base Point ამოჭრა საბაზო წერტილით + Cyan ცისფერი + Cylinder ცილინდრი + DWG DWG + DWG Reference... DWG მიმართვა... + DXF DXF + Dark ბნელი + Data Extraction... მონაცემების ამოღება... + Default ნაგულისხმევი + Data Link... მონაცემთა კავშირი... + Default Save Format შენახვის ნაგულისხმევი ფორმატი + Default Save Version შენახვის ნაგულისხმევი ვერსია + Define Attributes ატრიბუტების განსაზღვრა + Define Attributes... ატრიბუტების განსაზღვრა... + Defined width განსაზღვრული სიგანე + Degree გრადუსი + Degrees of Freedom თავისუფლების ხარისხები + Degrees of freedom: {n} თავისუფლების ხარისხი: {n} + Delete წაშლა + Delete Column სვეტის წაშლა + Delete Constraints შეზღუდვების წაშლა + Delete Dimension Style ზომის სტილის წაშლა + Delete Duplicate Objects დუბლიკატი ობიექტების წაშლა + Delete Layer შრის წაშლა + Delete Layer State შრეების მდგომარეობის წაშლა + Delete Layout განლაგების წაშლა + Delete Row სტრიქონის წაშლა + Delete Text Style ტექსტის სტილის წაშლა + Delta X დელტა X + Delta Y დელტა Y + Description აღწერა + Deselect All ყველა მონიშვნის მოხსნა + Diameter დიამეტრი + Dim style ზომის სტილი + Dimension Break ზომის გაწყვეტა + Dimension Edit ზომის რედაქტირება + Dimension ზომა + Dimension Objects Only მხოლოდ ზომის ობიექტები + Dimension Space ზომების დაშორება + Dimension Style Override ზომის სტილის ლოკალური ცვლილება + Dimension Style... ზომის სტილი... + Dimension Text Edit ზომის ტექსტის რედაქტირება + Dimension style ზომის სტილი + Dimensional Constraint ზომითი შეზღუდვა + Dimensional Constraint Parameters ზომითი შეზღუდვის პარამეტრები + Dimensional Constraints ზომითი შეზღუდვები + Disassociate Dimensions ზომების ასოციაციის მოხსნა + Display name საჩვენებელი სახელი + Distance მანძილი + Divide დაყოფა + Do not plot (click: plot) არ იბეჭდება (დაწკაპეთ: ბეჭდვა) + Donut რგოლი + Double-click to edit the description ორჯერ დაწკაპეთ აღწერის რედაქტირებისთვის + Down ქვემოთ + Drafting ხაზვა + Drafting Settings ხაზვის პარამეტრები + Drafting Settings... ხაზვის პარამეტრები... + Draw ხატვა + Draw Order ხატვის რიგი + Drawing (DWG) ნახაზი (DWG) + Drawing (DXF) ნახაზი (DXF) + Drawing Limits ნახაზის ზღვრები + Drawing Template (DWT) ნახაზის შაბლონი (DWT) + Drawing Utilities ნახაზის უტილიტები + Drawings (DWG, DXF) ნახაზები (DWG, DXF) + AutoLISP (LSP) AutoLISP (LSP) + SVG drawings (SVG, SVGZ) SVG ნახაზები (SVG, SVGZ) + Dynamic დინამიკური + Dynamic Dimensions დინამიკური ზომები + Dynamic Input დინამიკური შეყვანა + Dynamic Input (F12) დინამიკური შეყვანა (F12) + E E + Edit რედაქტირება + Edit Attributes... ატრიბუტების რედაქტირება... + Edit Text... ტექსტის რედაქტირება... + Edit Table Cell ცხრილის უჯრის რედაქტირება + Elevation დონე + Ellipse ელიფსი + Elliptical Arc ელიფსური რკალი + Enable Dynamic Input (F12) დინამიკური შეყვანის ჩართვა (F12) + End Object Isolation ობიექტების იზოლირების დასრულება + End Width ბოლო სიგანე + End X ბოლო X + End Y ბოლო Y + End angle ბოლო კუთხე + Endpoint ბოლო წერტილი + Enter შეყვანა + Enter Top, Zero or Bottom. შეიყვანეთ Top, Zero ან Bottom. + Enter a fit data option შეიყვანეთ მისადაგების მონაცემების ვარიანტი + Enter a pattern name შეიყვანეთ ნიმუშის სახელი + Enter a vertex editing option შეიყვანეთ წვეროს რედაქტირების ვარიანტი + Enter an option შეიყვანეთ ვარიანტი + Enter angle of xline შეიყვანეთ დამხმარე ხაზის კუთხე + Enter angle of xline (0) შეიყვანეთ დამხმარე ხაზის კუთხე (0) + Enter area of rectangle in current units შეიყვანეთ მართკუთხედის ფართობი მიმდინარე ერთეულებში + Enter attribute prompt შეიყვანეთ ატრიბუტის მოთხოვნა + Enter attribute tag name შეიყვანეთ ატრიბუტის ტეგის სახელი + Enter attribute value შეიყვანეთ ატრიბუტის მნიშვნელობა + Enter block name შეიყვანეთ ბლოკის სახელი + Enter constraint type შეიყვანეთ შეზღუდვის ტიპი + Enter continuity შეიყვანეთ უწყვეტობის ტიპი + Enter default attribute value შეიყვანეთ ატრიბუტის ნაგულისხმევი მნიშვნელობა + Enter degree of spline შეიყვანეთ სპლაინის ხარისხი + Enter delta angle შეიყვანეთ კუთხის ნამატი + Enter delta length შეიყვანეთ სიგრძის ნამატი + Enter dimension text შეიყვანეთ ზომის ტექსტი + Enter dimension text (<> = measurement) შეიყვანეთ ზომის ტექსტი (<> = გაზომილი მნიშვნელობა) + Enter dimension value or [name=expression] შეიყვანეთ ზომის მნიშვნელობა ან [name=expression] + Enter dimension variable name to override შეიყვანეთ გადასაფარავი ზომის ცვლადის სახელი + Enter justification type შეიყვანეთ სწორების ტიპი + Enter leader text შეიყვანეთ მიმთითებლის ტექსტი + Enter mline scale შეიყვანეთ მულტიხაზის მასშტაბი + Enter mode შეიყვანეთ რეჟიმი + Enter name of block to insert შეიყვანეთ ჩასასმელი ბლოკის სახელი + Enter new text შეიყვანეთ ახალი ტექსტი + Enter next point შეიყვანეთ შემდეგი წერტილი + Enter number of columns შეიყვანეთ სვეტების რაოდენობა + Enter number of data rows შეიყვანეთ მონაცემების სტრიქონების რაოდენობა + Enter number of items შეიყვანეთ ელემენტების რაოდენობა + Enter number of items along path შეიყვანეთ ელემენტების რაოდენობა ტრაექტორიის გასწვრივ + Enter number of sides შეიყვანეთ გვერდების რაოდენობა + Enter number of turns შეიყვანეთ ხვიების რაოდენობა + Enter percentage length შეიყვანეთ სიგრძე პროცენტებში + Enter rectangle length შეიყვანეთ მართკუთხედის სიგრძე + Enter rectangle width შეიყვანეთ მართკუთხედის სიგანე + Enter scale factor შეიყვანეთ მასშტაბის კოეფიციენტი + Enter text შეიყვანეთ ტექსტი + Enter text (use \P for new paragraphs) შეიყვანეთ ტექსტი (ახალი აბზაცისთვის გამოიყენეთ \P) + Enter the number of segments შეიყვანეთ სეგმენტების რაოდენობა + Enter twist direction of helix შეიყვანეთ სპირალის დახვევის მიმართულება + Entire drawing მთელი ნახაზი + Equal ტოლობა + Erase წაშლა + Evaluate გამოთვლა + Evaluate LISP LISP-ის გამოთვლა + Exclude from new selection set ახალი მონიშნულიდან გამორიცხვა + Explode დაშლა + Explode Attributes to Text ატრიბუტების ტექსტად დაშლა + Export ექსპორტი + Export Table ცხრილის ექსპორტი + Export to PDF... PDF-ად ექსპორტი... + Express Tools Express Tools + Expression გამოსახულება + Extend გაგრძელება + Extension გაგრძელება + Extents საზღვრები + External Reference გარე მიმართვა + External References გარე მიმართვები + Extrude ამოწევა + File ფაილი + File Tab ფაილის ჩანართი + Fillet მომრგვალება + Filter ფილტრი + Filters ფილტრები + Find and Replace ძებნა და ჩანაცვლება + Find... ძებნა... + First პირველი + First commit პირველი კომიტი + Fit Points მისადაგების წერტილები + Fix ფიქსაცია + Flatten Objects ობიექტების სიბრტყეზე დაგეგმილება + Font შრიფტი + Format ფორმატი + Freehand ხელით ხაზვა + Freeze გაყინვა + Freeze Layer შრის გაყინვა + Freeze in new viewports გაყინვა ახალ ხედვის არეებში + Freeze/Thaw გაყინვა/გალღობა + Freeze/Thaw in all viewports გაყინვა/გალღობა ყველა ხედვის არეში + Freeze/Thaw in the current viewport გაყინვა/გალღობა მიმდინარე ხედვის არეში + From წერტილიდან + From Template... შაბლონიდან... + General ზოგადი + Geometric Center გეომეტრიული ცენტრი + Geometric Constraint გეომეტრიული შეზღუდვა + Geometric Constraints გეომეტრიული შეზღუდვები + Geometry გეომეტრია + Get from the Drawing ნახაზიდან აღება + Get Variable ცვლადის მიღება + Get View ხედის მიღება + Global გლობალური + Global width საერთო სიგანე + Grab bag სხვადასხვა + Gradient გრადიენტი + Gradient... გრადიენტი... + Green მწვანე + Grid (F7) ბადე (F7) + Grid Display ბადის ჩვენება + Grid On (F7) ბადის ჩართვა (F7) + Grid snap ბადეზე მიბმა + Grid spacing ბადის ბიჯი + Grip Edit სახელურით რედაქტირება + Grip Mirror სახელურით არეკვლა + Grip Option სახელურის პარამეტრი + Grip Rotate სახელურით შემობრუნება + Grip Scale სახელურით მასშტაბირება + Grip Stretch სახელურით გაწელვა + Group დაჯგუფება + Group Edit ჯგუფის რედაქტირება + Group Options დაჯგუფების პარამეტრები + Group Selection ჯგუფის მონიშვნა + Hatch დაშტრიხვა + Hatch Edit დაშტრიხვის რედაქტირება + Hatch Patterns დაშტრიხვის ნიმუშები + Hatch... დაშტრიხვა... + Height სიმაღლე + Height: {height} სიმაღლე: {height} + Helix სპირალი + Help დახმარება + Hide All ყველას დამალვა + Hide All Constraint Bars შეზღუდვების ყველა ზოლის დამალვა + Hide All Dynamic Dimensions ყველა დინამიკური ზომის დამალვა + Hide Layer List შრეების სიის დამალვა + Hide Objects ობიექტების დამალვა + Hide Palettes პალიტრების დამალვა + History ისტორია + Home საწყისი ხედი + Horizontal ჰორიზონტალური + HorizontalDistance ჰორიზონტალური მანძილი + How to apply: გამოყენების წესი: + ID Point წერტილის კოორდინატები + Import იმპორტი + Align Multileaders მულტიმიმთითებლების სწორება + Collect შეგროვება + Collect Multileaders მულტიმიმთითებლების შეგროვება + Edit Multileader მულტიმიმთითებლის რედაქტირება + In მოახლოება + In-window Menu Bar მენიუს ზოლი ფანჯარაში + Include in new selection set ახალ მონიშნულ ნაკრებში ჩართვა + Increment angle კუთხის ბიჯი + Index Color ინდექსური ფერი + Index color: {index} ინდექსური ფერი: {index} + Infer Constraints შეზღუდვების ავტომატური დადგენა + Inquiry მოთხოვნა + Insert ჩასმა + Insert Block ბლოკის ჩასმა + Insert Column სვეტის ჩასმა + Insert Row სტრიქონის ჩასმა + Insert tab ტაბულაციის ჩასმა + Insert this block ამ ბლოკის ჩასმა + Insert Table Formula ცხრილში ფორმულის ჩასმა + Insertion ჩასმის წერტილი + Insertion X ჩასმის წერტილი X + Insertion Y ჩასმის წერტილი Y + Insertion Z ჩასმის წერტილი Z + Inspect Constraints შეზღუდვების შემოწმება + Inspect Drawing ნახაზის შემოწმება + Inspection შემოწმება + Interface Language ინტერფეისის ენა + Interface Theme ინტერფეისის თემა + Intersect გადაკვეთა + Intersection გადაკვეთა + Isolate იზოლირება + Isolate Layer შრის იზოლირება + Isolate Objects ობიექტების იზოლირება + Isometric Drafting იზომეტრიული ხაზვა + Jogged გატეხილი + Jogged Linear გატეხილი წრფივი + Join შეერთება + Join the ArtCraft Discord… შემოუერთდით ArtCraft-ის Discord-ს… + Join us on Discord შემოგვიერთდით Discord-ზე + Isometric Plane იზომეტრიული სიბრტყე + Isometric snap იზომეტრიული მიბმა + Language ენა + Last ბოლო + Last commit ბოლო კომიტი + Layer შრე + Layer Delete შრის წაშლა + Layer Match შრის მისადაგება + Layer Merge შრეების შერწყმა + Layer Off შრის გამორთვა + Layer Properties შრის თვისებები + Layer Properties Manager შრის თვისებების მენეჯერი + Layer Properties Manager — current viewport შრის თვისებების მენეჯერი — მიმდინარე ხედვის არე + Layer State შრის მდგომარეობა + Layer States Manager... შრის მდგომარეობების მენეჯერი... + Layer Tools შრის ხელსაწყოები + Layer contains objects (double-click to make current) შრეში ობიექტებია (მიმდინარედ გასახდომად ორჯერ დაწკაპეთ) + Layer is empty (double-click to make current) შრე ცარიელია (მიმდინარედ გასახდომად ორჯერ დაწკაპეთ) + Layers შრეები + Layers Palette შრეების პალიტრა + Hide Palette პალიტრის დამალვა + Layers displayed: {shown} of {total}. Current layer: {layer} ნაჩვენები შრეები: {shown} / {total}. მიმდინარე შრე: {layer} + Layout განლაგება + Layout list განლაგებების სია + Leader მიმთითებელი + Leaders Only მხოლოდ მიმთითებლები + Left მარცხნივ + Length სიგრძე + Length X სიგრძე X + Length Y სიგრძე Y + Lengthen დაგრძელება + Light ღია + Line ხაზი + Line delta სტრიქონების სხვაობა + Linear წრფივი + Lines +/− სტრიქონები +/− + Lines added დამატებული სტრიქონები + Lines deleted წაშლილი სტრიქონები + Lines of Command History ბრძანებების ისტორიის სტრიქონები + Linetype ხაზის ტიპი + Linetype Scale ხაზის ტიპის მასშტაბი + Linetype scale ხაზის ტიპის მასშტაბი + Ltscale ხაზის ტიპის მასშტაბი + Linetype... ხაზის ტიპი... + Lineweight ხაზის სისქე + Lineweight... ხაზის სისქე... + List სია + List Blocks ბლოკების სია + List Dimension Styles ზომის სტილების სია + List Groups ჯგუფების სია + List Layer States შრის მდგომარეობების სია + List Layouts განლაგებების სია + List System Variables სისტემის ცვლადების სია + List Text Styles ტექსტის სტილების სია + Load all ყველას ჩატვირთვა + Load... ჩატვირთვა... + Load Application... აპლიკაციის ჩატვირთვა... + Loaded linetypes ჩატვირთული ხაზის ტიპები + Lock ჩაკეტვა + Lock Layer შრის ჩაკეტვა + Lock viewport ხედვის არის ჩაკეტვა + Lock/Unlock ჩაკეტვა/განბლოკვა + Loft კვეთებით აგება + MIT OR Apache-2.0. Not affiliated with Autodesk, Inc. MIT OR Apache-2.0. Autodesk, Inc.-თან კავშირი არ აქვს. + MODEL მოდელი + MText MText + Magenta მეწამული + Major line every ყოველი N-ე ხაზი მთავარია + Make Current მიმდინარედ დაყენება + Make Object's Layer Current ობიექტის შრის მიმდინარედ დაყენება + Make... შექმნა... + Match Layer შრის მისადაგება + Match Properties თვისებების გადატანა + Measure გაზომვა + Measure Distance მანძილის გაზომვა + Measure Geometry გეომეტრიის გაზომვა + Merge Cells უჯრების შერწყმა + Merged PRs გაერთიანებული PR-ები + Mid Between 2 Points შუა 2 წერტილს შორის + Midpoint შუა წერტილი + Mirror არეკვლა + Model მოდელი + Model Space (in viewport) მოდელის სივრცე (ხედვის არეში) + Modeling მოდელირება + Models მოდელები + Modify შეცვლა + Move გადაადგილება + Move/Copy/Rotate გადაადგილება/კოპირება/შემობრუნება + Multileader მულტიმიმთითებელი + Multileader Style... მულტიმიმთითებლის სტილი... + Multileader style მულტიმიმთითებლის სტილი + Multiline მულტიხაზი + Multiline Text მრავალსტრიქონიანი ტექსტი + Multiline Text... მრავალსტრიქონიანი ტექსტი... + Multiple რამდენიმე + Multiple Point რამდენიმე წერტილი + My ჩემი + My properties: not available yet ჩემი თვისებები: ჯერ ხელმისაწვდომი არ არის + N N + Name სახელი + Name (A–Z) სახელი (ა–ჰ) + Named Viewports... დასახელებული ხედვის არეები... + Named Views... დასახელებული ხედები... + Nearest უახლოესი + New ახალი + New (metric) ახალი (მეტრული) + New Drawing ახალი ნახაზი + New Drawing (⌘N) ახალი ნახაზი (⌘N) + New Drawing... ახალი ნახაზი... + New Layer ახალი შრე + New Layout ახალი განლაგება + New VP Freeze გაყინვა ახალ ხედვის არეებში + New Viewports... ახალი ხედვის არეები... + New from Template... ახალი შაბლონიდან... + New layout ახალი განლაგება + New state name მდგომარეობის ახალი სახელი + Next Change შემდეგი ცვლილება + No არა + No blocks defined in this drawing. ამ ნახაზში ბლოკები არ არის განსაზღვრული. + No contributor data was built into this copy. ამ ასლში მონაწილეების მონაცემები არ არის ჩაშენებული. + No model credits were built into this copy. ამ ასლში მოდელების მონაცემები არ არის ჩაშენებული. + No saved layer states შრის შენახული მდგომარეობები არ არის + No selection მონიშნული არაფერია + Node კვანძი + None არცერთი + Not available მიუწვდომელია + Not available yet ჯერ ხელმისაწვდომი არ არის + Numbered list დანომრილი სია + OK OK + Object ობიექტი + Object Snap ობიექტზე მიბმა + Object Snap (F3) ობიექტზე მიბმა (F3) + Object Snap On (F3) ობიექტზე მიბმის ჩართვა (F3) + Object Snap Tracking მიბმის მიდევნება + Object Snap Tracking (F11) მიბმის მიდევნება (F11) + Object Snap Tracking Settings მიბმის მიდევნების პარამეტრები + Object type: ობიექტის ტიპი: + Oblique დახრა + Off გამორთული + Offset წანაცვლება + On ჩართული + On/Off ჩართვა/გამორთვა + One of the Crafting Apps by the ArtCraft team and community. ArtCraft-ის გუნდისა და საზოგადოების ერთ-ერთი Crafting App. + Only in this drawing: {n} მხოლოდ ამ ნახაზში: {n} + Only in {name}: {n} მხოლოდ ფაილში {name}: {n} + Open (⌘O) გახსნა (⌘O) + Open Sample Drawing სანიმუშო ნახაზის გახსნა + Open sample drawing სანიმუშო ნახაზის გახსნა + Open Xref გარე მიმართვის გახსნა + Open... გახსნა... + Open Recent ბოლოს გახსნილი ფაილების გახსნა + Clear Recent Files ბოლოს გახსნილი ფაილების სიის გასუფთავება + Operator: ოპერატორი: + Orbit ორბიტა + Ordinate ორდინატა + Ortho (F8) ორთო (F8) + Ortho Mode ორთო რეჟიმი + Ortho Mode (F8) ორთო რეჟიმი (F8) + Osnap Settings... ობიექტზე მიბმის პარამეტრები... + Out დაშორება + Over-constrained ზედმეტად შეზღუდული + Override გადაფარვა + PAPER ფურცელი + Percent პროცენტი + Polar (distance < angle) პოლარული (მანძილი < კუთხე) + PRs PR-ები + Page Setup Manager გვერდის პარამეტრების მენეჯერი + Page Setup Manager... გვერდის პარამეტრების მენეჯერი... + Pan პანორამა + Pan Down პანორამა ქვემოთ + Pan Left პანორამა მარცხნივ + Pan Right პანორამა მარჯვნივ + Pan Up პანორამა ზემოთ + Paper Space ფურცლის სივრცე + Parallel პარალელური + Parameters Manager პარამეტრების მენეჯერი + Parametric პარამეტრული + Paste ჩასმა + Paste as Block ბლოკად ჩასმა + Paste to Command Line ბრძანების სტრიქონში ჩასმა + Paste to Original Coordinates საწყის კოორდინატებზე ჩასმა + Path Array ტრაექტორიული მასივი + Pattern ნიმუში + Perpendicular მართობი + Plot დაბეჭდვა + Plot (click: do not plot) იბეჭდება (დაწკაპეთ, რომ არ დაიბეჭდოს) + Plot Preview ნახვა ამობეჭდვამდე + Plot Window ბეჭდვის ფანჯარა + Plot style ბეჭდვის სტილი + Plot style attached to ბეჭდვის სტილი მიმაგრებულია + Plot style table ბეჭდვის სტილების ცხრილი + Plot Style... ბეჭდვის სტილი... + Plot Style Manager ბეჭდვის სტილების მენეჯერი + Plot Style Manager... ბეჭდვის სტილების მენეჯერი... + Plot Styles... ბეჭდვის სტილები... + Plotter Manager პლოტერების მენეჯერი + Plotter Manager... პლოტერების მენეჯერი... + New CTB ახალი CTB + New STB ახალი STB + New style ახალი სტილი + Reset Panel Layout პანელების განლაგების ჩამოყრა + Send Hatches to Back დაშტრიხვების უკანა პლანზე გადატანა + Send Under Objects ობიექტების ქვეშ გადატანა + Text Objects Only მხოლოდ ტექსტური ობიექტები + Use for this layout ამ განლაგებისთვის გამოყენება + Display plot styles ბეჭდვის სტილების ჩვენება + No plot style tables. ბეჭდვის სტილების ცხრილები არ არის. + A built-in table: editing it keeps an edited copy in the drawing. ჩაშენებული ცხრილი: რედაქტირებისას შეცვლილი ასლი ნახაზში ინახება. + Keep an editable copy of this table in the drawing ამ ცხრილის რედაქტირებადი ასლის ნახაზში შენახვა + Layout {name}: {table} განლაგება {name}: {table} + Grayscale ნაცრისფერი ტონები + Screening ტონირება + Use object linetype ობიექტის ხაზის ტიპის გამოყენება + Use object lineweight ობიექტის ხაზის სისქის გამოყენება + Remove წაშლა + Add დამატება + Open a drawing first. ჯერ გახსენით ნახაზი. + Plot table type ბეჭდვის ცხრილის ტიპი + Color-dependent ფერზე დამოკიდებული + Named დასახელებული + Plus/minus პლუს/მინუს + Point წერტილი + Point Filters წერტილის ფილტრები + Point Style... წერტილის სტილი... + Polar Array პოლარული მასივი + Polar Tracking პოლარული მიდევნება + Polar Tracking (F10) პოლარული მიდევნება (F10) + Polar Tracking On (F10) პოლარული მიდევნების ჩართვა (F10) + Polar angle measurement პოლარული კუთხის ათვლა + Polar distance პოლარული მანძილი + Polar: {distance} < {angle}° პოლარული: {distance} < {angle}° + PolarSnap პოლარული მიბმა + Polygon მრავალკუთხედი + Polygonal მრავალკუთხა + Polygonal Viewport მრავალკუთხა ხედვის არე + Polyline ტეხილი + Polyline Edit ტეხილის რედაქტირება + Position X პოზიცია X + Position Y პოზიცია Y + Position Z პოზიცია Z + Previous წინა + Previous Change წინა ცვლილება + Previous Layer წინა შრე + Primitives პრიმიტივები + Print დაბეჭდვა + Print... დაბეჭდვა... + Properties თვისებები + Properties Inspector თვისებების ინსპექტორი + Properties: თვისებები: + Proxy პროქსი + Purge გაწმენდა + Pyramid პირამიდა + Quadrant კვადრანტი + Query Entities ობიექტების გამოთხოვნა + Quick სწრაფი + Quick Dimension სწრაფი ზომა + Quick Properties სწრაფი თვისებები + Quick Select სწრაფი მონიშვნა + Quick Select Properties სწრაფი მონიშვნის თვისებები + Quick Select... სწრაფი მონიშვნა... + QuickCalc სწრაფი კალკულატორი + QuickCalc Pick სწრაფი კალკულატორი: არჩევა + Quit CADCraft CADCraft-იდან გასვლა + Radius რადიუსი + Raster Image რასტრული გამოსახულება + Ray სხივი + Read-only მხოლოდ წასაკითხი + Real name ნამდვილი სახელი + Realtime რეალურ დროში + Reassociate Dimensions ზომების ხელახლა ასოცირება + Recent ბოლოდროინდელი + Recent Commands ბოლოდროინდელი ბრძანებები + Recent Input ბოლოდროინდელი შეყვანა + Recover... აღდგენა... + Rectangle მართკუთხედი + Recalculate Table Formulas ცხრილის ფორმულების გადათვლა + Rectangular მართკუთხა + Rectangular snap მართკუთხა მიბმა + Rectangular Array მართკუთხა მასივი + Red წითელი + Redo ხელახლა შესრულება + Redo (⇧⌘Z) ხელახლა შესრულება (⇧⌘Z) + Redraw გადახატვა + Regen რეგენერაცია + Regen All ყველაფრის რეგენერაცია + Region რეგიონი + Region/Mass Properties რეგიონის/მასის თვისებები + Reinitialize ხელახლა ინიციალიზება + Relative ფარდობითი + Relative to last segment ბოლო სეგმენტის მიმართ + Remove Leader მიმთითებლის მოცილება + Remove the viewport override ხედვის არის ცალკე პარამეტრის მოცილება + Rename Dimension Style ზომის სტილის სახელის შეცვლა + Rename Layer შრის სახელის შეცვლა + Rename Layer State შრეების მდგომარეობის სახელის შეცვლა + Rename Layout განლაგების სახელის შეცვლა + Rename Text Style ტექსტის სტილის სახელის შეცვლა + Rename... სახელის შეცვლა... + Repeat {command} გამეორება: {command} + Replace Block... ბლოკის ჩანაცვლება... + Requires a point (x,y, @dx,dy or @d მიუთითეთ მეორე წერტილი ან <პირველი წერტილი გამოიყენეთ წანაცვლებად> + Specify second source point მიუთითეთ მეორე საწყისი წერტილი + Specify side to offset მიუთითეთ წანაცვლების მხარე + Specify start angle მიუთითეთ საწყისი კუთხე + Specify start point მიუთითეთ საწყისი წერტილი + Specify start point of arc მიუთითეთ რკალის საწყისი წერტილი + Specify start point of polyline მიუთითეთ ტეხილის საწყისი წერტილი + Specify start point of text მიუთითეთ ტექსტის საწყისი წერტილი + Specify starting width მიუთითეთ საწყისი სიგანე + Specify starting width for next segment მიუთითეთ შემდეგი სეგმენტის საწყისი სიგანე + Specify tangent direction for the start point of arc მიუთითეთ მხების მიმართულება რკალის საწყის წერტილში + Specify the elevation for rectangles მიუთითეთ მართკუთხედების დონე + Specify thickness for rectangles მიუთითეთ მართკუთხედების სისქე + Specify third point on circle მიუთითეთ წრის მესამე წერტილი + Specify third point on circle: _tan to მიუთითეთ წრის მესამე წერტილი: _tan to + Specify third source point or მიუთითეთ მესამე საწყისი წერტილი ან <გაგრძელება> + Specify through point მიუთითეთ გავლის წერტილი + Specify top diameter მიუთითეთ ზედა დიამეტრი + Specify top radius მიუთითეთ ზედა რადიუსი + Specify total angle მიუთითეთ სრული კუთხე + Specify total length მიუთითეთ სრული სიგრძე + Specify width for rectangles მიუთითეთ მართკუთხედების სიგანე + Sphere სფერო + Spline სპლაინი + Spline Edit სპლაინის რედაქტირება + Stack (type 1/2 then select) დასტად დალაგება (აკრიფეთ 1/2 და მონიშნეთ) + Standard სტანდარტული + Start დასაწყისი + Start Width საწყისი სიგანე + Start X საწყისი X + Start Y საწყისი Y + Start angle საწყისი კუთხე + Start, Center, Angle დასაწყისი, ცენტრი, კუთხე + Start, Center, End დასაწყისი, ცენტრი, ბოლო + Start, Center, Length დასაწყისი, ცენტრი, სიგრძე + Start, End, Angle დასაწყისი, ბოლო, კუთხე + Start, End, Direction დასაწყისი, ბოლო, მიმართულება + Start, End, Radius დასაწყისი, ბოლო, რადიუსი + Status სტატუსი + Status Bar სტატუსის ზოლი + Stretch გაწელვა + Style: Standard სტილი: Standard + Subtract გამოკლება + Sweep ტრაექტორიით აგება + Switch Drawing ნახაზის გადართვა + Switch Layout განლაგების გადართვა + Switch between model space in a viewport and paper space გადართვა ხედვის არეში მოდელის სივრცესა და ფურცლის სივრცეს შორის + Symmetric სიმეტრია + Synchronize Attributes ატრიბუტების სინქრონიზაცია + To სადამდე + Toggle PICKADD (off: each pick replaces the selection) PICKADD-ის გადართვა (გამორთული: ყოველი არჩევა ცვლის მონიშნულს) + Toggle PICKADD (on: picks add to the selection) PICKADD-ის გადართვა (ჩართული: არჩეული ემატება მონიშნულს) + TOP ზედა + Table ცხრილი + Table Breaks ცხრილის გაწყვეტა + Table Cell Style ცხრილის უჯრის სტილი + Table Style... ცხრილის სტილი... + Table style ცხრილის სტილი + Table... ცხრილი... + Tan, Tan, Radius მხები, მხები, რადიუსი + Tan, Tan, Tan მხები, მხები, მხები + Tangent მხები + Temporary track point დროებითი მიდევნების წერტილი + Text ტექსტი + Text Editor ტექსტის რედაქტორი + Text Height ტექსტის სიმაღლე + Text Style... ტექსტის სტილი... + Text height ტექსტის სიმაღლე + Text override ტექსტის ჩანაცვლება + Text style ტექსტის სტილი + Thaw All Layers ყველა შრის გალღობა + Thaw Layer შრის გალღობა + There is nothing here yet. აქ ჯერ არაფერია. + Thickness სისქე + Time დრო + To get started, create or open a drawing. დასაწყებად შექმენით ან გახსენით ნახაზი. + Tool Bar ხელსაწყოთა ზოლი + Tool Sets ხელსაწყოთა ნაკრებები + Tools ხელსაწყოები + Torus ტორი + Trace სქელი ხაზი + Track orthogonally only მიდევნება მხოლოდ ორთოგონალურად + Track using all polar angle settings მიდევნება პოლარული კუთხის ყველა პარამეტრით + Transparency გამჭვირვალობა + Trim მოკვეთა + True Color ნამდვილი ფერი + Turn All Layers On ყველა შრის ჩართვა + Turn Off Layer შრის გამორთვა + Turn On Layer შრის ჩართვა + Turn Quick Properties off (QPMODE) სწრაფი თვისებების გამორთვა (QPMODE) + Type ტიპი + Type a command აკრიფეთ ბრძანება + Type text; Enter starts a new paragraph აკრიფეთ ტექსტი; Enter იწყებს ახალ აბზაცს + UCS Icon UCS-ის ხატულა + Undo დაბრუნება + Undo (⌘Z) დაბრუნება (⌘Z) + Ungroup დაჯგუფების მოხსნა + Union გაერთიანება + Unisolate Layer შრის იზოლირების მოხსნა + Units Conversion ერთეულების გარდაქმნა + Units... ერთეულები... + Unlock Layer შრის განბლოკვა + Unlock viewport ხედვის არის განბლოკვა + Unmerge Cells უჯრების შერწყმის გაუქმება + Unsaved Layer State შრეების შეუნახავი მდგომარეობა + Up ზემოთ + Update Data Links მონაცემთა ბმულების განახლება + Update განახლება + Use System Setting სისტემის პარამეტრის გამოყენება + User მომხმარებელი + User Parameters მომხმარებლის პარამეტრები + Username მომხმარებლის სახელი + Volume მოცულობა + VP Color ხედვის არის ფერი + VP Freeze ხედვის არეში გაყინვა + Value მნიშვნელობა + Value: მნიშვნელობა: + Variables ცვლადები + Version ვერსია + Version 2000 ვერსია 2000 + Version 2004 ვერსია 2004 + Version 2007 ვერსია 2007 + Version 2010 ვერსია 2010 + Version 2013 ვერსია 2013 + Version 2018 ვერსია 2018 + Version {version} ვერსია {version} + Vertical ვერტიკალური + VerticalDistance ვერტიკალური მანძილი + View ხედი + ViewCube ViewCube + Viewport ხედვის არე + Viewport Layer Freeze შრის გაყინვა ხედვის არეში + Viewport Properties ხედვის არის თვისებები + Viewport is locked ხედვის არე ჩაკეტილია + Viewport scale ხედვის არის მასშტაბი + Viewport {id} ხედვის არე {id} + Viewports ხედვის არეები + W W + WCS WCS + White თეთრი + Width factor სიგანის კოეფიციენტი + Window ფანჯარა + Wipeout მასკირება + Workspace Switching სამუშაო სივრცის გადართვა + Write Block ბლოკის ჩაწერა + Xline დამხმარე ხაზი + Yellow ყვითელი + Yes დიახ + Zoom მასშტაბი + Zoom All მასშტაბი: ყველაფერი + Zoom Dynamic მასშტაბი: დინამიკური + Zoom Extents მასშტაბი: საზღვრები + Zoom In მოახლოება + Zoom Object მასშტაბი: ობიექტი + Zoom Out დაშორება + Zoom Previous მასშტაბი: წინა + Zoom Realtime მასშტაბი: რეალურ დროში + Zoom Window მასშტაბი: ფანჯარა + error შეცდომა + {contributors} · {commits} {contributors} · {commits} + {kind} (constraint {id}) {kind} (შეზღუდვა {id}) + {kind} constraint {name} = {expression} (double-click to edit) {kind} შეზღუდვა {name} = {expression} (ორმაგი დაწკაპება — რედაქტირება) + {name}: {distance} < {angle}° {name}: {distance} < {angle}° + ƒx New User Parameter ƒx ახალი მომხმარებლის პარამეტრი + ΔLOC ΔLOC + −Bin −Bin + −LOC −LOC + ⌘↩ to finish ⌘↩ — დასრულება +@plural {n} commit {n} კომიტი +@plural {n} contributor {n} მონაწილე + Drawing as bytes ნახაზი ბაიტებად + Services სერვისები + Hide CADCraft CADCraft-ის დამალვა + Hide Others სხვების დამალვა + Accessibility ხელმისაწვდომობა + Show System Cursor სისტემის კურსორის ჩვენება + Animation Effects ანიმაციის ეფექტები + Animation effects ანიმაციის ეფექტები + Interface scale ინტერფეისის მასშტაბი + Import... იმპორტი... + Export... ექსპორტი... + Batch Publish... პაკეტური გამოქვეყნება... + Scale List... მასშტაბების სია... + Annotative Object Scale ანოტაციური ობიექტის მასშტაბი + Add Current Scale მიმდინარე მასშტაბის დამატება + Delete Current Scale მიმდინარე მასშტაბის წაშლა + Add/Delete Scales... მასშტაბების დამატება/წაშლა... + Synchronize Multiple-scale Positions მრავალმასშტაბიანი პოზიციების სინქრონიზაცია + Annotative Update ანოტაციური განახლება + Show Annotative Objects ანოტაციური ობიექტების ჩვენება + Current Scale Only მხოლოდ მიმდინარე მასშტაბი + All Scales ყველა მასშტაბი + Drawing Recovery Manager... ნახაზების აღდგენის მენეჯერი... + Tolerance... დაშვება... + Add Vertex წვეროს დამატება + Remove Vertex წვეროს მოშორება + Convert to Arc რკალად გარდაქმნა + Convert to Line ხაზად გარდაქმნა + Stretch Vertex წვეროს გაწელვა + Edit Array მასივის რედაქტირება + Save changes to {name}? შევინახო ცვლილებები ნახაზში {name}? + Your changes will be lost if you don't save them. თუ ცვლილებებს არ შეინახავთ, ისინი დაიკარგება. + Save changes to block "{name}"? შევინახო ცვლილებები ბლოკში „{name}“? + Don't Save არ შეინახო + Close Array Editing მასივის რედაქტირების დახურვა + Multiline... მულტიხაზი... + Multiline Style... მულტიხაზის სტილი... + Solid Editing სხეულის რედაქტირება + 3D Mouse... 3D მაუსი... + 3D Mouse 3D მაუსი + Calibrate 3D Mouse 3D მაუსის კალიბრაცია + 3D Mouse Navigation 3D მაუსით ნავიგაცია + 3D mouse input is unavailable on this platform 3D მაუსის შეყვანა ამ პლატფორმაზე მიუწვდომელია + No supported 3D mouse found მხარდაჭერილი 3D მაუსი ვერ მოიძებნა + Release the 3D mouse to calibrate its resting position გაუშვით 3D მაუსი ხელიდან, რომ მისი უძრავი მდგომარეობა დაკალიბრდეს + 3D mouse connected 3D მაუსი დაკავშირებულია + 3D mouse busy, possibly 3DxWare or missing device permissions 3D მაუსი დაკავებულია: შესაძლოა, 3DxWare-ის ან მოწყობილობის ნებართვების არქონის გამო + 3D mouse disconnected 3D მაუსი გათიშულია + 3D mouse input could not be started 3D მაუსის შეყვანა ვერ ჩაირთო + Enable 3D mouse navigation 3D მაუსით ნავიგაციის ჩართვა + Pan sensitivity პანორამის მგრძნობელობა + Zoom sensitivity მასშტაბის მგრძნობელობა + Reverse zoom direction მასშტაბის მიმართულების შებრუნება + Calibrate კალიბრაცია + Move sideways to pan; push/pull or twist to zoom. გვერდზე გაწევით — პანორამა; მიწევით/გამოწევით ან მობრუნებით — მასშტაბი. + Left device button: zoom extents. Right device button: calibrate. მოწყობილობის მარცხენა ღილაკი: მასშტაბი საზღვრებით. მარჯვენა ღილაკი: კალიბრაცია. + More toolbar commands ხელსაწყოთა ზოლის სხვა ბრძანებები + Default save version შენახვის ნაგულისხმევი ვერსია + Automatic save every ავტომატური შენახვა ყოველ + min წთ + Automatic save file location ავტომატური შენახვის ფაილის მდებარეობა + Backup copy სარეზერვო ასლი + Create backup copy with each save სარეზერვო ასლის შექმნა ყოველი შენახვისას + Drawings with no file yet are saved in the default version. 0 minutes turns automatic save off. ჯერ ფაილის არმქონე ნახაზები ნაგულისხმევ ვერსიაში ინახება. 0 წუთი ავტომატურ შენახვას გამორთავს. + Time-sensitive right-click: a quick click is Enter, holding opens the menu დროზე დამოკიდებული მარჯვენა დაწკაპება: მოკლე დაწკაპება Enter-ია, დაჭერით გაიხსნება მენიუ + Turned off, a right-click while a command runs always opens the shortcut menu. გამორთვისას ბრძანების შესრულების დროს მარჯვენა დაწკაპება ყოველთვის კონტექსტურ მენიუს ხსნის. + Hatch Pattern დაშტრიხვის ნიმუში + Search for pattern ნიმუშის ძიება + Run Script... სკრიპტის გაშვება... + Query Texts ტექსტების გამოთხოვნა + Analyze Shapes ფიგურების ანალიზი + Analyze Usage გამოყენების ანალიზი + Implied Loops არაცხადი შეკრული კონტურები + Hatch Pick დაშტრიხვის არჩევა + Hatch and Gradient დაშტრიხვა და გრადიენტი + Color 1 ფერი 1 + Color 2 ფერი 2 + Shape ფიგურა + Curved მრუდი + Spherical სფერული + Hemispherical ნახევარსფერული + Drawing Units ნახაზის ერთეულები + Insertion scale ჩასმის მასშტაბი + Units to scale inserted content ჩასმული შიგთავსის მასშტაბირების ერთეულები + Sample output გამოტანის ნიმუში + Architectural არქიტექტურული + Decimal ათწილადი + Engineering საინჟინრო + Fractional წილადური + Scientific სამეცნიერო + Decimal Degrees ათწილადი გრადუსები + Deg/Min/Sec გრადუსი/წუთი/წამი + Grads გრადი + Radians რადიანი + Surveyor's Units გეოდეზიური ერთეულები + Unitless ერთეულის გარეშე + Inches დუიმი + Feet ფუტი + Miles მილი + Millimeters მილიმეტრი + Centimeters სანტიმეტრი + Meters მეტრი + Kilometers კილომეტრი + Microinches მიკროდუიმი + Mils დუიმის მეათასედი + Yards იარდი + Angstroms ანგსტრემი + Nanometers ნანომეტრი + Microns მიკრონი + Decimeters დეციმეტრი + Decameters დეკამეტრი + Hectometers ჰექტომეტრი + Gigameters გიგამეტრი + Astronomical Units ასტრონომიული ერთეული + Light Years სინათლის წელი + Parsecs პარსეკი + US Survey Feet აშშ გეოდეზიური ფუტი + US Survey Inch აშშ გეოდეზიური დუიმი + US Survey Yard აშშ გეოდეზიური იარდი + US Survey Mile აშშ გეოდეზიური მილი + Inverted შებრუნებული + Centered ცენტრში + Hatch origin დაშტრიხვის საწყისი წერტილი + Use current origin მიმდინარე საწყისი წერტილის გამოყენება + Specified origin მითითებული საწყისი წერტილი + Click to set new origin დაწკაპეთ ახალი საწყისი წერტილის დასაყენებლად + Default to boundary extents ნაგულისხმევად საზღვრის გაბარიტები + Bottom left ქვედა მარცხენა + Bottom right ქვედა მარჯვენა + Top left ზედა მარცხენა + Top right ზედა მარჯვენა + Boundaries საზღვრები + Add: Pick points დამატება: წერტილების არჩევა + Add: Select objects დამატება: ობიექტების მონიშვნა + Boundaries picked: {n} არჩეული საზღვრები: {n} + Associate ასოცირება + Select boundaries to remove მონიშნეთ მოსაშორებელი საზღვრები + Island კუნძული + Associative ასოციაციური + Create separate hatches ცალკეული დაშტრიხვების შექმნა + Island detection კუნძულების აღმოჩენა + Normal ჩვეულებრივი + Outer გარე + Ignore უგულებელყოფა + Origin: {x}, {y} საწყისი წერტილი: {x}, {y} + Sheet Books to PDF... ფურცლების წიგნები PDF-ში... + Not a number or distance: {text} არც რიცხვია და არც მანძილი: {text} + Dynamic Block Data დინამიკური ბლოკის მონაცემები + Custom მორგებული + Dynamic Block Reference დინამიკური ბლოკის ჩასმა + Set Dynamic Property დინამიკური თვისების დაყენება + Dynamic Block Grips დინამიკური ბლოკის სახელურები + Drag Dynamic Grip დინამიკური სახელურის გადათრევა + Save Block ბლოკის შენახვა + Save Block As ბლოკის შენახვა როგორც + Close Block Editor ბლოკის რედაქტორის დახურვა + Unsaved changes შეუნახავი ცვლილებები + Edit Block Definition ბლოკის განსაზღვრების რედაქტირება + Block to create or edit შესაქმნელი ან დასარედაქტირებელი ბლოკი + Open in Block Editor ბლოკის რედაქტორში გახსნა + This drawing ეს ნახაზი + contains authoring elements. Open in Block Editor? შეიცავს ბლოკის აგების ელემენტებს. გაიხსნას ბლოკის რედაქტორში? + New block ახალი ბლოკი + Italic დახრილი + Underline ხაზგასმული + Overline ზედა ხაზი + Justify ორმხრივი სწორება + Text color ტექსტის ფერი + Click the ruler to add a tab stop, right-click to remove one დაწკაპეთ სახაზავზე ტაბულაციის პოზიციის დასამატებლად, მარჯვენა დაწკაპებით — წასაშლელად + Select using two clicks only მონიშვნა მხოლოდ ორი დაწკაპებით + Define each corner of the selection window with a separate click. მონიშვნის ფანჯრის თითოეული კუთხე ცალკე დაწკაპებით განისაზღვრება. + Type an alias name. აკრიფეთ ფსევდონიმის სახელი. + Choose the command the alias starts. აირჩიეთ ბრძანება, რომელსაც ფსევდონიმი გაუშვებს. + {command} is an unknown command. {command} უცნობი ბრძანებაა. + {alias} is already defined; select it and use Edit. {alias} უკვე განსაზღვრულია; მონიშნეთ და გამოიყენეთ „რედაქტირება“. + More than {n} aliases. {n}-ზე მეტი ფსევდონიმი. + Alias file: {file} ფსევდონიმების ფაილი: {file} + No alias file loaded. REINIT replaces these aliases with a file's. ფსევდონიმების ფაილი არ არის ჩატვირთული. REINIT ამ ფსევდონიმებს ფაილიდან წაკითხულით ჩაანაცვლებს. + Alias ფსევდონიმი + Command ბრძანება + overrides built-in ჩაშენებულს ჩაანაცვლებს + built-in ჩაშენებული + Add… დამატება… + Edit… რედაქტირება… + Save alias ფსევდონიმის შენახვა + Discard მოშორება + Customize მორგება + Edit Command Aliases (PGP)... ბრძანებების ფსევდონიმების რედაქტირება (PGP)... + Check for Updates… განახლებების შემოწმება… + CADCraft is up to date. CADCraft განახლებულია. + Could not check for updates. განახლებების შემოწმება ვერ მოხერხდა. + B B + CADCraft CADCraft + X X + Y Y +menu Dimension ზომების დატანა +menu Draw ხატვა +menu Modify შეცვლა +menu View ხედი + Arrow size ისრის ზომა + Dim scale overall ზომის საერთო მასშტაბი + Precision სიზუსტე + Layouts განლაგებები + Printer/plotter პრინტერი/პლოტერი + Paper size ფურცლის ზომა + Orientation ორიენტაცია + Portrait ვერტიკალური + Landscape ჰორიზონტალური + Plot area ბეჭდვის არე + Fit to paper ფურცელში ჩატევა + Center the plot ნაბეჭდის ცენტრირება + Plot object lineweights ობიექტების ხაზის სისქეების ბეჭდვა + Plot transparency გამჭვირვალობის ბეჭდვა + Apply to Layout განლაგებაზე გამოყენება + Enter name of LISP file to load შეიყვანეთ ჩასატვირთი LISP ფაილის სახელი + Enter geometric characteristic შეიყვანეთ გეომეტრიული მახასიათებელი + Enter block names to extract შეიყვანეთ ამოსაღები ბლოკების სახელები + Limits ზღვრები + Plot offset ბეჭდვის წანაცვლება + X offset (mm) X წანაცვლება (მმ) + Y offset (mm) Y წანაცვლება (მმ) + First corner პირველი კუთხე + Opposite corner საპირისპირო კუთხე + Window < ფანჯარა < + Oops წაშლილის აღდგენა + Change შეცვლა + Change Properties თვისებების შეცვლა + Units ერთეულები + Find All ყველას ძებნა + Find what: რა მოიძებნოს: + Match case რეგისტრის გათვალისწინება + Replace ჩანაცვლება + Replace All ყველას ჩანაცვლება + Replace with: ჩანაცვლება: + Replacement text ჩამნაცვლებელი ტექსტი + Results შედეგები + Searches the current space. ძიება მიმდინარე სივრცეში. + Text to find მოსაძებნი ტექსტი + Whole words მთლიანი სიტყვები + Nothing found ვერაფერი მოიძებნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 3f01bb695..fbf059dc0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1256,3 +1256,6 @@ menu Modify 수정 Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. 도면이 변경되었습니다. 창을 닫고 다시 여십시오. diff --git a/crates/ui-egui/src/i18n/pt_br.tsv b/crates/ui-egui/src/i18n/pt_br.tsv index 3d1791c1b..93905715c 100644 --- a/crates/ui-egui/src/i18n/pt_br.tsv +++ b/crates/ui-egui/src/i18n/pt_br.tsv @@ -1462,3 +1462,6 @@ menu Dimension Cota menu Draw Desenho menu Modify Modificar menu View Exibir + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. O desenho mudou. Feche a janela e abra-a novamente. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f1a5124f0..a34105023 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1027,3 +1027,6 @@ Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. Чертёж изменился. Закройте окно и откройте его снова. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d67d39c03..f34f32ca5 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1480,3 +1480,6 @@ menu Modify Ändra The current file is kept as {name} until the next save. Den aktuella filen sparas som {name} till nästa sparande. This format can't keep these objects yet: {objects}. Det här formatet kan ännu inte behålla följande objekt: {objects}. {count} more types {count} typer till + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. Ritningen har ändrats. Stäng fönstret och öppna det igen. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index f9f41c798..2d13612df 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -105,6 +105,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet { "dialogs", "hatchdlg", "aliasdlg", + "keys", "mtext_editor", "layers", "bedit", @@ -114,6 +115,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet { "vpscale", "options/dialog", "finddlg", + "textdlg", ]; let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); let mut files = Vec::new(); @@ -203,6 +205,7 @@ fn assert_additional_locale_aliases() { ("bs", &["bs", "bs-BA", "bs_BA.UTF-8", "BS-ba", " bs-BA ", "bs-Latn-BA"]), ("vi", &["vi", "vi-VN", "vi_VN.UTF-8", "VI-vn", " vi-VN "]), ("el", &["el", "el-GR", "el_GR.UTF-8", "EL-cy"]), + ("ka", &["ka", "ka-GE", "ka_GE.UTF-8", "KA-ge", " ka-GE "]), ("zh", &["zh", "zh-CN"]), ] { for tag in tags { @@ -214,7 +217,7 @@ fn assert_additional_locale_aliases() { fn assert_unrecognized_locale_tags() { // Look-alike codes, three-letter codes and endonyms pick nothing: `se` is Northern Sami. let look_alikes = ["ua", "ukulele", "pl-PL", "", "garbage", "💙", "ptolemy", "cz", "csharp", "csomething", "italic"]; - let others = ["kr", "korean", "kotlin", "se", "swe", "svenska", "hun", "magyar", "tur", "türkçe", "elvish"]; + let others = ["kr", "korean", "kotlin", "se", "swe", "svenska", "hun", "magyar", "tur", "türkçe", "elvish", "kat", "geo", "kab", "kartuli"]; for tag in look_alikes.into_iter().chain(others) { assert_eq!(locale_language(tag), None, "{tag}"); } @@ -482,7 +485,7 @@ fn dialogs_render_in_every_language_and_keep_their_source_ids() { #[test] fn interface_fonts_cover_every_letter_in_each_catalog() { for language in translated() { - let extra_font = ["ko", "zh", "ar", "vi"].contains(&language.code); + let extra_font = ["ko", "zh", "ar", "vi", "ka"].contains(&language.code); if extra_font && !crate::theme::can_show(language.code) { continue; } @@ -578,6 +581,22 @@ fn korean_ui_fonts_cover_the_language_picker_in_both_families() { assert!(missing.is_empty(), "missing Korean picker glyphs: {}", missing.join(", ")); } +/// A Georgian noun stays singular after a numeral, so one count form; the Dimension menu and the +/// dimension object take different words. Mtavruli (U+1C90–U+1CBF) is a display style, not upper +/// case: never in the catalog. +#[test] +fn georgian_counts_menu_headings_and_no_mtavruli() { + with_language("ka", || { + for n in [0, 1, 2, 5, 21, u64::MAX] { + assert_eq!(count(n, "{n} commit", "{n} commits"), format!("{n} კომიტი")); + } + assert_eq!(menu("Dimension"), "ზომების დატანა"); + assert_eq!(t("Dimension"), "ზომა"); + }); + let mtavruli: Vec = include_str!("ka.tsv").chars().filter(|c| ('\u{1c90}'..='\u{1cbf}').contains(c)).collect(); + assert!(mtavruli.is_empty(), "{mtavruli:?}"); +} + /// The production font chain covers alphanumeric ASCII in proportional and monospace, plus ⌘ ⇧ ↩ … − in proportional and ⇧ in monospace. #[test] fn production_font_chain_covers_latin_and_shortcut_symbols() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 26308975f..da8aae1d2 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1361,3 +1361,6 @@ menu View Görünüm Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. Çizim değişti. Pencereyi kapatıp yeniden açın. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 821f30c1b..0c661892c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1364,12 +1364,17 @@ More than {n} aliases. Понад {n} псевдонімів. Alias file: {file} Файл псевдонімів: {file} No alias file loaded. REINIT replaces these aliases with a file's. Файл псевдонімів не завантажено. REINIT замінює ці псевдоніми псевдонімами з файлу. + Aliases are saved in your CADCraft profile and survive restarts. Псевдоніми зберігаються в профілі CADCraft і не зникають після перезапуску. Alias Псевдонім Command Команда overrides built-in замінює вбудований built-in вбудований Add… Додати… Edit… Змінити… + Import… Імпортувати… + Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter. Імпорт: тут немає діалогу вибору файлів; запустіть ALIASEDIT із вмістом файлу в параметрі text. + {n} more warnings; see the command line. Ще {n} попереджень; див. командний рядок. + Alias files (PGP) Файли псевдонімів (PGP) Save alias Зберегти псевдонім Discard Скасувати зміни Customize Налаштування інтерфейсу @@ -1390,3 +1395,30 @@ Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. Креслення змінилося. Закрийте вікно та відкрийте його знову. + Keyboard Shortcuts... Комбінації клавіш... + Keyboard Shortcuts Комбінації клавіш + Replaces the shortcut of {commands} Замінює комбінацію клавіш команди: {commands} + Needs Ctrl, Alt or a function key Потрібна клавіша Ctrl, Alt або функціональна клавіша + Press the keys Натисніть клавіші + Back to CADCraft's shortcut Повернути комбінацію CADCraft + A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. Ваша комбінація клавіш має перевагу над комбінацією CADCraft. Зміни застосовуються одразу й зберігаються. + Right-Click Customization... Налаштування правої кнопки... + Right-Click Customization Налаштування правої кнопки + Turn on time-sensitive right-click Увімкнути залежне від часу клацання правою кнопкою + Longer click duration: Тривалість довгого клацання: + milliseconds мілісекунд + While a command runs, a quick click is Enter and a longer click opens the shortcut menu. Під час команди коротке клацання — Enter, довше відкриває контекстне меню. + Default Mode Режим за замовчуванням + No objects selected and no command running: Нічого не вибрано й команда не виконується: + Edit Mode Режим редагування + Objects selected and no command running: Об'єкти вибрано, команда не виконується: + Repeat last command Повторити останню команду + Shortcut Menu Контекстне меню + Command Mode Режим команди + While a command runs: Під час виконання команди: + ENTER Клавіша Enter + Shortcut Menu: always enabled Контекстне меню: завжди + Shortcut Menu: enabled when command options are present Контекстне меню: коли команда має параметри diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 91ed70cf7..c3cd41089 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1461,3 +1461,6 @@ menu Modify Hiệu chỉnh Text to find Text to find Whole words Whole words Nothing found Nothing found + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text + The drawing changed. Close the window and open it again. Bản vẽ đã thay đổi. Đóng cửa sổ và mở lại. diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index a07b4f027..f1ad91111 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -362,6 +362,7 @@ Join 合并 Join the ArtCraft Discord… 加入 ArtCraft Discord… Join us on Discord 在 Discord 上加入我们 + Keyboard Shortcuts... 键盘快捷键... Language 语言 Last 最后 Last commit 最后提交 @@ -1472,3 +1473,6 @@ menu View 视图 Clip Xref 剪裁外部参照 Xref 外部参照 Xref Clip Frame 外部参照剪裁边框 + Ctrl+Enter to apply Ctrl+Enter 应用 + Edit Text 编辑文字 + The drawing changed. Close the window and open it again. 图纸已切换。请关闭窗口后重新打开。 diff --git a/crates/ui-egui/src/keys.rs b/crates/ui-egui/src/keys.rs new file mode 100644 index 000000000..f0757c141 --- /dev/null +++ b/crates/ui-egui/src/keys.rs @@ -0,0 +1,697 @@ +//! The user's keyboard shortcuts (Tools ▸ Customize ▸ Keyboard Shortcuts...): any command can get +//! one, and a shortcut the user gives wins over CADCraft's own; the command that had it loses it, +//! and the dialog says so. They are kept with the other preferences (`shortcuts`). +//! +//! Recording a shortcut (click, press the keys, Esc to cancel) and the conflict rules come from +//! the storey shortcuts of #1703 (@Alex-BB44). + +use std::collections::BTreeMap; + +use egui::{Key, KeyboardShortcut, Modifiers, RichText, vec2}; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// The user's shortcuts: command id → registry shortcut ("Cmd+Shift+K"). Empty: the command has +/// none (its built-in one is removed). +pub type UserKeys = BTreeMap; + +/// At most this many user shortcuts are kept; longer shortcut strings are refused (preferences +/// and JSON calls are hostile input). +pub const MAX_KEYS: usize = 1000; +const MAX_LEN: usize = 64; + +/// Commands whose built-in key is handled outside the shortcut table and stays as it is: the +/// clipboard keys, Shift ones included, arrive as clipboard events, Delete belongs to the command +/// line, Cmd+Q to the macOS app menu. +const FIXED: &[&str] = &["copyclip", "cutclip", "pasteclip", "copybase", "pasteblock", "erase.selection", "ui.quit"]; + +/// The dialog name in `UiState::dialog`. +pub const DIALOG: &str = "shortcuts"; + +/// Whether two shortcuts are one key press. Outside macOS Ctrl is the command key, and one Ctrl +/// press runs a Ctrl and a Cmd shortcut alike, so they are compared as Cmd. +fn same(a: &KeyboardShortcut, b: &KeyboardShortcut) -> bool { + let pressed = |m: Modifiers| { + if !cfg!(target_os = "macos") && (m.ctrl || m.command || m.mac_cmd) { + Modifiers { ctrl: false, command: true, mac_cmd: false, ..m } + } else { + m + } + }; + a.logical_key == b.logical_key && pressed(a.modifiers) == pressed(b.modifiers) +} + +/// A registry shortcut string ("Cmd+Shift+G", "Alt+4", "F3") as a shortcut; `None` when empty or +/// not understood. Cmd is the command key (Ctrl on Windows and Linux); Ctrl alone is the Control +/// key of macOS, and Cmd+Ctrl both macOS keys. +pub fn parse(s: &str) -> Option { + let mut m = Modifiers::NONE; + let mut key = None; + for part in s.split('+').map(str::trim).filter(|p| !p.is_empty()) { + match part.to_ascii_lowercase().as_str() { + "cmd" | "command" => m |= Modifiers::COMMAND, + // Control on macOS (on Windows and Linux, Ctrl is written Cmd: it is the command key). + "ctrl" => m |= Modifiers::CTRL, + "shift" => m |= Modifiers::SHIFT, + "alt" | "option" => m |= Modifiers::ALT, + _ if key.is_none() => key = Some(Key::from_name(part)?), + _ => return None, + } + } + if m.command && m.ctrl { + m.mac_cmd = true; + } + key.map(|k| KeyboardShortcut::new(m, k)) +} + +/// A shortcut as a registry string ("Cmd+Shift+G"), the same on every platform: Cmd for the +/// command key, Ctrl for a Control that isn't it (macOS), so [`parse`] gives it back. +pub fn format(m: Modifiers, k: Key) -> String { + let mut s = String::new(); + if m.command || m.mac_cmd { + s.push_str("Cmd+"); + } + if m.ctrl && (m.mac_cmd || !m.command) { + s.push_str("Ctrl+"); + } + if m.shift { + s.push_str("Shift+"); + } + if m.alt { + s.push_str("Alt+"); + } + // "+" and "-" would read as separators. + s.push_str(match k { + Key::Plus => "Plus", + Key::Minus => "Minus", + k => k.name(), + }); + s +} + +/// Whether `s` can be a user shortcut: with Cmd, Ctrl or Alt, or a function or paging key alone. +/// The keys the drawing area and the command line live on (letters as typing, Space, Enter, Tab, +/// Esc, Delete, Backspace, the arrows), the clipboard keys and Cmd+Q never are. +pub fn allowed(s: &KeyboardShortcut) -> bool { + let k = s.logical_key; + let never = + [Key::Space, Key::Enter, Key::Tab, Key::Escape, Key::Delete, Key::Backspace, Key::ArrowUp, Key::ArrowDown, Key::ArrowLeft, Key::ArrowRight]; + if never.contains(&k) { + return false; + } + let m = s.modifiers; + let command = m.command || m.ctrl || m.mac_cmd; + // Cmd+C, X and V arrive as clipboard events whatever else is held (Shift+Cmd+C is Copy with + // Base Point, Shift+Cmd+V Paste as Block). + let reserved = command && ([Key::C, Key::X, Key::V].contains(&k) || k == Key::Q && !m.shift && !m.alt); + let alone_ok = matches!(k, Key::PageUp | Key::PageDown | Key::Home | Key::End) || k.name().starts_with('F') && k.name().len() > 1; + !reserved && (command || m.alt || alone_ok) +} + +/// Shortcuts are tried most specific first (egui lets a shortcut match with Shift or Alt held on +/// top), so Cmd+Shift+G reaches its own command before Cmd+G does. +pub fn by_specificity(pairs: &mut [(KeyboardShortcut, T)]) { + let weight = |s: &KeyboardShortcut| { + let m = s.modifiers; + u8::from(m.shift) + u8::from(m.alt) + u8::from(m.ctrl && (m.mac_cmd || !m.command)) + u8::from(m.command || m.mac_cmd) + }; + pairs.sort_by_key(|(s, _)| std::cmp::Reverse(weight(s))); +} + +/// CADCraft's own shortcuts: the shortcut table, plus Cmd+8 (QuickCalc), which the shortcut +/// handler reads before a focused text field can take it. +fn defaults() -> Vec<(KeyboardShortcut, &'static str)> { + let mut v = crate::menus::builtin_shortcuts(); + v.push((KeyboardShortcut::new(Modifiers::COMMAND, Key::Num8), "ui.toggle.quickcalc")); + v +} + +/// The command a built-in shortcut belongs to in the editor: the table runs some commands' UI +/// form (`ui.open` for OPEN), which is the same command for the user. +fn owner(id: &str) -> &str { + id.strip_prefix("ui.").filter(|c| cadcraft_engine::find_command(c).is_some()).unwrap_or(id) +} + +fn known(id: &str) -> bool { + cadcraft_engine::find_command(id).is_some() || crate::menus::is_ui_command(id) +} + +/// The shortcuts in force: the user's first, then CADCraft's own unless the user gave that +/// command another shortcut or gave the key to another command. Most specific first. +pub fn effective(user: &UserKeys) -> Vec<(KeyboardShortcut, String)> { + let mut out: Vec<(KeyboardShortcut, String)> = Vec::new(); + for (id, key) in user { + if let Some(s) = parse(key).filter(allowed) + && !out.iter().any(|(o, _)| same(o, &s)) + { + out.push((s, id.clone())); + } + } + for (s, id) in defaults() { + if !user.contains_key(owner(id)) && !out.iter().any(|(o, _)| same(o, &s)) { + out.push((s, id.to_string())); + } + } + by_specificity(&mut out); + out +} + +/// [`effective`], worked out again only when the user's shortcuts change (the shortcut handler +/// asks every frame). +pub fn effective_cached(ctx: &egui::Context, user: &UserKeys) -> Vec<(KeyboardShortcut, String)> { + let id = egui::Id::unique("user_keys_effective"); + if let Some((k, v)) = ctx.data(|m| m.get_temp::<(UserKeys, Vec<(KeyboardShortcut, String)>)>(id)) + && k == *user + { + return v; + } + let v = effective(user); + ctx.data_mut(|m| m.insert_temp(id, (user.clone(), v.clone()))); + v +} + +/// The shortcut a menu or the editor shows for `id`, whose built-in one is `default`: the user's, +/// or the built-in one unless the user gave that key to another command. +pub fn shown(user: &UserKeys, id: &str, default: Option<&str>) -> Option { + if let Some(k) = user.get(id) { + return (!k.is_empty()).then(|| k.clone()); + } + let d = default?; + let s = parse(d); + let taken = s.is_some_and(|s| user.iter().any(|(o, k)| o != id && parse(k).is_some_and(|u| same(&u, &s)))); + (!taken).then(|| d.to_string()) +} + +/// The built-in shortcut a command shows (its registry `key`, or a UI command's). +pub fn default_key(id: &str) -> Option<&'static str> { + cadcraft_engine::find_command(id).and_then(|c| c.shortcut).or_else(|| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).and_then(|c| c.3)) +} + +/// Give `id` the shortcut `key` ("" removes its shortcut). The commands that had the key, built +/// in or the user's, lose it; they are returned so the caller can say so. +pub fn assign(user: &mut UserKeys, id: &str, key: &str) -> Result, String> { + if !known(id) { + return Err(format!("{id}: unknown command")); + } + if FIXED.contains(&id) { + return Err(format!("{id}: this shortcut can't be changed")); + } + let key = key.trim(); + if key.len() > MAX_LEN { + return Err("shortcut too long".into()); + } + if user.len() >= MAX_KEYS && !user.contains_key(id) { + return Err(format!("more than {MAX_KEYS} shortcuts")); + } + if key.is_empty() { + user.insert(id.to_string(), String::new()); + return Ok(Vec::new()); + } + let s = parse(key).ok_or_else(|| format!("{key}: not a shortcut"))?; + if !allowed(&s) { + return Err(format!("{key}: needs Ctrl, Alt or a function key")); + } + let mut replaced = Vec::new(); + for (other, k) in user.iter_mut() { + if other != id && parse(k).is_some_and(|o| same(&o, &s)) { + k.clear(); + replaced.push(other.clone()); + } + } + // A built-in owner already lost the key to the user command that had it. + let held = !replaced.is_empty(); + for (o, other) in defaults() { + let other = owner(other); + if !held && other != id && same(&o, &s) && !user.contains_key(other) && !replaced.iter().any(|r| r == other) { + replaced.push(other.to_string()); + } + } + user.insert(id.to_string(), format(s.modifiers, s.logical_key)); + Ok(replaced) +} + +/// The user's shortcuts from saved preferences: unknown commands, bad strings, a shortcut an +/// earlier command already has (it would show on both, run one) and anything past [`MAX_KEYS`] +/// are dropped. +pub fn from_prefs(v: &Value) -> UserKeys { + let Some(m) = v.as_object() else { return UserKeys::new() }; + let mut out = UserKeys::new(); + let mut taken: Vec = Vec::new(); + for (id, k) in m.iter().filter_map(|(id, k)| Some((id, k.as_str()?))) { + if out.len() >= MAX_KEYS { + break; + } + if id.len() > MAX_LEN || k.len() > MAX_LEN || !known(id) || FIXED.contains(&id.as_str()) { + continue; + } + if !k.is_empty() { + let Some(s) = parse(k).filter(allowed) else { continue }; + if taken.iter().any(|o| same(o, &s)) { + continue; + } + taken.push(s); + } + out.insert(id.clone(), k.to_string()); + } + out +} + +/// `ui.shortcuts`: from a menu or typed, the Keyboard Shortcuts dialog; with parameters +/// `{set?: {command: shortcut or ""}, reset?: bool}` the JSON form, which answers the user's +/// shortcuts and the commands that lost theirs. +pub fn command(app: &mut CadApp, params: &Value) -> Result { + if params.is_null() { + app.ui.dialog = Some(DIALOG.into()); + return Ok(Value::Null); + } + let mut keys = app.ui.shortcuts.clone(); + if params.get("reset").and_then(Value::as_bool) == Some(true) { + keys.clear(); + } + let mut replaced = Vec::new(); + if let Some(set) = params.get("set") { + let set = set.as_object().ok_or("`set` must be an object of command: shortcut")?; + if set.len() > MAX_KEYS { + return Err(format!("more than {MAX_KEYS} shortcuts")); + } + for (id, key) in set { + let key = key.as_str().ok_or_else(|| format!("{id}: the shortcut must be a string"))?; + replaced.extend(assign(&mut keys, &id.to_ascii_lowercase(), key)?); + } + } + app.ui.shortcuts = keys; + Ok(json!({ "shortcuts": app.ui.shortcuts, "replaced": replaced })) +} + +const RECORDING: &str = "user_keys_recording"; + +/// Whether a shortcut is being recorded (every shortcut stays quiet meanwhile). +pub fn recording(ctx: &egui::Context) -> bool { + ctx.data(|m| m.get_temp::(egui::Id::unique(RECORDING))).is_some() +} + +pub fn stop_recording(ctx: &egui::Context) { + ctx.data_mut(|m| m.remove::(egui::Id::unique(RECORDING))); +} + +/// The commands the editor lists, sorted by the label shown: (id, label, what tells same labels +/// apart: the command name to type, or the menu an interface command sits in). +fn rows() -> Vec<(&'static str, String, String)> { + let mut v: Vec<(&'static str, String, String)> = Vec::new(); + for c in cadcraft_engine::command_specs() { + if !c.label.is_empty() && !v.iter().any(|(id, ..)| *id == c.id) { + v.push((c.id, crate::i18n::t(c.label).to_string(), c.id.to_ascii_uppercase())); + } + } + for (id, label, menu, _) in crate::menus::UI_COMMANDS { + if !label.is_empty() && !menu.is_empty() && owner(id) == *id && !v.iter().any(|(i, ..)| i == id) { + let path: Vec<&str> = menu.iter().take(menu.len().saturating_sub(1)).map(|m| crate::i18n::menu(m)).collect(); + v.push((id, crate::i18n::t(label).to_string(), path.join(" ▸ "))); + } + } + v.sort_by(|a, b| a.1.to_lowercase().cmp(&b.1.to_lowercase()).then(a.0.cmp(b.0))); + v +} + +fn label_of(id: &str) -> String { + cadcraft_engine::find_command(id) + .map(|c| crate::i18n::t(c.label).to_string()) + .or_else(|| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| crate::i18n::t(c.1).to_string())) + .unwrap_or_else(|| id.to_string()) +} + +/// The Keyboard Shortcuts dialog: every command with its shortcut, a filter, a click to record a +/// new one. Changes apply at once. +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let t = Tokens::get(); + let mac = ctx.os().is_mac(); + let rec_id = egui::Id::unique(RECORDING); + let filter_id = egui::Id::unique("user_keys_filter"); + let note_id = egui::Id::unique("user_keys_note"); + let mut recording: Option = ctx.data(|m| m.get_temp(rec_id)); + let mut filter: String = ctx.data(|m| m.get_temp(filter_id)).unwrap_or_default(); + let mut note: Option<(String, bool)> = ctx.data(|m| m.get_temp(note_id)); + // A key pressed while recording becomes that command's shortcut; Esc stops recording. + if let Some(id) = recording.clone() { + let pressed = ctx.input(|inp| { + inp.events.iter().find_map(|e| match e { + egui::Event::Key { key, pressed: true, modifiers, .. } => Some((*key, *modifiers)), + _ => None, + }) + }); + if let Some((k, m)) = pressed { + if k != Key::Escape { + note = Some(match assign(&mut app.ui.shortcuts, &id, &format(m, k)) { + Ok(lost) if lost.is_empty() => (String::new(), false), + Ok(lost) => { + let names: Vec = lost.iter().map(|l| label_of(l)).collect(); + (crate::tf!("Replaces the shortcut of {commands}", commands = names.join(", ")), false) + } + Err(_) => (crate::tl!("Needs Ctrl, Alt or a function key").to_string(), true), + }); + } + recording = None; + ctx.input_mut(|inp| inp.events.clear()); + } + } + let mut reset_all = false; + egui::Window::new(crate::tl!("Keyboard Shortcuts")) + .id(egui::Id::unique("shortcuts_dialog")) + .open(open) + .collapsible(false) + .default_size(vec2(600.0, 520.0)) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.label(crate::tl!("Filter")); + ui.text_edit_singleline(&mut filter); + }); + let f = filter.trim().to_lowercase(); + let rows: Vec<(&'static str, String, String)> = rows() + .into_iter() + .filter(|(_, label, detail)| f.is_empty() || label.to_lowercase().contains(&f) || detail.to_lowercase().contains(&f)) + .collect(); + let row_h = ui.spacing().interact_size.y + 4.0; + egui::ScrollArea::vertical().max_height(360.0).auto_shrink([false, true]).show_rows(ui, row_h, rows.len(), |ui, range| { + for (id, label, detail) in rows.get(range).unwrap_or_default() { + ui.horizontal(|ui| { + let cell = |ui: &mut egui::Ui, w: f32, text: RichText| { + ui.allocate_ui_with_layout(vec2(w, row_h - 4.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_width(w); + ui.add(egui::Label::new(text).truncate()); + }); + }; + cell(ui, 190.0, RichText::new(label.as_str())); + cell(ui, 140.0, RichText::new(detail.as_str()).color(t.text_dim).small()); + let fixed = FIXED.contains(id); + let key = shown(&app.ui.shortcuts, id, default_key(id)); + let text = if recording.as_deref() == Some(*id) { + crate::tl!("Press the keys").to_string() + } else { + key.as_deref().map_or_else(|| crate::tl!("None").to_string(), |k| crate::menus::shortcut_label(k, mac)) + }; + let b = egui::Button::new(text).selected(recording.as_deref() == Some(*id)).min_size(vec2(120.0, 0.0)); + if ui.add_enabled(!fixed, b).clicked() { + recording = Some(id.to_string()); + note = None; + } + if !fixed && key.is_some() && ui.small_button(crate::tl!("Clear")).clicked() { + let _ = assign(&mut app.ui.shortcuts, id, ""); + } + if app.ui.shortcuts.contains_key(*id) + && ui.small_button(crate::tl!("Default")).on_hover_text(crate::tl!("Back to CADCraft's shortcut")).clicked() + { + app.ui.shortcuts.remove(*id); + } + }); + } + }); + match ¬e { + Some((n, true)) => { + ui.colored_label(t.warn, n.as_str()); + } + Some((n, false)) if !n.is_empty() => { + ui.label(RichText::new(n.as_str()).color(t.text_dim)); + } + _ => {} + } + ui.separator(); + ui.horizontal(|ui| { + reset_all = ui.button(crate::tl!("Reset to Defaults")).clicked(); + }); + ui.label( + RichText::new(crate::tl!("A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time.")) + .color(t.text_dim) + .small(), + ); + }); + if reset_all { + app.ui.shortcuts.clear(); + note = None; + } + if !*open { + recording = None; + note = None; + } + ctx.data_mut(|m| { + match &recording { + Some(r) => { + m.insert_temp(rec_id, r.clone()); + } + None => { + m.remove::(rec_id); + } + } + m.insert_temp(filter_id, filter); + match note { + Some(n) => { + m.insert_temp(note_id, n); + } + None => { + m.remove::<(String, bool)>(note_id); + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use cadcraft_engine::Session; + + fn app() -> CadApp { + CadApp::new(Session::new(), crate::Services::default()) + } + + fn key(s: &str) -> KeyboardShortcut { + parse(s).unwrap_or_else(|| panic!("{s}")) + } + + fn runs(user: &UserKeys, s: &str) -> Option { + effective(user).into_iter().find(|(o, _)| same(o, &key(s))).map(|(_, id)| id) + } + + #[test] + fn shortcut_strings_round_trip() { + for s in ["Cmd+Shift+G", "Cmd+4", "F3", "Alt+PageUp", "Cmd+Plus", "Cmd+Minus", "Ctrl+K", "Cmd+Ctrl+K"] { + let k = key(s); + assert_eq!(format(k.modifiers, k.logical_key), s); + } + // Keys as egui reports them: Ctrl on Linux and Windows is the command key; macOS Control + // and Command+Control keep their Control. + let linux_ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let mac_ctrl = Modifiers { ctrl: true, ..Modifiers::NONE }; + let mac_cmd_ctrl = Modifiers { ctrl: true, command: true, mac_cmd: true, ..Modifiers::NONE }; + assert_eq!(format(linux_ctrl, Key::K), "Cmd+K"); + assert_eq!(format(mac_ctrl, Key::K), "Ctrl+K"); + assert_eq!(format(mac_cmd_ctrl, Key::K), "Cmd+Ctrl+K"); + assert!(parse("").is_none() && parse("Cmd+").is_none() && parse("Cmd+G+H").is_none() && parse("Hyper+G").is_none()); + } + + #[test] + fn typing_keys_clipboard_keys_and_quit_are_never_user_shortcuts() { + for s in [ + "L", + "Shift+L", + "Space", + "Enter", + "Escape", + "Cmd+C", + "Cmd+V", + "Cmd+X", + "Cmd+Shift+C", + "Cmd+Shift+V", + "Cmd+Alt+C", + "Cmd+Alt+X", + "Cmd+Alt+V", + "Cmd+Q", + "ArrowUp", + "Delete", + ] { + assert!(!allowed(&key(s)), "{s}"); + } + for s in ["Cmd+L", "Alt+L", "F4", "PageDown", "Cmd+Shift+Q", "Ctrl+K"] { + assert!(allowed(&key(s)), "{s}"); + } + } + + #[test] + fn any_command_gets_a_shortcut_and_it_runs_it() { + let mut user = UserKeys::new(); + assert_eq!(assign(&mut user, "line", "Cmd+L"), Ok(vec![])); + assert_eq!(runs(&user, "Cmd+L").as_deref(), Some("line")); + // The built-in ones are untouched. + assert_eq!(runs(&user, "Cmd+S").as_deref(), Some("qsave")); + assert_eq!(runs(&UserKeys::new(), "Cmd+L"), None); + } + + #[test] + fn control_and_command_control_shortcuts_keep_their_control() { + let mut user = UserKeys::new(); + assert_eq!(assign(&mut user, "line", "Ctrl+K"), Ok(vec![])); + // Outside macOS both are one Ctrl press, so Circle takes it from Line. + let lost = if cfg!(target_os = "macos") { vec![] } else { vec!["line".to_string()] }; + assert_eq!(assign(&mut user, "circle", "Cmd+Ctrl+K"), Ok(lost)); + assert_eq!(user.get("circle").map(String::as_str), Some("Cmd+Ctrl+K")); + let eff = effective(&user); + let of = |id: &str| eff.iter().find(|(_, i)| i == id).map(|(s, _)| s.modifiers); + assert_eq!(of("circle"), Some(Modifiers { ctrl: true, command: true, mac_cmd: true, ..Modifiers::NONE })); + if cfg!(target_os = "macos") { + assert_eq!(user.get("line").map(String::as_str), Some("Ctrl+K")); + assert_eq!(of("line"), Some(Modifiers::CTRL)); + // Command+Control+K is tried before Control+K, which it holds too. + let at = |id: &str| eff.iter().position(|(_, i)| i == id); + assert!(at("circle") < at("line")); + } + } + + #[test] + fn a_user_shortcut_wins_over_a_built_in_one_and_says_which() { + let mut user = UserKeys::new(); + assert_eq!(assign(&mut user, "line", "Cmd+P"), Ok(vec!["plot".to_string()])); + assert_eq!(runs(&user, "Cmd+P").as_deref(), Some("line")); + assert_eq!(shown(&user, "plot", default_key("plot")), None, "Plot no longer shows Cmd+P"); + assert_eq!(shown(&user, "line", default_key("line")).as_deref(), Some("Cmd+P")); + // Given to a third command, the first user one loses it too. + assert_eq!(assign(&mut user, "circle", "Cmd+P"), Ok(vec!["line".to_string()])); + assert_eq!(runs(&user, "Cmd+P").as_deref(), Some("circle")); + assert_eq!(shown(&user, "line", default_key("line")), None); + // A table entry that runs a command's UI form belongs to that command (Cmd+O, OPEN). + assert_eq!(assign(&mut user, "line", "Cmd+O"), Ok(vec!["open".to_string()])); + assert_eq!(assign(&mut user, "line", "Cmd+8"), Ok(vec!["ui.toggle.quickcalc".to_string()])); + } + + /// On Windows and Linux one Ctrl press runs a Ctrl and a Cmd shortcut alike, so they are one + /// key: giving it takes it from the command that had it, and preferences keep it once. + #[test] + #[cfg(not(target_os = "macos"))] + fn ctrl_and_cmd_are_one_key_outside_macos() { + let mut user = UserKeys::new(); + assert_eq!(assign(&mut user, "line", "Ctrl+P"), Ok(vec!["plot".to_string()])); + assert_eq!(runs(&user, "Cmd+P").as_deref(), Some("line")); + assert_eq!(assign(&mut user, "circle", "Cmd+P"), Ok(vec!["line".to_string()])); + let user = from_prefs(&json!({"circle": "Cmd+K", "line": "Ctrl+K"})); + assert_eq!(user.values().filter(|k| !k.is_empty()).count(), 1, "{user:?}"); + } + + #[test] + fn a_new_shortcut_replaces_the_commands_own_and_clear_removes_it() { + let mut user = UserKeys::new(); + assert_eq!(assign(&mut user, "qsave", "Cmd+Shift+K"), Ok(vec![])); + assert_eq!(runs(&user, "Cmd+S"), None, "Save's own Cmd+S is replaced"); + assert_eq!(runs(&user, "Cmd+Shift+K").as_deref(), Some("qsave")); + assert_eq!(assign(&mut user, "plot", ""), Ok(vec![])); + assert_eq!(runs(&user, "Cmd+P"), None); + assert_eq!(shown(&user, "plot", default_key("plot")), None); + // OPEN through its UI form: its Cmd+O goes when OPEN gets another key. + assert_eq!(assign(&mut user, "open", "F4"), Ok(vec![])); + assert_eq!(runs(&user, "Cmd+O"), None); + } + + #[test] + fn bad_shortcuts_and_commands_are_refused() { + let mut user = UserKeys::new(); + assert!(assign(&mut user, "nosuchcommand", "Cmd+L").is_err()); + assert!(assign(&mut user, "line", "L").is_err()); + assert!(assign(&mut user, "line", "Cmd+Nothing").is_err()); + assert!(assign(&mut user, "line", &"Cmd+".repeat(1000)).is_err()); + assert!(assign(&mut user, "copyclip", "Cmd+K").is_err(), "the clipboard keys stay"); + assert!(assign(&mut user, "pasteblock", "Cmd+K").is_err(), "Shift+Cmd+V is a clipboard event too"); + assert!(user.is_empty()); + } + + #[test] + fn the_json_form_sets_resets_and_never_opens_the_dialog() { + let mut app = app(); + let v = app.run("ui.shortcuts", json!({"set": {"LINE": "Cmd+P"}})).unwrap(); + assert_eq!(v["shortcuts"], json!({"line": "Cmd+P"})); + assert_eq!(v["replaced"], json!(["plot"])); + assert_eq!(app.ui.dialog, None); + assert!(app.run("ui.shortcuts", json!({"set": {"line": 3}})).is_err()); + assert!(app.run("ui.shortcuts", json!({"set": "Cmd+P"})).is_err()); + assert_eq!(app.ui.shortcuts.get("line").map(String::as_str), Some("Cmd+P"), "a refused call changes nothing"); + let v = app.run("ui.shortcuts", json!({"reset": true})).unwrap(); + assert_eq!(v["shortcuts"], json!({})); + app.start("ui.shortcuts"); + assert_eq!(app.ui.dialog.as_deref(), Some(DIALOG)); + } + + #[test] + fn shortcuts_are_kept_with_the_preferences_and_hostile_ones_dropped() { + let mut a = app(); + let _ = a.run("ui.shortcuts", json!({"set": {"line": "Cmd+L", "plot": ""}})); + let mut b = app(); + b.load_prefs(&a.prefs_json()); + assert_eq!(b.ui.shortcuts, a.ui.shortcuts); + let hostile = + json!({"shortcuts": {"line": "L", "nosuch": "Cmd+K", "copyclip": "Cmd+K", "circle": 5, "arc": "Cmd+K", "x".repeat(5000): "Cmd+J"}}); + let mut c = app(); + c.load_prefs(&hostile.to_string()); + assert_eq!(c.ui.shortcuts, UserKeys::from([("arc".to_string(), "Cmd+K".to_string())])); + let many: serde_json::Map = (0..5000).map(|i| (format!("c{i}"), json!("Cmd+K"))).collect(); + c.load_prefs(&json!({ "shortcuts": many }).to_string()); + assert!(c.ui.shortcuts.len() <= MAX_KEYS); + c.load_prefs(r#"{"shortcuts": "Cmd+K"}"#); + // One key for two commands (an edited file): the first keeps it, the other is dropped. + c.load_prefs(r#"{"shortcuts": {"arc": "Cmd+K", "line": "Cmd+K", "circle": "Cmd+J"}}"#); + assert_eq!(c.ui.shortcuts, UserKeys::from([("arc".to_string(), "Cmd+K".to_string()), ("circle".to_string(), "Cmd+J".to_string())])); + } + + /// Window ▸ Reset Palettes puts the palettes back, not the user's shortcuts. + #[test] + fn reset_palettes_keeps_the_users_shortcuts() { + let mut app = app(); + let _ = app.run("ui.shortcuts", json!({"set": {"line": "Cmd+L"}})); + app.run("ui.resetpalettes", json!({})).unwrap(); + assert_eq!(app.ui.shortcuts, UserKeys::from([("line".to_string(), "Cmd+L".to_string())])); + } + + #[test] + fn the_menus_show_the_shortcut_in_force() { + let mut app = app(); + let _ = app.run("ui.shortcuts", json!({"set": {"line": "Cmd+P"}})); + let mut found = (None, None); + fn walk(es: &[crate::menus::Entry], found: &mut (Option>, Option>)) { + for e in es { + match e { + crate::menus::Entry::Item { id, shortcut, .. } if id == "line" => found.0 = Some(shortcut.clone()), + crate::menus::Entry::Item { id, shortcut, .. } if id == "plot" => found.1 = Some(shortcut.clone()), + crate::menus::Entry::Sub { children, .. } => walk(children, found), + _ => {} + } + } + } + for (_, es) in crate::menus::tree(&app) { + walk(&es, &mut found); + } + assert_eq!(found, (Some(Some("Cmd+P".into())), Some(None))); + } + + #[test] + fn a_recorded_key_runs_its_command_and_quiets_shortcuts_while_recording() { + let ctx = egui::Context::default(); + let mut app = app(); + let _ = app.run("ui.shortcuts", json!({"set": {"line": "F4"}})); + let press = |key: Key| egui::RawInput { + events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }], + ..Default::default() + }; + let mut out = ctx.run_ui(press(Key::F4), |ui| crate::menus::shortcuts(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert_eq!(app.session.summary()["running"], json!("line")); + app.session.cancel(); + // Recording in the dialog: F4 becomes the recorded key, nothing runs. + app.ui.dialog = Some(DIALOG.into()); + ctx.data_mut(|m| m.insert_temp(egui::Id::unique(RECORDING), "circle".to_string())); + let mut out = ctx.run_ui(press(Key::F6), |ui| { + crate::menus::shortcuts(&mut app, ui.ctx()); + let mut open = true; + dialog(&mut app, ui.ctx(), &mut open); + }); + out.textures_delta.clear(); + assert_eq!(app.session.summary()["running"], Value::Null); + assert_eq!(app.ui.shortcuts.get("circle").map(String::as_str), Some("F6")); + assert!(!recording(&ctx)); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d27712da2..41787b002 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -40,6 +40,8 @@ mod mtext_editor; mod panel_state; pub mod spacemouse; pub mod switch; +// The Edit Text window, opened from the shortcut menu's Edit Text entry. +pub mod textdlg; // The External References palette. pub mod xrefs; @@ -49,6 +51,7 @@ pub mod gpu; pub mod grip_dyn; pub mod i18n; pub mod icons; +pub mod keys; pub mod layers; pub mod managers; pub mod menus; @@ -117,6 +120,8 @@ pub struct UiState { pub start_tab: bool, pub dialog: Option, pub history_lines: usize, + /// The user's keyboard shortcuts ([`keys`]). + pub shortcuts: keys::UserKeys, /// Interface theme: "system" (follow the OS light/dark appearance), "light" or "dark". pub theme: theme::ThemePref, /// Animation effects (dialog and menu fades, smoothed scrolling): "system" (follow the OS @@ -131,6 +136,8 @@ pub struct UiState { pub recent_files: Vec, /// The folder the last APPLOAD file came from: the next pick starts there. pub last_lisp_dir: Option, + /// The folder the Command Aliases dialog last imported a `.pgp` file from. + pub last_pgp_dir: Option, } /// A DXF/DWG file version (2000 … 2018). @@ -203,12 +210,14 @@ impl Default for UiState { start_tab: false, dialog: None, history_lines: 3, + shortcuts: keys::UserKeys::new(), theme: theme::ThemePref::default(), animations: animation::AnimationPref::default(), save_format: SaveFormat::default(), save_version: SaveVersion::default().year().to_string(), recent_files: Vec::new(), last_lisp_dir: None, + last_pgp_dir: None, } } } @@ -218,6 +227,12 @@ impl Default for UiState { pub struct Services { pub pick_open: Option Option>>, pub pick_save: Option Option>>, + /// Where set, the file dialogs are shown with this instead of calling `pick_open` / + /// `pick_save` / `pick_lisp` (which must still be set, to say which dialogs there are), and + /// the answer is acted on in a later frame ([`CadApp::pick_then`]). macOS needs it: a panel run modally + /// inside the window's event handler gets the window events of its own resizing sent back + /// into that handler, and winit aborts the app (#1527). + pub start_pick: Option, /// Pick a `.lsp` file for APPLOAD, starting in the given folder (empty for the default one). /// `None` where there is no native file dialog: the desktop without one asks for the name, /// and the web (no file system) says to drop the file (`no_file_system`). @@ -225,6 +240,38 @@ pub struct Services { /// The host has no file system to read a path from (the browser): a dropped file's contents /// are what it loads, and APPLOAD says so instead of asking for a name it cannot read. pub no_file_system: bool, + /// Pick a `.pgp` alias file, starting in the folder given (the last import's). + pub pick_pgp: Option) -> Option>>, +} + +/// The file dialog to show: Open, Save with the suggested file name, APPLOAD's `.lsp` picker or +/// ALIASEDIT's `.pgp` picker, starting in the given folder (empty for the default one). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Pick { + Open, + Save(String), + Lisp(String), + Pgp(String), +} + +/// Shows a file dialog without waiting for it and calls the callback (from any thread) with the +/// chosen path, or `None` when the dialog is cancelled ([`Services::start_pick`]). +pub type StartPick = Box) + Send>)>; + +/// What to do with the path a file dialog chose ([`CadApp::pick_then`]). +type PickDone = Box Result>; + +/// A file dialog shown with [`Services::start_pick`] that has not answered yet. +struct PendingPick { + answer: Receiver>, + /// The drawing (its `uid`) the answer is for: Save As writes that drawing, export and plot + /// read it, and so on, whichever drawing is active when the answer arrives. `None` for the + /// dialogs that open a drawing (Open, New from Template, Recover). + doc: Option, + /// The close prompt's Save is waiting for this dialog: its other answers wait too + /// ([`closing`]). + for_close: bool, + then: PickDone, } pub struct CadApp { @@ -318,6 +365,8 @@ pub struct CadApp { pub hatch_dlg: Option, /// The Edit Block Definition dialog ([`bedit`]). pub bedit: bedit::State, + /// A file dialog shown with [`Services::start_pick`]: its answer, and what to do with it. + pending_pick: Option, /// The startup update check and its prompt (desktop; [`updates_ui`]). #[cfg(not(target_arch = "wasm32"))] pub updates_rt: updates_ui::Runtime, @@ -378,9 +427,139 @@ impl CadApp { bedit: bedit::State::default(), #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), + pending_pick: None, } } + /// Ask for a file with the host's dialog (`pick`) and run `then` with the chosen path, on the + /// drawing that is active now. `None` when the host has no dialog of that kind. Cancelling + /// gives `Ok(Null)`. With a synchronous picker the result is `then`'s; with + /// [`Services::start_pick`] the dialog opens and this returns `Ok(Null)` at once: `then` runs + /// in a later frame ([`Self::logic`]) with that drawing made active again (if something else + /// was switched to meanwhile, such as a control-channel `document.switch`), and not at all if + /// the drawing was closed. Its error, if any, shows in the status bar. With no drawing open + /// it refuses without showing a dialog. While one dialog is open, no other is shown: the + /// request is refused with an error, also shown in the status bar. + pub fn pick_then( + &mut self, + pick: Pick, + then: impl FnOnce(&mut CadApp, String) -> Result + 'static, + ) -> Option> { + self.pick_for(pick, true, Box::new(then)) + } + + /// [`Self::pick_then`] for a dialog that opens a drawing (Open, New from Template, Recover): + /// `then` does not act on the drawing that was active, so it runs whatever was switched to + /// or closed meanwhile. + pub fn pick_then_open( + &mut self, + pick: Pick, + then: impl FnOnce(&mut CadApp, String) -> Result + 'static, + ) -> Option> { + self.pick_for(pick, false, Box::new(then)) + } + + /// Show the dialog `pick` for `then`, bound to the active drawing when `bound`. + fn pick_for(&mut self, pick: Pick, bound: bool, then: PickDone) -> Option> { + let available = match pick { + Pick::Open => self.services.pick_open.is_some(), + Pick::Save(_) => self.services.pick_save.is_some(), + Pick::Lisp(_) => self.services.pick_lisp.is_some(), + Pick::Pgp(_) => self.services.pick_pgp.is_some(), + }; + if !available { + return None; + } + if self.pending_pick.is_some() { + return Some(Err(self.refuse_pick("A file dialog is already open; answer it first.".into()))); + } + // A bound answer must not land on a drawing created or opened while the dialog is up. + let doc = match (bound, self.session.state()) { + (false, _) => None, + (true, Ok(st)) => Some(st.uid), + (true, Err(e)) => { + let why = e.to_string(); + return Some(Err(self.refuse_pick(why))); + } + }; + if let Some(start) = &self.services.start_pick { + let (tx, answer) = std::sync::mpsc::channel(); + start( + pick, + Box::new(move |path| { + let _ = tx.send(path); + }), + ); + self.pending_pick = Some(PendingPick { answer, doc, for_close: false, then }); + return Some(Ok(Value::Null)); + } + let path = match &pick { + Pick::Open => self.services.pick_open.as_ref().and_then(|f| f()), + Pick::Save(name) => self.services.pick_save.as_ref().and_then(|f| f(name)), + Pick::Lisp(dir) => self.services.pick_lisp.as_ref().and_then(|f| f(dir)), + Pick::Pgp(dir) => self.services.pick_pgp.as_ref().and_then(|f| f(Some(dir.as_str()).filter(|d| !d.is_empty()))), + }; + Some(match path { + Some(path) => then(self, path), + None => Ok(Value::Null), + }) + } + + /// A file dialog that is not shown: the reason goes to the status bar too, since a typed or + /// menu command's result is not shown ([`Self::start`]). + fn refuse_pick(&mut self, why: String) -> String { + self.set_status(why.clone()); + why + } + + /// Start the interactive command `id` with a dialog's answer. `was_prompting`: whether a + /// command was running when the dialog was asked for. Starting cancels the running command, + /// so a command started while the dialog was open (a control request, say) is kept and this + /// one refused instead; one that was already running is cancelled as when the dialog answers + /// at once. + pub fn start_after_pick(&mut self, id: &str, was_prompting: bool) -> Result<(), String> { + if !was_prompting && self.session.prompting() { + return Err(format!("{}: another command started while the file dialog was open; run it again.", id.to_ascii_uppercase())); + } + self.session.start(id).map_err(|e| e.to_string()) + } + + /// Act on the answer of a dialog started with [`Services::start_pick`], once it arrives. + fn finish_pick(&mut self, ctx: &egui::Context) { + let Some(pending) = &self.pending_pick else { return }; + match pending.answer.try_recv() { + Err(std::sync::mpsc::TryRecvError::Empty) => ctx.request_repaint_after(std::time::Duration::from_millis(100)), + Ok(None) => self.pending_pick = None, + // The host dropped the answer without giving one: the dialog never opened (its + // thread could not start) or failed. + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + self.pending_pick = None; + self.set_status("The file dialog could not be shown."); + } + Ok(Some(path)) => { + if let Some(PendingPick { doc, then, .. }) = self.pending_pick.take() + && let Err(e) = self.make_active(doc, &path).and_then(|()| then(self, path)) + { + self.set_status(e); + } + ctx.request_repaint(); + } + } + } + + /// Make the drawing `uid` active again for the answer `path` of a dialog it asked for, or + /// refuse when it was closed meanwhile. + fn make_active(&mut self, uid: Option, path: &str) -> Result<(), String> { + let Some(uid) = uid else { return Ok(()) }; + let Some(i) = self.session.docs.iter().position(|d| d.uid == uid) else { + return Err(format!("The drawing was closed before the file dialog answered; nothing was done with {path}.")); + }; + if self.session.active != i { + self.run("document.switch", json!({ "index": i }))?; + } + Ok(()) + } + /// The interface language shown: the chosen one, or English when this computer has no font /// for it (Chinese or Korean without a suitable font would be boxes). pub fn language(&self) -> &'static str { @@ -488,6 +667,12 @@ impl CadApp { if let Some(dir) = &self.ui.last_lisp_dir { prefs["lispDir"] = json!(dir); } + if let Some(dir) = self.ui.last_pgp_dir.as_deref().filter(|d| !d.is_empty()) { + prefs["lastPgpDir"] = json!(dir); + } + if !self.ui.shortcuts.is_empty() { + prefs["shortcuts"] = json!(self.ui.shortcuts); + } prefs.to_string() } @@ -521,6 +706,12 @@ impl CadApp { if let Some(dir) = v.get("lispDir").and_then(Value::as_str).filter(|d| !d.is_empty()) { self.ui.last_lisp_dir = Some(dir.to_string()); } + if let Some(dir) = v.get("lastPgpDir").and_then(Value::as_str).filter(|d| !d.is_empty()) { + self.ui.last_pgp_dir = Some(dir.to_string()); + } + if let Some(keys) = v.get("shortcuts").filter(|k| k.is_object()) { + self.ui.shortcuts = keys::from_prefs(keys); + } } /// Make the system cursor the interface default (`on`) and turn it on; saved preferences and @@ -640,7 +831,8 @@ impl CadApp { Err(e) => self.set_status(e), Ok(v) => { self.ui.start_tab = false; - self.canvas.zoom_pending = true; + // A drawing that opened on the view it was saved at keeps it (#1626). + self.canvas.zoom_pending = !v.get("saved_view").and_then(Value::as_bool).unwrap_or(false); let doc = v.get("index").and_then(Value::as_u64).and_then(|i| self.session.docs.get(usize::try_from(i).ok()?)); if let Some(path) = doc.and_then(|d| d.path.clone()) { self.remember_recent(path); @@ -678,6 +870,7 @@ impl CadApp { // Consume-based queues: each item is handled once, whichever callback delivers it. A // reply arriving during a later pass is never starved until the next frame. self.drain_control(ctx); + self.finish_pick(ctx); self.finish_opening(); // Finishing an open switches to the new drawing. capture::note_identity(self, ctx); diff --git a/crates/ui-egui/src/managers.rs b/crates/ui-egui/src/managers.rs index 42266d3b6..e1bafb0d8 100644 --- a/crates/ui-egui/src/managers.rs +++ b/crates/ui-egui/src/managers.rs @@ -11,9 +11,9 @@ use std::sync::atomic::{AtomicU32, Ordering}; use egui::{RichText, Sense, Stroke, vec2}; use serde_json::{Value, json}; -use crate::CadApp; use crate::parametric::expr_field; use crate::theme::Tokens; +use crate::{CadApp, Pick}; /// The Block Attribute Manager (BATTMAN). mod battman; @@ -121,6 +121,7 @@ fn linetype(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { let library: Vec = cadcraft_doc::library::standard_linetypes().into_iter().map(|l| l.name).filter(|n| d.linetype(n).is_none()).collect(); let mut sel = temp::(ctx, "ltmgr_sel").filter(|s| rows.iter().any(|r| r.0.eq_ignore_ascii_case(s))).unwrap_or_else(|| current.clone()); let mut action = None; + let mut pick_lin = false; egui::Window::new("Linetype Manager").open(open).default_size(vec2(520.0, 360.0)).resizable(true).show(ctx, |ui| { ui.horizontal(|ui| { craft_ui::ComboBox::from_id_salt("ltmgr_load").selected_text("Load...").width(110.0).show_ui(ui, |ui| { @@ -135,12 +136,10 @@ fn linetype(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { } } // The user's own .lin file (where the host has a file picker). - if let Some(pick) = app.services.pick_open.as_ref() { + if app.services.pick_open.is_some() { ui.separator(); - if ui.selectable_label(false, "From File...").clicked() - && let Some(path) = pick() - { - action = Some(("linetype", json!({ "load": "*", "file": path }))); + if ui.selectable_label(false, "From File...").clicked() { + pick_lin = true; } } }); @@ -187,6 +186,10 @@ fn linetype(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { }); }); set_temp(ctx, "ltmgr_sel", sel); + // The user's .lin file, asked for once the window is drawn. Errors are echoed by `run`. + if pick_lin { + let _ = app.pick_then(Pick::Open, |app, path| app.run("linetype", json!({ "load": "*", "file": path }))); + } action } @@ -306,7 +309,7 @@ fn point_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action enum Field { Num(&'static str, &'static str, f64), Bool(&'static str, &'static str, bool), - Choice(&'static str, &'static str, String, Vec), + Choice(&'static str, &'static str, String, std::sync::Arc<[String]>), } struct Style { @@ -371,7 +374,8 @@ fn mleader_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Acti no_drawing(ctx, "Multileader Style", open); return None; }; - let text_styles: Vec = d.text_styles.iter().map(|s| s.name.clone()).collect(); + // One list shared by every row: a copy per style multiplied the two counts. + let text_styles: std::sync::Arc<[String]> = d.text_styles.iter().map(|s| s.name.clone()).collect(); let mut styles: Vec